'index was outside the bounds of the array' exception handling error - c#

I am using the below code to find the base address of a running process. It's within a timer control for other purposes. If the target process is not running I want to display "Process is not running" in the label text, but keep checking for the running process and when/if found continue with the next code block. I have tried a few ways I thought would work, such as a 'try' with exception handling, but the form I am using to hold the label just freezes, I am quit new to c#. Here is the code,
private void timer1_Tick(object sender, EventArgs e)
{
#region BaseAddress
Process[] test = Process.GetProcessesByName("process");
int Base = test[0].MainModule.BaseAddress.ToInt32();
#endregion
//Other code
}
The exception when run is: "IndexOutOfRange exception was unhandled" - Index was outside the bounds of the array. Hopefully someone can help. Thanks.

private void timer1_Tick(object sender, EventArgs e)
{
#region BaseAddress
Process[] test = Process.GetProcessesByName("process");
if (test.Length > 0)
{
int Base = test[0].MainModule.BaseAddress.ToInt32();
}
else
{
myLabel.Text = "Process is not running";
}
#endregion
//Other code
}

Rather than use a try–catch block to handle the error, you should check whether the process was found before trying to access it:
private void timer1_Tick(object sender, EventArgs e)
{
#region BaseAddress
Process[] test = Process.GetProcessesByName("process");
if (test.Any())
{
// Process is running.
int Base = test[0].MainModule.BaseAddress.ToInt32();
// Perform any processing you require on the "Base" address here.
}
else
{
// Process is not running.
// Display "Process is not running" in the label text.
}
#endregion
//Other code
}

I think that the Process with the name "process" does not exist. You need to give a real processname. So the array does not contain any elements. Try debugging to see if the array contains any elements and add error handling or a verification that the array length is higher than 0 before doing the second line of your code.

Related

Generating Report in C# causing error

I'm generating report in C# by using background worker but I'm getting this error.
Source code as follows:
I have to access my datagridview Records to access it's data.
A small window opens up in my datagridview which asks user to enter date from and to generate report, then i access back my datagridview convert into data table write in XML file and generate report.
Global Variables
// This is the form where the data lies, I'm accessing it's instance.
Records TR = new Records();
// This is the form where report will be displayed.
TReportDisplay TRD = new TReportDisplay();
// This is the report.
Treport treport1 = new Treport();
private void button1_Click(object sender, EventArgs e)
{
// FIXED HERE - 1
// FIXED - 2 IN THE ANSWER BELOW.
// Accessing my DataGridView Form Instance.
TR = Application.OpenForms.OfType<Records>().ElementAt(0);
treport1.SetDataSource(TR.ds);
TRD.crystalReportViewer2.ReportSource = treport1;
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
TRD.crystalReportViewer2.ReportSource = treport1;
ParameterFieldDefinitions Parameters;
ParameterFieldDefinition Parameter;
ParameterValues Values = new ParameterValues();
ParameterDiscreteValue DiscreteValue = new ParameterDiscreteValue();
DiscreteValue.Value = dateTimePicker1.Text;
Parameters = treport1.DataDefinition.ParameterFields;
Parameter = Parameters["fromdate"];
Values = Parameter.CurrentValues;
Values.Clear();
Values.Add(DiscreteValue);
Parameter.ApplyCurrentValues(Values);
DiscreteValue.Value = dateTimePicker2.Text;
Parameters = treport1.DataDefinition.ParameterFields;
Parameter = Parameters["todate"];
Values = Parameter.CurrentValues;
Values.Add(DiscreteValue);
Parameter.ApplyCurrentValues(Values);
}
}
catch (Exception ex) { MessageBox.Show(ex.Message.ToString(), "Message"); };
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
TRD.ShowDialog();
}
There were two issues, first of all updating progress bar from a different thread for which I got answer, another calling form instance after background worker was causing the issue, just put the variable before background worker start async and fixed.
The error message is telling you that the only way to update the controls is via the thread that the controls are running on. You are currently running on a different thread (the one for the back ground worker).
Take a look at the example in this link for another question on SO Invoke(Delegate) . You basically should have a method that you can call, to update the UI, which can check if it is on the correct thread and if it is not gets the correct thread to call it.
This is a snippet of code that was on the link parvee gave above that shows how you can do this.
public void UpdateProgress(int percentComplete)
{
if (!InvokeRequired)
{
ProgressBar.Value = percentComplete;
}
else
{
Invoke(new Action<int>(UpdateProgress), percentComplete);
}
}

