Why looping twice on string length test - c#

I'm working in C# (2013) Windows Forms. My instructor wanted us to ensure that the txtStateInput is upperCase when we hit the calculate button. However when I input a two character string such as "wi" and then hit calculate, it throws the message "enter valid state" and clears out the textbox. When I enter the "wi" in a second time then it works. I can't figure out why this is happening, the code would lead me to believe that it would check to ensure the string in txtStateInput is two characters and then when calculate is clicked it would uppercase the string. I can't figure out why it only works once I enter in the state "wi" a second time.
private void btnCalc_Click(object sender, EventArgs e)
{
//declare variables.
int startPop = 0;
int endPop = 0;
string Message = "Error";
decimal Percent = 0.0m;
string State = "";
string City = String.Empty;
int dTimes = 0;
try
{
City = txtCityInput.Text;
//System Globalization was initialized so this method works.
TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
txtCityInput.Text = myTI.ToTitleCase(City);
if(txtStateInput.Text.Length != 2)
{
MessageBox.Show("Enter valid State");
txtStateInput.Focus();
txtStateInput.SelectAll();
}
else
{
State = txtStateInput.Text.ToUpper();
txtStateInput.Text = State;
if ((int.TryParse(txtStartPopInput.Text, out startPop)) && int.TryParse(txtEndPopInput.Text, out endPop))
{
if ((startPop > 0) && (endPop > 0))
{
//if population has decreased.
if ((startPop > endPop))
{
Percent = ((decimal.Parse(endPop.ToString()) - decimal.Parse(startPop.ToString())) / decimal.Parse(startPop.ToString()));
Message = "Pop. Decrease of " + Percent.ToString("p");
}
//if population has increased.
if ((startPop < endPop))
{
Percent = ((decimal.Parse(endPop.ToString()) - decimal.Parse(startPop.ToString())) / decimal.Parse(startPop.ToString()));
Message = "Pop. Increase of " + Percent.ToString("p");
}
//if population has not changed.
if ((startPop == endPop))
{
Percent = ((decimal.Parse(endPop.ToString()) - decimal.Parse(startPop.ToString())) / decimal.Parse(startPop.ToString()));
Message = "No Change in Population";
}
}
else
{
MessageBox.Show("Please enter valid population figures.");
}
}
if (int.TryParse(txtDisplayTimes.Text, out dTimes))
{
if (dTimes > 0)
{
lstResults.Items.Clear();
int iSum = 0;
int iLoopCount = dTimes;
//displays the results according to value in txtDisplayTimes.
for (iSum = 1; iSum <= iLoopCount; iSum++)
{
lstResults.Items.Add(Message);
}
}
}
}
}
catch
{
MessageBox.Show("Something went wrong.");
}
}

Related

C# it shows null in Console for an else condition, instead of what I want it to display

So I have this code that will calculate the arithmetic mean. The user has to introduce random numbers, and when the input is "x" the code will stop and calculate the arithmetic mean. The code works fine if I introduce any numbers. However, if the first input is "x" I have to display "0". In the console, I get null ("") instead of 0.
The problem is the 'else' condition, the rest of the code works as expected. I tried to write the condition in different ways and even to put it in another block because I thought it is unreachable, but it is still null. I am not sure what I am missing.
Thank you in advance!
string line = Console.ReadLine();
double sum = 0;
double count = 0;
while (line != "x")
{
double number = Convert.ToInt32(line);
sum += number;
count++;
line = Console.ReadLine();
if (line == "x")
{
if (count > 0)
{
double ma = sum / count;
Console.WriteLine((float)ma);
}
else {
Console.WriteLine(0);
}
}
}
This worked for me. It wasn't clear what to do if user enters something other than 'x' or a number, so I put some error handling which ensures the app doesn't crash. I added a flag to detect if at least one valid number has been entered.
static void Main(string[] args)
{
string line = Console.ReadLine();
double sum = 0;
double count = 0;
bool numberHasBeenEntered = false;
while (line != "x")
{
double number;
//some error handling in case user enters something other than x or a number
try
{
number = Convert.ToInt32(line);
numberHasBeenEntered = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
break;
}
sum += number;
count++;
line = Console.ReadLine();
if (line == "x")
{
if (count > 0)
{
double ma = sum / count;
Console.WriteLine((float)ma);
}
else
{
Console.WriteLine(0);
}
}
}
if (numberHasBeenEntered == false) Console.WriteLine(0);
}
If your first line is "X" then the code inside the while loop is not executed at all.
Use a do While loop
string line = Console.ReadLine();
double sum = 0;
double count = 0;
double number;
double ma;
do
{
if (line == "x")
{
if (count > 0)
{
line = Console.ReadLine();
ma = sum / count;
Console.WriteLine((float)ma);
}
else {
Console.WriteLine("0");
}
}
else
{
number = Convert.ToInt32(line);
sum += number;
count++;
}
}
while(line != "x")

