I have a system which inserts some recopies into a table. The thing is when I click the update button repeatedly it insert duplicate records into my database. Please help me to fix it.
Note: When I try to use the data in the table, these duplicate data does crash the program.
private void button1_Click(object sender, EventArgs e)
{
(sender as Button).Enabled = false;
string ItemCode;
string ItemDesc;
string ItID;
string InItID;
decimal EntQty;
string EntUOM;
decimal TQty;
string NewRec;
bool Prt;
TQty = 0;
foreach (DataRow RowVal in dataSetMaster.ITEM_LINE)//
{
ItemCode = RowVal["InITCode"].ToString();
ItemDesc = RowVal["InITDesc"].ToString();
ItID = RowVal["ItemID"].ToString();
InItID = RowVal["Ingredient_ItemID"].ToString();
EntQty = Convert.ToDecimal(RowVal["Entry_Qty"].ToString());
TQty = Convert.ToDecimal(RowVal["T_Qty"].ToString());
NewRec = RowVal["NewRec"].ToString();
EntUOM = RowVal["Entry_UOM"].ToString();
Prt = Convert.ToBoolean(RowVal["Print"].ToString());
// MessageBox.Show("Items in the grid " + ItemCode + " == " + ItemDesc+" /"+Convert.ToString(EntQty)+" / "+Convert.ToString(TQty));
string ComdTextItemCode;
string ComdTextItemCodeInsert;
string Itcode;
Itcode = TextBoxCode.Text.Trim();
string X1;
X1 = "TEST";
sqlConnection1.Open();
if (NewRec == "True")
{
Guid newGuid;
Guid newGuid2;
if (Guid.TryParseExact(ItID, "D", out newGuid))
{
Console.WriteLine("Converted {0} to a Guid", ItID);
}
else
{
Console.WriteLine("Unable to convert {0} to a Guid",
ItID);
}
if (Guid.TryParseExact(InItID, "D", out newGuid2))
{
Console.WriteLine("Converted {0} to a Guid", InItID);
}
else
{
Console.WriteLine("Unable to convert {0} to a Guid",
InItID);
}
// MessageBox.Show("Test");
Guid ItmID = newGuid;
Guid IngItmID = newGuid2;
Guid GuItem_LineID = Guid.NewGuid();
//INSERT INTO ITEM_LINE (Item_LineID,ItemID,Ingredient_ItemID,Entry_Qty,Entry_UOM) VALUES (convert(uniqueidentifier, #Item_LineID),convert(uniqueidentifier, #ItemID),convert(uniqueidentifier, #Ingredient_ItemID),#Entry_Qty,#Entry_UOM)
ComdTextItemCodeInsert = "INSERT INTO ITEM_LINE (Item_LineID,ItemID,Ingredient_ItemID,Entry_Qty,Entry_UOM,[Print],T_Qty)" +
"VALUES (convert(uniqueidentifier, #Item_LineID),convert(uniqueidentifier, #ItemID),convert(uniqueidentifier, #Ingredient_ItemID),#Entry_Qty,#Entry_UOM,#Print,#T_Qty)";
sqlInsertItemDtl.CommandText = ComdTextItemCodeInsert;
sqlInsertItemDtl.Parameters["#Item_LineID"].Value = GuItem_LineID;
sqlInsertItemDtl.Parameters["#ItemID"].Value = ItmID; // roleID;
sqlInsertItemDtl.Parameters["#Ingredient_ItemID"].Value = IngItmID;
sqlInsertItemDtl.Parameters["#Entry_Qty"].Value = EntQty;
sqlInsertItemDtl.Parameters["#Entry_UOM"].Value = EntUOM;
sqlInsertItemDtl.Parameters["#Print"].Value = Prt;
sqlInsertItemDtl.Parameters["#T_Qty"].Value = TQty;
sqlDADetail.InsertCommand.ExecuteNonQuery();
}
else
{
ComdTextItemCode = "UPDATE ITEM_LINE SET ITEM_LINE.T_Qty=" + #TQty +",ITEM_LINE.[Print]='"+ #Prt +
"' WHERE ITEM_LINE.ItemID=convert(uniqueidentifier,'" + ItID + "') AND ITEM_LINE.Ingredient_ItemID=convert(uniqueidentifier,'" + InItID + "')";
sqlUpdateDtl.CommandText = ComdTextItemCode;
sqlDADetail.UpdateCommand.ExecuteNonQuery();
}
sqlConnection1.Close();
}
MessageBox.Show("Material Master updated.");
}
Related
I have a listbox in which my selected products are stored like this ...
'Product name'.padright(30) 'price' 'quantity'
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + 1 );
but when I read price of a product it selects price and quantity
string currentPriceString = foundItem.Replace(details.Name.PadRight(30), "");
string quantityString = foundItem.Replace(details.Name.PadRight(33), "");
I only want price in currentPriceString and quantity in quantityString
here is complete code of this method
private void ProductButton_Click(object sender, EventArgs e)
{
Button ProductButton = sender as Button;
DataAccess dataAccess = new DataAccess();
int ProductID = Convert.ToInt32(ProductButton.Tag);
Details details = dataAccess.ReadProductDetails(ProductID);
decimal price = details.Price;
string foundItem = CheckProductInListBox(details.Name);
if (!String.IsNullOrEmpty(foundItem))
{
string currentPriceString = foundItem.Replace(details.Name.PadRight(30), "");
decimal currentPriceValue;
string quantityString = foundItem.Replace(details.Name.PadRight(33), "");
int quantiy;
MessageBox.Show(currentPriceString);
if (Decimal.TryParse(currentPriceString, out currentPriceValue))
{
quantiy = Convert.ToInt16(quantityString);
currentPriceValue += price;
quantiy++;
string newItem = details.Name.PadRight(30) + currentPriceValue.ToString() + quantiy.ToString();
int index = listBox1.Items.IndexOf(foundItem);
listBox1.Items[index] = newItem;
}
else
{
MessageBox.Show("Error");
}
}
else
{
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + 1 );
}
}
private string CheckProductInListBox(string name)
{
foreach (string item in listBox1.Items)
{
if (item.Contains(name))
{
return item;
}
}
return String.Empty;
}
On replacing (foundItem.Replace(details.Name.PadRight(33), "");), you are just removing the name part from the string, so the price and quantity will be there for sure.
You should can try this code,
// suppose your found text is like this,
//foundItem = "AMIT".PadRight(30) + "200" + " " + "1";
You can get price and quantity separately like below:
string currentPriceQuantityString = foundItem.Replace(details.Name.PadRight(30), "");
//currentPriceQuantityString => "200 1"
string[] strArray = currentPriceQuantityString.Split();
string currentPriceString = strArray[0]; //currentPriceString => "200"
string quantityString = strArray[1]; //quantityString => "1"
Side note:
I guess your line:
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + 1 );
..should be:
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + "1" );
With the code below I am able to save files to folder.
My problem is only two upload fields are mandatory and the remaining three are not. The code works if all the upload fields have a files selected otherswise its throws a NullReferenceException.
if (AnnualReport != null || ProjectReports != null || Publications != null || Other != null || RegistDoc != null) {
int filesize = AnnualReport.PostedFile.ContentLength;
int filesizeP = ProjectReports.PostedFile.ContentLength;
int filesizePub = Publications.PostedFile.ContentLength;
int filesizeOther = Other.PostedFile.ContentLength;
int filesizeReg = RegistDoc.PostedFile.ContentLength;
if (filesize > 2097152 && filesizeP > 2097152 && filesizePub > 1048576 && filesizeOther > 1048576 && filesizeReg > 1048576) {
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximum File size For Annual/Project reports is 1.5MB and for the Publications/Other Attachemnets is 1MB');", true);
} else {
const string ReportDirectory = "REPORTS/";
//Other Document
string OtherPath = ReportDirectory + Other.FileName;
string fileNameWithoutExtensionOther = System.IO.Path.GetFileNameWithoutExtension(Other.FileName);
int iterationOther = 1;
while (System.IO.File.Exists(Server.MapPath(OtherPath))) {
OtherPath = string.Concat(ReportDirectory, fileNameWithoutExtensionOther, "-", iterationOther, ".pdf");
iterationOther++;
}
//Registration Document
string RigisDocPath = ReportDirectory + RegistDoc.FileName;
string fileNameWithoutExtensionRegis = System.IO.Path.GetFileNameWithoutExtension(RegistDoc.FileName);
int iterationRE = 1;
while (System.IO.File.Exists(Server.MapPath(RigisDocPath))) {
RigisDocPath = string.Concat(ReportDirectory, fileNameWithoutExtensionRegis, "-", iterationRE, ".pdf");
iterationRE++;
}
//Annual Reports
string ReportPath = ReportDirectory + AnnualReport.FileName;
string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(AnnualReport.FileName);
int iteration = 1;
while (System.IO.File.Exists(Server.MapPath(ReportPath))) {
ReportPath = string.Concat(ReportDirectory, fileNameWithoutExtension, "-", iteration, ".pdf");
iteration++;
}
//Project Report
string ProjecttPath = ReportDirectory + ProjectReports.FileName;
string fileNameWithoutExtensionP = System.IO.Path.GetFileNameWithoutExtension(ProjectReports.FileName);
int iterationP = 1;
while (System.IO.File.Exists(Server.MapPath(ProjecttPath))) {
ProjecttPath = string.Concat(ReportDirectory, fileNameWithoutExtensionP, "-", iterationP, ".pdf");
iterationP++;
}
//publication
string publicationPath = ReportDirectory + Publications.FileName;
string fileNameWithoutExtensionPub = System.IO.Path.GetFileNameWithoutExtension(Publications.FileName);
int iterationPub = 1;
while (System.IO.File.Exists(Server.MapPath(publicationPath))) {
publicationPath = string.Concat(ReportDirectory, fileNameWithoutExtensionPub, "-", iterationPub, ".pdf");
iterationPub++;
}
ProjectReports.SaveAs(Server.MapPath(ProjecttPath));
AnnualReport.SaveAs(Server.MapPath(ReportPath));
Publications.SaveAs(Server.MapPath(publicationPath));
RegistDoc.SaveAs(Server.MapPath(RigisDocPath));
Other.SaveAs(Server.MapPath(OtherPath));
The code you posted is very poorly formated. However, the solution to your immediate problem is to move the null checks down to each individual document.
Instead of doing a huge if line (which has questionable logic, as it only checks if ANY of the documents were uploaded)
You can just check if the required documents are present. (looking at your exising code, present means document name object is not null)
If not, throw an error.
If they are, then proceed with the rest of the code, but wrap the individual processing of optional documents in their own null check if-s.
ie.
if (AnnualReport != null) {
//the block that does stuff with the anual report object
}
I did beak down the code into diferent methods like #irreal suggested, like below;
public void PublicationReporting() {
//connection for the datareader
string csoWConn = ConfigurationManager.ConnectionStrings["RegisterCon"].ToString();
SqlConnection csoW_connection = new SqlConnection(csoWConn);
string database = csoW_connection.DataSource.ToString();
csoW_connection.Open();
if (Publications == null)
{
Publications.Dispose();
////
String MyString = #"UPDATE tb_Quadrennial_Report SET PublicationsPath='' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
int LastInsertedRecordID;
LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
}
else
{
int filesizeP = Publications.PostedFile.ContentLength;
if (filesizeP > 2097152)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximum File size For Publication is 2.0 MB');", true);
}
else
{
const string ReportDirectory = "REPORTS/";
//publication
string publicationPath = ReportDirectory + Publications.FileName;
string fileNameWithoutExtensionPub = System.IO.Path.GetFileNameWithoutExtension(Publications.FileName);
int iteration = 1; while (System.IO.File.Exists(Server.MapPath(publicationPath)))
{
publicationPath = string.Concat(ReportDirectory, fileNameWithoutExtensionPub, "-", iteration, ".pdf");
iteration++;
}
Publications.SaveAs(Server.MapPath(publicationPath));
String MyString = #"UPDATE tb_Quadrennial_Report SET PublicationsPath='" + publicationPath + "' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
int LastInsertedRecordID;
LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
}
}
}
I then called it o the click event
try{
PublicationReporting();
}
catch (Exception ex)
{
pgError.Text = "Publication Exception Message: " + ex.Message;
}
finally
{
csoW_connection.Close();
}
From here it was pretty easy to figure out the problem.
I just needed to dispose the content in the upload field if no file was selected like this
public void PublicationReporting() {
//connection for the datareader
string csoWConn = ConfigurationManager.ConnectionStrings["RegisterCon"].ToString();
SqlConnection csoW_connection = new SqlConnection(csoWConn);
string database = csoW_connection.DataSource.ToString();
csoW_connection.Open();
if (Publications == null)
{
Publications.Dispose();
////
String MyString = #"UPDATE tb_Quadrennial_Report SET PublicationsPath='' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
int LastInsertedRecordID;
LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
}
else{
//program continues}
So I am trying to validate a string I received from a MySQL database but for some reason cannot access. I am sure this is a dumb question but can anyone help me out? I feel like it might be related to the public vs private and the static but after playing around with every combination I can think of to pass through the variables, it still keeps giving me errors. Any ideas?
string failReason = "";
int valid = 0;
public static void getNewRow()
{
try
{
string getNewRow = "SELECT * FROM appointments WHERE valid IS NULL";
DbConnection mysqlDB = new DbConnection();
MySqlCommand mysqlCommand = new MySqlCommand(getNewRow, mysqlDB.GetLocalMySQLConnection());
MySqlDataReader reader = mysqlCommand.ExecuteReader();
while (reader.Read())
{
int id = reader.GetInt32("id");
string accountID = reader.GetString("accountID");
string appDate = reader.GetString("appDate");
string appTime = reader.GetString("apptime");
string patientName = reader.GetString("patientName");
string appPhone = reader.GetString("appPhone");
string appPhone2 = reader.GetString("appPhone2");
string smsPhone = reader.GetString("smsPhone");
string special = reader.GetString("special");
string email = reader.GetString("email");
string provider = reader.GetString("provider");
string location = reader.GetString("location");
string other = reader.GetString("other");
Console.WriteLine("ID: " + id);
Console.WriteLine("AccountID: " + accountID);
Console.WriteLine("Appointment Date: " + appDate);
Console.WriteLine("Appointment Time: " + appTime);
Console.WriteLine("Patient Name: " + patientName);
Console.WriteLine("Phone 1: " + appPhone);
Console.WriteLine("Phone 2: " + appPhone2);
Console.WriteLine("SMS Phone: " + smsPhone);
Console.WriteLine("Special: " + special);
Console.WriteLine("Email: " + email);
Console.WriteLine("Provider: " + provider);
Console.WriteLine("Location: " + location);
Console.WriteLine("Other: " + other);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
}
}
private bool validName()
{
if (patientName.Length < 20)
{
failReason = "Bad Name";
return false;
}
else
{
return true;
}
}
private bool validName()
{
if (patientName.Length < 20)
{
failReason = "Bad Name";
return false;
}
else
{
return true;
}
}
patientName exists only within the scope of getNewRow. You need to make that a class-scoped variable (like you did with failReason if you want to use them anywhere outside of getNewRow. You can also pass them as parameters, but I don't see that your methods have parameters to begin with.
string patientName = reader.GetString("patientName");
is local to
public static void getNewRow()
make it as such:
static string failReason = "";
static int valid = 0;
static string patientName = string.Empty;
public static void getNewRow()
{
try
{
string getNewRow = "SELECT * FROM appointments WHERE valid IS NULL";
DbConnection mysqlDB = new DbConnection();
MySqlCommand mysqlCommand = new MySqlCommand(getNewRow, mysqlDB.GetLocalMySQLConnection());
MySqlDataReader reader = mysqlCommand.ExecuteReader();
while (reader.Read())
{
int id = reader.GetInt32("id");
string accountID = reader.GetString("accountID");
string appDate = reader.GetString("appDate");
string appTime = reader.GetString("apptime");
patientName = reader.GetString("patientName");
string appPhone = reader.GetString("appPhone");
string appPhone2 = reader.GetString("appPhone2");
string smsPhone = reader.GetString("smsPhone");
string special = reader.GetString("special");
string email = reader.GetString("email");
string provider = reader.GetString("provider");
string location = reader.GetString("location");
string other = reader.GetString("other");
Console.WriteLine("ID: " + id);
Console.WriteLine("AccountID: " + accountID);
Console.WriteLine("Appointment Date: " + appDate);
Console.WriteLine("Appointment Time: " + appTime);
Console.WriteLine("Patient Name: " + patientName);
Console.WriteLine("Phone 1: " + appPhone);
Console.WriteLine("Phone 2: " + appPhone2);
Console.WriteLine("SMS Phone: " + smsPhone);
Console.WriteLine("Special: " + special);
Console.WriteLine("Email: " + email);
Console.WriteLine("Provider: " + provider);
Console.WriteLine("Location: " + location);
Console.WriteLine("Other: " + other);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
}
}
private static bool validName()
{
if (patientName.Length < 20)
{
failReason = "Bad Name";
return false;
}
else
{
return true;
}
}
private static bool validName()
{
if (patientName.Length < 20)
{
failReason = "Bad Name";
return false;
}
else
{
return true;
}
}
You should decide to make all your methods static or not. You cannot call a non static method from a static method.
I'm trying to get a report from a custom query accessing to a Microsoft Access Database filling a Dataset and then a CrystalReportViwer but I just got an empty report with the column names.
This is my connection:
public String ConectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data";
public OleDbConnection miconexion;
public Int32 retorna = 0;
public Int32 conectar(String location){
try
{
ConectionString += #" Source="+location;
miconexion = new OleDbConnection(ConectionString);
//Open Database Conexion
miconexion.Open();
retorna = 1;
}
catch (OleDbException ex){
retorna = 0;
MessageBox.Show("Database Error: "+ex.ToString());
}
return retorna;
}
public void desconectar() {
if(miconexion.State == ConnectionState.Open){
miconexion.Close();
}
}
Method that process the sql //---------------------------------
//txt_CustomConsult is the textbox that contains the custom query.
public String ExecuteSQl()
{
string sql = null;
string inSql = null;
string firstPart = null;
string LastPart = null;
int SelectStart = 0;
int fromStart = 0;
string[] fields = null;
string[] sep = { "," };
int i = 0;
TextObject MyText;
inSql = txt_CustomConsult.Text;
inSql = inSql.ToUpper();
SelectStart = inSql.IndexOf("SELECT");
fromStart = inSql.IndexOf("FROM");
SelectStart = SelectStart + 6;
firstPart = inSql.Substring(SelectStart, (fromStart - SelectStart));
LastPart = inSql.Substring(fromStart, inSql.Length - fromStart);
fields = firstPart.Split(',');
firstPart = "";
for (i = 0; i <= fields.Length - 1; i++) {
if (i > 0)
{
firstPart = firstPart + ", " + fields[i].ToString() + " AS COLUMN" + (i + 1);
firstPart.Trim();
MyText = (TextObject)ObjRep.ReportDefinition.ReportObjects[i + 1];
MyText.Text = fields[i].ToString();
}
else {
firstPart = firstPart + fields[i].ToString() + " AS COLUMN"+(i+1);
firstPart.Trim();
MyText = (TextObject)ObjRep.ReportDefinition.ReportObjects[i + 1];
MyText.Text = fields[i].ToString();
}
}
sql = "SELECT "+firstPart+" "+LastPart;
return sql;
}
// ---------------------------------------------------
Method that exceute report. lstbx_Tablas is the ListBox that contains all tables,
I got all the tables but report doesn't work.
public void DynamicRep() {
try {
//Windows Form where the rpt is located
ReporteResult mirepres = new ReporteResult();
//Connection
conexion miconect = new conexion();
miconect.conectar(Environment.GetEnvironmentVariable("dbUbicacion"));
String sql = ExecuteSQl();
OleDbDataAdapter dscm = new OleDbDataAdapter(sql,miconect.miconexion);
MisConsultas Dataset1 = new MisConsultas();
dscm.Fill(Dataset1,lstbx_Tablas.SelectedItem.ToString());
ObjRep.SetDataSource(Dataset1.Tables[0]);
mirepres.crv_Reporte.ReportSource = ObjRep;
mirepres.crv_Reporte.Refresh();
mirepres.Show();
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
}
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.