How to prevent stack overflow error in javascript? - c#

I have a javascript function called MakeInput.
It has got approximately 150 lines.
And I have to call that function about 300 times in my code.
My C# code called that function through webbrowser control.
It has to call that function 300 times, until DataTable in C# finishes looping.
But maybe javascript in webbrowser thinks that I am calling an infinite recursive function, so when it comes to about 60 times, it always throws an error called stack overflow at line 38.
How can I prevent this error?
How can I do a long time function in javascript?
EDIT
OK.
I am posting my code.
Here it goes.
C#
ieBrowser.Document.InvokeScript("setPageIndex", new object[] { currentPage });
ieBrowser.Document.InvokeScript("fnSearch");
JavaScript
function fnSearch() {
var frm = document.searchFrm;
var str = encryptData(frm, _currentPage);
}
function encryptData(form, _currentPage) {
var retValue = "";
try {
var crypto = document.getElementById("SomeActiveX");
var resultVal = MakeInput(form);
var inputStr = "";
if (resultVal[0] != "" && resultVal[1] != "") {
inputStr = resultVal[0] + "&" + resultVal[1];
}
else if (resultVal[0] == "") {
inputStr = resultVal[1];
}
else if (resultVal[1] == "") {
inputStr = resultVal[0];
}
else {
inputStr = "";
}
retValue = crypto.Encrypt(inputStr);
}
catch (e) {
alert(e);
}
return retValue;
}
function MakeInput(form) {
var result = new Array(2);
try {
var keyProc = document.getElementById("SomeActiveX");
var name = new Array(form.elements.length);
var value = new Array(form.elements.length);
var enc_name = new Array();
var enc_value = new Array();
var enc_idx = 0;
var j = 0;
var len = form.elements.length;
for (i = 0; i < len; i++) {
if ((form.elements[i].type != "button") && (form.elements[i].type != "reset") &&
(form.elements[i].type != "submit")) {
if ((form.elements[i].type == "radio") || (form.elements[i].type == "checkbox")) {
if (form.elements[i].checked == true) {
name[j] = form.elements[i].name;
value[j] = form.elements[i].value;
j++;
}
}
else if ((form.elements[i].type == "text") || (form.elements[i].type == "password")) {
name[j] = form.elements[i].name;
value[j] = form.elements[i].value;
j++;
if (keyProc != null && (form.elements[i].getAttribute("enc") == "on")) {
enc_name[enc_idx] = "_E2E_" + form.elements[i].name;
enc_value[enc_idx] = keyProc.GetEncData("", form.name, form.elements[i].name);
enc_idx++;
}
}
else {
if (form.elements[i].type == "select-one") {
var ind = form.elements[i].selectedIndex;
var singleLen = form.elements[i].length;
if (singleLen > 0) {
if (ind >= 0) {
name[j] = form.elements[i].name;
value[j] = form.elements[i].options[ind].value;
j++;
}
else {
}
}
else {
}
}
else if (form.elements[i].type == "select-multiple") {
var multiLen = form.elements[i].length;
for (k = 0; k < multiLen; k++) {
if (form.elements[i].options[k].selected) {
name[j] = form.elements[i].name;
value[j] = form.elements[i].options[k].value;
j++;
}
}
}
else {
name[j] = form.elements[i].name;
value[j] = form.elements[i].value;
j++;
}
}
}
}
var flag1 = false;
var flag2 = false;
var signed_text = "";
var unsigned_text = "";
for (i = 0; i < j; i++) {
if (name[i].charAt(0) != "_") {
if (flag1) {
signed_text += "&";
}
else {
flag1 = true;
}
signed_text += name[i];
signed_text += "=";
signed_text += escape_url(value[i]);
}
else {
if (flag2) {
unsigned_text += "&";
}
else {
flag2 = true;
}
unsigned_text += name[i];
unsigned_text += "=";
unsigned_text += escape_url(value[i]);
}
}
for (i = 0; i < enc_idx; i++) {
if (flag2) {
unsigned_text += "&";
}
else {
flag2 = true;
}
unsigned_text += enc_name[i];
unsigned_text += "=";
unsigned_text += enc_value[i];
}
if (enc_idx > 0) {
if (flag2) {
unsigned_text += "&";
}
else {
flag2 = true;
}
unsigned_text += "_ENCSEED";
unsigned_text += "=";
unsigned_text += keyProc.GetEncData(serverCert, "", "");
}
result[0] = signed_text;
result[1] = unsigned_text;
}
catch (e) {
throw e;
}
return result;
}
And the error message was captured.
Sorry, the error message is written in Korean.
But it says, "Stack overflow(at line 38)".
But I think the number is not pointing at the line number, coz I've changed lines but the error message is always 38.

