So my program works as it should. When I click the save button everything is saved to the database. However when I click the save button a second time it fails to work.Index was outside the bounds of the array. is the error in private void btnTest_click on line string Ullage = splitstring[2];
private void btnSave_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\2014-06-26 TEK687 Config Tool\TEK687 Config Tool\bin\Debug\Results.mdb");
string SqlString = "insert into Table1 (PassOrFail,DateTested,TekNum,BatchNum,WeekNum,Serial,FirmwareVer,HardwareVer,TestPC,SettingsTest,Deleted,Ullage,SRC,Vbatt,Tamb,Ullage2,SRC2,Vbatt2,Tamb2) Values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("PassOrFail", txtPassFail.Text);
cmd.Parameters.AddWithValue("DateTested", txtDateTested.Text);
cmd.Parameters.AddWithValue("TekNum", txtTekPartNo.Text);
cmd.Parameters.AddWithValue("BatchNum", txtBatchNumber.Text);
cmd.Parameters.AddWithValue("WeekNum", txtWeekYearNo.Text);
cmd.Parameters.AddWithValue("Serial", txtSerialNumber.Text);
cmd.Parameters.AddWithValue("FirmwareVer", txtFirmwareVer.Text);
cmd.Parameters.AddWithValue("HardwareVer", txtHardwareVer.Text);
cmd.Parameters.AddWithValue("TestPC", txtTestPC.Text);
cmd.Parameters.AddWithValue("SettingsTest", cboSettingsProfiles.SelectedIndex);
cmd.Parameters.AddWithValue("Deleted", txtDeleted.Text);
cmd.Parameters.AddWithValue("Ullage", txtUllage1.Text);
cmd.Parameters.AddWithValue("SRC", txtSRC1.Text);
cmd.Parameters.AddWithValue("Vbatt", txtVbatt1.Text);
cmd.Parameters.AddWithValue("Tamb", txtTamb1.Text);
cmd.Parameters.AddWithValue("Ullage2", txtUllage2.Text);
cmd.Parameters.AddWithValue("SRC2", txtSRC2.Text);
cmd.Parameters.AddWithValue("Vbatt2", txtVbatt2.Text);
cmd.Parameters.AddWithValue("Tamb2", txtTamb2.Text);
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored successfully");
}
ClearTextBoxes(this);
}
Here is the code to add values to database error is at string Ullage = splitstring[2];
private void btnTest_Click(object sender, EventArgs e)
{
Cancel = false;
if (DiscoverDevice(false) == false)
{
MessageBox.Show("Error, device is not responding");
return;
}
string servo = "";
MyModemSerialInterfaceLayer.WriteTextAndWaitForResponse("TL,S," + txtToolID.Text + ",30,\r\n", "\r\n", 4, ref servo, 500);
string test = "";
MyModemSerialInterfaceLayer.WriteTextAndWaitForResponse("TL,T," + txtToolID.Text + "\r\n", "\r\n", 4, ref test, 500);
string[] splitstring = test.Split(',');
**string Ullage = splitstring[2];**
string SRC = splitstring[3];
string RSSI = splitstring[4];
string AlarmStatus = splitstring[5];
string RateofChange = splitstring[6];
string Tamb = splitstring[7];
string Vbatt = splitstring[8];
Ullage = Ullage.Replace("u:", "");
Tamb = Tamb.Replace("t:", "");
Vbatt = Vbatt.Replace("v:", "");
int Ull = Convert.ToInt32(Ullage);
int src = Convert.ToInt32(SRC);
int BV = Convert.ToInt32(Vbatt);
int temp = Convert.ToInt32(Tamb);
StringBuilder sb = new StringBuilder();
sb.Append(Ull);
txtUllage1.Text += sb.ToString();
StringBuilder sc = new StringBuilder();
sc.Append(src);
txtSRC1.Text += sc.ToString();
StringBuilder sd = new StringBuilder();
sd.Append(BV);
txtVbatt1.Text += sd.ToString();
StringBuilder se = new StringBuilder();
se.Append(temp);
txtTamb1.Text += se.ToString();
StringBuilder sm = new StringBuilder();
if ((Ull < 11) || (Ull > 13) || (src < 9) || (BV < 29))
{
txtPassFail.Text += "12cm FAIL";
txtResultsReading.Font = new Font(txtResultsReading.Font, FontStyle.Bold);
StringBuilder th = new StringBuilder();
th.Append("12cm FAIL");
txtResultsReading.Text += th.ToString();
}
string servoTwo = "";
MyModemSerialInterfaceLayer.WriteTextAndWaitForResponse("TL,S," + txtToolID.Text + ",31,\r\n", "\r\n", 4, ref servoTwo, 500);
string tests = "";
MyModemSerialInterfaceLayer.WriteTextAndWaitForResponse("TL,T," + txtToolID.Text + "\r\n", "\r\n", 4, ref tests, 500);
string[] splitstrings = tests.Split(',');
string Ullage2 = splitstrings[2];
string SRC2 = splitstrings[3];
string RSSI2 = splitstrings[4];
string AlarmStatus2 = splitstrings[5];
string RateofChange2 = splitstrings[6];
string Tamb2 = splitstrings[7];
string Vbatt2 = splitstrings[8];
Ullage2 = Ullage2.Replace("u:", "");
Tamb2 = Tamb2.Replace("t:", "");
Vbatt2 = Vbatt2.Replace("v:", "");
int Ull2 = Convert.ToInt32(Ullage2);
int src2 = Convert.ToInt32(SRC2);
int BV2 = Convert.ToInt32(Vbatt2);
int temp2 = Convert.ToInt32(Tamb2);
StringBuilder sf = new StringBuilder();
sf.Append(Ull2);
txtUllage2.Text += sf.ToString();
StringBuilder sg = new StringBuilder();
sg.Append(src2);
txtSRC2.Text += sg.ToString();
StringBuilder sh = new StringBuilder();
sh.Append(BV2);
txtVbatt2.Text += sh.ToString();
StringBuilder si = new StringBuilder();
si.Append(temp2);
txtTamb2.Text += si.ToString();
txtDateTested.Text = DateTime.Now.ToString();
txtTestPC.Text = System.Environment.UserName;
//boSettingsProfiles.Text= Settings.SettingsFile;
txtDeleted.Text = "CURRENT";
if ((Ull < 11) || (Ull > 13) || (src < 9) || (BV < 29))
{
txtPassFail.Text += " 3M FAIL";
txtResultsReading.Font = new Font(txtResultsReading.Font, FontStyle.Bold);
StringBuilder tg = new StringBuilder();
tg.Append(Environment.NewLine);
tg.Append("3M FAIL");
txtResultsReading.Text += tg.ToString();
}
else if ((Ull >= 11) && (Ull <= 13) && (src == 9) && (BV >= 29) &&
(Ull2 >= 11) && (Ull2 <= 13) && (src2 == 9) && (BV2 >= 29))
{
txtPassFail.Text += "PASS";
txtResultsReading.Font = new Font(txtResultsReading.Font, FontStyle.Bold);
txtResultsReading.Text += "PASS";
}
ReleaseDevice();//release the config tool after config is completed
}
}
Your splitstrings object doesn't have three objects in it, therefore you can't access the object at index 2. Therefore, you should implement a check to make sure it contains an object at that index before accessing, then handle the case where it doesn't as appropriate.
By the way, next time you ask a question about why something doesn't work, it's absolutely critical that you tell us about the exception you're getting, rather than making us ask for it. And you need to include the code that throws the exception. See How to create a Minimal, Complete, and Verifiable example.
Inspect the variable coming out of the WriteTextAndWaitForResponse call. It probably doesn't have 3 commas.
Related
When I open a file (I made myself) I need to use somethings out of the string of text that comes trough. I want to use some parts of the text as coordinates to draw a graph with.
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
char XgetalEen;
char XgetalTwee;
char YgetalEen;
char Ygetaltwee;
string XgetalSamen = "";
string YgetalSamen = "";
int coordinaatX;
int coordinaatY;
DialogResult lel = MessageBox.Show("Do you want to close this file?", "OPEN", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (lel == DialogResult.Yes)
{
Open();
foreach(string s in Gcowde)
{
XgetalEen = s[5];
XgetalTwee = s[6];
YgetalEen = s[8];
Ygetaltwee = s[9];
XgetalSamen += XgetalEen + XgetalTwee;
YgetalSamen += YgetalEen + Ygetaltwee;
if(XgetalTwee==' ')
{
XgetalSamen = "";
XgetalTwee = '0';
XgetalSamen += XgetalTwee + XgetalEen;
YgetalEen = s[7];
Ygetaltwee = s[8];
YgetalSamen = "";
YgetalSamen += YgetalEen + Ygetaltwee;
}
if(Ygetaltwee==' ')
{
Ygetaltwee = '0';
YgetalSamen = "";
YgetalSamen += Ygetaltwee + YgetalEen;
}
MessageBox.Show(XgetalSamen + " " + YgetalSamen);
Int32.TryParse(XgetalSamen, out coordinaatX);
Int32.TryParse(YgetalSamen, out coordinaatY);
currentLocation.X += coordinaatX;
currentLocation.Y += coordinaatY;
Coord.Add(new Point(currentLocation.X, currentLocation.Y));
}
drawerryting();
}
}
public void Open()
{
Gcowde.Clear();
listBox1.Items.Clear();
Coord.Clear();
werkVlak.Clear(Color.Black);
Coord.Add(new Point(pictureBox1.Width / 2, pictureBox1.Height / 2));
drawerryting();
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(openFileDialog1.FileName);
string errything = sr.ReadToEnd();
string charAdded = "";
foreach (char s in errything)
{
if (s == '\n')
{
Gcowde.Add(charAdded);
charAdded = "";
}
else
{
charAdded += s;
}
}
foreach (string s in Gcowde)
{
listBox1.Items.Add(s);
}
sr.Close();
}
This is the code how I open the file and get the coordinates out of the string. The string is of this kind L1 G2 X50 Y50. i need to get the 2 50s out of the string.
ps.: the variables are in dutch.
XgetalEen = XnumberOne, XgetalTwee=XnumberTwo,
same goes for Y.
XgetalSamen=XnumberTogether, YgetalSamen=YnumberTogether.
This is a simple example how you could parse the file:
// Read your file using File.ReadAllLines
String[] lines = new[] { "L1 G2 X50 Y50", "L1 G2 X50 Y50" };
foreach (var line in lines)
{
String[] values = line.Split(' ');
string x = values.Where(s => s.StartsWith("X")).First().Replace("X", String.Empty);
int xCoordinate = Convert.ToInt32(x);
}
Don't forget to add all necessary checks and reading of other variables.
private static void PizzaHutPizzaScrapper()
{
try
{
MatchCollection mclName;
MatchCollection mclPrice;
WebClient webClient = new WebClient();
string strUrl = "http://www.pizzahut.com.pk/pizzas.html";
byte[] reqHTML;
reqHTML = webClient.DownloadData(strUrl);
UTF8Encoding objUTF8 = new UTF8Encoding();
string pageContent = objUTF8.GetString(reqHTML);
Regex r = new Regex("(<p class=\"MenuDescHead\">[A-Za-z\\s*]+[0-9]*)");
// Regex r1 = new Regex("(<p class=\"MenuDescPrice\">[A-Za-z.\\s?]+[0-9]*[A-Za-z\\s?]*[0-9]*[A-Za-z.\\s?]*)");
Regex r1 = new Regex("(<p class=\"MenuDescPrice\">[0-9]*)");
mclName = r.Matches(pageContent);
mclPrice = r1.Matches(pageContent);
StringBuilder strBuilder = new StringBuilder();
string name = "";
string price = "";
List<string> menuPriceList = new List<string>();
foreach (Match ml in mclPrice)
{
price = ml.Value.Remove(0, ml.Value.IndexOf(">") + 1).Trim();
if (price != "")
{
menuPriceList.Add(ml.Value);
}
}
int j = 0;
for (int i = 0; i < mclName.Count; i++)
{
name = mclName[i].Value.Remove(0, mclName[i].Value.IndexOf(">") + 1);
if (i == 0 || i == 4)
{
price = menuPriceList[j].Remove(0, menuPriceList[j].IndexOf(">") + 1);
strBuilder.Append(name.Trim() + ", " + price.Trim() + " , PizzaHut\r\n");
j++;
}
price = menuPriceList[j].Remove(0, menuPriceList[j].IndexOf(">") + 1);
strBuilder.Append(name.Trim() + ", " + price.Trim() + " ,PizzaHut\r\n");
j++;
}`
i want to select numeric values only...but it fetch alphabets as well..
i want to select only numeric values from HTML and using [0-9]* as regular expression, but its not working and show alphabets as well. i want only numeric values, what is correct regular expression? any idea??
Here you go, what you're looking for are Grouping Constructs:
MatchCollection mclName;
MatchCollection mclPrice;
WebClient webClient = new WebClient();
string strUrl = "http://www.pizzahut.com.pk/pizzas.html";
byte[] reqHTML;
reqHTML = webClient.DownloadData(strUrl);
UTF8Encoding objUTF8 = new UTF8Encoding();
string pageContent = objUTF8.GetString(reqHTML);
Regex nameRegex = new Regex("<p class=\"MenuDescHead\">([A-Za-z\\s]+[0-9]*)");
Regex priceRegex = new Regex("<p class=\"MenuDescPrice\">[^0-9]*([0-9]*)");
mclName = nameRegex.Matches(pageContent);
mclPrice = priceRegex.Matches(pageContent);
StringBuilder strBuilder = new StringBuilder();
List<string> menuPriceList = new List<string>();
foreach (Match ml in mclPrice)
{
string price = ml.Groups[1].ToString();
if (price != "" && price != "0")
{
menuPriceList.Add(price);
}
}
int j = 0;
for (int i = 0; i < mclName.Count; i++)
{
string price;
string name = mclName[i].Groups[1].ToString();
if (i == 0 || i == 4)
{
price = menuPriceList[j];
strBuilder.Append(name.Trim() + ", " + price.Trim() + " , PizzaHut\r\n");
j++;
}
price = menuPriceList[j];
strBuilder.Append(name.Trim() + ", " + price.Trim() + " ,PizzaHut\r\n");
j++;
}
Console.WriteLine(strBuilder.ToString());
how to recognize new line c# while uploading word documents..? i have to give next line as a new word in word document here what is happening means if i add three or more words in .doc in separate line its taking as one word i want to separate the words but if i give a space after a word it is taking as expected without giving space if i start a new word in new line its taking as one word
money
power
cash
moneypowercash
like this iam getting here if i give space after these words its getting as expected
how to resolve this issue here i will give my code to generating this keyword
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
if (cmbDepartment.SelectedValue != "0" && cmbDocumentType.SelectedValue != "0")
{
TodayDate = DateTime.Today.ToString("yyyy-MM-dd");
TempFolder = System.Configuration.ConfigurationManager.AppSettings["TempWorkFolder"];
TextReader reader = new FilterReader(TempFolder + Session["EncyptImgName"]);
StringBuilder Keywords = new StringBuilder();
using (reader)
{
Keywords = Keywords.Append(reader.ReadToEnd());
}
//remove common words
string[] removablewords = { ":", ".", "~"};
foreach (string st in removablewords)
{
Keywords.Replace(st, " ");
}
//Reomve unwated spaces
while (Keywords.ToString().Contains(" "))
{
Keywords.Replace(" ", " ");
}
string str = Keywords.ToString();
Keywords.Clear();
Keywords.Append("<words><s>" + str.Replace(" ", "</s><s>") + "</s></words>");
string xml = Keywords.ToString();
XElement items = XElement.Parse(xml);
var groups = from t in items.Descendants("s")
group t by t.Value.ToLower() into g
select new KeyFrequency(g.Key, g.Count());
groups = groups.OrderByDescending(g => g.Frequency).Take(15);
keyvalues = new List<string>();
foreach (KeyFrequency g in groups)
{
keyvalues.Add(g.Key);
}
for (key = 0; key < keyvalues.Count && key < 10; key++)
{
Button btn = (Button)pnlKeywords.FindControl("Button" + Convert.ToString(key + 1));
btn.Visible = true;
btn.Text = keyvalues[key];
btn.CommandArgument = keyvalues[key];
}
if (key < 10)
{
for (key = key; key < 10; key++)
{
Button btn = (Button)pnlKeywords.FindControl("Button" + Convert.ToString(key + 1));
btn.Visible = false;
}
}
else
{
AsyncFileUpload1.BackColor = System.Drawing.Color.Red;
}
}
}
catch (Exception ex)
{
Button1.Text = "Keywords Not Available for This Document";
Button1.CommandArgument = null;
Button2.Visible = false;
Button3.Visible = false;
Button4.Visible = false;
Button5.Visible = false;
Button6.Visible = false;
Button7.Visible = false;
Button8.Visible = false;
Button9.Visible = false;
Button10.Visible = false;
}
}
For each new line, try replacing \n with "</w:t><w:br/><w:t>". It worked for me.
string.Replace("\n", "</w:t><w:br/><w:t>")
Through a series of loops and Database calls (Select statements only) saved as datatables I am generating a .txt file with the values. It runs fine for a little while (19 rows...19 full loop cycles) then I get a runtime exception being thrown by connection.Open()
I have the entire loop inside a try catch block in order to catch the exception and produce the message then 2 blank lines then the stack trace.
I have tried to read this and figure out what to do but I am a bit of a Novice when it comes to DB connections. I have looked elsewhere but do not seem to find a question that quite fits my situation.
FYI: C# 4.0 Windows Form Application, Access DB
I am hoping to find some suggestions on where to begin looking. I am positive that my connection is closed when this error is thrown due to the validation i implemented as shown here:
internal IDbConnection GetConnection()
{
try
{
var connection = _assemblyProvider.Factory.CreateConnection();
connection.ConnectionString = _connectionString;
_connectionState = connection.State.ToString();
if (_connectionState == "Open")
GetConnection();
else
{
connection.Open();
}
return connection;
}
catch (Exception exept)
{
throw new Exception(exept.ToString() + "\n\n" + exept.StackTrace.ToString());
}
}
This method is being called from here:
public DataTable ExecuteDataTable(string commandText, string tableName, DbParameterCollection paramCollection, CommandType commandType)
{
DataTable dtReturn;
IDbConnection connection = null;
try
{
connection = _connectionManager.GetConnection();
dtReturn = _dbAdapterManager.GetDataTable(commandText, paramCollection, connection, tableName, commandType);
}
finally
{
if (connection != null)
{
connection.Close();
connection.Dispose();
}
}
return dtReturn;
}
public DataTable ExecuteDataTable(string commandText, string tableName, CommandType commandType)
{
return ExecuteDataTable(commandText, tableName, new DbParameterCollection(), commandType);
}
public DataTable ExecuteDataTable(string commandText)
{
return ExecuteDataTable(commandText, string.Empty, CommandType.Text);
}
and
//read from DB using a SQL statement and return a DataTable
internal static DataTable readDB(string SQL)
{
var dbHelper = new DbHelper();
using (IDbConnection connection = dbHelper.GetConnObject())
{
return dbHelper.ExecuteDataTable(SQL);
}
}
Here is the loop (its kinda long and could probably be done better but I just want to find why its breaking after its worked several times)
The exception is thrown from the line that Reads:
DataTable iRecNum2ClaimRecNumFromClaim = dbConnect.readDB(SQLString);
inside this:
SQLString = "SELECT * FROM Claim WHERE ClaimStatus <> 1";
DataTable allRecsFromClaimNotStatus1 = dbConnect.readDB(SQLString);
if (allRecsFromClaimNotStatus1.Rows.Count == 0)
return;
else
{
string path = txtExtractFileLocation.Text;
if (txtExtractFileLocation.Text.Substring(txtExtractFileLocation.Text.Length - 2) == "\\\\")
{
path = path.Substring(0, path.Length - 1);
}
if (path.Substring(path.Length - 1) == "\\")
path += "DI_Extract.txt";
else
path += #"\DI_Extract.txt";
using (StreamWriter sw = new StreamWriter(#path))
{
for (int i = 0; i < allRecsFromClaimNotStatus1.Rows.Count; i++)
{
rNum = allRecsFromClaimNotStatus1.Rows[i][2].ToString().Trim();//Claim.InsuredRecNum
SQLString = "SELECT * FROM Insured WHERE RecNum = " + rNum;
DataTable allInsuredByRecNum = dbConnect.readDB(SQLString);
lossDate = allRecsFromClaimNotStatus1.Rows[i][11].ToString().Trim();//Claim.LossDate
lossDate = (Convert.ToDateTime(lossDate)).Date.ToString("MM/dd/yyyy");
reportedDate = allRecsFromClaimNotStatus1.Rows[i][9].ToString().Trim();//Claim.ReportedDate
reportedDate = (Convert.ToDateTime(reportedDate)).Date.ToString("MM/dd/yyyy");
claim = allRecsFromClaimNotStatus1.Rows[i][0].ToString().Trim();//Claim.ClaimNumber
if (chkIncludePaymentsForCurrentMonth.Checked == true)
{
direct = allRecsFromClaimNotStatus1.Rows[i][4].ToString().Trim();//Claim.DirectReserve
WP = allRecsFromClaimNotStatus1.Rows[i][5].ToString().Trim();//Claim.WPReserve
ceded = allRecsFromClaimNotStatus1.Rows[i][6].ToString().Trim();//Claim.CededReserve
}
else
{
direct = allRecsFromClaimNotStatus1.Rows[i][29].ToString().Trim();//Claim.MonthEndDirect
WP = allRecsFromClaimNotStatus1.Rows[i][30].ToString().Trim();//Claim.MonthEndWP
ceded = allRecsFromClaimNotStatus1.Rows[i][31].ToString().Trim();//Claim.MonthEndCeded
}
ced = Convert.ToDecimal(ceded);
wav = Convert.ToDecimal(WP);
ceded = ced.ToString("#.##");
WP = wav.ToString("#.##");
if (ceded == "")
ceded = "0";
if (WP == "")
WP = "0";
if ((allRecsFromClaimNotStatus1.Rows[i][10].ToString().Trim() != null) &&
(allRecsFromClaimNotStatus1.Rows[i][10].ToString().Trim() != ""))//Claim.WaiverDate
{
onWaiver = "YES";
}
else
{
onWaiver = "NO";
}
reinsPreNotice = "NO";
reinsCeded = "NO";
switch (allRecsFromClaimNotStatus1.Rows[i][7].ToString().Trim())//Claim.CededPre
{
case "1":
{
reinsPreNotice = "YES";
break;
}
case "2":
{
reinsCeded = "YES";
break;
}
}//end switch
state = allRecsFromClaimNotStatus1.Rows[i][8].ToString().Trim();//Claim.LossState
lName = allInsuredByRecNum.Rows[0][1].ToString().Trim();//Insured.LastName
fName = allInsuredByRecNum.Rows[0][0].ToString().Trim();//Insured.FirstName
mi = allInsuredByRecNum.Rows[0][2].ToString().Trim();//Insured.MI
policy = allInsuredByRecNum.Rows[0][43].ToString().Trim();//Insured.PolicyNumber
DOB = allInsuredByRecNum.Rows[0][10].ToString().Trim();//Insured.DOB
DOB = (Convert.ToDateTime(DOB)).Date.ToString("MM/dd/yyyy");
age = allInsuredByRecNum.Rows[0][11].ToString().Trim();//Insured.TrueAge
issueAge = calculateAge(Convert.ToDateTime(allInsuredByRecNum.Rows[0][10].ToString().Trim()), //Insured.DOB
Convert.ToDateTime(allInsuredByRecNum.Rows[0][45].ToString().Trim()));//Insured.EffectiveDate
SQLString = "SELECT InsuredRecNum, RecNum FROM Claim WHERE InsuredRecNum = " + rNum;
DataTable iRecNum2ClaimRecNumFromClaim = dbConnect.readDB(SQLString);
rNum = iRecNum2ClaimRecNumFromClaim.Rows[0][1].ToString().Trim();
issueDate = allInsuredByRecNum.Rows[0][45].ToString().Trim();//Insured.EffectiveDate
issueDate = (Convert.ToDateTime(issueDate)).Date.ToString("MM/dd/yyyy");
sex = allInsuredByRecNum.Rows[0][13].ToString().Trim();//Insured.Gender
planCode = allInsuredByRecNum.Rows[0][44].ToString().Trim();//Insured.PlanMnemonic
issueAmt = allInsuredByRecNum.Rows[0][49].ToString().Trim();//Insured.BenefitAmount (Monthly Benefit Amount before Offset)
benefitPeriod = allInsuredByRecNum.Rows[0][50].ToString().Trim();//Insured.BenefitPeriod
if (allInsuredByRecNum.Rows[0][54].ToString().Trim().Length == 2)//Insured.EliminationPeriod
eliminationPeriod = "0" + allInsuredByRecNum.Rows[0][54].ToString().Trim();
else
eliminationPeriod = allInsuredByRecNum.Rows[0][54].ToString().Trim();
premiumAmount = allInsuredByRecNum.Rows[0][48].ToString().Trim();//Insured.AnnualPremium
occupationClass = allInsuredByRecNum.Rows[0][55].ToString().Trim();//Insured.OccupationClass
//select only status = EXEC (0)
SQLString = "SELECT * FROM Offset WHERE ClaimRecNum = " + rNum + " AND Status = 0";
DataTable allOffsetByClaimRecNumAndStatus0 = dbConnect.readDB(SQLString);
offsetAmt = 0;
dblSTDOffsetAmount = 0;
dblRecOffsetAmount = 0;
RECOffsetOcc = "0";
RECOffsetExecuted = "0";
int offsetCount = allOffsetByClaimRecNumAndStatus0.Rows.Count;
if (offsetCount != 0)
{
for (int j = 0; j < offsetCount; j++)
{
//accumulate standard offset (STD) and Recovery offset (REC)
if (allOffsetByClaimRecNumAndStatus0.Rows[0][1].ToString().Trim() == "0")//Offset.Type
{
//Standard Type
dblSTDOffsetAmount += Convert.ToDouble(allOffsetByClaimRecNumAndStatus0.Rows[j][4].ToString().Trim());//Offset.Amount
}
else
{
//Recovery type
dblRecOffsetAmount = Convert.ToDouble(allOffsetByClaimRecNumAndStatus0.Rows[j][4].ToString().Trim());//Offset.Amount
RECOffsetOcc = allOffsetByClaimRecNumAndStatus0.Rows[j][5].ToString().Trim();//Offset.Occurance
RECOffsetExecuted = allOffsetByClaimRecNumAndStatus0.Rows[j][6].ToString().Trim();//Offset.Executed
}//end if
}//end for loop
}//end if
STDOffsetAmount = dblSTDOffsetAmount.ToString();
RECOffsetAmount = dblRecOffsetAmount.ToString();
if (chkIncludePaymentsForCurrentMonth.Checked == true)
SQLString = "SELECT * FROM Payment WHERE InsuredRecNum = " + rNum + " AND IssueDate >= #01/01/" + DateTime.Today.Date.Year + "# AND IssueDate <= #" + DateTime.Today.Date.ToShortDateString() + "#";
else
SQLString = "SELECT * FROM Payment WHERE InsuredRecNum = " + rNum + " AND IssueDate >= #01/01/" + endDate.Substring(endDate.Length - 4) + "# AND IssueDate <= #" + Convert.ToDateTime(endDate).Date.ToShortDateString() + "#";
DataTable allPaymentByIRecNumAndIssDateInRange = dbConnect.readDB(SQLString);
YTDPmt = 0;
if (allPaymentByIRecNumAndIssDateInRange.Rows.Count == 0)
YTDPmt = 0;
else
{
int paymentCount = allPaymentByIRecNumAndIssDateInRange.Rows.Count;
double issAmt;
for (int k = 0; k < paymentCount; k++)
{
issAmt = Convert.ToDouble(allPaymentByIRecNumAndIssDateInRange.Rows[0][30].ToString().Trim());//Payment.IssueAmount
YTDPmt += issAmt;
}// end loop
}//end if
YTDPmts = YTDPmt.ToString();
if (chkIncludePaymentsForCurrentMonth.Checked == true)
SQLString = "SELECT * FROM Payment WHERE ClaimRecNum = " + rNum;
else
SQLString = "SELECT * FROM Payment WHERE ClaimRecNum = " + rNum + " AND IssueDate <= #" + Convert.ToDateTime(endDate).Date.ToShortDateString() + "#";
DataTable allPaymentByRNum = dbConnect.readDB(SQLString);
totalPmt = 0;
if (allPaymentByRNum.Rows.Count == 0)
totalPmt = 0;
else
{
double issAmt = Convert.ToDouble(allPaymentByRNum.Rows[0][30].ToString().Trim());
for (int m = 0; m < allPaymentByRNum.Rows.Count; m++)
{
totalPmt += issAmt;
}
}
allPmts = totalPmt.ToString();
//set spacing for output
string block1 = policy + claim + planCode;
block1 = setSpacing(block1, 28);
string block2 = setSpacing(benefitPeriod, 3) + eliminationPeriod + occupationClass;
block2 = setSpacing(block2, 11);
issueAmt = setSpacing(issueAmt, 8);
STDOffsetAmount = setSpacing(STDOffsetAmount, 8);
RECOffsetAmount = setSpacing(RECOffsetAmount, 8);
RECOffsetOcc = setSpacing(RECOffsetOcc, 3);
RECOffsetExecuted = setSpacing(RECOffsetExecuted, 3);
string block3 = lossDate + age;
block3 = setSpacing(block3, 13);
issueAge = setSpacing(issueAge, 3);
string block4 = issueDate + DOB + sex + onWaiver + premiumAmount;
block4 = setSpacing(block4, 32);
reinsPreNotice = setSpacing(reinsPreNotice, 3);
reinsCeded = setSpacing(reinsCeded, 4);
double ap = Convert.ToDouble(allPmts);
allPmts = ap.ToString("#.#");
allPmts = setSpacing(allPmts, 8);
YTDPmts = setSpacing(YTDPmts, 8);
lName = setSpacing(lName, 19);
fName = fName + " " + mi;
fName = setSpacing(fName, 20);
string block5 = state + direct;
block5 = setSpacing(block5, 10);
ceded = setSpacing(ceded, 8);
WP = setSpacing(WP, 8);
reportedDate = setSpacing(reportedDate, 10);
//save row data for text file
dataOutput = (block1 + block2 + issueAmt + STDOffsetAmount + RECOffsetAmount + RECOffsetOcc + RECOffsetExecuted +
block3 + issueAge + block4 + reinsPreNotice + reinsCeded + allPmts + YTDPmts + lName + fName +
block5 + ceded + WP + reportedDate);
//Write to the output record DI_Extract.txt
sw.WriteLine(dataOutput);
counter++;
pbrRecordsProcessed.Value = counter;
}//end for loop
}//end streamwriter
}//end if
After looking deeper into the code I realized that the connection was trying to open 3 times before it closed. Not sure why I was not getting exceptions all the time but correcting this issue not only sped up the application tremendously it cleared the exception.
I am trying to split the incoming data from a Serial Port, and update text boxes with subsequent data. I first see if a split on '$' is possible, and if the next word after splitting is "GPGGA". If yes, I would like to extract data from this sentence where ',' serves as the separator.
Now, as you see, I update the entire data read by the Serial Port first, and this works fine. The full sentence containing the "GPGGA" line is displayed. But after I split it, the part of the sentence that contains the "GPGGA" looks something like this"GPGGA,1\0\0\0\0\0..." when really the sentence that was just updated to the text box before was "GPGGA,160333,,,......". I am absolutely certain that there is a value after GPGGA in the sentence but when i try to look at it in the debug mode, the string 'ser_data', and hence its subsequent substrings all show the same junk. So, the final text box that I want to update inevitably ends up displaying just 1.
Could anyone tell me why this is happening, and how I can correct it. I need it urgently for my thesis work.
Thanks,
Brett
P.S: I've attached the code below.
private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] bData = null;
bData = new byte[40];
serialPort.Read(bData, 0, 40);
string ser_data = System.Text.Encoding.GetEncoding("utf-8").GetString(bData);
txtAck.Invoke(new UpdateTextCallback(this.UpdateTextAck), new object[] { ser_data });
string[] str = null;
str = new string[40];
string[] str_ack = null;
str = ser_data.Split('$');
if (str.Length > 1)
{
for (int i = 1; i < str.Length; i++)
{
string temp1 = null;
temp1 = str[i];
if (temp1.StartsWith("GPGGA"))
{
string[] temp2 = null;
temp2 = temp1.Split(',');
StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
if (temp2.Length > 1)
{
string Time_GPS = temp2[1];
txtEasting.Invoke(new UpdateTextCallback(this.UpdateTextEast), new object[] { Time_GPS });
string text = "Time : " + Time_GPS;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 2)
{
string Lat = temp2[2];
txtLatitude.Invoke(new UpdateTextCallback(this.UpdateTextLat), new object[] { Lat });
string text = " Latitude : " + Lat;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 4)
{
string Long = temp2[4];
txtLongitude.Invoke(new UpdateTextCallback(this.UpdateTextLong), new object[] { Long });
string text = " Longitude : " + Long;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 9)
{
string Alt = temp2[9];
txtNorthing.Invoke(new UpdateTextCallback(this.UpdateTextNorth), new object[] { Alt });
string text = " Altitude : " + Alt;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
string Text = "." + '\n';
objWriter.WriteLine(Text);
objWriter.Close();
temp2 = null;
flag_status = 0;
}
temp1 = null;
}
}
str = null;
SerialPort.Read does not necessarily read the number of characters you ask for.
You need to save the return value, which is the number of characters read.
// nBytesRead will be between 0 and 40, depending on how many bytes were waiting.
int nBytesRead = serialPort.Read(bData, 0, 40);
// Only decode the number of bytes actually retrieved.
string ser_data = System.Text.Encoding.GetEncoding("utf-8").GetString(bData, 0, nBytesRead);
Fixed and majorly cleaned up. This assumes two things: that your encoding is really UTF-8, and that your lines end with newline characters.
private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
serialPort.Encoding = ASCIIEncoding.UTF8;
string ser_data = serialPort.ReadLine();
txtAck.Invoke(new UpdateTextCallback(this.UpdateTextAck), new object[] { ser_data });
string[] str = ser_data.Split(new char[] { '$' }, 2);
if (str.Length > 1)
{
for (int i = 1; i < str.Length; i++)
{
string temp1 = str[i];
if (temp1.StartsWith("GPGGA"))
{
StreamWriter objWriter = new StreamWriter(#"D:\Server.txt", true);
try
{
string[] temp2 = temp1.Split(',');
if (temp2.Length > 1)
{
string Time_GPS = temp2[1];
txtEasting.Invoke(new UpdateTextCallback(this.UpdateTextEast), new object[] { Time_GPS });
string text = "Time : " + Time_GPS;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 2)
{
string Lat = temp2[2];
txtLatitude.Invoke(new UpdateTextCallback(this.UpdateTextLat), new object[] { Lat });
string text = " Latitude : " + Lat;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 4)
{
string Long = temp2[4];
txtLongitude.Invoke(new UpdateTextCallback(this.UpdateTextLong), new object[] { Long });
string text = " Longitude : " + Long;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 9)
{
string Alt = temp2[9];
txtNorthing.Invoke(new UpdateTextCallback(this.UpdateTextNorth), new object[] { Alt });
string text = " Altitude : " + Alt;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
objWriter.WriteLine(".\n");
}
finally
{
objWriter.Close();
}
flag_status = 0;
}
}
}
}