How can I add spell-checking to my rich text box?

I would like to know if there's an easy way to implement spell check to my rich text box? I have heard there's a way to use the spell check from MS Word, but I would like to know if I could add an independent spell check to my application. If somebody could provide me with a tutorial on how to do this (video or webpage or example or anything), then I'd really
appreciate it.
--EDIT--
Following on from the answer I received, I implemented the spell check to my code and it is now as follows:
private NetSpell.SpellChecker.Spelling spelling;
private NetSpell.SpellChecker.Dictionary.WordDictionary wordDictionary;
internal System.Windows.Forms.Button spellButton;
internal System.Windows.Forms.RichTextBox demoRichText;
private System.ComponentModel.IContainer components2;
internal System.Windows.Forms.RichTextBox Document;
internal NetSpell.SpellChecker.Spelling SpellChecker;
private System.ComponentModel.IContainer components1;
internal NetSpell.SpellChecker.Dictionary.WordDictionary WordDictionary;
...
private void toolStripButton1_Click(object sender, EventArgs e)
{
try
{
this.spelling.Text = this.richTextBoxPrintCtrl1.Text; // I get an error on this line.
this.spelling.SpellCheck();
}
catch
{
MessageBox.Show("Error loading Spell Checker. Please reload application and try again.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void spelling_DeletedWord(object sender, NetSpell.SpellChecker.SpellingEventArgs e)
{
int start = this.richTextBoxPrintCtrl1.SelectionStart;
int length = this.richTextBoxPrintCtrl1.SelectionLength;
this.richTextBoxPrintCtrl1.Select(e.TextIndex, e.Word.Length);
this.richTextBoxPrintCtrl1.SelectedText = "";
if (start > this.richTextBoxPrintCtrl1.Text.Length)
start = this.richTextBoxPrintCtrl1.Text.Length;
if ((start + length) > this.richTextBoxPrintCtrl1.Text.Length)
length = 0;
this.richTextBoxPrintCtrl1.Select(start, length);
}
private void spelling_ReplacedWord(object sender, NetSpell.SpellChecker.ReplaceWordEventArgs e)
{
int start = this.richTextBoxPrintCtrl1.SelectionStart;
int length = this.richTextBoxPrintCtrl1.SelectionLength;
this.richTextBoxPrintCtrl1.Select(e.TextIndex, e.Word.Length);
this.richTextBoxPrintCtrl1.SelectedText = e.ReplacementWord;
if (start > this.richTextBoxPrintCtrl1.Text.Length)
start = this.richTextBoxPrintCtrl1.Text.Length;
if ((start + length) > this.richTextBoxPrintCtrl1.Text.Length)
length = 0;
this.richTextBoxPrintCtrl1.Select(start, length);
}
private void spelling_EndOfText(object sender, System.EventArgs e)
{
Console.WriteLine("EndOfText");
}
However, when I try to load the checker, I get a NullReferenceExeption was unhandled error on the line uncommented in the code.
Any ideas? I don't know where to go from this point. I can load the program, but I get an error on the uncommented line of code. I've tried following the demo, but I can't seem to see why the demos code works but mine refuses to play nice... My code is exactly the same as the demo example (from what I can see), so why is it now working and giving me an error when I try to run the spell checker?
It's a little older, but I have personally used NetSpell which seems to be pretty easy to set up, just include the project in your Visual Studio solution and it should be good to go.
http://www.codeproject.com/Articles/5277/NetSpell-Spell-Checker-for-NET

handle "The operation completed successfully" error

I have a vast application running WPF and I occasionally get the
The operation completed successfully
error randomly, could be a whole host of things.
Is there any way to trap this code and just restart the app.
I'm already using
#region "Error Checking"
void OnAppDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
HandleError("OnAppDomainUnhandledException", e.ExceptionObject.ToString(), e.ExceptionObject.ToString());
}
void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
string error = string.Empty;
if (e.Exception.InnerException != null)
error = e.Exception.InnerException.Message;
HandleError("OnDispatcherUnhandledException", e.Exception.Message.ToString(),error);
e.Handled = true;
}
#endregion
but this does not appear to catch/handle the error
When I Google it seems that it has something to do with SplashScreens...
Maybe this may help you, or this.

Created event in System.IO.FileSystemWatcher

I have a folder. When a file copied to that folder I need to rename it. Hence I have used a System.IO.FileSystemWatcher to do that. And I have implemented a service to do it.
My code as follows.
private System.IO.FileSystemWatcher FSWatcherTest;
FSWatcherTest.Created += new FileSystemEventHandler(FSWatcherTest_Created);
--------
private void FSWatcherTest_Created(object sender, System.IO.FileSystemEventArgs e)
{
//Some code
File.Move(oldfilepath, newfilepath);
//some code
}
When I copy a text file from my local machine it is working finely. But when I copy I large file from the network this is not working. Error is when it is copping this will fired. So the file is not accessible to this method. But I’m wondering why this is fired while it’s copping.
I’m using VS 2008 and C# for this application.
Thanks in advance.
Hacky solution:
If there is no way to know when the file has been fully copied, you could keep trying to do it until it works.
Something like this:
private void FSWatcherTest_Created(object sender, System.IO.FileSystemEventArgs e)
{
FileMover(object sender, System.IO.FileSystemEventArgs e);
}
private void FileMover(object sender, System.IO.FileSystemEventArgs e)
{
try{
//Some code
File.Move(oldfilepath, newfilepath);
//some code
}
catch
{
//Call an asynchronous method that will wait 1 second then call FileMover again
//with the same arguments,
//a BackGroundWorker would be perfect for that job.
}
}
Just found this snippit
Dim F As Short = FreeFile()
FileOpen(F, sFile, OpenMode.Binary, OpenAccess.ReadWrite, OpenShare.LockReadWrite)
FileClose(F)
Would it be possible to wrap it in a 'WHILE' loop so it waits until the copy process is free?

AutoComplete Texbox error - write to protected memory

I have an autocompleate textbox that looks into a data base. Some times while I'm typing I received the following error.
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Here is the code
private void tBSearchName_TextChanged(object sender, EventArgs e)
{
try
{
//test length
if (tBSearchName.Text.Length > 3)
{
//prevent db lookups
if (!tBSearchName.Text.ToLower().Contains(oldName) || oldName == String.Empty)
{
//test for a name + first letter of last name
if (Regex.IsMatch(tBSearchName.Text, #"(\w)+\s(\w)+(\.)*"))
{
tBSearchName.AutoCompleteCustomSource = AccessDB.serachByNemberName(tBSearchName.Text);
tBSearchName.AutoCompleteMode = AutoCompleteMode.Suggest;
//prevent db lookups
oldName = tBSearchName.Text.ToLower();
}
}
}
}
catch
{
}
}
My insight is that I should frezz typing into the application while search is done, can some suggest how to do this. Or any other insight on what is happening
It is a bug in Windows Forms's wrapper of autocomplete APIs. Windows Forms does not protect the AutoCompleteCustomSource object from being replaced while it is being enumerated by a background thread created by autocomplete.
Instead of replacing the data store, you can try replace the autocomplete object or use the IAutoCompleteDropDown interface to reset the enumerator.
You can use lock:
private void tBSearchName_TextChanged(object sender, EventArgs e)
{
lock(this) { /* do magic */
}
Do note that it's bad practice to perform long tasks in the event handlers. If the search takes more then 30ms, better use a worker thread.

Categories

Resources