It doesn't think you are in a continuous loop. It fails when memory runs out in stack. The same code might work on a computer with higher memory. Each time a function is called a stack entry is kept in stack to move to calee once the function is done, so in your case the stack space runs out after 60 calls. The line 38 is not line number in your code.
Why dont you try same code on a high end PC

Related

Why Is This Code Running Longer Character Combinations Than Necessary?

I'm a math student with little to no experience programming, but I wrote this to act like a brute force algorithm. It seems to run fine except that it runs all the password combinations out to 3 characters for passwords as short as 2. Also I'm sure there's a way to refactor the for and if statements as well. Any help would be appreciated, thanks.
I've already been testing to see if some of the if statements aren't executing, and it looks like the statements with "console.writeln(Is this executing)" aren't executing but I'm not really sure.
public Form1()
{
InitializeComponent();
}
static char[] Match ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j' ,'k','l','m','n','o','p',
'q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','C','L','M','N','O','P',
'Q','R','S','T','U','V','X','Y','Z','!','?',' ','*','-','+'};
private string[] tempPass;
private void button1_Click(object sender, EventArgs e)
{
string tempPass1 = "lm";
string result = String.Empty;
int passLength = 1;
int maxLength = 17;
tempPass = new string[passLength];
for (int i = 0; i < Match.Length; i++)
{
if (tempPass1 != result)
{
tempPass[0] = Match[i].ToString();
result = String.Concat(tempPass);
if (passLength > 1)
{
for (int j = 0; j < Match.Length; j++)
{
if (tempPass1 != result)
{
tempPass[1] = Match[j].ToString();
result = String.Concat(tempPass);
if (passLength > 2)
{
for (int k = 0; k < Match.Length; k++)
{
if (tempPass1 != result)
{
tempPass[2] = Match[k].ToString();
result = String.Concat(tempPass);
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass[2] == "+" && tempPass1 != result)
{
Console.WriteLine("This will execute?");
passLength++;
tempPass = new string[passLength];
k = 0;
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is big gay: " + result);
break;
}
}
}
}
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass1 != result)
{
Console.WriteLine("Did this execute?");
passLength++;
tempPass = new string[passLength];
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is bigger gay: " + result);
break;
}
}
}
}
//tempPass[1] = "World!";
//Console.WriteLine(result);
if (tempPass[tempPass.Length - 1] == "+" && tempPass1 != result)
{
passLength++;
tempPass = new string[passLength];
Console.WriteLine(tempPass.Length + " " + result + " " + "Success");
Console.WriteLine(i);
i = 0; /**update
j = 0;
k = 0;
l = 0;
m = 0;*/
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is biggest gay: " + result);
}
}
}
}
Play with this; modified from my answer here. It'll show you all the 2 and 3 length combinations. Clicking the button will start/stop the generation process. You need a button, label, and a timer:
public partial class Form1 : Form
{
private Revision rev;
public Form1()
{
InitializeComponent();
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = !timer1.Enabled;
}
private void timer1_Tick(object sender, EventArgs e)
{
rev.NextRevision();
if (rev.CurrentRevision.Length == 4)
{
timer1.Stop();
MessageBox.Show("Sequence Complete");
// make it start back at the beginning?
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
else
{
label1.Text = rev.CurrentRevision;
}
}
}
public class Revision
{
private string chars;
private char[] values;
private System.Text.StringBuilder curRevision;
public Revision()
{
this.DefaultRevision();
}
public Revision(string validChars)
{
if (validChars.Length > 0)
{
chars = validChars;
values = validChars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
else
{
this.DefaultRevision();
}
}
public Revision(string validChars, string startingRevision)
: this(validChars)
{
curRevision = new System.Text.StringBuilder(startingRevision.ToUpper());
int i = 0;
for (i = 0; i <= curRevision.Length - 1; i++)
{
if (Array.IndexOf(values, curRevision[i]) == -1)
{
curRevision = new System.Text.StringBuilder(values[0]);
break;
}
}
}
private void DefaultRevision()
{
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
values = chars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
public string ValidChars
{
get { return chars; }
}
public string CurrentRevision
{
get { return curRevision.ToString(); }
}
public string NextRevision(int numRevisions = 1)
{
bool forward = (numRevisions > 0);
numRevisions = Math.Abs(numRevisions);
int i = 0;
for (i = 1; i <= numRevisions; i++)
{
if (forward)
{
this.Increment();
}
else
{
this.Decrement();
}
}
return this.CurrentRevision;
}
private void Increment()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index < (chars.Length - 1))
{
index = index + 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[0];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index < (values.Length - 1))
{
index = index + 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[0];
}
}
curRevision.Insert(0, values[0]);
}
}
private void Decrement()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[values.Length - 1];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[values.Length - 1];
}
}
curRevision.Remove(0, 1);
if (curRevision.Length == 0)
{
curRevision.Insert(0, values[0]);
}
}
}
}