Enter button does not work at textbox

I'm a beginner in c# and first time need your help, because I can't find any solution to this problem.
I make a typewriting tutorial, I have a richtextbox filled with randomly generated characters, spaces and 3 new line.
The user must type the characters in a textbox, and if he typed the adequate character the character turn to green in richtextbox and he can type the the next one. If he makes a mistake, he cant move to next character until the the right button was pressed.
My problem is everything works, except new line part.
When the program compare the 2 new line accept the new line but just when ctrl+enter was pressed, simple enter wont work, the program somehow thinks enter is a wrong character.
I need to make this user friendly and a simple enter needed for this.
I tried this so far:
Make textbox MultiLine makes no difference.
Changed Acceptsreturn to true makes no difference.
Changed in string that will be the text of richtextbox the Environment.Newline to \r and \n and \r\n and its makes no difference.
Changed the textbox to Richtextbox makes no difference.
I tried every possible combination above and I cant work out what is the problem.
Here it is the random character generating part:
public partial class Form1 : Form
{
char[] karakterek = { 'a','á','b','c','d','e','é','f','g','h','i','í','j','k','l','m','n','o','ó','ö','ő','p','q','r','s','t','u','ú','ü','ű','v','x','y','z' };
char[] nemkarakterek = {'0','1','2','3','4','5','6','7','8','9','"',',','+','%','/','=',':','-',};
char egykarakter;
string teljes = "";
int mutato = 0;
Random r = new Random();
public Form1()
{
InitializeComponent();
karakterfeltolt();
}
private void karakterfeltolt()
{
int hanyszor = 0;
do
{
string egesz = "";
if (hanyszor < 3)
{
do
{
if (egesz.Length < 150)
{
if (r.Next(1,15)<14)
{
egykarakter = karakterek[r.Next(0, karakterek.Length)];
egesz = egesz + egykarakter;
}
else
{
egykarakter = nemkarakterek[r.Next(0, nemkarakterek.Length)];
egesz = egesz + egykarakter;
}
}
} while (egesz.Length < 150);
if (egesz.Length > 150)
{
egesz = egesz.Substring(0, 150);
}
int vanespace = 0;
egesz = egesz.Insert(r.Next(2, 10), " ");
for (int i = 0; i < egesz.Length - 10; i++)
{
if (egesz[i] == ' ')
{
vanespace = i;
int eselynovelo = r.Next(0, 10);
if (eselynovelo > 6)
{
egesz = egesz.Insert(r.Next(vanespace + 3, vanespace + 10), " ");
}
else
{
egesz = egesz.Insert(r.Next(vanespace + 6, vanespace + 10), " ");
}
}
}
string nagybetus = egesz.Substring(0, 1).ToUpper() + egesz.Substring(1);
nagybetus = nagybetus.Insert(nagybetus.Length, ".\r\n");
teljes = teljes + nagybetus;
hanyszor++;
}
} while (hanyszor < 3);
richTextBox1.Text = teljes;
}
And here is the textbox compare part:
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == richTextBox1.Text[mutato])
{
richTextBox1.SelectionStart = 0;
richTextBox1.SelectionLength = mutato + 1;
richTextBox1.SelectionColor = Color.Green;
mutato++;
label2.Text = "OK";
}
else
{
label2.Text = "Wrong";
e.Handled = true;
}
}
What else can I do? Please help me.

Application running in ASP.NET is not giving the desired output

