using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; namespace AdvertsingProfitControl { class DatabaseWriter { private OleDbConnection gConnectionObject = new OleDbConnection(); private LogConsole logConsole = LogConsole.GetStaticInstance; public DatabaseWriter(string connectionString) { gConnectionObject.ConnectionString = connectionString; } /// /// Infrastructure for the DatabaseWriter class, not meant to be used with external code. /// This function provides a centralized way to establish a connection with the database, /// and does so in a manner that eliminates the worry of opening multiple connections. /// private void OpenConnection() { //10 to 1 ratio of tries to code //http://codebetter.com/karlseguin/2006/04/05/understanding-and-using-exceptions/ try { if (gConnectionObject.State == ConnectionState.Closed) { gConnectionObject.Open(); } } catch (OleDbException ex) { //Clean up not fixing the error logConsole.WriteToLog(LogConsole.Level.Error, "Failed to open connection with the database." + ex.Message); logConsole.WriteToLog(LogConsole.Level.Debug, ex.Message + "\n" + ex.StackTrace); //Making damn sure things get cleaned up; guaranteed to execute. if (gConnectionObject.State != ConnectionState.Closed) { gConnectionObject.Close(); } throw; } } public bool InsertIntoWeekEnding(string dateString) { //Assume the INSERT operation failed in case anything other error arises. var insertWasSuccessful = false; //Set up the command object, SQL command string and parameters. var oleDbCommand = new OleDbCommand(); oleDbCommand.CommandText = "INSERT INTO WeekEnding(EndOfWeekDate) VALUES ( dateString )"; oleDbCommand.Parameters.AddWithValue("dateString", dateString); oleDbCommand.Connection = gConnectionObject; //Try to execute the query try { var numberOfRowsEffected = 0; //Check for the existence of the date string that was provided. oleDbCommand.CommandText = "SELECT ID FROM WeekEnding WHERE EndOfWeekDate = @dateString"; oleDbCommand.Parameters.AddWithValue("@dateString", dateString); oleDbCommand.Connection = gConnectionObject; OpenConnection(); //Execute the SELECT statement and retrieve the row(s) effected. var reader = oleDbCommand.ExecuteReader(); var recordIndex = 0; while (reader.Read()) { if (reader[recordIndex].ToString() != "") { numberOfRowsEffected++; } recordIndex++; } reader.Close(); //IF one row was affected, then return with "True", since the value is already there. if (numberOfRowsEffected == 1) { //Success! Without even lifting a finger, how nice. return true; } //ELSE IF more then one row was effected, then that means we have redundancy... else if (numberOfRowsEffected > 1) { oleDbCommand.CommandText = "DELETE FROM WeekEnding WHERE EndOfWeekDate = @dateString"; oleDbCommand.Parameters.Clear(); oleDbCommand.Parameters.AddWithValue("@dateString", dateString); numberOfRowsEffected = oleDbCommand.ExecuteNonQuery(); if (numberOfRowsEffected > 1) { //Deletion of extra dates has completed successfully so add in the provided date string. oleDbCommand.CommandText = "INSERT INTO WeekEnding(EndOfWeekDate) VALUES(@dateString)"; oleDbCommand.Parameters.Clear(); oleDbCommand.Parameters.AddWithValue("@dateString", dateString); numberOfRowsEffected = oleDbCommand.ExecuteNonQuery(); if (numberOfRowsEffected != 1) { //? logConsole.WriteToLog(LogConsole.Level.Debug, "An error has occurred attempting to insert the date " + dateString + " into the week ending table."); } } } else if (numberOfRowsEffected == 0) { oleDbCommand.CommandText = "INSERT INTO WeekEnding(EndOfWeekDate) VALUES (?)"; oleDbCommand.Parameters.Clear(); oleDbCommand.Parameters.AddWithValue("dateString", dateString); numberOfRowsEffected = oleDbCommand.ExecuteNonQuery(); if (numberOfRowsEffected != 1) { //? logConsole.WriteToLog(LogConsole.Level.Debug, "An error has occurred attempting to insert the date " + dateString + " into the week ending table."); } else { insertWasSuccessful = true; } } } catch (OleDbException e) { logConsole.WriteToLog(LogConsole.Level.Error, "An error occurred trying to write a record to the Week Ending table."); logConsole.WriteToLog(LogConsole.Level.Debug, e.Message + "\n" + e.StackTrace); } finally { //Make certain that the connection is closed before returning. gConnectionObject.Close(); } return insertWasSuccessful; } public bool RedundantlessInsertIntoComments(string comments, string dateIdString) { //Again, assume a failed operation so there are no false positives. var insertWasSuccessful = false; var storedComment = ""; //Set up the command object, SQL command string and parameters. var oleDbCommand = new OleDbCommand(); oleDbCommand.Connection = gConnectionObject; //Try to execute the query try { int numberOfRowsEffected = 0; //IF one row was affected, then check to see if the comments are the same. //Check to see if the comments already exist. //TODO: Perform a little Regex magic to determine if the comments are just different due to spaces or small word changes. oleDbCommand.CommandText = "SELECT Comment FROM Comment WHERE FK_DateID = dateID"; oleDbCommand.Parameters.Clear(); oleDbCommand.Parameters.AddWithValue("dateID", dateIdString); gConnectionObject.Open(); //OpenConnection(); OleDbDataReader reader = oleDbCommand.ExecuteReader(); int recordIndex = 0; while (reader != null && reader.Read()) { if (recordIndex == 0) { storedComment = reader[0].ToString(); } else { storedComment += reader[0].ToString(); } if (storedComment != "") { recordIndex++; } } if (reader != null) reader.Close(); //IF there is a comment that has the same date then check to see if it is the same as the one entered. if (recordIndex == 1) { if (storedComment == comments) { //The comments match so return true. return true; } else { //ELSE the comments are different, therefore the entry needs to be updated. oleDbCommand.CommandText = "UPDATE Comment SET Comment.Comment = ? WHERE [Comment.FK_DateID] = ?;"; oleDbCommand.Parameters.Clear(); oleDbCommand.Parameters.AddWithValue("comment", storedComment + "\r\n" + comments); oleDbCommand.Parameters.AddWithValue("dateID", dateIdString); numberOfRowsEffected = oleDbCommand.ExecuteNonQuery(); if (numberOfRowsEffected == 1) { //Update was successful, so return true. return true; } else { logConsole.WriteToLog(LogConsole.Level.Error, "An error has occurred trying to update a comment with the date ID of " + dateIdString + "."); return false; } } } else if (recordIndex > 1) { //ELSE IF more then one record was found with the same date ID, then clear the redundancy and rewrite to the database. numberOfRowsEffected = 0; oleDbCommand.CommandText = "DELETE FROM Comment WHERE FK_DateID = dateID"; oleDbCommand.Parameters.Clear(); oleDbCommand.Parameters.AddWithValue("dateID", dateIdString); numberOfRowsEffected = oleDbCommand.ExecuteNonQuery(); if (numberOfRowsEffected > 1) { oleDbCommand.CommandText = "INSERT INTO Comment(Comment, FK_DateID) VALUES(comments, dateID)"; oleDbCommand.Parameters.Clear(); oleDbCommand.Parameters.AddWithValue("comments", storedComment + "\r\n" + comments); oleDbCommand.Parameters.AddWithValue("dateID", dateIdString); numberOfRowsEffected = oleDbCommand.ExecuteNonQuery(); if (numberOfRowsEffected == 1) { return true; } else { logConsole.WriteToLog(LogConsole.Level.Debug, "An error occurred trying to insert a new comment after attempting to delete redundant entries."); return false; } } else { logConsole.WriteToLog(LogConsole.Level.Debug, "An error occurred trying to delete redundant comments."); return false; } } //Reset the number effected so there is no confusion. numberOfRowsEffected = 0; //Now execute the INSERT statement since no redundancy was found. //The comments are not found to be used in the database anywhere, nor the date ID so add a brand new row. oleDbCommand.CommandText = "INSERT INTO Comment(Comment, FK_DateID) VALUES (comments, dateID)"; oleDbCommand.Parameters.Clear(); oleDbCommand.Parameters.AddWithValue("comments", comments); oleDbCommand.Parameters.AddWithValue("dateID", dateIdString); numberOfRowsEffected = oleDbCommand.ExecuteNonQuery(); if (numberOfRowsEffected == 1) { insertWasSuccessful = true; } else if (numberOfRowsEffected == 0) { logConsole.WriteToLog(LogConsole.Level.Error, "Failed to insert new comments into the Comment table."); insertWasSuccessful = false; } } catch (OleDbException e) { logConsole.WriteToLog(LogConsole.Level.Error, "An error occurred trying to write a record to the Comment table."); logConsole.WriteToLog(LogConsole.Level.Debug, "Message " + e.Message); } finally { //Make certain that the connection is closed before returning. gConnectionObject.Close(); } return insertWasSuccessful; } public List RedundantlessInsertIntoAPC(DataTable parameters) { //Check to see if the DataTable is empty, and if it is one return -1 as the error. if (parameters == null || parameters.Rows.Count == 0) { //Create new List variable and assign it to -1. var noRowsAdded = new List(); noRowsAdded.Add(-1); return noRowsAdded; } var rowsAdded = new List(); var rowNumber = 0; OpenConnection(); //DataTable's structure will reflect the APC database table structure. foreach (DataRow row in parameters.Rows) { var adItemID = ReturnAdItemIDFromAdItemString(row[16].ToString()); var dateID = row[18].ToString(); //The nineteenth (19th) entry is the dateID field. if (adItemID == "-1") { //IF the ad item could not be found in the database, add it in. adItemID = InsertAdItem(row[16].ToString()); //IF the ID is still -1, then something went wrong... if (adItemID == "-1") { //Add an error code to the end of the array; something went wrong adding the new item to the database. rowsAdded.Add(-1); return rowsAdded; } } if (!DoesEntryExist(adItemID, dateID)) { //IF the ad item isn't in the APC table with the specified date, then add it to the database. OleDbCommand oleDbCommand = new OleDbCommand(); int rowsEffected = 0; oleDbCommand.CommandText = "INSERT INTO APC(ProjectionSold, ProjectionSalePrice, ProjectionTotalSales, ProjectionCost, ProjectionProfitReturn, ProjectionTotalProfitReturn, BeginingInventory, Received, TotalInventory, EndingInventory, ActualSold, ActualSalePrice, ActualTotalSales, ActualCost, ActualProfitReturn, ActualTotalProfitReturn, FK_AdItemID, FK_GroupID, FK_DateID) VALUES (prSold, prSalesPrice, prTotalSales, prCost, prProfitReturn, prTotalProfitReturn, beginningInv, receivedInv, totalInv, endingInv, acSold, acSalePrice, acTotalSales, acCost, acProfitReturn, acTotalProfitReturn, adItemID, groupID, dateID)"; oleDbCommand.Parameters.AddWithValue("prSold", row[0]); oleDbCommand.Parameters.AddWithValue("prSalesPrice", row[1]); oleDbCommand.Parameters.AddWithValue("prTotalSales", row[2]); oleDbCommand.Parameters.AddWithValue("prCost", row[3]); oleDbCommand.Parameters.AddWithValue("prProfitReturn", row[4]); oleDbCommand.Parameters.AddWithValue("prTotalProfitReturn", row[5]); oleDbCommand.Parameters.AddWithValue("beginingInv", row[6]); oleDbCommand.Parameters.AddWithValue("receivedInv", row[7]); oleDbCommand.Parameters.AddWithValue("totalInv", row[8]); oleDbCommand.Parameters.AddWithValue("endingInv", row[9]); oleDbCommand.Parameters.AddWithValue("acSold", row[10]); oleDbCommand.Parameters.AddWithValue("acSalesPrice", row[11]); oleDbCommand.Parameters.AddWithValue("acTotalSales", row[12]); oleDbCommand.Parameters.AddWithValue("acCost", row[13]); oleDbCommand.Parameters.AddWithValue("acProfitReturn", row[14]); oleDbCommand.Parameters.AddWithValue("acTotalProfitReturn", row[15]); oleDbCommand.Parameters.AddWithValue("adItemID", adItemID); oleDbCommand.Parameters.AddWithValue("groupID", row[17]); oleDbCommand.Parameters.AddWithValue("dateID", row[18]); oleDbCommand.Connection = gConnectionObject; try { OleDbDataReader reader = oleDbCommand.ExecuteReader(); while (reader.Read()) { rowsEffected++; } rowsAdded.Add(rowNumber); } catch (OleDbException e) { logConsole.WriteToLog(LogConsole.Level.Error, "An error occurred trying to write a record to the APC table."); logConsole.WriteToLog(LogConsole.Level.Debug, e.Message + "\n" + e.StackTrace); gConnectionObject.Close(); //Add an error code at the end of array of rows that were added to show an error occurred. rowsAdded.Add(-1); return rowsAdded; } } else { //Perform an update operation on the row in question. if (!UpdateRow(adItemID, dateID, row)) { //IF the update fails, then return with an error appended to the end of the array. rowsAdded.Add(-1); logConsole.WriteToLog(LogConsole.Level.Error, "An error occurred trying to update a record APC table."); logConsole.WriteToLog(LogConsole.Level.Debug, "An error occurred trying to update ad item ID " + adItemID + " and dateID " + dateID + "."); return rowsAdded; } } rowNumber++; } //Close the database connection before returning. gConnectionObject.Close(); return rowsAdded; } /// /// Infrastructure for the DatabaseWriter class, not meant to be used with external code; expects an open connection when called. /// Checks to see if an ad item exists based on its end of week date. /// /// The ID of the item. /// The ID of the end of week date. /// True if the item exists, or false if it doesn't. private bool DoesEntryExist(string adItemID, string dateID) { var exists = false; var oleDbCommand = new OleDbCommand(); var rowsEffected = 0; oleDbCommand.CommandText = "SELECT ID FROM APC WHERE FK_AdItemID = adItemID AND FK_DateID = dateID"; oleDbCommand.Parameters.AddWithValue("adItemID", adItemID); oleDbCommand.Parameters.AddWithValue("dateID", dateID); oleDbCommand.Connection = gConnectionObject; //OpenConnection(); try { var reader = oleDbCommand.ExecuteReader(); while (reader != null && reader.Read()) { rowsEffected++; } } catch (OleDbException ex) { logConsole.WriteToLog(LogConsole.Level.Error, "An error occurred trying to check for the existence of an ad item with the ID of " + adItemID + "."); logConsole.WriteToLog(LogConsole.Level.Debug, ex.Message); } if (rowsEffected == 1) { exists = true; } else if (rowsEffected > 1) { //Throw custom exception, or add a function to correct this issue. logConsole.WriteToLog(LogConsole.Level.Critical, "A redundant entry has been found with the following values: AdItemID " + adItemID + " and DateID " + dateID + "."); exists = true; } return exists; } /// /// Infrastructure for the DatabaseWriter class, not meant to be used with external code; expects an open connection when called. /// This method adds a specified ad item to the database's ad item table. /// /// The name of the ad item. /// The ID number of the ad item, or -1 on fail. private string InsertAdItem(string adItemName) { //Remove all nulls from the adItemName and check if it is null. string cleanedAdItemName = adItemName.Replace(" ", ""); if (adItemName == "") { // //throw new System.ArgumentException("Attempted to insert a null ad item name into the database."); return "-1"; } else if (cleanedAdItemName.Length == 1) { // //throw new System.ArgumentException("Attempted to insert an ad item name with invalid length."); return "-1"; } //Record the number of rows affected when the statement is executed, again assume nothing was affected. var adItemID = "-1"; var rowsEffected = 0; var oleDbCommand = new OleDbCommand(); oleDbCommand.CommandText = "INSERT INTO AdItem (AdItem) VALUES (?)"; oleDbCommand.Parameters.AddWithValue("adItem", adItemName); oleDbCommand.Connection = gConnectionObject; //Attempt to execute the INSERT SQL statement. try { rowsEffected = oleDbCommand.ExecuteNonQuery(); //IF one (1) row was affected, then get the ad item's ID and set it to the return value. if (rowsEffected == 1) { //Modify the OleDbCommand object to query the ad item with the highest ID value since that would be the most recent item added. oleDbCommand.CommandText = "SELECT ID FROM AdItem WHERE ID = (SELECT MAX(AdItem.ID) FROM AdItem)"; OleDbDataReader reader = oleDbCommand.ExecuteReader(); while (reader != null && reader.Read()) { adItemID = reader[0].ToString(); } reader.Close(); } //ELSE IF more then one (1) row was affected... else if (rowsEffected > 1) { //? } //ELSE IF no rows are effected due to an uncaught exception, log it. else if (rowsEffected == 0) { logConsole.WriteToLog(LogConsole.Level.Critical, "Failed to add " + adItemName + " into the database; zero (0) rows affected."); return "-1"; } } catch (OleDbException ex) { logConsole.WriteToLog(LogConsole.Level.Error, "An error occurred trying to add " + adItemName + " to the database."); logConsole.WriteToLog(LogConsole.Level.Debug, ex.Message); } return adItemID; } /// /// Infrastructure for the DatabaseWriter class, not meant to be used with external code; expects an open connection when called. /// Returns the ad item ID from the ad item's name. /// /// The ID of the specified item. private string ReturnAdItemIDFromAdItemString(string adItemName) { var ID = "-1"; decimal dec = 0; //Clear all invalid characters and check if its a null entry. if (adItemName.Replace(" " , "") == "") { //throw? return ID; } if (Decimal.TryParse(adItemName, out dec)) { //A number has been found so error out. return "-1"; } OleDbCommand oleDbCommand = new OleDbCommand(); oleDbCommand.CommandText = "SELECT ID FROM AdItem WHERE AdItem.AdItem = adItemName"; oleDbCommand.Parameters.AddWithValue("adItemName", adItemName); oleDbCommand.Connection = gConnectionObject; OpenConnection(); try { var adItemID = ""; var reader = oleDbCommand.ExecuteReader(); while (reader != null && reader.Read()) { adItemID = reader[0].ToString(); } //Grab the ad item's ID. if (adItemID != "") { ID = adItemID; } else { //Return -1 as the ad item doesn't exist. return ID; } } catch (OleDbException ex) { logConsole.WriteToLog(LogConsole.Level.Error, "An error occurred trying to obtain the ad item ID for " + adItemName + "."); logConsole.WriteToLog(LogConsole.Level.Debug, "Error Message " + ex.Message); } return ID; } /// /// Infrastructure for the DatabaseWriter class, not meant to be used with external code; expects an open connection when called. /// Performs an update operation on the row with matching IDs in the ad item and date ID columns. /// This is to be called when an ad item already exists and simply needs updating with new values. /// /// /// /// /// private bool UpdateRow(string adItemID, string dateID, DataRow parameters) { bool updateSuccessful = false; int numberOfRowsEffected = 0; OleDbCommand oleDbCommand = new OleDbCommand(); oleDbCommand.CommandText = "UPDATE APC SET ProjectionSold = ?, ProjectionSalePrice = ?, ProjectionTotalSales = ?, ProjectionCost = ?, ProjectionProfitReturn = ?, ProjectionTotalProfitReturn = ?, BeginingInventory = ?, Received = ?, TotalInventory = ?, EndingInventory = ?, ActualSold = ?, ActualSalePrice = ?, ActualTotalSales = ?, ActualCost = ?, ActualProfitReturn = ?, ActualTotalProfitReturn = ?, FK_GroupID = ? WHERE FK_DateID = ? AND FK_AdItemID = ?"; oleDbCommand.Parameters.AddWithValue("prSold", parameters[0]); oleDbCommand.Parameters.AddWithValue("prSalesPrice", parameters[1]); oleDbCommand.Parameters.AddWithValue("prTotalSales", parameters[2]); oleDbCommand.Parameters.AddWithValue("prCost", parameters[3]); oleDbCommand.Parameters.AddWithValue("prProfitReturn", parameters[4]); oleDbCommand.Parameters.AddWithValue("prTotalProfitReturn", parameters[5]); oleDbCommand.Parameters.AddWithValue("beginingInv", parameters[6]); oleDbCommand.Parameters.AddWithValue("receivedInv", parameters[7]); oleDbCommand.Parameters.AddWithValue("totalInv", parameters[8]); oleDbCommand.Parameters.AddWithValue("endingInv", parameters[9]); oleDbCommand.Parameters.AddWithValue("acSold", parameters[10]); oleDbCommand.Parameters.AddWithValue("acSalesPrice", parameters[11]); oleDbCommand.Parameters.AddWithValue("acTotalSales", parameters[12]); oleDbCommand.Parameters.AddWithValue("acCost", parameters[13]); oleDbCommand.Parameters.AddWithValue("acProfitReturn", parameters[14]); oleDbCommand.Parameters.AddWithValue("acTotalProfitReturn", parameters[15]); oleDbCommand.Parameters.AddWithValue("groupID", parameters[17]); oleDbCommand.Parameters.AddWithValue("dateID", parameters[18]); oleDbCommand.Parameters.AddWithValue("adItemID", adItemID); oleDbCommand.Connection = gConnectionObject; try { numberOfRowsEffected = oleDbCommand.ExecuteNonQuery(); if (numberOfRowsEffected == 1) { updateSuccessful = true; } else if (numberOfRowsEffected > 1) //? { logConsole.WriteToLog(LogConsole.Level.Warning, "Redundancy found: Ad item ID " + parameters[0] + " (" + parameters[16] + ") and date ID " + parameters[18] + "."); updateSuccessful = true; } logConsole.WriteToLog(LogConsole.Level.Info, "Affected " + numberOfRowsEffected + " updating the ad item " + parameters[16] + "."); } catch (OleDbException ex) { logConsole.WriteToLog(LogConsole.Level.Error, "Failed to update ad item with the ID of " + parameters[0] + " (" + parameters[16] + ") and a date ID of " + parameters[18] + "."); logConsole.WriteToLog(LogConsole.Level.Debug, ex.Message); return false; } return updateSuccessful; } /// /// /// /// A copy of the Supplier DataGridView table. /// public List RedundantlessInsertIntoInvoice(DataTable parameters) { //Create an array that hold the indexes of all the rows that were successfully written to the database. var rowsAdded = new List(); var supplierId = ""; //Setup object for each of the three (3) tasks that need to be performed. //Checking for the ID of a particular supplier, by name. var supplierQueryCommand = new OleDbCommand(); supplierQueryCommand.CommandText = "SELECT ID FROM Supplier WHERE SupplierName = ?"; supplierQueryCommand.Connection = gConnectionObject; //Grabbing the ID of the invoice by the invoice number and the supplier's ID. var invoiceCheckCommand = new OleDbCommand(); invoiceCheckCommand.CommandText = "SELECT ID FROM Invoice WHERE InvoiceNumber = ? AND FK_Supplier = ?"; invoiceCheckCommand.Connection = gConnectionObject; //Inserting a new record into the Invoice table. var insertNewInvoice = new OleDbCommand(); insertNewInvoice.CommandText = "INSERT INTO Invoice (InvoiceDate, InvoiceNumber, InvoiceNetAmountAtCost, InvoiceNetAmount, InvoiceNote, FK_Supplier, FK_DateID) VALUES (?, ?, ?, ?, ?, ?, ?)"; insertNewInvoice.Connection = gConnectionObject; OpenConnection(); foreach (DataRow row in parameters.Rows) { var itemCount = 0; var index = 0; foreach (var obj in row.ItemArray) { //Check for null objects, row size is 8 on creation for some reason. if (index < 7) { if ((string)obj != "") { itemCount++; } else { row[index] = 0; } } index++; } if (itemCount < 2) { break; } var recordCount = 0; try { //Check for the existence of the supplier to be written. supplierQueryCommand.Parameters.Clear(); supplierQueryCommand.Parameters.AddWithValue("SupplierName", row[1]); var reader = supplierQueryCommand.ExecuteReader(); //Read in the value(s) from the database. while (reader != null && reader.Read()) { if (recordCount == 0) { supplierId = reader[0].ToString(); } recordCount++; } reader.Close(); //IF no records were pulled, then ad the supplier's name into the database and pull the ID for the new entry. if (recordCount == 0) { supplierId = InsertSupplier(row[1].ToString()); if (supplierId != "-1") { recordCount = 1; } //ELSE IF the supplier ID wasn't set, indicting an error, so break out of the loop and add -1 to the end of the rows effected array. else { rowsAdded.Add(-1); break; } } //IF the supplier exists in the database, then check for the presence of the supplier and the supplied invoice number. if (recordCount == 1) { invoiceCheckCommand.Parameters.Clear(); invoiceCheckCommand.Parameters.AddWithValue("InvoiceNumber", row[2]); invoiceCheckCommand.Parameters.AddWithValue("SupplierID", supplierId); reader = invoiceCheckCommand.ExecuteReader(); recordCount = 0; while (reader != null && reader.Read()) { recordCount++; } if (reader != null) reader.Close(); //IF the entry does exist, then update it with the new information provided. if (recordCount == 1) { //Call the update function and attempt to update the information. if (!UpdateInvoice(row, supplierId)) { //IF the update failed log the failure, add in a failure at the row that failed, and break out. //LOGGING GOES HERE logConsole.WriteToLog(LogConsole.Level.Error, "Failed to update the record for " + row[1] + "."); rowsAdded.Add(-1); break; } } else if (recordCount > 1) { //TODO: Clean up the database's redundant entries. } else if (recordCount == 0) { //ELSE IF no records were found, then insert the new invoice into the Invoice table. insertNewInvoice.Parameters.Clear(); insertNewInvoice.Parameters.AddWithValue("InvoiceDate", row[0]); insertNewInvoice.Parameters.AddWithValue("InvoiceNumber", row[2]); insertNewInvoice.Parameters.AddWithValue("InvoiceNetAmountAtCost", row[3]); insertNewInvoice.Parameters.AddWithValue("InvoiceNetAmount", row[4]); insertNewInvoice.Parameters.AddWithValue("InvoiceNote", row[5]); insertNewInvoice.Parameters.AddWithValue("SupplierID", supplierId); insertNewInvoice.Parameters.AddWithValue("DateID", row[6]); var rowsEffected = insertNewInvoice.ExecuteNonQuery(); if (rowsEffected == 1) continue; logConsole.WriteToLog(LogConsole.Level.Error, "Failed to write new invoice to the database for supplier " + row[1] + " ID of " + supplierId + "."); rowsAdded.Add(-1); break; } } //ELSE IF more then one record was found, clean up the redundancy. else if (recordCount > 1) { logConsole.WriteToLog(LogConsole.Level.Info, "Redundancy found in the invoices table with supplier " + row[1] + "."); } } catch (OleDbException e) { logConsole.WriteToLog(LogConsole.Level.Error, "Failed to write supplier " + row[1] + " into the invoice table."); logConsole.WriteToLog(LogConsole.Level.Debug, e.Message); break; } } gConnectionObject.Close(); return rowsAdded; } /// /// Infrastructure for the DatabaseWriter class, not meant to be used with external code; expects an open connection when called. /// /// /// /// private string InsertSupplier(string supplierName) { if (supplierName == "") { return "-1"; } var supplierNameId = "-1"; var oleDbCommand = new OleDbCommand {CommandText = "INSERT INTO Supplier (SupplierName) VALUES (?)"}; oleDbCommand.Parameters.AddWithValue("SupplierName", supplierName); oleDbCommand.Connection = gConnectionObject; try { int rowsEffected = 0; rowsEffected = oleDbCommand.ExecuteNonQuery(); if (rowsEffected == 1) { oleDbCommand.CommandText = "SELECT ID FROM Supplier WHERE ID = (SELECT MAX(Supplier.ID) FROM Supplier)"; var reader = oleDbCommand.ExecuteReader(); while (reader != null && reader.Read()) { supplierNameId = reader[0].ToString(); } } else if (rowsEffected > 1) { //TODO: Clean up the database. } else { logConsole.WriteToLog(LogConsole.Level.Critical, "Failed to write supplier name " + supplierName + " to the suppliers table."); } } catch (OleDbException e) { logConsole.WriteToLog(LogConsole.Level.Critical, "Failed to write supplier name " + supplierName + "."); logConsole.WriteToLog(LogConsole.Level.Debug, e.Message); } return supplierNameId; } /// /// Infrastructure for the DatabaseWriter class, not meant to be used with external code; expects an open connection when called. /// /// /// /// private bool UpdateInvoice(DataRow invoiceField, string supplierID) { var updateSuccessful = false; var oleDbCommand = new OleDbCommand { CommandText = "UPDATE Invoice SET InvoiceDate = ?, InvoiceNetAmountAtCost = ?, InvoiceNetAmount = ?, InvoiceNote = ? WHERE InvoiceNumber = ? AND FK_Supplier = ? AND FK_DateID = ?" }; oleDbCommand.Parameters.AddWithValue("InvoiceDate", invoiceField[0]); oleDbCommand.Parameters.AddWithValue("InvoiceNetAmountAtCost", invoiceField[3]); oleDbCommand.Parameters.AddWithValue("InvoiceNetAmount", invoiceField[4]); oleDbCommand.Parameters.AddWithValue("InvoiceNote", invoiceField[5]); oleDbCommand.Parameters.AddWithValue("InvoiceNumber", invoiceField[2]); oleDbCommand.Parameters.AddWithValue("SupplierID", supplierID); oleDbCommand.Parameters.AddWithValue("DateID", invoiceField[6]); oleDbCommand.Connection = gConnectionObject; try { var rowsEffected = oleDbCommand.ExecuteNonQuery(); if (rowsEffected == 1) { updateSuccessful = true; } else { logConsole.WriteToLog(LogConsole.Level.Error, "Failed to update record with invoice number " + invoiceField[2] + " for " + invoiceField[1] + "."); } } catch (OleDbException e) { logConsole.WriteToLog(LogConsole.Level.Error, "Failed to update invoice record invoice number " + invoiceField[2] + " for supplier " + invoiceField[1] + "."); logConsole.WriteToLog(LogConsole.Level.Error, e.Message); } return updateSuccessful; } /// /// /// /// /// public int RedundantlessInsertIntoWeeklySales(DataRow parameters) { var rowsEffected = 0; var recordsRead = 0; //Object to check for the presence of an entry with the supplied date. var weekEndingDateCheck = new OleDbCommand { CommandText = "SELECT ID FROM WeeklySales WHERE FK_DateID = ?" }; weekEndingDateCheck.Parameters.AddWithValue("DateID", parameters[8]); weekEndingDateCheck.Connection = gConnectionObject; //Object to update a field with the date supplied, assuming an entry was found with the previous object. var updateWeeklySales = new OleDbCommand { CommandText = "UPDATE WeeklySales SET Sunday = ?, Monday = ?, Tuesday = ?, Wednesday = ?, Thursday = ?, Friday = ?, Saturday = ?, TotalSales = ? WHERE FK_DateID = ?" }; updateWeeklySales.Parameters.AddWithValue("Sunday", parameters[0]); updateWeeklySales.Parameters.AddWithValue("Monday", parameters[1]); updateWeeklySales.Parameters.AddWithValue("Tuesday", parameters[2]); updateWeeklySales.Parameters.AddWithValue("Wednesday", parameters[3]); updateWeeklySales.Parameters.AddWithValue("Thursday", parameters[4]); updateWeeklySales.Parameters.AddWithValue("Friday", parameters[5]); updateWeeklySales.Parameters.AddWithValue("Saturday", parameters[6]); updateWeeklySales.Parameters.AddWithValue("TotalSales", parameters[7]); updateWeeklySales.Parameters.AddWithValue("DateID", parameters[8]); updateWeeklySales.Connection = gConnectionObject; //Object to insert a new field into the database if no entry is present. var insertWeeklySales = new OleDbCommand { CommandText = "INSERT INTO WeeklySales (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, TotalSales, FK_DateID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)" }; insertWeeklySales.Parameters.AddWithValue("Sunday", parameters[0]); insertWeeklySales.Parameters.AddWithValue("Monday", parameters[1]); insertWeeklySales.Parameters.AddWithValue("Tuesday", parameters[2]); insertWeeklySales.Parameters.AddWithValue("Wednesday", parameters[3]); insertWeeklySales.Parameters.AddWithValue("Thursday", parameters[4]); insertWeeklySales.Parameters.AddWithValue("Friday", parameters[5]); insertWeeklySales.Parameters.AddWithValue("Saturday", parameters[6]); insertWeeklySales.Parameters.AddWithValue("TotalSales", parameters[7]); insertWeeklySales.Parameters.AddWithValue("DateID", parameters[8]); insertWeeklySales.Connection = gConnectionObject; //Open the connection to the database. OpenConnection(); try { //Execute the select statement to check for the presence of an entry with the supplied date (parameters[8]). var reader = weekEndingDateCheck.ExecuteReader(); while (reader != null && reader.Read()) { recordsRead++; } //IF there are no records with the date ID then add the current sales into the database. if (recordsRead == 0) { rowsEffected = insertWeeklySales.ExecuteNonQuery(); } //ELSE IF one already exists, then update it with the information provided. else if (recordsRead == 1) { rowsEffected = updateWeeklySales.ExecuteNonQuery(); } //ELSE IF more then one entry is detected, remove all redundant entries and insert the current sales into the database. else if (recordsRead > 1) { //TODO: clean up the redundant entries. } } catch (OleDbException e) { logConsole.WriteToLog(LogConsole.Level.Error, "An error has occurred trying to write the weekly sales to the database."); logConsole.WriteToLog(LogConsole.Level.Debug, e.Message); } finally { gConnectionObject.Close(); } return rowsEffected; } public int RedundantlessInsertIntoGroupCategory(string groupName) { // var rowsEffected = 0; //Setup an object to check for the existence of the group name to be added. var categoryDescCheckQueryCommand = new OleDbCommand { CommandText = "SELECT ID FROM GroupCategory WHERE GroupDescription = ?" }; categoryDescCheckQueryCommand.Parameters.AddWithValue("GroupName", groupName); categoryDescCheckQueryCommand.Connection = gConnectionObject; //Setting up an object to insert a new ad special keyword. var insertNewCategoryDesc = new OleDbCommand { CommandText = "INSERT INTO GroupCategory (GroupDescription) VALUES (?)" }; insertNewCategoryDesc.Parameters.AddWithValue("GroupName", groupName); insertNewCategoryDesc.Connection = gConnectionObject; try { OpenConnection(); var reader = categoryDescCheckQueryCommand.ExecuteReader(); while (reader != null && reader.Read()) { rowsEffected++; } reader.Close(); if (rowsEffected == 0) { rowsEffected = insertNewCategoryDesc.ExecuteNonQuery(); if (rowsEffected == 0) { logConsole.WriteToLog(LogConsole.Level.Error, "An error has occurred trying to insert " + groupName + " into the database."); } } } catch (OleDbException ex) { logConsole.WriteToLog(LogConsole.Level.Error, "An error has occurred trying to write a new ad special key word to the database."); logConsole.WriteToLog(LogConsole.Level.Debug, ex.Message); } finally { gConnectionObject.Close(); } return rowsEffected; } public int RemoveRecord(string adItemId, string dateId) { var recordsDeleted = 0; var deleteCommand = new OleDbCommand { CommandText = "DELETE FROM APC WHERE FK_AdItemID = ? AND FK_DateID = ?" }; deleteCommand.Parameters.AddWithValue("AdItemID", adItemId); deleteCommand.Parameters.AddWithValue("DateID", dateId); deleteCommand.Connection = gConnectionObject; try { gConnectionObject.Open(); recordsDeleted = deleteCommand.ExecuteNonQuery(); } catch (OleDbException e) { logConsole.WriteToLog(LogConsole.Level.Error, "Failed to delete the record with an ad item ID of " + adItemId + " and a date ID of " + dateId + "."); logConsole.WriteToLog(LogConsole.Level.Debug, e.Message); } finally { gConnectionObject.Close(); } return recordsDeleted; } public int RemoveInvoice(string invoiceNumber, string dateId) { var recordsAffected = 0; var oleDbCommand = new OleDbCommand() { CommandText = "DELETE FROM Invoice WHERE InvoiceNumber = ? AND FK_DateID = ?" }; oleDbCommand.Parameters.AddWithValue("InvoiceNumber", invoiceNumber); oleDbCommand.Parameters.AddWithValue("DateID", dateId); oleDbCommand.Connection = gConnectionObject; try { gConnectionObject.Open(); recordsAffected = oleDbCommand.ExecuteNonQuery(); } catch (OleDbException e) { logConsole.WriteToLog(LogConsole.Level.Error, "Failed to delete invoice number " + invoiceNumber + " with the date ID of " + dateId + "."); logConsole.WriteToLog(LogConsole.Level.Debug, e.Message); } finally { gConnectionObject.Close(); } return recordsAffected; } /// /// Removes all records by the date ID passed in, and also removes /// the year's entry from the WeekEnding table. /// /// The ID of the date to be purged. /// The number of records cleared from the database. public int RemoveAllEntriesAndYearById(string dateId) { var recordsRemoved = 0; //Object to clear the APC records associated with the date ID. var clearAPCommand = new OleDbCommand() { CommandText = "DELETE FROM APC WHERE FK_DateID = ?" }; clearAPCommand.Parameters.AddWithValue("DateID", dateId); clearAPCommand.Connection = gConnectionObject; //Object to clear comments associated with the date ID. var clearCommentsCommand = new OleDbCommand() { CommandText = "DELETE FROM Comment WHERE FK_DateID = ?" }; clearCommentsCommand.Parameters.AddWithValue("DateID", dateId); clearCommentsCommand.Connection = gConnectionObject; //Object to clear the invoices associated with the date ID. var clearInvoicesCommand = new OleDbCommand() { CommandText = "DELETE FROM Invoice WHERE FK_DateID = ?" }; clearInvoicesCommand.Parameters.AddWithValue("DateID", dateId); clearInvoicesCommand.Connection = gConnectionObject; //Object to clear the weekly sales associated with the date ID. var clearWeeklySalesCommand = new OleDbCommand() { CommandText = "DELETE FROM WeeklySales WHERE FK_DateID = ?" }; clearWeeklySalesCommand.Parameters.AddWithValue("DateID", dateId); clearWeeklySalesCommand.Connection = gConnectionObject; //Object to clear the date associated with the ID passed in. var clearEndOfWeekDateCommand = new OleDbCommand() { CommandText = "DELETE FROM WeekEnding WHERE ID = ?" }; clearEndOfWeekDateCommand.Parameters.AddWithValue("DateID", dateId); clearEndOfWeekDateCommand.Connection = gConnectionObject; try { gConnectionObject.Open(); recordsRemoved += clearAPCommand.ExecuteNonQuery(); recordsRemoved += clearCommentsCommand.ExecuteNonQuery(); recordsRemoved += clearInvoicesCommand.ExecuteNonQuery(); recordsRemoved += clearWeeklySalesCommand.ExecuteNonQuery(); recordsRemoved += clearEndOfWeekDateCommand.ExecuteNonQuery(); } catch (OleDbException e) { logConsole.WriteToLog(LogConsole.Level.Error, "And error has occurred attempting to delete all records associated with the date ID of " + dateId + "."); logConsole.WriteToLog(LogConsole.Level.Debug, e.Message); } finally { gConnectionObject.Close(); } return recordsRemoved; } /// /// Updates the comments stored in a particular date. /// TODO: Fix this bug... /// IF the delete command deletes more then one row it returns 0. /// /// /// /// Returns true if the row is deleted and false if a row fails to be deleted. public bool UpdateCommentsByDateId(string comment, string dateId) { bool wasSuccessful = false; var oleDbCommand = new OleDbCommand() { CommandText = "UPDATE Comment SET Comment.Comment = ? WHERE FK_DateID = ?" }; oleDbCommand.Parameters.AddWithValue("Comment", comment); oleDbCommand.Parameters.AddWithValue("DateID", dateId); oleDbCommand.Connection = gConnectionObject; try { //IF the delete command deletes more then one row it returns 0. gConnectionObject.Open(); var recordsEffected = oleDbCommand.ExecuteNonQuery(); if (recordsEffected == 1) { wasSuccessful = true; } } catch (OleDbException e) { logConsole.WriteToLog(LogConsole.Level.Error, "And error has occurred attempting to update the comments for the date ID of " + dateId + "."); logConsole.WriteToLog(LogConsole.Level.Debug, e.Message); } finally { gConnectionObject.Close(); } return wasSuccessful; } } }