How to count the a specific value on a multidimensional array c#(Unity)

I'm having trouble on counting the number of my TIE value in my list
here is my code :
string[,] table = new string[104, 15];
int xIndex = 0;
int yIndex = 0;
for (int i = 0; i < list.Count; i++)
{
newString[0] += list[i].r;
newString[0] += ",";
}
string[] newChars = newString[0].Split(',');
string result = ""; // variable for the substring
string previousValue_ = ""; // store here the newprevious value without the T
int counterForTie = 0;
int counterForRow = 1;
int justMoveToY = 1;
foreach (string previousValue in newChars)
{
//check the length so that it wont throw an error
if (previousValue.Length > 1)
{
//get only the first letter of value P,B,T
result = previousValue.Substring(0, 1);
}
else
{
result = "";
}
if (table.GetLength(0) < xIndex)
{
break;
}
if (result.Equals(newPreviousValue) || result.Equals("T") && yIndex < table.GetLength(1))
{
if (counterForRow == 1)
{
yIndex = 0;
table[xIndex, yIndex] = result;
counterForRow++;
if (firstDragonTail)
{
counterForTieSecondTime++;
}
else if (secondDragonTail)
{
counterForTieThirdTime++;
}
else
{
counterForTie++;
}
}
else
{
yIndex += 1;
table[xIndex, yIndex] = result;
if (firstDragonTail)
{
counterForTieSecondTime++;
}
else if (secondDragonTail)
{
counterForTieThirdTime++;
}
else
{
counterForTie++;
}
}
}
else if (result.Equals(newPreviousValue) && previousValue.Equals("T") && yIndex < table.GetLength(1))
{
yIndex += 1;
table[xIndex, yIndex] = result;
if (firstDragonTail)
{
counterForTieSecondTime++;
}
else if (secondDragonTail)
{
counterForTieThirdTime++;
}
else
{
counterForTie++;
}
}
else
{
if (justMoveToY == 1 && counterForRow == 1)
{
xIndex = 0;
yIndex = 0;
table[xIndex, yIndex] = result;
justMoveToY++;
counterForRow++;
}
else if (justMoveToY == 1)
{
xIndex = 0;
yIndex += 1;
table[xIndex, yIndex] = result;
justMoveToY++;
}
else {
if (firstDragonTail)
{
xIndex += 1;
yIndex = 0;
table[xIndex, yIndex] = result;
counterForTieSecondTime = 0;
if (counterForTieSecondTime == 0)
{
secondDragonTail = true;
firstDragonTail = false;
}
else
{
secondDragonTail = false;
}
}
else if (secondDragonTail)
{
xIndex += 1;
yIndex = 0;
table[xIndex, yIndex] = result;
counterForTieThirdTime = 0;
if (counterForTieThirdTime == 0)
{
thirdDragonTail = true;
secondDragonTail = false;
}
else
{
thirdDragonTail = false;
}
}
else
{
xIndex += 1;
yIndex = 0;
table[xIndex, yIndex] = result;
counterForTie = 0;
}
}
}
previousValue_ = result;
if (!result.Equals("T"))
{
newPreviousValue = previousValue_;
}
}
My problem here is that i couldn't count separately all the TIE value . All i want just to count the TIE value on every column .
For example like this image
As you can see on the image above i want to know if the TIE value is on the PLAYER value(blue) / BANKER value(red) and count the TIE value if how many is it on the Player column and vice versa.
I tried this
//count tie in a row
if (result.Equals("T") && result.Equals("P"))
{
tieCounterPlayer++;
Debug.Log("TIE FOR PLAYER :" + tieCounterPlayer);
}
else if(result.Equals("T") && result.Equals("B"))
{
tieCounterBanker++;
Debug.Log("TIE FOR BANKER :" + tieCounterBanker);
}
But unfortunately it didn't work.
Sorry for asking
This is what i did.
if (newPreviousValue.Contains("B"))
{
if (result.Equals("T"))
{
tieCounterBanker++;
Debug.Log("TIE FOR BANKER : " + tieCounterBanker);
}
else
{
tieCounterBanker = 0;
}
}
else if(newPreviousValue.Contains("P"))
{
if (result.Equals("T"))
{
tieCounterPlayer++;
Debug.Log("TIE FOR PLAYER : " + tieCounterPlayer);
}
else
{
tieCounterPlayer = 0;
}
}