I have an application not calculating the percentage correctly. It is suppose to calculate the input in percent. But there is bug somewhere which is preventing it from doing so.
For example, if I input any number starting with decimals like 0.01 or 0.001 or 0.02 etc it will give me the output 1, 0.1 and 2 respectively. If I punch in any whole numbers like 1, 2, 3, 10, etc, it will always give the same output i.e 0.01.
This application was done by some contractors 5 years ago. The main in-charge of this application has left. Which leaves me and my little experience in c# and asp.net in figuring out the issue. Before I seek any further help, I thought I should ask geniuses out there and see what they have to say, may be I will end up figuring out the issue with your help. I did talk to other IT people in my department, they guess it might be because of the code below.
if (int.TryParse(string.IsNullOrEmpty(txtminup.Text) ? "0" : txtminup.Text, out n))
I am not 100% sure how to debug or find the issue. If anyone can point me out anything that might help or provide me some resources that I can look it up, it will be really helpful. I have copied few of the lines of code. I can provide more information but don't know which one will be more relevant.
protected string MinUp
{
get
{
return (string)ViewState["minup"];
}
set
{
ViewState["minup"] = value;
}
}
==============
MinUp = rows["process_minimum_up"].ToString();
PIMSSource = rows["pims_source"].ToString();
//MinUp = Convert.ToDouble()
if (MinUp != string.Empty || MinUp.Length > 0)
{
MinUp = Convert.ToString(Convert.ToDouble(MinUp) * 100);
}
=====================
if (DCFoption != "P")
{
MinUp = "";
}
if (DcfmSeq != "0")
{
int caret;
caret = ddlvbcfmseq.SelectedValue.IndexOf("^");
DcfmSeq = DcfmSeq.Substring(0, caret);
}
if (DCFoption != "P" && ddlpdwnlst.SelectedItem.Value == "0")
{
MinUp = "";
}
if (PIMSTagId == "Not specified")
{
PIMSTagId = "";
}
if (MinUp != string.Empty || MinUp.Length > 0)
{
int n;
if (int.TryParse(string.IsNullOrEmpty(txtminup.Text) ? "0" : txtminup.Text, out n))
{
MinUp = Convert.ToString(Convert.ToInt32(MinUp) / 100);
if (Convert.ToInt32(MinUp) < 0)
{
MinUp = "0";
}
else if (Convert.ToInt32(MinUp) > 1)
{
MinUp = "1";
}
}
}
if ((DCFoption == string.Empty || DCFoption.Length < 1) || DCFoption == "D")
{
MinUp = "";
}
if (MinUp != string.Empty || MinUp.Length > 0)
{
int n;
if (int.TryParse(string.IsNullOrEmpty(txtminup.Text) ? "0" : txtminup.Text, out n))
{
if (Convert.ToDouble(MinUp) <= 0)
{
MinUp = ".0001";
}
}
}
=======================
if (rdbProcess.Checked == true && (txtminup.Text == string.Empty || txtminup.Text.Length < 1) && ddlpdwnlst.SelectedItem.Value == "0")
{
Utilities.ShowAlert(this.Page, Resources.Resource.RIPimsUpload_MinUptime.ToString());
txtminup.Focus();
======================
int n;
if (!int.TryParse(string.IsNullOrEmpty(txtRound.Text) ? "0" : txtRound.Text, out n))
{
Utilities.ShowAlert(this.Page, Resources.Resource.RIPimsUpload_RoundingNum.ToString());
}
else if (!IsDouble(txtminup.Text))
======================
try
{
DBResults objDBResult = new DBResults();
WEIS.RIPimsUpload objRI = new WEIS.RIPimsUpload();
objDBResult = objRI.SaveItemInsert(reciseq, shortname, name, eiscprocess2, period, media, euseq, eqmtseq, eiscuom, pollseq, dcfmseq, rounding, formula, physmin, physmax, warn1min, warn1max, warn2min, warn2max, pimsStatus, pimsTagidp, datapoint, freq, periodoffset, initpimstTagId, initDataPoint, initLoadFrequency, initperiodoffset, day0result, retention, audituser, dcfoption, minup, pimssource);
if (objDBResult.oraErrMsg.Trim().ToString().Length > 1)
{
Exception ex = new Exception(objDBResult.oraErrMsg.ToString());
throw ex;
}
return objDBResult.oraIntReturn;
}
===============================
protected int SaveItemUpdate(int reciseq, string shortname, string name, int eiscprocess2, int period, int media, int euseq, int eqmtseq, int eiscuom, int pollseq, int dcfmseq, string rounding, string formula, string physmin, string physmax, string warn1min, string warn1max, string warn2min, string warn2max, string pimsStatus, string pimsTagidp, string datapoint, string freq, char periodoffset, string initpimstTagId, char initDataPoint, char initLoadFrequency, char initperiodoffset, string day0result, string retention, string audituser, string dcfoption, string minup, string pimssource)
{
try
{
DBResults objDBResult = new DBResults();
WEIS.RIPimsUpload objRI = new WEIS.RIPimsUpload();
objDBResult = objRI.SaveItemUpdate(reciseq, shortname, name, eiscprocess2, period, media, euseq, eqmtseq, eiscuom, pollseq, dcfmseq, rounding, formula, physmin, physmax, warn1min, warn1max, warn2min, warn2max, pimsStatus, pimsTagidp, datapoint, freq, periodoffset, initpimstTagId, initDataPoint, initLoadFrequency, initperiodoffset, day0result, retention, audituser, dcfoption, minup, pimssource);
if (objDBResult.oraErrMsg.Trim().ToString().Length > 1)
{
Exception ex = new Exception(objDBResult.oraErrMsg.ToString());
throw ex;
}
=============================
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
lblUserMsgText.Text = "";
bool dcfm = ddlvbcfmseq.Enabled;
string minup, dcfoption="";
minup = txtminup.Text;
if (rdbNone.Checked == true)
{
dcfoption = "NONE";
}
else if (rdbProcess.Checked == true)
{
dcfoption = "P";
}
else if (rdbData.Checked == true)
{
dcfoption = "D";
}
Index = Convert.ToInt32(rdbListradios.SelectedIndex);
SaveItem();
RetainClientControlValues(dcfm, dcfoption, minup);
}
==============================
protected void btnExcMod_Click(object sender, EventArgs e)
{
try
{
lblUserMsgText.Text = "";
bool dcfm = ddlvbcfmseq.Enabled;
string minup, dcfoption = "";
Index = Convert.ToInt32(rdbListradios.SelectedIndex);
minup = txtminup.Text;
if (rdbNone.Checked == true)
{
dcfoption = "NONE";
}
else if (rdbProcess.Checked == true)
{
dcfoption = "P";
}
else if (rdbData.Checked == true)
{
dcfoption = "D";
}
Button btn = (Button)sender;
int evntseq = Convert.ToInt32(btn.CommandArgument.ToString());
RetainClientControlValues(dcfm, dcfoption, minup);
//Response.Write("you clicked on button");
}
#Umamaheswaran thanks for the hint.
int n;
if (int.TryParse(string.IsNullOrEmpty(txtminup.Text) ? "0" : txtminup.Text, out n))
Above was the initial code and i changed it to
double n;
if (double.TryParse(string.IsNullOrEmpty(txtminup.Text) ? "0" : txtminup.Text, out n))
and also whereever it was converting to
Convert.ToInt32
I changed it to
Convert.ToDouble
I don't know whatever was the issue as I am not very much familiar with asp.net and c# but changing above code solved the issue. Now whenever I input a number it will change to percentage and save it to correct format.
Thank you all for your help and concern. I have few more different issues. I will try to solve it if not I will post it here and try to be concise and to the point.

Broken C# else if returning error page

I am trying to work with if else statements for different things. I need one that pulls the value of a dropdown list to determine what the calculation will be, another that pulls the value of a check box and assigns a calculation, another for input validation for if the number exceeds 32, and the last to give me a value determined by the amount (up to 32) entered into the textbox. I think i've gotten the checkbox statement corrected (guideFee), and the input validation and the one that goes with it seem to be correct already, but I am having trouble assigning the constant decimal values to the dropdown list values and I don't understand why. I have the basetourRate = Convert.ToDecimal(riverTour) and the if statement that follows, but when I run the program I get an error page. I have pasted the whole code. If anyone could help me out i'd greatly appreciate it, thank you!
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void butCalculate_Click(object sender, EventArgs e )
{
//1. Declare Variables
decimal totalBaseTourFee;
decimal totalGuideFee;
decimal totalWeekendSurcharge;
decimal subtotal;
decimal salesTaxCharge;
decimal totalCharge;
decimal baseTourRate;
decimal guideFee = 0m;
bool isGuidedTour;
int numberOfRafters;
int numberOfRaftsNeeded;
string riverTour;
string timeOfWeek;
string displayTotalBaseTourFee;
string displayNumberOfRaftsNeeded;
string displayTotalGuideFee;
string displayTotalWeekendSurcharge;
string displaySubtotal;
string displaySalesTaxCharge;
string displayTotalCharge;
const decimal FRENCH_BROAD = 40m;
const decimal NANTAHALA = 30m;
const decimal TUCK = 20m;
const decimal WEEKEND_SURCHARGE = 10M;
const decimal GUIDE_FEE = 35M;
const decimal SALES_TAX_RATE = .07M;
//2. Get Values
numberOfRafters = Convert.ToInt32(txtNumberOfRafters.Text);
riverTour = ddlTour.SelectedValue;
isGuidedTour = chkGuided.Checked;
timeOfWeek = rblDay.SelectedValue;
Trace.Warn("numberOfRafters = " + numberOfRafters);
Trace.Warn(("isGuidedTour = " + isGuidedTour));
Trace.Warn("riverTour = " + riverTour);
Trace.Warn("timeOfWeek = " + timeOfWeek);
//Input Validation
if (numberOfRafters > 32)
{
Console.WriteLine("Sorry, we can't handle this large of a group!");
return;
}
//3. Do Calculations
baseTourRate = Convert.ToDecimal(riverTour);
if (riverTour == "FB")
{
baseTourRate = FRENCH_BROAD;
}
else if (riverTour == "NH")
{
baseTourRate = NANTAHALA;
}
else if (riverTour == "TK")
{
baseTourRate = TUCK;
}
if (isGuidedTour == true)
{
guideFee = GUIDE_FEE;
}
else if (!isGuidedTour == false)
{
guideFee = 0;
}
totalBaseTourFee = numberOfRafters * baseTourRate;
numberOfRaftsNeeded = numberOfRafters;
if (numberOfRafters <= 8)
{
numberOfRaftsNeeded = 1;
}
else if (numberOfRafters <= 16)
{
numberOfRaftsNeeded = 3;
}
else if (numberOfRafters <= 24)
{
numberOfRaftsNeeded = 3;
}
else if (numberOfRafters <=32)
{
numberOfRaftsNeeded = 4;
}
totalGuideFee = numberOfRaftsNeeded * guideFee;
totalWeekendSurcharge = numberOfRafters * WEEKEND_SURCHARGE;
subtotal = totalBaseTourFee + totalGuideFee + totalWeekendSurcharge;
salesTaxCharge = subtotal * SALES_TAX_RATE;
totalCharge = subtotal + salesTaxCharge;
//4. Display Results
displayTotalBaseTourFee = totalBaseTourFee.ToString("C") + "<br>";
displayNumberOfRaftsNeeded = numberOfRaftsNeeded.ToString("C") + "<br>";
displayTotalGuideFee = totalGuideFee.ToString("C") + "<br>";
displayTotalWeekendSurcharge = totalWeekendSurcharge.ToString("C") + "<br>";
displaySubtotal = subtotal.ToString("C") + "<br>";
displaySalesTaxCharge = salesTaxCharge.ToString("C") + "<br>";
displayTotalCharge = totalCharge.ToString("C") + "<br>";
lblTotalBaseTourFee.Text = displayTotalBaseTourFee;
lblNumberOfRafts.Text = displayNumberOfRaftsNeeded;
lblTotalGuideFee.Text = displayTotalGuideFee;
lblTotalWeekendSurcharge.Text = displayTotalWeekendSurcharge;
lblSubtotal.Text = displaySubtotal;
lblSalesTaxCharge.Text = displaySalesTaxCharge;
lblTotalCharge.Text = displayTotalCharge;
}
protected void butClear_Click(object sender, EventArgs e)
{
//Clear TextBox and Label
txtNumberOfRafters.Text = "";
lblTotalBaseTourFee.Text = "";
lblNumberOfRafts.Text = "";
lblTotalGuideFee.Text = "";
lblTotalWeekendSurcharge.Text = "";
lblSubtotal.Text = "";
lblSalesTaxCharge.Text = "";
lblTotalCharge.Text = "";
ddlTour.SelectedIndex = -1;
rblDay.SelectedIndex = -1;
chkGuided.Checked = false;
//Set focus back to name textbox
txtNumberOfRafters.Focus();
}
}
The one thing that sticks out to me is the Convert.ToDecimal(...) call.
baseTourRate = Convert.ToDecimal(riverTour);
if (riverTour == "FB")
{
baseTourRate = FRENCH_BROAD;
}
else if (riverTour == "NH")
{
baseTourRate = NANTAHALA;
}
else if (riverTour == "TK")
{
baseTourRate = TUCK;
}
You are attempting to convert a string to a decimal but then you are comparing that string to a string. My guess is that riverTour is not really a decimal and therefore you are getting an exception. Basically, the logic does not make sense. Convert.ToDecimal will throw an exception if it is not a valid decimal. Therefore, riverTour cannot contain a convertible value to decimal and a comparable value to FB/NH/TK. What exactly are you trying to accomplish? If you are trying to convert to decimal if it is valid and then check those 3 cases if it is not then you should look into decimal.TryParse(string, out decimal) https://msdn.microsoft.com/en-us/library/9zbda557(v=vs.110).aspx. This might help you achieve what you are trying to do.
If the input is always numeric, then you should consider using NumericUpDown. Or, at the very least, use TryParse methods so you can tell if the input is valid or invalid.
numberOfRafters = Convert.ToInt32(txtNumberOfRafters.Text);
Is also unsafe.

Thread with while (true) loop exits somehow

I have a thread that is supposed to run continuously in my program and parse incoming serial data from a collection of sensors.
//initialized as a global variable
System.Threading.Thread processThread = new System.Threading.Thread(ProcessSerialData);
//this gets called when you press the start button
processThread.Start();
private void ProcessSerialData()
{
while (true)
{
//do a whole bunch of parsing stuff
}
int howDidYouGetHere = 0;
}
How is it possible that my program is reaching the "int howDidYouGetHere = 0" line??
Full code can be found here:
/// <summary>
/// ProcessSerialData thread will be used to continue testing the connection to the controller,
/// process messages in the incoming message queue (actually a linked list),
/// and sends new messages for updated data.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ProcessSerialData()
{
while (true)
{
UpdateAhTextbox(test.ampHoursOut.ToString());
if (!relayBoard.OpenConn())
{
MessageBox.Show("Connection to controller has been lost.");
testInterrupted = "Lost connection. Time = " + test.duration;
UpdateStatusText(false);
ShutErDown();
}
/////////////////////////////////////////////////////
if (incomingData.Count > 0)
{
string dataLine = "";
try
{
dataLine = incomingData.First();
UpdateParsedDataTextbox(dataLine + "\r\n");
}
catch (System.InvalidOperationException emai)
{
break; //data hasn't come in yet, it will by the time this runs next.
}
incomingData.RemoveFirst();
if (dataLine.Contains("GET")) // some sensor values (analog/temp/digital) has come in
{
if (dataLine.Contains("GETANALOG")) // an analog value has come in
{
int index = dataLine.IndexOf("CH");
int pin = (int)Char.GetNumericValue(dataLine[index + 2]);
double value = 0;
int dataLineLength = dataLine.Length;
if (dataLineLength > 13) // value is appended to end of line
{
try
{
value = Convert.ToDouble(dataLine.Substring(13));
}
catch // can't convert to double
{
int index2 = dataLine.IndexOf("CH", 3);
if (index2 != -1) // there happen to be two sets of commands stuck together into one
{
string secondHalf = dataLine.Substring(index2);
incomingData.AddFirst(secondHalf);
}
}
}
else // value is on the next line
{
try
{
value = Convert.ToDouble(incomingData.First());
incomingData.RemoveFirst();
}
catch // can't convert to double
{
MessageBox.Show("Error occured: " + dataLine);
}
}
switch (pin)
{
case 1:
ReadVoltage(value);
break;
case 2:
ReadAmperage(value);
break;
}
}
else if (dataLine.Contains("GETTEMP")) // received reply with temperature data
{
int index = dataLine.IndexOf("CH");
int pin = (int)Char.GetNumericValue(dataLine[index + 2]); // using index of CH, retrieve which pin this message is coming from
double value = 0;
int dataLineLength = dataLine.Length;
if (dataLineLength > 11) // value is appended to end of line
{
try
{
value = Convert.ToDouble(dataLine.Substring(11));
}
catch // can't convert to double
{
int index2 = dataLine.IndexOf("CH", 3);
if (index2 != -1) // there happen to be two sets of commands stuck together into one
{
string secondHalf = dataLine.Substring(index2);
incomingData.AddFirst(secondHalf);
}
}
}
else // value is on the next line
{
value = Convert.ToDouble(incomingData.First());
incomingData.RemoveFirst();
}
ReadTemperature(pin, value);
}
else // must be CH3.GET
{
int index = dataLine.IndexOf("CH");
int pin = (int)Char.GetNumericValue(dataLine[index + 2]); // using index of CH, retrieve which pin this message is coming from
if (pin == 3) // only care if it's pin 3 (BMS), otherwise it's a mistake
{
double value = 0;
int dataLineLength = dataLine.Length;
if (dataLineLength > 7) // value is appended to end of line
{
try
{
value = Convert.ToDouble(dataLine.Substring(7));
}
catch // can't convert to double
{
int index2 = dataLine.IndexOf("CH", 3);
if (index2 != -1) // there happen to be two sets of commands stuck together into one
{
string secondHalf = dataLine.Substring(index2);
incomingData.AddFirst(secondHalf);
}
}
}
else // value is on the next line
{
value = Convert.ToDouble(incomingData.First());
incomingData.RemoveFirst();
}
ReadBMS(value);
}
}
}
else if (dataLine.Contains("REL")) // received reply about relay turning on or off.
{
if (dataLine.Contains("RELS")) // all relays turning on/off
{
if (dataLine.Contains("ON"))
{
for (int pin = 1; pin <= 4; pin++)
{
test.contactors[pin] = true;
}
}
else // "OFF"
{
for (int pin = 1; pin <= 4; pin++)
{
test.contactors[pin] = false;
}
}
}
else // single relay is turning on/off
{
int index = dataLine.IndexOf("REL");
int pin = (int)Char.GetNumericValue(dataLine[index + 3]);
if (dataLine.Contains("ON"))
{
test.contactors[pin] = true;
}
else if (dataLine.Contains("OFF"))
{
test.contactors[pin] = false;
}
else if (dataLine.Contains("GET"))
{
if (Convert.ToInt32(incomingData.First()) == 1)
test.contactors[pin] = true;
else
test.contactors[pin] = false;
incomingData.RemoveFirst();
}
}
}
}
/////////////////////////////////////////////////////
// we only want more data if we're done processing the current data, otherwise we're stuck with too much and processing is heavily delayed.
if (isTestRunning && incomingData.Count < 3)
{
//read & output v, a, bms state
sendToController("CH1.GETANALOG"); // get voltage
sendToController("CH2.GETANALOG"); // get amperage
sendToController("CH3.GET"); // get BMS state
//read & output temperature
sendToController("CH4.GETTEMP"); // get temperature
sendToController("CH5.GETTEMP");
string lines = "Ah Out: " + test.ampHoursOut + ", Voltage: " + test.voltage +
", Amperage: " + test.amperage + ", Cell Temperature: " + test.tempBattery +
", Load Temperature: " + test.tempLoad;
WriteToLog(lines);
}
}
int howDidYouGetHere = 0;
}
The break (ignoring those inside the nested switch) breaks out of the while loop.
Perhaps you have tried to update your UI using UpdateParsedDataTextbox This will cause InvalidOperationException(then breaks the while loop) because you tries to access the UI control from thread that doesn't own the control.

Categories