I want the for loop to continue execution if an exception occurs (99 out of 100, wiil be conection problem to portal), meaning move to connecting to next portal.
I thought using I finally compined with a goto but I dislike using goto.
for (int i = 0; i < Portals.Count; i++)
{
try
{
if (!Portals[i].IsConnected)
{
Portals[i].Connect();
///..Permorm variours actioms...
}
}
catch
{
Window7 win = new Window7();
win.label1.Content = "Connect to Portal " + (i + 1).ToString() + " Failed..";
win.ShowDialog();
return;
}
If you wish to continue with the code placed after the try/catch use this :
(simply remove the return; statement)
for (int i = 0; i < Portals.Count; i++)
{
try
{
if (!Portal[i].IsConnected)
{
Portal[i].Connect();
///..Permorm variours actioms...
}
}
catch
{
Window7 win = new Window7();
win.label1.Content = "Connect to Portal " + (i + 1).ToString() + " Failed..";
win.ShowDialog();
}
// TODO - Some more code here
}
If you wish to stop that iteration if an Exception occurs, simply replace your return by a continue :
for (int i = 0; i < Portals.Count; i++)
{
try
{
if (!Portal[i].IsConnected)
{
Portal[i].Connect();
///..Permorm variours actioms...
}
}
catch
{
Window7 win = new Window7();
win.label1.Content = "Connect to Portal " + (i + 1).ToString() + " Failed..";
win.ShowDialog();
continue;
}
// TODO - Some more code here
}
Related
This question already has answers here:
C# - Read in a large (150MB) text file into a Rich Text Box
(2 answers)
Closed 1 year ago.
I have a large text files for example 39000 lines and above , i want to load it into richtextbox , using normal way like this:
Richtextbox1.Text=File.ReadAllLines(file);
or
Richtextbox1.LoadFile(...);
it take long time and freeze the UI even i use BackgroundWorker, so i decide to split file into parts each part is 1000 lines and append them to the richtextbox , i mean i read 1000 lines from file into string and then append it to the richtextbox, here is my code:
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
StreamReader reader = null;
try
{
//
int ProgressPercentage = 0;
//enable stop Correct button
BTN_Send_Ref.Invoke((MethodInvoker)(() =>
{
BTN_Send_Ref.Enabled = true;
}));
string[] Lines = File.ReadAllLines(InputTextFile);
//MessageBox.Show("Lines : " + Lines.Length);
int i= 0;
int j = 0;
string LinesCollection = "";
while (true)
{
if (worker.CancellationPending)
{
if (reader != null)
{
reader.Close();
reader = null;
}
e.Cancel = true;
//cancel backgroundworker
return;
}
LinesCollection = "";
if (i > Lines.Length ||
j >= Lines.Length)
{
break;
}
i += 1000;
if (i >= Lines.Length)
{
i = Lines.Length ;
}
while ( j < i)
{
if (worker.CancellationPending)
{
if (reader != null)
{
reader.Close();
reader = null;
}
e.Cancel = true;
//cancel backgroundworker
return;
}
if (j < Lines.Length)
{
if (LinesCollection == "")
{
LinesCollection = Lines[j];
}
else
{
LinesCollection += Environment.NewLine + Lines[j];
}
}
ProgressPercentage = (int)Math.Round((((double)j) / Lines.Length) * 100);
if (ProgressPercentage < 100)
{
//report progress
worker.ReportProgress(ProgressPercentage);
}
ProgressPercentage++;
j++;
}
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.AppendText(LinesCollection +Environment.NewLine);
}));
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
}
/*int Tmp_Count = 0;
if (RichTXT_OutText_Ref.InvokeRequired)
{
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.LoadFile(InputTextFile, RichTextBoxStreamType.PlainText);
}));
}
else
{
RichTXT_OutText_Ref.LoadFile(InputTextFile, RichTextBoxStreamType.PlainText);
}
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
*/
/*reader= File.OpenText(InputTextFile);
string Line = "";
int LinesCounter = 0;
while ((Line = reader.ReadLine()) != null)
{
if (worker.CancellationPending)
{
if (reader != null)
{
reader.Close();
reader = null;
}
e.Cancel = true;
//cancel backgroundworker
return;
}
if(LinesCounter >0 && LinesCounter <= 1000)
{
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.AppendText(LinesCollection);
}));
LinesCollection = "";
LinesCounter = 0;
}
else
{
if (LinesCollection == "")
{
LinesCollection= Line;
}
else
{
LinesCollection += Environment.NewLine + Line;
}
}
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
//calculate progress value
ProgressPercentage = (int)Math.Round((((double)PercentageCounter) / Lines.Length) * 100);
if (ProgressPercentage < 100)
{
//report progress
worker.ReportProgress(ProgressPercentage);
}
TempCount++;
PercentageCounter++;
Tmp_Count++;
}
*/
if (reader != null)
{
reader.Close();
reader = null;
}
//disable Correct button because
//we are out of loop
if (BTN_Send_Ref != null)
{
//we call this btn Correct
//from another thread
//so we must use Invoke
BTN_Send_Ref.Invoke((MethodInvoker)(() =>
{
BTN_Send_Ref.Enabled = false;
}));
}
}
catch (Exception ex)
{
if (reader != null)
{
reader.Close();
reader = null;
}
MessageBox.Show(ex.Message+"\n"+ex.StackTrace.ToString());
throw ex;
}
}
the problem is that the code work fine with some file say less than 1000 but when i use large file has size greater than 1000,the count of lines is less than actual file lines
for example i attach text file
my text file
which has size 62077 but the after use my code the richtextbox lines is 62028, and count of characters also is less the actual count of characters of file, but the start and the end of content in richtextbox and file are the same, i do not know where is the error, all i want is to read text file , combine every 1000 lines in one string append it the richtextbox repeat the operation until end of file content.
i do not want to use Richtextbox1.LoadFile(...)and Richtextbox1.Text=File.ReadAllLines(file); because they freeze and hung the UI this happen when using large files more than 39000 lines,
i want to know what is the wrong with code?why dose not get right result?
i hope you help me.
i use this code and it work fine:
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
//
int ProgressPercentage = 0;
BTN_Send_Ref.Invoke((MethodInvoker)(() =>
{
BTN_Send_Ref.Enabled = true;
}));
string[] Lines = File.ReadAllLines(InputTextFile);
string LinesCollection = "";
for(int x = 0; x < Lines.Length; x++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
//cancel backgroundworker
return;
}
LinesCollection += Lines[x] + Environment.NewLine;
if (x>0 && x % 1000 == 0)
{
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.AppendText(LinesCollection );
}));
LinesCollection = "";
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
}
if(x==Lines.Length-1 && LinesCollection != "")
{
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.AppendText(LinesCollection.TrimEnd(Environment.NewLine.ToCharArray()) );
}));
LinesCollection = "";
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
}
ProgressPercentage = (int)Math.Round((((double)x) / Lines.Length) * 100);
if (ProgressPercentage < 100)
{
//report progress
worker.ReportProgress(ProgressPercentage);
}
}
//disable Correct button because
//we are out of loop
if (BTN_Send_Ref != null)
{
BTN_Send_Ref.Invoke((MethodInvoker)(() =>
{
BTN_Send_Ref.Enabled = false;
}));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message+"\n"+ex.StackTrace.ToString());
throw ex;
}
}
So i have the following code:
public void tViewers(int? start, int? stop)
{
for (int? i0 = start; i0 <= stop; i0++)
{
StartLabel:
Viewer v = new Viewer(channelNameTextBox.Text, this);
if (urlWithTokens.Contains(v.getViewerLink()))
{
goto StartLabel;
}
else
{
if (v.getViewerLink() != "")
{
Console.WriteLine("[V #" + i0 + "] SUCCESS");
urlWithTokens.Add(v.getViewerLink());
}
else
{
Console.WriteLine("Channel not found.");
showError("The channel name is not valid.", true);
this.Invoke(new Action(() => this.botControlls.Enabled = true));
urlWithTokens.Clear();
}
}
v = null; // clear
}
Console.WriteLine("[V] " + start + " to " + stop + " COMPLETED");
start = null;
stop = null;
GC.SuppressFinalize(this);
}
Which is executed by:
for (int i = 0; i < maxThreads; i++)
{
taskFactory.StartNew(() => tViewers(someValue, someHigherValue));
}
The problem here is the local parameters "start" and "stop" in tViwers and it returst some stange values.
fx if i print "start" it should return the "someValue" and "someHigherValue" depending on what "thread" it is running in, however it returns strange values 40, 50 or something (even if it should return 1, 2, 3...
I have tried using the GC.SuppressFinalize(this); and setting the int's to null my allowing them to be null (int?). However the problem is still there...
Can someone help me?
I'm wanting to add +1 every time a radiobox or checkbox is used. This happens when calculate is pressed and putting it into a string then when the summary button is pushed it displays it in a messagebox with the final total of times it was pushed.
this is my code so far but it doesnt seem to work,
This is my Calculate button
int Quantity;
int Finalprice;
if (lunchRadioButton.Checked == true)
{
Meal = Lunch;
}
else if (tableCheckBox.Checked && waiterCheckBox.Checked)
{
Extras = Waiter + Table;
}
else if (waiterCheckBox.Checked)
{
Extras = Waiter;
}
else if (tableCheckBox.Checked)
{
Extras = Table;
}
//Early Evening Meal
if (earlyEveningRadioButton.Checked == true)
{
Meal = Early;
}
else if (tableCheckBox.Checked && waiterCheckBox.Checked)
{
Extras = Table + Waiter;
}
else if (waiterCheckBox.Checked)
{
Extras = Waiter;
}
else if (tableCheckBox.Checked)
{
Extras = Table;
}
//Late evening options
if (lateEveningRadioButton.Checked == true)
{
Meal = Late;
}
//Late Evening, Corner table and Dedicated waiter selected.
else if (tableCheckBox.Checked && waiterCheckBox.Checked)
{
Extras = Table + Waiter;
}
//Late Evening and Dedicated waiter selected.
else if (waiterCheckBox.Checked)
{
Extras = Waiter;
}
//Late Evening and Corner Table
else if (tableCheckBox.Checked)
{
Extras = Table;
;
}
try
{
Quantity = int.Parse(guestTextBox.Text);
Mealprice = (Meal * Quantity);
Finalprice = (Mealprice + Extras);
finalAmountLabel.Text = Finalprice.ToString("C");
}
catch
{
guestTextBox.Focus();
guestTextBox.SelectAll();
MessageBox.Show("Please enter a quantity in numerical form","Quantity Error!");
}
This is the Summary Button
int TotalLunch = 0;
int TotalEarly = 0;
int TotalLate = 0;
int TotalBookings = 0;
int TotalWaiters = 0;
int LateWaiters = 0;
int EarlyWaiters = 0;
int LunchWaiters = 0;
int TotalCornerTables = 0;
int EarlyCornerTables = 0;
int LateCornerTables = 0;
int LunchCornerTables = 0;
if (earlyEveningRadioButton.Checked == true)
{
TotalEarly = +1;
TotalEarly.ToString();
}
else if (earlyEveningRadioButton.Checked && waiterCheckBox.Checked)
{
EarlyWaiters = +1;
EarlyWaiters.ToString();
}
else if (tableCheckBox.Checked && earlyEveningRadioButton.Checked)
{
EarlyCornerTables = +1;
EarlyCornerTables.ToString();
}
else if (waiterCheckBox.Checked && tableCheckBox.Checked)
{
EarlyWaiters = +1;
EarlyCornerTables = +1;
EarlyWaiters.ToString();
EarlyCornerTables.ToString();
}
MessageBox.Show("Number of Early Bookings" + " " + TotalEarly + " " +
"Number of Early Evening Waiters" + " " + EarlyWaiters
+ "number of Early Evening Corner Tables tables" + " " + EarlyCornerTables
);
Any suggestions or help would be greately appriciated :)
The best way you can do this, is using the eventhandler CheckedChanged foreach checkbox.
in the event do this:
if(checkBox.Checked)
{
//int +1
}
I'll start with an answer to your question...
Your code will not increment TotalEarly by one, but it will assign +1 to the variable.
TotalEarly = +1;
For incrementing you should either use the ++ or the += operator:
TotalEarly++; // increments by 1
TotalEarly += 1; // also increments by 1, but += can be used with other numbers
Some other notes, not related to your question:
TotalEarly.ToString();
This will not do anything since you do not assign the result to a variable. This will not convert TotalEarly to a string variable! The type of TotalEarly is fixed to int as you specified.
You would have to write
var totalEarlyString = TotalEarly.ToString();
to be able to use the result afterwards. You might wonder why your MessageBox still displays that number as a string although you use the int variable:
"Number of Early Bookings" + " " + TotalEarly
This is because the ToString() method is called automatically in this case. So, you can really save some lines by removing your calls to ToString() after the assignments.
One more thing: local variables are typically named using camelCase. That means, the first character is lower case and every additional word starts with an uppercase character. PascalCase (i.e. also starting with uppercase character) is typically used for properties, methods, class names etc, but not for local or member variables.
It seems like you want each value in the MessageBox to be on a separate line (at least I assume that is why you added some spaces at the end of the first line:
MessageBox.Show("Number of Early Bookings" + " " + TotalEarly + " " +
"Number of Early Evening Waiters" + " " + EarlyWaiters
+ "number of Early Evening Corner Tables tables" + " " + EarlyCornerTables
);
This might not work on all machines. The MessageBox has different sizing behavior on differnt versions of Windows. Some will wrap the text to multiple lines, some will not, or at least at different widths!
Therefore, you better add an Environment.NewLine at the end of each line. This will add a line break to your string which will be interpreted as such by the MessageBox:
MessageBox.Show("Number of Early Bookings " + TotalEarly + Environment.NewLine +
"Number of Early Evening Waiters " + EarlyWaiters + Environment.NewLine +
"Number of Early Evening Corner Tables tables " + EarlyCornerTables);
Accordion to your comments in your code I think the problem is that your if else statements are wrong.
Q1: Should it calculate on every checkbox click or only when you click calculate?
- if it should calculate on every checkbox click then you have to use the CheckedChanged event as RaZor points out.
Q2: Is it true that de client can have a lunch + waiter + table?
- if that is true then your if else statement should be as follows:
if (lunchRadioButton.Checked == true)
{
Meal = Lunch;
if (tableCheckBox.Checked && waiterCheckBox.Checked)
{
Extras = Waiter + Table;
}
else if (waiterCheckBox.Checked)
{
Extras = Waiter;
}
else if (tableCheckBox.Checked)
{
Extras = Table;
}
}
I have a .NET Winforms-based program I wrote in C# where I programmatically select text within a TextBox using the Select() method. I can see the selected text on the screen and the SelectionLength member reports an accurate amount of selected characters, but the SelectedText member doesn't contain any text:
int indexPeriod = strLectureText.IndexOfAny(terminators, indexStart);
thisTextbox.Focus();
if (indexPeriod > -1)
{
thisTextbox.Select(indexStart, (indexPeriod - indexStart) + 1);
}
else
{
thisTextbox.Select(indexStart, thisTextbox.Text.Length);
}
Log.Debug("jtext len=" + thisTextbox.SelectionLength + " txt=" + thisTextbox.SelectedText);
thisTextbox.ScrollToCaret();
What's going on?
Update Nov 16 2013
I am adding additional code per #KingKing's request:
delegate void delegateMoveToNextTextFragment(ref TextBox thisTextbox, char[] terminators);
private void MoveToNextTextFragment(ref TextBox thisTextbox, char[] terminators)
{
string strLectureText = String.Empty;
strLectureText = thisTextbox.Text;
int currentStartPos = thisTextbox.SelectionStart + thisTextbox.SelectionLength - 1
// search the rest of the buffer after the currently-selected string to find the next period
int skipLastChar = 0;
// don't include last selected character in search
try
{
if ((thisTextbox.SelectionLength > 0) & (strLectureText[currentStartPos] != '.'))
{
skipLastChar = 1;
}
}
catch (Exception ex)
{
Debug.WriteLine("exception caught! ex=" + ex.Message);
skipLastChar = 0;
}
int indexStart = 0;
if (currentStartPos == 0)
{
indexStart = 0;
}
else
{
indexStart = currentStartPos + 1;
}
int indexPeriod = strLectureText.IndexOfAny(terminators, indexStart);
if (indexPeriod > -1)
{
thisTextbox.Select(indexStart, (indexPeriod - indexStart) + 1);
}
else
{
thisTextbox.Select(indexStart, thisTextbox.Text.Length);
}
thisTextbox.Focus();
Log.Debug("jtext len=" + thisTextbox.SelectionLength + " txt=" + thisTextbox.SelectedText);
thisTextbox.ScrollToCaret();
}
I'm receiving an error on the 5th line, listCell.Count() tried resolving it with listCell.Items.Count() but that didn't work... any idea? error: does not contain a definition for count.
int listCellCounter = 0;
for (int x = 0; x < listId.Items.Count; x++)
{
Console.WriteLine("something " + listId.Items[x] + " " + listCell.Items[listCellCounter]);
if (listCellCounter == listCell.Count() - 1)
{
listCellCounter = 0;
}
else
{
listCellCounter += 1;
}
}
Im not quite sure what collection the listCell is but I'd imagine that .Count() should be a property. So try to change your code to this:
...
if (listCellCounter == listCell.Count - 1) // or listCell.Items.Count - 1
{
listCellCounter = 0;
}
...
The error you are getting basicly just means that there is no Count() method in listCell.