Why is my program not receiving data the right way and right order?

I wrote a c# program where I will send functions to a pic and receive the desired data from it. After the last function is sent, it will loop and send the first function again. However, afterwards the received data is not consistent. Sometimes it has missing data or the received data is not in the right order as it should. I am not sure what the problem is because the data should be received and displayed the same way every time since I am sending the functions in the same order. I already attempted putting the Thread.Sleep function just in case the data is being sent or received too fast but that did not help as much. Any suggestions??? P.s. It is connected through serial port.
My code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.Timers;
using System.IO;
using System.Net;
using System.Threading;
namespace serialreadwrite
{
class Program
{
static void Main(string[] args)
{
#region Initialize Code
SerialPort _serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
#region Initialize Serial and Open
_serialPort.Handshake = Handshake.None;
_serialPort.ReadTimeout = 1000;
_serialPort.WriteTimeout = 1000;
_serialPort.RtsEnable = true;
_serialPort.DtrEnable = true;
_serialPort.Open();
#endregion
int num;
Console.WriteLine("How often will you like to transmit: \nMins:");
num = Convert.ToInt32(Console.ReadLine());
int num2 = 60000 * num;
#endregion
int i = 0;
bool Array_Volt_Flag = false;
bool Array_Amps_Flag = false;
bool Auto_MPPT_Flag = false;
bool Motor_Volt_Flag = false;
bool Motor_Amps_Flag = false;
bool Max_Motor_Flag = false;
bool Motor_RPM_Flag = false;
bool SN_Flag = false;
bool SMC_Type_Flag = false;
bool Auto_MPPV_Flag = false;
string[] temp_Array = null;
while (true) //Loops the whole code (send/receive) over and over
{
string time = Convert.ToString(DateTime.Now); // Added time to the loop
try
{
/*Send*/
string c = Convert.ToString(i);
byte[] array_out = Encoding.ASCII.GetBytes(c);
_serialPort.Write(array_out, 0, array_out.Length);
byte[] array_out2 = new byte[1];
array_out2[0] = 0xD;
_serialPort.Write(array_out2, 0, array_out2.Length);
Thread.Sleep(3000);
int reader = 0;
string fullstring = "";
/*Receive*/
for (int jj = 0; jj < _serialPort.BytesToRead; jj++)
{
reader = _serialPort.ReadByte();
fullstring += Convert.ToChar(reader);
}
string[] Array = fullstring.Split('\r');
for (int x = 0; x < Array.Length; x++)
{
if (Array[x].Contains("Switched") || Array[x].Contains("Action"))
continue;
else if (Array[x].Contains("Array Volt") && Array_Volt_Flag == false)
{
temp_Array = Array[x].Split('=');
if (temp_Array.Length == 2)
{
Console.WriteLine(time + "\n");
Console.WriteLine("Array Volt =" + temp_Array[1]);
Array_Volt_Flag = true;
}
}
else if (Array[x].Contains("Array Amps") && Array_Amps_Flag == false)
{
temp_Array = Array[x].Split('=');
if (temp_Array.Length == 2)
{
Console.WriteLine("Array Amps =" + temp_Array[1]);
Array_Amps_Flag = true;
}
}
else if (Array[x].Contains("Auto MPPT") && Auto_MPPT_Flag == false)
{
Console.WriteLine("Auto MPPT");
Auto_MPPT_Flag = true;
}
else if (Array[x].Contains("Motor Volt") && Motor_Volt_Flag == false)
{
temp_Array = Array[x].Split('=');
if (temp_Array.Length == 2)
{
Console.WriteLine("Motor Volt =" + temp_Array[1]);
Motor_Volt_Flag = true;
}
}
else if (Array[x].Contains("Motor Amps") && Motor_Amps_Flag == false)
{
temp_Array = Array[x].Split('=');
if (temp_Array.Length == 2)
{
Console.WriteLine("Motor Amps =" + temp_Array[1]);
Motor_Amps_Flag = true;
}
}
else if (Array[x].Contains("Max Motor") && Max_Motor_Flag == false)
{
temp_Array = Array[x].Split('=');
if (temp_Array.Length == 2)
{
Console.WriteLine("Max Motor =" + temp_Array[1]);
Max_Motor_Flag = true;
}
}
else if (Array[x].Contains("Motor RPM") && Motor_RPM_Flag == false)
{
temp_Array = Array[x].Split('=');
if (temp_Array.Length == 2)
{
Console.WriteLine("Motor RPM =" + temp_Array[1]);
Motor_RPM_Flag = true;
}
}
else if (Array[x].Contains("Sn") && SN_Flag == false)
{
temp_Array = Array[x].Split('n');
if (temp_Array.Length == 2)
{
Console.WriteLine("Sn" + temp_Array[1]);
SN_Flag = true;
}
}
else if (Array[x].Contains("SMC") && SMC_Type_Flag == false)
{
temp_Array = Array[x].Split('M');
if (temp_Array.Length == 2)
{
Console.WriteLine("SM" + temp_Array[1]);
SMC_Type_Flag = true;
}
}
else if (Array[x].Contains("Array MPP") && Auto_MPPV_Flag == false)
{
Console.WriteLine("Auto MPPT");
Auto_MPPV_Flag = true;
}
}
Thread.Sleep(6000);
} //end try
catch (Exception e)
{
Console.WriteLine(e.Message);
} //end catch
i++;
if (i == 12)
{
Thread.Sleep(num2);
Array_Volt_Flag = false;
Array_Amps_Flag = false;
Auto_MPPT_Flag = false;
Motor_Volt_Flag = false;
Motor_Amps_Flag = false;
Max_Motor_Flag = false;
Motor_RPM_Flag = false;
Auto_MPPV_Flag = false;
SN_Flag = false;
SMC_Type_Flag = false;
i = 0;
}
}//end while
}
}
}

Wait 20 Seconds In Timer Before Executing Next Line Without Thread.Sleep.C#

I'm trying to wait for 20 seconds before adding + 1 value to i (Int), But i want to do it without Thread.Sleep.
This is my code, By the way I'm not a Pro programmer.
private void Refresh_App_TimerNH_Tick(object sender, EventArgs e)
{
label18.Text = "Timer Activated";
int i = 0;
i = i + 1;
if (i == 16)
{
i = 0;
}
else
{
}
if (i == 1)
{
webBrowser1.Refresh();
userIdLabel1.BackColor = Color.Red;
label20.Text = "+1";
//**i want to add 20 second gap here**
i = i + 1;
}
else
{
}
if (i == 2)
{
webBrowser2.Refresh();
userIdLabel2.BackColor = Color.Red;
label20.Text = "+2";
i = i + 1;
}
else
{
}
if (i == 3)
{
webBrowser3.Refresh();
userIdLabel3.BackColor = Color.Red;
label20.Text = "+3";
i = i + 1;
}
else
{
}
if (i == 4)
{
webBrowser4.Refresh();
userIdLabel4.BackColor = Color.Red;
label20.Text = "+4";
i = i + 1;
}
else
{
}
if (i == 5)
{
webBrowser5.Refresh();
userIdLabel5.BackColor = Color.Red;
label20.Text = "+5";
i = i + 1;
}
else
{
}
if (i == 6)
{
webBrowser6.Refresh();
userIdLabel6.BackColor = Color.Red;
label20.Text = "+6";
i = i + 1;
}
else
{
}
if (i == 7)
{
webBrowser7.Refresh();
userIdLabel7.BackColor = Color.Red;
label20.Text = "+7";
i = i + 1;
}
else
{
}
if (i == 8)
{
webBrowser8.Refresh();
userIdLabel8.BackColor = Color.Red;
label20.Text = "+8";
i = i + 1;
}
else
{
}
if (i == 9)
{
webBrowser9.Refresh();
userIdLabel9.BackColor = Color.Red;
label20.Text = "+9";
i = i + 1;
}
else
{
}
if (i == 10)
{
webBrowser10.Refresh();
userIdLabel10.BackColor = Color.Red;
label20.Text = "+10";
i = i + 1;
}
else
{
}
if (i == 11)
{
webBrowser11.Refresh();
userIdLabel11.BackColor = Color.Red;
label20.Text = "+11";
i = i + 1;
}
else
{
}
if (i == 12)
{
webBrowser12.Refresh();
userIdLabel12.BackColor = Color.Red;
label20.Text = "+12";
i = i + 1;
}
else
{
}
if (i == 13)
{
webBrowser13.Refresh();
userIdLabel13.BackColor = Color.Red;
label20.Text = "+13";
i = i + 1;
}
else
{
}
if (i == 14)
{
webBrowser14.Refresh();
userIdLabel14.BackColor = Color.Red;
label20.Text = "+14";
i = i + 1;
}
else
{
}
if (i == 15)
{
webBrowser15.Refresh();
userIdLabel15.BackColor = Color.Red;
label20.Text = "+15";
i = i + 1;
}
else
{
}
if (i == 16)
{
webBrowser16.Refresh();
userIdLabel16.BackColor = Color.Red;
label20.Text = "+16";
i = i + 1;
}
else
{
}
Refresh_App_TimerNH.Stop();
label18.Text = "Timer De-Activated";
Refresh_App_TimerNH.Start();
}
I think it might be easy but not for me, Because i'm new to c#
First off, Tim S's answer -- break up your logic into smaller chunks and simplify the timer logic -- is good. But to answer your specific question, which was "how do I delay between statements without Sleep", is: make the method async and then use await Task.Delay(...).
You are right to avoid Sleep; using it is a bad programming practice, and will hang your application. await Task.Delay does an asynchronous wait -- that is, the method returns immediately, the app keeps on processing UI messages, and when the delay is done, the program schedules the remainder of the method to execute later.
Note that during an asynchronous wait, by design messages keep on getting processed. If one of those messages causes your event handler to run again then you can get into the very confusing situation of having multiple control points in the same non-recursive method. Try to avoid that.
Right now your logic is convoluted, and probably very different from what you want it to do.
Your code will be much simpler if you put your webBrowserX and userIdLabelX items in some sort of list together.
public class MyPair
{
public WebBrowser WebBrowser { get; set; }
public Label UserIdLabel { get; set; }
}
private List<MyPair> pairs;
private int refreshIndex = 0;
private void StartTimer()
{
pairs = // populate pairs somehow
refreshIndex = 0;
var timer = new System.Windows.Forms.Timer();
timer.Interval = 20000
timer.Tick += MyTickHandler;
timer.Start();
label18.Text = "Timer Activated";
}
private void MyTickHandler(object sender, EventArgs e)
{
pairs[refreshIndex].WebBrowser.Refresh();
pairs[refreshIndex].UserIdLabel.BackColor = Color.Red;
label20.Text = "+" + (refreshIndex + 1);
refreshIndex = (refreshIndex + 1) % pairs.Count;
}
Note that this timer never deactivates, it loops through the list of pairs repeatedly.

C# program with COM port going NOT RESPONDING

I have C#/.NET program which uses a COM port and SQL CE Database with a WCF service. Sometimes the program becomes unresponsive (the window freezes) and even in debug mode I cannot the reason.
I can restart the program after restarting my PC or the COM port. The problem isn't with my COM port problem because I have tried it on many PCs and all have the same problem.
How could I resolve this?
private void timer_Tick(object sender, EventArgs e)
{
try
{
labeltimer.Text = DateTime.Now.ToString();
if (timerstarted == true)
{
return;
}
timerstarted = true;
_CARDCODE = 0;
string error = "";
bool hasbassed = false;
if (this._Close == true)
{
this.Close();
}
if (serialPort1.IsOpen)
{
if (i < 8)
{
i++;
}
else
{
i = 0;
}
to[0] = (byte)(128 + i);
try
{
serialPort1.Write(to, 0, 1);
}
catch (System.Exception ex)
{
ListViewItem Lvi = new ListViewItem((++rowcount).ToString());
Lvi.SubItems.Add("");
Lvi.SubItems.Add("");
Lvi.SubItems.Add("Disconnected");
Lvi.SubItems.Add("");
listView.Items.Add(Lvi);
StartPort();
}
if (progressBar.Value >= 1500)
progressBar.Value = 0;
else
progressBar.Value += 10;
if (serialPort1.BytesToRead != 0)
{
byte[] data = new byte[serialPort1.BytesToRead];
from = new byte[3];
try
{
serialPort1.Read(data, 0, data.Length);
}
catch (System.Exception ex)
{
ListViewItem LVi = new ListViewItem((++rowcount).ToString());
LVi.SubItems.Add("");
LVi.SubItems.Add("");
LVi.SubItems.Add("Disconnected");
LVi.SubItems.Add("");
listView.Items.Add(LVi);
StartPort();
}
// data.Length == 4 by Button or HassPassed
if (data.Length == 4)
{
if (data[1] > 2)
DBS.AddButtonPass(data[0], data[1] / 4);
else
{
DBS.EditPass((int)data[0]);
timerstarted = false;
return;
}
}
else if ((data[data.Length - 1] != 255) || (data.Length < 4))
{
from[0] = data[0];
from[1] = 0;
from[2] = 0;
serialPort1.Write(from, 0, 3);
timerstarted = false;
return;
}
//RegistoringSubscriber_ID Add Subscriber Card
else if ((RegistoringSubscriber_ID > 0) && (RegisterCheckpoint != 0) && (data[0] == RegisterCheckpoint))
{
Registoring = false;
if (RegistorNewCard(Convert.ToInt32(data[2].ToString() + data[3].ToString() + data[4].ToString())) > 0)
FormBringPC.AnswerType = 1;
else
FormBringPC.AnswerType = 2;
RegistoringSubscriber_ID = 0;
error = "register card";
}
// RegistoringSubscriber_ID < 0 Add Bonus Card
else if ((RegistoringSubscriber_ID < 0) && (RegisterCheckpoint != 0) && (data[0] == RegisterCheckpoint))
{
Registoring = false;
if (RegistorBonusCard(Convert.ToInt32(data[2].ToString() + data[3].ToString() + data[4].ToString())) > 0)
FormBringPC.AnswerType = 1;
else
FormBringPC.AnswerType = 2;
RegistoringSubscriber_ID = 0;
error = "register Bonus card";
}
else if ((List_Checkpoint_ID.Contains(data[0]) && ((data[1] == 130) || (data[1] == 129))))
{
// DBS.EditPass((int)data[0]);
}
else if ((List_Checkpoint_ID.Contains(data[0]) && (data.Length == 7)))
{
_CARDCODE = Convert.ToInt32(data[2].ToString() + data[3].ToString() + data[4].ToString());
GlobalTypes.InvalidPass pass = DBS.CheckPassStatus(_CARDCODE, (int)data[0], (int)data[1]);
if (pass == GlobalTypes.InvalidPass.Valid)
{
from[0] = data[0];
from[1] = 1;
from[2] = 1;
serialPort1.Write(from, 0, 3);
LBTitle.Text = DateTime.Now.ToLongTimeString();
hasbassed = true;
}
else
{
from[0] = data[0];
from[1] = 0;
from[2] = 0;
serialPort1.Write(from, 0, 3);
switch (pass)
{
case GlobalTypes.InvalidPass.InvalidCard:
{
error = "Չգրանցված քարտ";
break;
}
case GlobalTypes.InvalidPass.InvalidCount:
{
error = "Այց. քանակ";
break;
}
case GlobalTypes.InvalidPass.InvalidGraphic:
{
error = "Ժամանակ hh:mm:ss";
break;
}
case GlobalTypes.InvalidPass.InvalidPeriod:
{
error = "Ժամանակահատված xxxx.dd.yyy";
break;
}
case GlobalTypes.InvalidPass.InvalidStatus:
{
error = "Հառացված աբոնենտ";
break;
}
case GlobalTypes.InvalidPass.InvalidSuscribe:
{
error = "Անհայտ բաժանորդ";
break;
}
default:
{
error = "esim inch";
break;
}
}
}
}
else if ((List_Checkpoint_ID.Contains(data[0]) && (data.Length > 0)))
{
try
{
byte[] ticket = new byte[data.Length - 6];
for (int ii = 0; ii < data.Length - 6; ii++)
{
ticket[ii] = data[ii + 2];
}
_CARDCODE = Convert.ToInt32(Encoding.ASCII.GetString(ticket.ToArray()));
GlobalTypes.HasPass pass = DBS.CheckTicketPassStatus(_CARDCODE, (int)data[0], (int)data[1]);
if (pass == GlobalTypes.HasPass.TruePass)
{
from[0] = data[0];
from[1] = 1;
from[2] = 1;
serialPort1.Write(from, 0, 3);
LBTitle.Text = DateTime.Now.ToLongTimeString();
hasbassed = true;
}
else
{
from[0] = data[0];
from[1] = 0;
from[2] = 0;
serialPort1.Write(from, 0, 3);
switch (pass)
{
case GlobalTypes.HasPass.CardNotFound:
{
error = "Not registored ticket";
break;
}
case GlobalTypes.HasPass.CardRepeat:
{
error = "ReEntring";
break;
}
case GlobalTypes.HasPass.ValidationPeriodError:
{
error = "Ժամանակ hh:mm:ss";
break;
}
case GlobalTypes.HasPass.SeasonError:
{
error = "Ժամանակահատված xxxx.dd.yyy";
break;
}
case GlobalTypes.HasPass.WeekOfDayError:
{
error = "Day of Weak";
break;
}
default:
{
error = "esim inch";
break;
}
}
}
}
catch { timerstarted = false; return; }
}
if (rowcount >= 10)
{
rowcount = 0;
listView.Items.Clear();
}
ListViewItem lvi = new ListViewItem((++rowcount).ToString());
lvi.SubItems.Add(data[0].ToString());
if (data.Length == 4)
hasbassed = true;
if (((data[1] == 2) || (data[1] == 8)) && ((data.Length == 4) || (Dictionary_Chekpoint[data[0]].CheckPointType == 2)))
{
lvi.SubItems.Add("Ելք");
}
else
{
lvi.SubItems.Add("Մուտք");
}
if (data.Length != 4)
lvi.SubItems.Add(_CARDCODE.ToString());
else
lvi.SubItems.Add("Հերթապահ");
lvi.SubItems.Add(error);
if (hasbassed == true)
{
lvi.BackColor = Color.LightGreen;
}
else
{
lvi.BackColor = Color.LightPink;
}
listView.Items.Add(lvi);
}
}
else MessageBox.Show("Serial port is closed!", "RS232 tester", MessageBoxButtons.OK, MessageBoxIcon.Error);
timerstarted = false;
}
catch
{
timerstarted = false;
return;
}
}
C# programs show as NOT RESPONDING whenever there is processing happening in the main UI thread that is preventing UI processing. The general answer here is to push that work into a different thread, so that UI events can continue to process (see references below for more information). In the case of serial ports, the easiest thing to do is hook the SerialPort.DataReceived event instead of polling it: https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived%28v=vs.110%29.aspx
Ref:
GUI not responding while fetching data
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
https://msdn.microsoft.com/en-us/library/windows/desktop/dd744765%28v=vs.85%29.aspx
http://www.dreamincode.net/forums/topic/246911-c%23-multi-threading-in-a-gui-environment/

Categories