diff --git a/AdvertsingProfitControl/APCDatabase.accdb b/AdvertsingProfitControl/APCDatabase.accdb
index 4a5dad4..2d21841 100644
Binary files a/AdvertsingProfitControl/APCDatabase.accdb and b/AdvertsingProfitControl/APCDatabase.accdb differ
diff --git a/AdvertsingProfitControl/APCTemplate.accdb b/AdvertsingProfitControl/APCTemplate.accdb
deleted file mode 100644
index 5ba13bd..0000000
Binary files a/AdvertsingProfitControl/APCTemplate.accdb and /dev/null differ
diff --git a/AdvertsingProfitControl/AdvertisingProfitControlTableHelper.cs b/AdvertsingProfitControl/AdvertisingProfitControlTableHelper.cs
index 79b4bd5..e085326 100644
--- a/AdvertsingProfitControl/AdvertisingProfitControlTableHelper.cs
+++ b/AdvertsingProfitControl/AdvertisingProfitControlTableHelper.cs
@@ -418,16 +418,4 @@ namespace AdvertsingProfitControl
InvoiceNote = 6,
IsDirty = 7
}
-
- ///
- /// TODO: Push into a stand alone object.
- ///
- public enum TrimmingOperationResult
- {
- FailedToTrim = 0,
- CreatedNewInsertionTable = 1,
- CreatedUpdateTable = 2,
- CreatedNewInsertionAndUpdateTables = 3,
- NoChangesRequired = 4
- }
}
diff --git a/AdvertsingProfitControl/AdvertsingProfitControl.csproj b/AdvertsingProfitControl/AdvertsingProfitControl.csproj
index 009e534..e3d9a27 100644
--- a/AdvertsingProfitControl/AdvertsingProfitControl.csproj
+++ b/AdvertsingProfitControl/AdvertsingProfitControl.csproj
@@ -254,9 +254,6 @@
Always
-
- Always
-
diff --git a/AdvertsingProfitControl/FrmMain.cs b/AdvertsingProfitControl/FrmMain.cs
index 3e90fdb..5d9685a 100644
--- a/AdvertsingProfitControl/FrmMain.cs
+++ b/AdvertsingProfitControl/FrmMain.cs
@@ -14,10 +14,10 @@ namespace AdvertsingProfitControl
{
public partial class FrmMain : Form
{
- private double _salesProducedByAdItems;
- private double _totalProfitReturnFromAdItems;
- private double _totalInvoicePurchases; //Total Purchases
- private double _departmentSales; //weekly sales total
+ private decimal _salesProducedByAdItems;
+ private decimal _totalProfitReturnFromAdItems;
+ private decimal _totalInvoicePurchases; //Total Purchases
+ private decimal _departmentSales; //weekly sales total
private DateTime _currentActiveDate;
private readonly FrmLogConsole _console = FrmLogConsole.GetStaticInstance;
private int _LazyPageCounter;
@@ -39,7 +39,7 @@ namespace AdvertsingProfitControl
monthCalendar.BoldedDates = db.WeekEndingDates.Select(zdate => zdate.EndingDate).ToArray();
ConstructApcDataGridViews();
ConstructInvoicesDataGridView();
- //RowParsing.AdSpecialGroups.AddRange(databaseReader.ReturnGroupNameList(databaseTracker.DatabaseConnectionString));
+ RowParsing.AdSpecialGroups.AddRange(db.AdSpecials.Select(x => x.Name));
//Select the most recent date from the database.
var recentDate = db.WeekEndingDates.OrderByDescending(x => x.EndingDate).FirstOrDefault();
if (recentDate != null)
@@ -51,14 +51,10 @@ namespace AdvertsingProfitControl
//projectionsDataGridView.KeyDown += FrmMain_KeyDown;
//var margin = new Margins(50, 50, 0, 0);
//_printDoc.DefaultPageSettings.Margins = margin;
- //var adItem = new AdItem {Name = "Celery"};
- //var db = new AdvertisingProfitControlContext();
- //db.AdItems.Add(adItem);
- //db.SaveChanges();
}
- private void CalculateProfitAnalysis(double shrink = 0.30)
+ private void CalculateProfitAnalysis(decimal shrink = 0.30m)
{
if (actualSalesDataGridView.Rows.Count == 0)
{
@@ -73,12 +69,12 @@ namespace AdvertsingProfitControl
var incompleteData = false;
//First grab the total sales and the total profit return generated by the actual sales of product.
if (
- double.TryParse(
+ decimal.TryParse(
actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[3].EditedFormattedValue
.ToString(), out _salesProducedByAdItems))
{
//The sales parsed properly so there is data in the cell. Next try to grab the total profit return.
- if (double.TryParse(
+ if (decimal.TryParse(
actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[6].EditedFormattedValue
.ToString(), out _totalProfitReturnFromAdItems))
{
@@ -112,7 +108,7 @@ namespace AdvertsingProfitControl
//Again assume the total profit return is larger then zero (0).
totalProfitFromAdItemsLabel.Text = @"Total Profit Return" + Environment.NewLine + @" From Ad Items (B): " + _totalProfitReturnFromAdItems.ToString("C");
//Shrink is being used as a place holder for Cross Profit % which is obtained by dividing the total profit return from the department weekly retail sales.
- var totalProfitReturnFromRemainingSales = shrink*remainingSales;
+ var totalProfitReturnFromRemainingSales = shrink * remainingSales;
//
totalProfitReturnFromRemaingLabel.Text = @"Total Profit Return" + Environment.NewLine + @" From Remaining Sales: " + totalProfitReturnFromRemainingSales.ToString("C");
var totalProfitReturn = _totalProfitReturnFromAdItems + totalProfitReturnFromRemainingSales;
@@ -242,12 +238,12 @@ namespace AdvertsingProfitControl
var dateId =
databaseReader.RetrieveDateIdByDateString(monthCalendar.SelectionStart.ToShortDateString(),
databaseTracker.DatabaseConnectionString);
- double remaingingSales = _departmentSales - _salesProducedByAdItems;
- double totalProfitReturnFromReminaingSales = remaingingSales*.3;
- double totalProfitReturn = _totalProfitReturnFromAdItems + totalProfitReturnFromReminaingSales;
- test.BuildFormFrontCompressedLayout(dateId, _departmentSales, _salesProducedByAdItems, remaingingSales,
- _totalProfitReturnFromAdItems, totalProfitReturnFromReminaingSales, totalProfitReturn,
- commentsTextBox.Text);
+ var remaingingSales = _departmentSales - _salesProducedByAdItems;
+ var totalProfitReturnFromReminaingSales = remaingingSales * .3m;
+ var totalProfitReturn = _totalProfitReturnFromAdItems + totalProfitReturnFromReminaingSales;
+ //test.BuildFormFrontCompressedLayout(dateId, _departmentSales, _salesProducedByAdItems, remaingingSales,
+ //_totalProfitReturnFromAdItems, totalProfitReturnFromReminaingSales, totalProfitReturn,
+ //commentsTextBox.Text);
test.RenderHtmlToImage();
backPageTest.GenerateWeeklyInventoryControlPage(dateId);
backPageTest.RenderHtmlToImage();
@@ -371,8 +367,11 @@ namespace AdvertsingProfitControl
LoadInventoryTable(dateRecord);
LoadActualSalesTable(dateRecord);
LoadInvoices(dateRecord);
- var note = db.Notes.Single(x => x.FkDateId == dateRecord.Id);
- commentsTextBox.Text = note.Remark;
+ if (db.Notes.Any(x => x.FkDateId == dateRecord.Id))
+ {
+ var note = db.Notes.Single(x => x.FkDateId == dateRecord.Id);
+ commentsTextBox.Text = note.Remark;
+ }
LoadWeeklySales(dateRecord);
LoadTaxable(dateRecord);
LoadCostAnalysis(dateRecord);
@@ -423,6 +422,7 @@ namespace AdvertsingProfitControl
}
}
//Now add the totals row.
+ if (projectionsDataGridView.RowCount == 0) return;
var totalsRow = new DataGridViewRow();
projectionsDataGridView.Rows.Add(totalsRow);
projectionsDataGridView.Rows[projectionsDataGridView.Rows.Count - 1].Cells[0].Value = "Total";
@@ -517,6 +517,7 @@ namespace AdvertsingProfitControl
}
}
//Now add the totals row.
+ if (actualSalesDataGridView.RowCount == 0) return;
var totalsRow = new DataGridViewRow();
actualSalesDataGridView.Rows.Add(totalsRow);
actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].Cells[0].Value = "Total";
@@ -553,7 +554,7 @@ namespace AdvertsingProfitControl
invoicesDataGridView.Rows[index].Cells[2].Value = invoice.InvoiceNumber;
invoicesDataGridView.Rows[index].Cells[3].Value = $@"{invoice.InvoiceNetAmountAtCost:N2}";
invoicesDataGridView.Rows[index].Cells[4].Value = $@"{invoice.InvoiceNetAmount:N2}";
- if (invoice.InvoiceNetAmount != null) _totalInvoicePurchases += (double)invoice.InvoiceNetAmount;
+ if (invoice.InvoiceNetAmount != null) _totalInvoicePurchases += (decimal) invoice.InvoiceNetAmount;
invoicesDataGridView.Rows[index].Cells[5].Value = invoice.InvoiceNote;
}
//Add the total purchases row to the invoice table.
@@ -574,19 +575,19 @@ namespace AdvertsingProfitControl
var weeklySales = db.WeeklySales.Where(x => x.WeekEndingDate.Id == dateRecord.Id).Select(x => x);
foreach (var sale in weeklySales)
{
- if (sale.Sunday != null) _departmentSales += (double)sale.Sunday;
+ if (sale.Sunday != null) _departmentSales += (decimal) sale.Sunday;
sundayWeeklySalesLabel.Text = @"Sunday: " + $@"{sale.Sunday:c}";
- if (sale.Monday != null) _departmentSales += (double)sale.Monday;
+ if (sale.Monday != null) _departmentSales += (decimal) sale.Monday;
mondayWeeklySalesLabel.Text = @"Monday: " + $@"{sale.Monday:c}";
- if (sale.Tuesday != null) _departmentSales += (double)sale.Tuesday;
+ if (sale.Tuesday != null) _departmentSales += (decimal) sale.Tuesday;
tuesadayWeeklySalesLabel.Text = @"Tuesday: " + $@"{sale.Tuesday:c}";
- if (sale.Wednesday != null) _departmentSales += (double)sale.Wednesday;
+ if (sale.Wednesday != null) _departmentSales += (decimal) sale.Wednesday;
wednesdayWeeklySalesLabel.Text = @"Wednesday: " + $@"{sale.Wednesday:c}";
- if (sale.Thursday != null) _departmentSales += (double)sale.Thursday;
+ if (sale.Thursday != null) _departmentSales += (decimal)sale.Thursday;
thursdayWeeklySalesLabel.Text = @"Thursday: " + $@"{sale.Thursday:c}";
- if (sale.Friday != null) _departmentSales += (double)sale.Friday;
+ if (sale.Friday != null) _departmentSales += (decimal) sale.Friday;
fridayWeeklySalesLabel.Text = @"Friday: " + $@"{sale.Friday:c}";
- if (sale.Saturday != null) _departmentSales += (double)sale.Saturday;
+ if (sale.Saturday != null) _departmentSales += (decimal) sale.Saturday;
saturdayWeeklySalesLabel.Text = @"Saturday: " + $@"{sale.Saturday:c}";
totalWeeklySalesLabel.Text = @"Total Sales: " + $@"{sale.TotalSales:c}";
}
@@ -608,6 +609,11 @@ namespace AdvertsingProfitControl
saturdayTaxableLabel.Text = @"Saturday: " + $@"{taxable.Saturday:c}";
totalTaxableLabel.Text = @"Total: " + $@"{taxable.Total:c}";
}
+ ////See if there are any items and see if any of them are holidays (have a value of zero).
+ //if (taxables.ToList().Count == 1)
+ //{
+ // var Spam = taxables.Select(x => x.)
+ //}
}
private void LoadCostAnalysis(WeekEndingDate dateRecord)
diff --git a/AdvertsingProfitControl/NewModifyRecord.cs b/AdvertsingProfitControl/NewModifyRecord.cs
index e3d3cba..a561561 100644
--- a/AdvertsingProfitControl/NewModifyRecord.cs
+++ b/AdvertsingProfitControl/NewModifyRecord.cs
@@ -2,10 +2,12 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
+using System.Data.Entity.Infrastructure;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
+using System.Transactions;
using System.Windows.Forms;
namespace AdvertsingProfitControl
@@ -15,13 +17,13 @@ namespace AdvertsingProfitControl
//http://stackoverflow.com/questions/6219454/efficient-way-to-remove-all-whitespace-from-string
private static readonly FrmLogConsole LogConsole = FrmLogConsole.GetStaticInstance;
//Create an array that contains all the ad items from the database.
- private readonly List _adItemCollection;
+ private List _adItemCollection;
//This object contains all the unused ad items.
private AutoCompleteStringCollection _trimmedAdItemCollection = new AutoCompleteStringCollection();
//Contains all the ad specials that are in the database (i.e. "Daily Coupons").
- private readonly AutoCompleteStringCollection _adSpecialList;
+ private readonly AutoCompleteStringCollection _adSpecialList = new AutoCompleteStringCollection();
//This object contains all the suppliers that were found in the database.
- private readonly AutoCompleteStringCollection _supplierCollection;
+ private readonly AutoCompleteStringCollection _supplierCollection = new AutoCompleteStringCollection();
//This array keeps track of the number of times an Ad Item is used, if used once then it may only be used AFTER an AdSpecialRow and only once after that.
//Once an item has been used twice, it will not appear again in the AutoCompleteSuggestions.
//The structure of the used ad item list is as follows:
@@ -42,120 +44,10 @@ namespace AdvertsingProfitControl
public NewModifyRecord(DateTime date)
{
InitializeComponent();
- //Start by grabbing all the AdItems and putting them into memory.
- var databaseTracker = new DatabaseTracker();
- var databaseReader = new DatabaseReader();
- weekEndingCalendar.BoldedDates = databaseReader.RetrieveDates(databaseTracker.DatabaseConnectionString).ToArray();
+ //
weekEndingCalendar.SelectionStart = date;
_currentActiveDate = date;
- weekEndingCalendar.DateChanged += ValidateDateChanged;
- //next pull all the ad items into memory.
- _adItemCollection = databaseReader.GetAdItemsSuggestionList(databaseTracker.DatabaseConnectionString);
- //Now pull all the suppliers and the ad special list into memory.
- _supplierCollection = databaseReader.GetSupplierSuggestionList(databaseTracker.DatabaseConnectionString);
- _adSpecialList = databaseReader.RetrieveAdSpecialList(databaseTracker.DatabaseConnectionString);
- //Initialize the used ad item collection.
- _usedAdItems[0] = new List();
- _usedAdItems[1] = new List();
- //Assign the events for the comments text box and display the remaining character count for the user.
- commentsTextBox.TextChanged += DisplayRemainingCommentCharacterCount;
- commentsGroupBox.Text = @"Comments (Characters Remaining: " + commentsTextBox.MaxLength + @")";
- //Setup the events for that the Projected and Actual Sales DataGridViews will share.
- //Events are assigned with regard to which event gets triggered first and so on..
- //Hook the row add event so we can paint a row number in the header cell of the row.
- projectionsDataGridView.RowsAdded += DisplayRowNumbers;
- inventoryDataGridView.RowsAdded += DisplayRowNumbers;
- actualSalesDataGridView.RowsAdded += DisplayRowNumbers;
- //Assign all the tables to store the cell's contents on enter so changes (if any) can be detected and flagged (marked as dirty).
- projectionsDataGridView.CellEnter += StoreBeginningCellValue;
- inventoryDataGridView.CellEnter += StoreBeginningCellValue;
- actualSalesDataGridView.CellEnter += StoreBeginningCellValue;
- //Update the contents of the used as item list on row leave.
- projectionsDataGridView.RowLeave += UpdateUsedAdItemCollectionOnRowLeave;
- inventoryDataGridView.RowLeave += UpdateUsedAdItemCollectionOnRowLeave;
- actualSalesDataGridView.RowLeave += UpdateUsedAdItemCollectionOnRowLeave;
- //Validate, clean and format the contents of the cell that fires the cell validating event.
- projectionsDataGridView.CellValidating += ValidateSalesDataGridViewCellContents;
- inventoryDataGridView.CellValidating += ValidateInventoryCellContents;
- actualSalesDataGridView.CellValidating += ValidateSalesDataGridViewCellContents;
- //Validate that the row the user is trying to leave is legal (has at least an ad item entered) and prevent the user from leaving the row is its not.
- projectionsDataGridView.RowValidating += ValidateProjectedRow;
- inventoryDataGridView.RowValidating += ValidateInventoryRow;
- actualSalesDataGridView.RowValidating += ValidateActualSalesRow;
- //Update the used ad item collection by removing the contents of the ad item column when a row is deleted.
- projectionsDataGridView.UserDeletingRow += UpdateUsedAdItemCollectionOnRowRemoving;
- inventoryDataGridView.UserDeletingRow += UpdateUsedAdItemCollectionOnRowRemoving;
- actualSalesDataGridView.UserDeletingRow += UpdateUsedAdItemCollectionOnRowRemoving;
- //Once a row has been removed update the other tables keep them uniform.
- projectionsDataGridView.RowsRemoved += ProjectionRowRemoved;
- inventoryDataGridView.RowsRemoved += InventoryRowRemoved;
- actualSalesDataGridView.RowsRemoved += ActualSalesRowRemoved;
- //Grab the underlying text box object in the ad item cell, and build an auto complete list for the user.
- projectionsDataGridView.EditingControlShowing += DisplayAutoCompleteOnEditingControlShowing;
- inventoryDataGridView.EditingControlShowing += DisplayAutoCompleteOnEditingControlShowing;
- actualSalesDataGridView.EditingControlShowing += DisplayAutoCompleteOnEditingControlShowing;
- //After all events have been set, construct the DataGridVeiws for use.
- ConstructApcDataGridViews();
- //Set-up events for the Invoice table.
- invoicesDataGridView.CellEnter += StoreBeginningCellValue;
- //Validate that the row the user is trying to leave is legal (has at least an ad item entered) and prevent the user from leaving the row is its not.
- invoicesDataGridView.RowValidating += ValidateInvoiceRow;
- //Validate, clean and format the contents of the cell that fires the cell validating event.
- invoicesDataGridView.CellValidating += ValidateInvoicesCellContents;
- //Grab the underlying text box object in the ad item cell, and build an auto complete list for the user.
- invoicesDataGridView.EditingControlShowing += DisplaySupplierAutoComleteOnEditingShadowControl;
- //Subscribe the method to allow the user to delete saved rows from the Invoices table.
- invoicesDataGridView.UserDeletingRow += UpdateInvoicesOnRowDeleting;
- //Finally build the last DataGridView for the form.
- ConstructInvoicesDataGridView();//No weekly sales table is nice.
- //Subscribe the comments text box to check if changes have been made on leave.
- commentsTextBox.Enter += StoreBeginningTextBoxValue;
- commentsTextBox.KeyDown += CheckForKeyCommand;
- commentsTextBox.Leave += CheckForTextChangeOnLeave;
- //Subscribe the weekly sales text boxes to validation, update required checks and auto-complete methods.
- sundayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
- sundayWeeklySalesTextBox.Validating += ValidateWeeklySales;
- mondayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
- mondayWeeklySalesTextBox.Validating += ValidateWeeklySales;
- tuesdayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
- tuesdayWeeklySalesTextBox.Validating += ValidateWeeklySales;
- wednesdayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
- wednesdayWeeklySalesTextBox.Validating += ValidateWeeklySales;
- thursdayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
- thursdayWeeklySalesTextBox.Validating += ValidateWeeklySales;
- fridayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
- fridayWeeklySalesTextBox.Validating += ValidateWeeklySales;
- saturdayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
- saturdayWeeklySalesTextBox.Validating += ValidateWeeklySales;
- totalWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
- totalWeeklySalesTextBox.Validating += ValidateWeeklySales;
- //Subscribe the taxable text boxes to validation and update events.
- sundayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
- sundayTaxableTextBox.Validating += ValidateTaxableFields;
- mondayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
- mondayTaxableTextBox.Validating += ValidateTaxableFields;
- tuesdayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
- tuesdayTaxableTextBox.Validating += ValidateTaxableFields;
- wednesdayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
- wednesdayTaxableTextBox.Validating += ValidateTaxableFields;
- thursdayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
- thursdayTaxableTextBox.Validating += ValidateTaxableFields;
- fridayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
- fridayTaxableTextBox.Validating += ValidateTaxableFields;
- saturdayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
- saturdayTaxableTextBox.Validating += ValidateTaxableFields;
- totalTaxableTextBox.Enter += StoreBeginningTextBoxValue;
- totalTaxableTextBox.Validating += ValidateTaxableFields;
- //Subscribe the Cost Analysis text boxes to the validation and update events.
- salesPerManHourTextBox.Enter += StoreBeginningTextBoxValue;
- salesPerManHourTextBox.Validating += ValidateCostAnalysisValues;
- salaryPercentageTextBox.Enter += StoreBeginningTextBoxValue;
- salaryPercentageTextBox.Validating += ValidateCostAnalysisValues;
- salaryDollarsTextBox.Enter += StoreBeginningTextBoxValue;
- salaryDollarsTextBox.Validating += ValidateCostAnalysisValues;
- suppliesTextBox.Enter += StoreBeginningTextBoxValue;
- suppliesTextBox.Validating += ValidateCostAnalysisValues;
- //
+ InitializeForm();
mainTabControl.TabPages.Remove(mainTabControl.TabPages[4]);
Text = @"Modify Record (Current Record: " + date.ToShortDateString() + @")";
_formRoll = FormRoll.ModifyRecord;
@@ -165,17 +57,38 @@ namespace AdvertsingProfitControl
public NewModifyRecord()
{
InitializeComponent();
- //Start by grabbing all the AdItems and putting them into memory.
- var databaseTracker = new DatabaseTracker();
- var databaseReader = new DatabaseReader();
- weekEndingCalendar.BoldedDates = databaseReader.RetrieveDates(databaseTracker.DatabaseConnectionString).ToArray();
- SetNewRecordDate(databaseReader.RetrieveMostRecentDate(databaseTracker.DatabaseConnectionString), 1);
+ var db = new AdvertisingProfitControlModel();
+ //Check to see if there are dates in the database.
+ if (db.WeekEndingDates.Any())
+ {
+ //The database is not empty, so grab the first value from descending.
+ var date = db.WeekEndingDates.OrderByDescending(x => x.EndingDate).FirstOrDefault();
+ if (date != null)
+ SetNewRecordDate(date.EndingDate, 1);
+ }
+ else
+ {
+ SetNewRecordDate(DateTime.Today);
+ }
_currentActiveDate = weekEndingCalendar.SelectionStart;
+ InitializeForm();
+ //_debugTabPage = mainTabControl.TabPages[4];
+ mainTabControl.TabPages.Remove(mainTabControl.TabPages[4]);
+ Text = @"Add New Record (Current Record: " + _currentActiveDate.ToShortDateString() + @")";
+ _formRoll = FormRoll.AddRecord;
+ addRecordButton.Text = @"Add Record";
+ }
+
+ public void InitializeForm()
+ {
+ var db = new AdvertisingProfitControlModel();
+ weekEndingCalendar.BoldedDates = db.WeekEndingDates.Select(zdate => zdate.EndingDate).ToArray();
+ weekEndingCalendar.DateChanged += ValidateDateChanged;
//next pull all the ad items into memory.
- _adItemCollection = databaseReader.GetAdItemsSuggestionList(databaseTracker.DatabaseConnectionString);
+ _adItemCollection = db.AdItems.Select(x => x.Name).ToList();
//Now pull all the suppliers and the ad special list into memory.
- _supplierCollection = databaseReader.GetSupplierSuggestionList(databaseTracker.DatabaseConnectionString);
- _adSpecialList = databaseReader.RetrieveAdSpecialList(databaseTracker.DatabaseConnectionString);
+ _supplierCollection.AddRange(db.Suppliers.Select(x => x.Name).ToArray());
+ _adSpecialList.AddRange(db.AdSpecials.Select(x => x.Name).ToArray());
//Initialize the used ad item collection.
_usedAdItems[0] = new List();
_usedAdItems[1] = new List();
@@ -277,12 +190,6 @@ namespace AdvertsingProfitControl
salaryDollarsTextBox.Validating += ValidateCostAnalysisValues;
suppliesTextBox.Enter += StoreBeginningTextBoxValue;
suppliesTextBox.Validating += ValidateCostAnalysisValues;
- //
- //_debugTabPage = mainTabControl.TabPages[4];
- mainTabControl.TabPages.Remove(mainTabControl.TabPages[4]);
- Text = @"Add New Record (Current Record: " + _currentActiveDate.ToShortDateString() + @")";
- _formRoll = FormRoll.AddRecord;
- addRecordButton.Text = @"Add Record";
}
public sealed override string Text
@@ -2559,37 +2466,8 @@ namespace AdvertsingProfitControl
{
if (_formRoll == FormRoll.AddRecord)
{
- //If the form is dirty then prompt the user to save changes.
- if (_isFormDirty)
- {
- var result = MessageBox.Show(
- @"Would you like to save the changes you have made to this record?", @"Changes Detected",
- MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
- if (result == DialogResult.Yes)
- {
- //Save the changes made to the database then clear and load the date picked by the user.
- if (SaveRecords(false))
- {
- informationLabel.Text = @"Saved all changes successfully." + Environment.NewLine;
- }
- else
- {
- errorLabel.Text = @"Failed to save all changes." + Environment.NewLine;
- }
- }
- else if (result == DialogResult.Cancel)
- {
- //Cancel this method, select the active current date and return.
- weekEndingCalendar.SelectionStart = _currentActiveDate;
- }
- //The "No" button doesn't need to be processed since it just means continue on with the method.
- }
- else
- {
- //Change the active date of the form.
- _currentActiveDate = e.Start;
- Text = Text = @"Add New Record (Current Record: " + e.Start.ToString("d") + @")";
- }
+ _currentActiveDate = e.Start;
+ Text = @"Add New Record (Current Record: " + e.Start.ToString("d") + @")";
}
}
else
@@ -2601,7 +2479,7 @@ namespace AdvertsingProfitControl
if (result == DialogResult.Yes)
{
//Save the changes made to the database then clear and load the date picked by the user.
- if (SaveRecords(false))
+ if (SaveRecords())
{
informationLabel.Text = @"Saved all changes successfully." + Environment.NewLine;
}
@@ -2626,7 +2504,7 @@ namespace AdvertsingProfitControl
ClearFormState();
//Load the specified date from the database.
LoadDate(e.Start);
- }
+ }
}
private void SetNewRecordDate(DateTime date, int weeksAhead = 0)
@@ -2856,6 +2734,8 @@ namespace AdvertsingProfitControl
{
var databaseTracker = new DatabaseTracker();
var databaseReader = new DatabaseReader();
+ var db = new AdvertisingProfitControlModel();
+ var dateRecord = db.WeekEndingDates.Single(x => x.EndingDate == date);
var dateId = databaseReader.RetrieveDateIdByDateString(date.ToString("d"), databaseTracker.DatabaseConnectionString);
if (dateId == 0)
{
@@ -2863,12 +2743,9 @@ namespace AdvertsingProfitControl
return;
}
informationLabel.Text = @"Loading data for " + _currentActiveDate.ToString("d") + @"." + Environment.NewLine;
- var projections = databaseReader.ReturnProjectionsTable(dateId, databaseTracker.DatabaseConnectionString);
- var inventory = databaseReader.ReturnInventoryTable(dateId, databaseTracker.DatabaseConnectionString);
- var actualSales = databaseReader.ReturnActualSales(dateId, databaseTracker.DatabaseConnectionString);
- LoadProjectionsTable(projections);
- LoadInventory(inventory);
- LoadActualSales(actualSales);
+ LoadProjectionsTable(dateRecord);
+ LoadInventory(dateRecord);
+ LoadActualSales(dateRecord);
var invoices = databaseReader.ReturnInvoiceTable(dateId, databaseTracker.DatabaseConnectionString);
var comments = databaseReader.RetrieveComments(int.Parse(dateId.ToString()), databaseTracker.DatabaseConnectionString);
if (comments.Count == 2)
@@ -2911,7 +2788,7 @@ namespace AdvertsingProfitControl
_formRoll = FormRoll.ModifyRecord;
}
- private void LoadProjectionsTable(DataTable projections)
+ private void LoadProjectionsTable(WeekEndingDate dateRecord)
{
//Assuming all the tables are correctly aligned.
//Disable the relevant events in the DataGridViews
@@ -2920,115 +2797,50 @@ namespace AdvertsingProfitControl
projectionsDataGridView.CellValidating -= ValidateSalesDataGridViewCellContents;
projectionsDataGridView.RowValidating -= ValidateProjectedRow;
- for (var rowIndex = 0; rowIndex < projections.Rows.Count; rowIndex++)
+ var db = new AdvertisingProfitControlModel();
+ var adSpecialIndex = -1;
+ var projections = db.Projections.Where(x => x.WeekEndingDate.Id == dateRecord.Id).Select(x => x).OrderBy(x => x.RowPosition);
+ var index = 0;
+ foreach (var projection in projections)
{
- var newRow = new DataGridViewRow();
- var isMemberRow = false;
- for (var cellIndex = 0; cellIndex < projections.Rows[rowIndex].ItemArray.Length; cellIndex++)
- {
- //ID and Ad Item.
- if (cellIndex <= 1)
- {
- var cell = new DataGridViewTextBoxCell
- {
- Value = projections.Rows[rowIndex].ItemArray[cellIndex].ToString()
- };
- newRow.Cells.Add(cell);
- continue;
- }
- //Everything in between the ad item cell and the row attribute cells.
- if (cellIndex > 1 && cellIndex <= 7)
- {
- //Only allow zeros in the Sold columns otherwise just leave them blank.
- if (cellIndex == (int) SalesTableColumns.Sold)
- {
- var cell = new DataGridViewTextBoxCell { Value = projections.Rows[rowIndex].ItemArray[cellIndex].ToString() };
- newRow.Cells.Add(cell);
- }
- else if (projections.Rows[rowIndex].ItemArray[cellIndex].ToString() == "0.0000" || projections.Rows[rowIndex].ItemArray[cellIndex].ToString() == "0")
- {
- var cell = new DataGridViewTextBoxCell {Value = string.Empty};
- newRow.Cells.Add(cell);
- }
- else
- {
- var cell = new DataGridViewTextBoxCell {Value = projections.Rows[rowIndex].ItemArray[cellIndex].ToString()};
- newRow.Cells.Add(cell);
- }
- continue;
- }
- //Check the attribute cell.
- if (cellIndex == 8)
- {
- var isHeaderCell = new DataGridViewCheckBoxCell();
- var isMemberCell = new DataGridViewCheckBoxCell();
- var rowAttribute = int.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString());
- switch (rowAttribute)
- {
- case 1:
- //Header row
- isHeaderCell.Value = true;
- newRow.DefaultCellStyle.BackColor = ApplicationColors.HeaderRow;
- break;
- case 2:
- //Member Row
- isMemberCell.Value = true;
- isMemberRow = true;
- newRow.DefaultCellStyle.BackColor = ApplicationColors.MemberRow;
- break;
- default:
- isHeaderCell.Value = false;
- isMemberCell.Value = false;
- break;
- }
- newRow.Cells.Add(isHeaderCell);
- newRow.Cells.Add(isMemberCell);
- continue;
- }
- //Check the group it is part of if any.
- if (cellIndex == 9)
- {
- //Check to see if this row belongs to an ad special group.
- if (projections.Rows[rowIndex].ItemArray[cellIndex].ToString() != "0")
- {
- //If so add the ad item in it to section two (2) of the used ad item array.
- _usedAdItems[1].Add(projections.Rows[rowIndex].ItemArray[1].ToString());
- //If the ad special index is not set, then create the ad special row with the human friendly group name.
- if (_adSpecialIndex == -1)
- {
- var databaseTracker = new DatabaseTracker();
- var databaseReader = new DatabaseReader();
- var groupName = databaseReader.ReturnGroupNameFromGroupId(projections.Rows[rowIndex].ItemArray[cellIndex].ToString(), databaseTracker.DatabaseConnectionString);
- var adSpecialRow = new DataGridViewRow();
- projectionsDataGridView.Rows.Add(adSpecialRow);
- projectionsDataGridView.Rows[rowIndex].Cells[1].Value = groupName;
- projectionsDataGridView.Rows[rowIndex].DefaultCellStyle.BackColor = ApplicationColors.AdSpecial;
- _adSpecialIndex = rowIndex;
- }
- }
- else
- {
- //The ad item belongs in section one (1) of the used ad item array.
- _usedAdItems[0].Add(projections.Rows[rowIndex].ItemArray[1].ToString());
- }
- }
+ projectionsDataGridView.Rows.Add();
+ projectionsDataGridView.Rows[index].Cells[0].Value = projection.Id;
+ projectionsDataGridView.Rows[index].Cells[1].Value = projection.AdItem.Name;
+ projectionsDataGridView.Rows[index].Cells[2].Value = projection.Sold == "0" ? "" : projection.Sold;
+ projectionsDataGridView.Rows[index].Cells[3].Value = projection.SalePrice == "0" ? "" : projection.SalePrice;
+ projectionsDataGridView.Rows[index].Cells[4].Value = projection.TotalSales == 0 ? "" : projection.SalePrice;
+ projectionsDataGridView.Rows[index].Cells[5].Value = projection.Cost == 0 ? "" : projection.SalePrice;
+ projectionsDataGridView.Rows[index].Cells[6].Value = projection.ProfitReturn == 0 ? "" : projection.SalePrice;
+ projectionsDataGridView.Rows[index].Cells[7].Value = projection.TotalProfitReturn == 0 ? "" : projection.SalePrice;
+ projectionsDataGridView.Rows[index].Cells[(int) SalesTableColumns.IsDirty].Value = false;
- if (!isMemberRow) continue;
- //Clear all values from the member row, they are not needed.
- newRow.Cells[2].Value = string.Empty;
- newRow.Cells[3].Value = string.Empty;
- newRow.Cells[4].Value = string.Empty;
- newRow.Cells[5].Value = string.Empty;
- newRow.Cells[6].Value = string.Empty;
- newRow.Cells[7].Value = string.Empty;
- }
- //Set the is dirty cell to false.
- var isDirtyCell = new DataGridViewCheckBoxCell
+ switch (projection.RowAttribute)
{
- Value = false
- };
- newRow.Cells.Add(isDirtyCell);
- projectionsDataGridView.Rows.Add(newRow);
+ case 1:
+ projectionsDataGridView.Rows[index].DefaultCellStyle.BackColor = ApplicationColors.HeaderRow;
+ projectionsDataGridView.Rows[index].Cells[(int) SalesTableColumns.IsHeaderRow].Value = true;
+ projectionsDataGridView.Rows[index].Cells[(int)SalesTableColumns.IsMemberRow].Value = false;
+ break;
+ case 2:
+ projectionsDataGridView.Rows[index].DefaultCellStyle.BackColor = ApplicationColors.MemberRow;
+ projectionsDataGridView.Rows[index].Cells[(int) SalesTableColumns.IsHeaderRow].Value = false;
+ projectionsDataGridView.Rows[index].Cells[(int) SalesTableColumns.IsMemberRow].Value = true;
+ break;
+ default:
+ projectionsDataGridView.Rows[index].Cells[(int)SalesTableColumns.IsHeaderRow].Value = false;
+ projectionsDataGridView.Rows[index].Cells[(int)SalesTableColumns.IsMemberRow].Value = false;
+ break;
+ }
+ if (projection.FkAdSpecialId != 0 && adSpecialIndex == -1)
+ {
+ adSpecialIndex = index;
+ projectionsDataGridView.Rows.Insert(index, 1);
+ //Apply the ad special text.
+ projectionsDataGridView.Rows[index].DefaultCellStyle.BackColor = ApplicationColors.AdSpecial;
+ var adSpecial = db.AdSpecials.Single(x => x.Id == projection.FkAdSpecialId);
+ projectionsDataGridView.Rows[index].Cells[1].Value = adSpecial.Name;
+ }
+ index++;
}
//Manually write the row number to the new row.
projectionsDataGridView.Rows[projectionsDataGridView.Rows.Count - 1].HeaderCell.Value = projectionsDataGridView.Rows.Count.ToString();
@@ -3039,7 +2851,7 @@ namespace AdvertsingProfitControl
projectionsDataGridView.RowValidating += ValidateProjectedRow;
}
- private void LoadInventory(DataTable inventoryTable)
+ private void LoadInventory(WeekEndingDate dateRecord)
{
//Assuming all the tables are correctly aligned.
//Disable the relevant events in the DataGridViews
@@ -3048,89 +2860,48 @@ namespace AdvertsingProfitControl
inventoryDataGridView.CellValidating -= ValidateInventoryCellContents;
inventoryDataGridView.RowValidating -= ValidateInventoryRow;
//Create a local ad special index since Projections should have filled the ad special index in for the class.
+ var db = new AdvertisingProfitControlModel();
var adSpecialIndex = -1;
-
- for (var rowIndex = 0; rowIndex < inventoryTable.Rows.Count; rowIndex++)
+ var inventories = db.Inventories.Where(x => x.WeekEndingDate.Id == dateRecord.Id).Select(x => x).OrderBy(x => x.RowPosition);
+ var index = 0;
+ foreach (var inventory in inventories)
{
- var newRow = new DataGridViewRow();
- var isMemberRow = false;
- for (var cellIndex = 0; cellIndex < inventoryTable.Rows[rowIndex].ItemArray.Length; cellIndex++)
- {
- //ID and Ad Item.
- if (cellIndex <= 1)
- {
- var cell = new DataGridViewTextBoxCell
- {
- Value = inventoryTable.Rows[rowIndex].ItemArray[cellIndex].ToString()
- };
- newRow.Cells.Add(cell);
- continue;
- }
- //Everything in between the ad item cell and the row attribute cells.
- if (cellIndex > 1 && cellIndex <= 5)
- {
- var cell = new DataGridViewTextBoxCell {Value = inventoryTable.Rows[rowIndex].ItemArray[cellIndex].ToString()};
- newRow.Cells.Add(cell);
- continue;
- }
- //Check the attribute cell.
- if (cellIndex == 6)
- {
- var isHeaderCell = new DataGridViewCheckBoxCell();
- var isMemberCell = new DataGridViewCheckBoxCell();
- var rowAttribute = int.Parse(inventoryTable.Rows[rowIndex].ItemArray[cellIndex].ToString());
- switch (rowAttribute)
- {
- case 1:
- //Header row
- isHeaderCell.Value = true;
- newRow.DefaultCellStyle.BackColor = ApplicationColors.HeaderRow;
- break;
- case 2:
- //Member Row
- isMemberCell.Value = true;
- isMemberRow = true;
- newRow.DefaultCellStyle.BackColor = ApplicationColors.MemberRow;
- break;
- default:
- isHeaderCell.Value = false;
- isMemberCell.Value = false;
- break;
- }
- newRow.Cells.Add(isHeaderCell);
- newRow.Cells.Add(isMemberCell);
- continue;
- }
- //Check the group it is part of if any.
- if (cellIndex == 7)
- {
- if (inventoryTable.Rows[rowIndex].ItemArray[cellIndex].ToString() != "0" && adSpecialIndex == -1)
- {
- var databaseTracker = new DatabaseTracker();
- var databaseReader = new DatabaseReader();
- var groupName = databaseReader.ReturnGroupNameFromGroupId(inventoryTable.Rows[rowIndex].ItemArray[cellIndex].ToString(), databaseTracker.DatabaseConnectionString);
- var adSpecialRow = new DataGridViewRow();
- inventoryDataGridView.Rows.Add(adSpecialRow);
- inventoryDataGridView.Rows[rowIndex].Cells[1].Value = groupName;
- inventoryDataGridView.Rows[rowIndex].DefaultCellStyle.BackColor = ApplicationColors.AdSpecial;
- adSpecialIndex = rowIndex;
- }
- }
+ inventoryDataGridView.Rows.Add();
+ inventoryDataGridView.Rows[index].Cells[0].Value = inventory.Id;
+ inventoryDataGridView.Rows[index].Cells[1].Value = inventory.AdItem.Name;
+ inventoryDataGridView.Rows[index].Cells[2].Value = inventory.BeginningInventory;
+ inventoryDataGridView.Rows[index].Cells[3].Value = inventory.Recieved;
+ inventoryDataGridView.Rows[index].Cells[4].Value = inventory.TotalInventory;
+ inventoryDataGridView.Rows[index].Cells[5].Value = inventory.EndingInventory;
+ inventoryDataGridView.Rows[index].Cells[(int)InventoryTableColumns.IsDirty].Value = false;
- if (!isMemberRow) continue;
- //Clear all values from the member row, they are not needed.
- newRow.Cells[2].Value = string.Empty;
- newRow.Cells[3].Value = string.Empty;
- newRow.Cells[4].Value = string.Empty;
- newRow.Cells[5].Value = string.Empty;
- }
- //Set the is dirty cell to false.
- var isDirtyCell = new DataGridViewCheckBoxCell
+ switch (inventory.RowAttribute)
{
- Value = false
- };
- newRow.Cells.Add(isDirtyCell);
- inventoryDataGridView.Rows.Add(newRow);
+ case 1:
+ inventoryDataGridView.Rows[index].DefaultCellStyle.BackColor = ApplicationColors.HeaderRow;
+ inventoryDataGridView.Rows[index].Cells[(int)InventoryTableColumns.IsHeaderRow].Value = true;
+ inventoryDataGridView.Rows[index].Cells[(int)InventoryTableColumns.IsMemberRow].Value = false;
+ break;
+ case 2:
+ inventoryDataGridView.Rows[index].DefaultCellStyle.BackColor = ApplicationColors.MemberRow;
+ inventoryDataGridView.Rows[index].Cells[(int)InventoryTableColumns.IsHeaderRow].Value = false;
+ inventoryDataGridView.Rows[index].Cells[(int)InventoryTableColumns.IsMemberRow].Value = true;
+ break;
+ default:
+ inventoryDataGridView.Rows[index].Cells[(int)InventoryTableColumns.IsHeaderRow].Value = false;
+ inventoryDataGridView.Rows[index].Cells[(int)InventoryTableColumns.IsMemberRow].Value = false;
+ break;
+ }
+ if (inventory.FkAdSpecialId != 0 && adSpecialIndex == -1)
+ {
+ adSpecialIndex = index;
+ inventoryDataGridView.Rows.Insert(index, 1);
+ //Apply the ad special text.
+ inventoryDataGridView.Rows[index].DefaultCellStyle.BackColor = ApplicationColors.AdSpecial;
+ var adSpecial = db.AdSpecials.Single(x => x.Id == inventory.FkAdSpecialId);
+ inventoryDataGridView.Rows[index].Cells[1].Value = adSpecial.Name;
+ }
+ index++;
}
//Manually write the row number to the new row.
inventoryDataGridView.Rows[inventoryDataGridView.Rows.Count - 1].HeaderCell.Value = inventoryDataGridView.Rows.Count.ToString();
@@ -3141,7 +2912,7 @@ namespace AdvertsingProfitControl
inventoryDataGridView.RowValidating += ValidateInventoryRow;
}
- private void LoadActualSales(DataTable actualSales)
+ private void LoadActualSales(WeekEndingDate dateRecord)
{
//Assuming all the tables are correctly aligned.
//Disable the relevant events in the DataGridViews
@@ -3150,105 +2921,50 @@ namespace AdvertsingProfitControl
actualSalesDataGridView.CellValidating -= ValidateSalesDataGridViewCellContents;
actualSalesDataGridView.RowValidating -= ValidateActualSalesRow;
//Create a local ad special index since Projections should have filled the ad special index in for the class.
+ var db = new AdvertisingProfitControlModel();
var adSpecialIndex = -1;
-
- for (var rowIndex = 0; rowIndex < actualSales.Rows.Count; rowIndex++)
+ var actualSales = db.ActualSales.Where(x => x.WeekEndingDate.Id == dateRecord.Id).Select(x => x).OrderBy(x => x.RowPosition);
+ var index = 0;
+ foreach (var actualSale in actualSales)
{
- var newRow = new DataGridViewRow();
- var isMemberRow = false;
- for (var cellIndex = 0; cellIndex < actualSales.Rows[rowIndex].ItemArray.Length; cellIndex++)
- {
- //ID and Ad Item.
- if (cellIndex <= 1)
- {
- var cell = new DataGridViewTextBoxCell
- {
- Value = actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString()
- };
- newRow.Cells.Add(cell);
- continue;
- }
- //Everything in between the ad item cell and the row attribute cells.
- if (cellIndex > 1 && cellIndex <= 7)
- {
- //Only allow zeros in the Sold columns otherwise just leave them blank.
- if (cellIndex == (int)SalesTableColumns.Sold)
- {
- var cell = new DataGridViewTextBoxCell { Value = actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString() };
- newRow.Cells.Add(cell);
- }
- else if (actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString() == "0.0000" || actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString() == "0")
- {
- var cell = new DataGridViewTextBoxCell { Value = string.Empty };
- newRow.Cells.Add(cell);
- }
- else
- {
- var cell = new DataGridViewTextBoxCell {Value = actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString()};
- newRow.Cells.Add(cell);
- }
- continue;
- }
- //Check the attribute cell.
- if (cellIndex == 8)
- {
- var isHeaderCell = new DataGridViewCheckBoxCell();
- var isMemberCell = new DataGridViewCheckBoxCell();
- var rowAttribute = int.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString());
- switch (rowAttribute)
- {
- case 1:
- //Header row
- isHeaderCell.Value = true;
- newRow.DefaultCellStyle.BackColor = ApplicationColors.HeaderRow;
- break;
- case 2:
- //Member Row
- isMemberCell.Value = true;
- isMemberRow = true;
- newRow.DefaultCellStyle.BackColor = ApplicationColors.MemberRow;
- break;
- default:
- isHeaderCell.Value = false;
- isMemberCell.Value = false;
- break;
- }
- newRow.Cells.Add(isHeaderCell);
- newRow.Cells.Add(isMemberCell);
- continue;
- }
- //Check the group it is part of if any.
- if (cellIndex == 9)
- {
- if (actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString() != "0" && adSpecialIndex == -1)
- {
- var databaseTracker = new DatabaseTracker();
- var databaseReader = new DatabaseReader();
- var groupName = databaseReader.ReturnGroupNameFromGroupId(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString(), databaseTracker.DatabaseConnectionString);
- var adSpecialRow = new DataGridViewRow();
- actualSalesDataGridView.Rows.Add(adSpecialRow);
- actualSalesDataGridView.Rows[rowIndex].Cells[1].Value = groupName;
- actualSalesDataGridView.Rows[rowIndex].DefaultCellStyle.BackColor = ApplicationColors.AdSpecial;
- adSpecialIndex = rowIndex;
- }
- }
+ actualSalesDataGridView.Rows.Add();
+ actualSalesDataGridView.Rows[index].Cells[0].Value = actualSale.Id;
+ actualSalesDataGridView.Rows[index].Cells[1].Value = actualSale.AdItem.Name;
+ actualSalesDataGridView.Rows[index].Cells[2].Value = actualSale.Sold == "0" ? "" : actualSale.Sold;
+ actualSalesDataGridView.Rows[index].Cells[3].Value = actualSale.SalePrice == "0" ? "" : actualSale.SalePrice;
+ actualSalesDataGridView.Rows[index].Cells[4].Value = actualSale.TotalSales == 0 ? "" : actualSale.SalePrice;
+ actualSalesDataGridView.Rows[index].Cells[5].Value = actualSale.Cost == 0 ? "" : actualSale.SalePrice;
+ actualSalesDataGridView.Rows[index].Cells[6].Value = actualSale.ProfitReturn == 0 ? "" : actualSale.SalePrice;
+ actualSalesDataGridView.Rows[index].Cells[7].Value = actualSale.TotalProfitReturn == 0 ? "" : actualSale.SalePrice;
+ actualSalesDataGridView.Rows[index].Cells[(int)SalesTableColumns.IsDirty].Value = false;
- if (!isMemberRow) continue;
- //Clear all values from the member row, they are not needed.
- newRow.Cells[2].Value = string.Empty;
- newRow.Cells[3].Value = string.Empty;
- newRow.Cells[4].Value = string.Empty;
- newRow.Cells[5].Value = string.Empty;
- newRow.Cells[6].Value = string.Empty;
- newRow.Cells[7].Value = string.Empty;
- }
- //Set the is dirty cell to false.
- var isDirtyCell = new DataGridViewCheckBoxCell
+ switch (actualSale.RowAttribute)
{
- Value = false
- };
- newRow.Cells.Add(isDirtyCell);
- actualSalesDataGridView.Rows.Add(newRow);
+ case 1:
+ actualSalesDataGridView.Rows[index].DefaultCellStyle.BackColor = ApplicationColors.HeaderRow;
+ actualSalesDataGridView.Rows[index].Cells[(int)SalesTableColumns.IsHeaderRow].Value = true;
+ actualSalesDataGridView.Rows[index].Cells[(int)SalesTableColumns.IsMemberRow].Value = false;
+ break;
+ case 2:
+ actualSalesDataGridView.Rows[index].DefaultCellStyle.BackColor = ApplicationColors.MemberRow;
+ actualSalesDataGridView.Rows[index].Cells[(int)SalesTableColumns.IsHeaderRow].Value = false;
+ actualSalesDataGridView.Rows[index].Cells[(int)SalesTableColumns.IsMemberRow].Value = true;
+ break;
+ default:
+ actualSalesDataGridView.Rows[index].Cells[(int)SalesTableColumns.IsHeaderRow].Value = false;
+ actualSalesDataGridView.Rows[index].Cells[(int)SalesTableColumns.IsMemberRow].Value = false;
+ break;
+ }
+ if (actualSale.FkAdSpecialId != 0 && adSpecialIndex == -1)
+ {
+ adSpecialIndex = index;
+ actualSalesDataGridView.Rows.Insert(index, 1);
+ //Apply the ad special text.
+ actualSalesDataGridView.Rows[index].DefaultCellStyle.BackColor = ApplicationColors.AdSpecial;
+ var adSpecial = db.AdSpecials.Single(x => x.Id == actualSale.FkAdSpecialId);
+ actualSalesDataGridView.Rows[index].Cells[1].Value = adSpecial.Name;
+ }
+ index++;
}
//Manually write the row number to the new row.
actualSalesDataGridView.Rows[actualSalesDataGridView.Rows.Count - 1].HeaderCell.Value = actualSalesDataGridView.Rows.Count.ToString();
@@ -3611,11 +3327,11 @@ namespace AdvertsingProfitControl
///
/// Saves all changes made to the form to the database.
///
- /// Whether or not to update the information label with the status.
/// True on success otherwise, false.
- private bool SaveRecords(bool displayInformation = true)
+ private bool SaveRecords()
{
var success = true;
+ var db = new AdvertisingProfitControlModel();
//Get the date ID for the current active date.
if (_currentActiveDate.DayOfWeek != DayOfWeek.Saturday)
{
@@ -3628,7 +3344,6 @@ namespace AdvertsingProfitControl
var weekAhead = 1;
while (weekEndingCalendar.BoldedDates.Contains(_currentActiveDate.AddDays(7 * weekAhead)))
{
-
weekAhead++;
}
var result = MessageBox.Show(@"The date " + _currentActiveDate.ToShortDateString() + @" is already in the database. Did you mean to select " + _currentActiveDate.AddDays(7 * weekAhead).ToShortDateString() + @" instead?", @"", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
@@ -3649,748 +3364,966 @@ namespace AdvertsingProfitControl
}
}
}
- var dateId = GetDateId(_currentActiveDate.ToString("d"));
- if (dateId == 0)
+ //Create the DateTime object that represents the week ending date key.
+ var date = new WeekEndingDate
{
- MessageBox.Show(@"Failed to get the date ID number.", @"Invalid ID Number", MessageBoxButtons.OK, MessageBoxIcon.Error);
+ EndingDate = weekEndingCalendar.SelectionStart
+ };
+
+ try
+ {
+ if (!db.WeekEndingDates.Any(x => x.EndingDate == weekEndingCalendar.SelectionStart))
+ {
+ db.WeekEndingDates.Add(date);
+ db.SaveChanges();
+ }
+ else
+ {
+ date = db.WeekEndingDates.Single(x => x.EndingDate == weekEndingCalendar.SelectionStart);
+ }
+ }
+ catch (DbUpdateException e)
+ {
+ errorLabel.Text = @"Failed to update the current date " + _currentActiveDate.ToString("d") + @".";
+ informationLabel.Text = @"Record updating aborted.";
+ LogConsole.WriteToLog(FrmLogConsole.Level.Critical, e.Message);
return false;
}
- if (displayInformation) informationLabel.Text = "";
- //Create the database interaction objects.
- var dbT = new DatabaseTracker();
- var dbW = new DatabaseWriter(dbT.DatabaseConnectionString);
- DataTable newInsertProjectionsTable;
- DataTable updateProjectionsTable;
- var projectionsTrimmingStatus = ConstructCleanedSalesTable("Projections", dateId, out newInsertProjectionsTable, out updateProjectionsTable);
- if (projectionsTrimmingStatus != TrimmingOperationResult.NoChangesRequired && projectionsTrimmingStatus != TrimmingOperationResult.FailedToTrim)
+ //Clear the error and information labels.
+ informationLabel.Text = string.Empty;
+ errorLabel.Text = string.Empty;
+
+ try
{
- //Check to see if the insert table has any items.
- if (newInsertProjectionsTable.Rows.Count > 0)
+ using (var scope = new TransactionScope())
{
- var writerResult = dbW.InsertIntoSalesTable(newInsertProjectionsTable, dbT.DatabaseConnectionString);
- if (writerResult.GetWritingOperationStatus() != WritingOperationStatus.Failed)
- {
- //Spin through the collection and update the affected rows.
- foreach (var rowIndex in writerResult.GetRowCollection())
- {
- projectionsDataGridView.Rows[rowIndex.Key - 1].Cells[(int) SalesTableColumns.Id].Value = rowIndex.Value;
- projectionsDataGridView.Rows[rowIndex.Key - 1].Cells[(int) SalesTableColumns.IsDirty].Value = false;
- projectionsDataGridView.Rows[rowIndex.Key - 1].HeaderCell.Style.BackColor = ApplicationColors.EditingSaved;
- }
- }
- else
- {
- success = false;
- }
+ SaveProjections(date);
+ SaveInventory(date);
+ SaveActualSales(date);
+ scope.Complete();
}
- //Next check to see if the update table has anything.
- if (updateProjectionsTable.Rows.Count > 0)
+ //All completed without error so mark all the APC table rows as committed.
+ //TODO: Find a better way so this doesn't fire every time this method executes.
+ for (var i = 0; i < projectionsDataGridView.RowCount - 1; i++)
{
- var writerResult = dbW.UpdateSalesTable(updateProjectionsTable, dbT.DatabaseConnectionString);
- if (writerResult.GetWritingOperationStatus() != WritingOperationStatus.Failed)
- {
- //Spin through the collection and update the affected rows.
- foreach (var rowIndex in writerResult.GetRowCollection())
- {
- //Only reset the IsDirty value to false since the updates when through.
- projectionsDataGridView.Rows[rowIndex.Key - 1].Cells[(int) SalesTableColumns.IsDirty].Value = false;
- projectionsDataGridView.Rows[rowIndex.Key - 1].HeaderCell.Style.BackColor = ApplicationColors.EditingSaved;
- }
- }
- else
- {
- success = false;
- }
+ projectionsDataGridView.Rows[i].Cells[(int) SalesTableColumns.IsDirty].Value = false;
+ projectionsDataGridView.Rows[i].HeaderCell.Style.BackColor = ApplicationColors.EditingSaved;
+ inventoryDataGridView.Rows[i].Cells[(int)InventoryTableColumns.IsDirty].Value = false;
+ inventoryDataGridView.Rows[i].HeaderCell.Style.BackColor = ApplicationColors.EditingSaved;
+ actualSalesDataGridView.Rows[i].Cells[(int)SalesTableColumns.IsDirty].Value = false;
+ actualSalesDataGridView.Rows[i].HeaderCell.Style.BackColor = ApplicationColors.EditingSaved;
}
- if (displayInformation) informationLabel.Text += @"Successfully saved projections." + Environment.NewLine;
}
- else if (projectionsTrimmingStatus == TrimmingOperationResult.NoChangesRequired)
- {
- if (displayInformation) informationLabel.Text += @"No changes to projections detected." + Environment.NewLine;
- }
- else
- {
- errorLabel.Text += @"Failed to process projections." + Environment.NewLine;
- }
- DataTable inventoryNewTable;
- DataTable inventoryUpdateTable;
- var inventoryTrimmingStatus = ConstructCleanedInventoryTable(dateId, out inventoryNewTable, out inventoryUpdateTable);
- if (inventoryTrimmingStatus != TrimmingOperationResult.NoChangesRequired && inventoryTrimmingStatus != TrimmingOperationResult.FailedToTrim)
- {
- if (inventoryNewTable.Rows.Count > 0)
- {
- var writerResult = dbW.InsertIntoInventoryTable(inventoryNewTable, dbT.DatabaseConnectionString);
- if (writerResult.GetWritingOperationStatus() != WritingOperationStatus.Failed)
- {
- //Spin through the collection and update the affected rows.
- foreach (var rowIndex in writerResult.GetRowCollection())
- {
- //Only reset the IsDirty value to false since the updates when through.
- inventoryDataGridView.Rows[rowIndex.Key - 1].Cells[(int) InventoryTableColumns.Id].Value = rowIndex.Value;
- inventoryDataGridView.Rows[rowIndex.Key - 1].Cells[(int) InventoryTableColumns.IsDirty].Value = false;
- inventoryDataGridView.Rows[rowIndex.Key - 1].HeaderCell.Style.BackColor = ApplicationColors.EditingSaved;
- }
- }
- else
- {
- success = false;
- }
- }
- //Next check to see if the update table has anything.
- if (inventoryUpdateTable.Rows.Count > 0)
- {
- var writerResult = dbW.UpdateInventoryTable(inventoryUpdateTable, dbT.DatabaseConnectionString);
- if (writerResult.GetWritingOperationStatus() != WritingOperationStatus.Failed)
- {
- //Spin through the collection and update the affected rows.
- foreach (var rowIndex in writerResult.GetRowCollection())
- {
- //Only reset the IsDirty value to false since the updates when through.
- inventoryDataGridView.Rows[rowIndex.Key - 1].Cells[(int) InventoryTableColumns.IsDirty].Value = false;
- inventoryDataGridView.Rows[rowIndex.Key - 1].HeaderCell.Style.BackColor = ApplicationColors.EditingSaved;
- }
- }
- else
- {
- success = false;
- }
- }
- if (displayInformation) informationLabel.Text += @"Successfully saved inventory." + Environment.NewLine;
- }
- else if (inventoryTrimmingStatus == TrimmingOperationResult.NoChangesRequired)
- {
- if (displayInformation) informationLabel.Text += @"No changes to inventory detected." + Environment.NewLine;
- }
- else
- {
- errorLabel.Text += @"Failed to process inventory." + Environment.NewLine;
- }
- DataTable actualSalesNewTable;
- DataTable actualSalesUpdateTable;
- var actualSalesTrimmingStatus = ConstructCleanedSalesTable("ActualSales", dateId, out actualSalesNewTable, out actualSalesUpdateTable);
- if (actualSalesTrimmingStatus != TrimmingOperationResult.NoChangesRequired && actualSalesTrimmingStatus != TrimmingOperationResult.FailedToTrim)
- {
- //Check to see if the insert table has any items.
- if (actualSalesNewTable.Rows.Count > 0)
- {
- var writerResult = dbW.InsertIntoSalesTable(actualSalesNewTable, dbT.DatabaseConnectionString);
- if (writerResult.GetWritingOperationStatus() != WritingOperationStatus.Failed)
- {
- //Spin through the collection and update the affected rows.
- foreach (var rowIndex in writerResult.GetRowCollection())
- {
- actualSalesDataGridView.Rows[rowIndex.Key - 1].Cells[(int) SalesTableColumns.Id].Value = rowIndex.Value;
- actualSalesDataGridView.Rows[rowIndex.Key - 1].Cells[(int) SalesTableColumns.IsDirty].Value = false;
- actualSalesDataGridView.Rows[rowIndex.Key - 1].HeaderCell.Style.BackColor = ApplicationColors.EditingSaved;
- }
- }
- else
- {
- success = false;
- }
- }
- //Next check to see if the update table has anything.
- if (actualSalesUpdateTable.Rows.Count > 0)
- {
- var writerResult = dbW.UpdateSalesTable(actualSalesUpdateTable, dbT.DatabaseConnectionString);
- if (writerResult.GetWritingOperationStatus() != WritingOperationStatus.Failed)
- {
- //Spin through the collection and update the affected rows.
- foreach (var rowIndex in writerResult.GetRowCollection())
- {
- //Only reset the IsDirty value to false since the updates when through.
- actualSalesDataGridView.Rows[rowIndex.Key - 1].Cells[(int) SalesTableColumns.IsDirty].Value = false;
- actualSalesDataGridView.Rows[rowIndex.Key - 1].HeaderCell.Style.BackColor = ApplicationColors.EditingSaved;
- }
- }
- else
- {
- success = false;
- }
- }
- if (displayInformation) informationLabel.Text += @"Successfully saved actual sales." + Environment.NewLine;
- }
- else if (actualSalesTrimmingStatus == TrimmingOperationResult.NoChangesRequired)
- {
- if (displayInformation) informationLabel.Text += @"No changes to actual sales detected." + Environment.NewLine;
- }
- else
- {
- errorLabel.Text += @"Failed to process actual sales." + Environment.NewLine;
- }
- if (!SaveInvoices(dateId, displayInformation))
- {
- success = false;
- }
- if (!SaveComments(dateId, displayInformation))
- {
- success = false;
- }
- if (!SaveWeeklySales(dateId, displayInformation))
- {
- success = false;
- }
- if (!SaveTaxable(dateId, displayInformation))
- {
- success = false;
- }
- if (!SaveCostAnalysis(dateId, displayInformation))
+ catch (TransactionAbortedException e)
{
+ LogConsole.WriteToLog(FrmLogConsole.Level.Error, e.Message);
+ informationLabel.Text = e.Message;
success = false;
+ //Spin through all the rows and check to see if their IDs are in the database.
+ //TODO: WRITE CODE BLOCK
+ for (var i = 0; i < projectionsDataGridView.RowCount - 1; i++)
+ {
+ if (projectionsDataGridView.Rows[i].Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString() != string.Empty)
+ {
+ var id = int.Parse(projectionsDataGridView.Rows[i].Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString());
+ if (!db.Projections.Any(x => x.Id == id))
+ {
+ projectionsDataGridView.Rows[i].Cells[(int) SalesTableColumns.Id].Value = string.Empty;
+ }
+ }
+ if (inventoryDataGridView.Rows[i].Cells[(int)InventoryTableColumns.Id].EditedFormattedValue.ToString() != string.Empty)
+ {
+ var id = int.Parse(inventoryDataGridView.Rows[i].Cells[(int)InventoryTableColumns.Id].EditedFormattedValue.ToString());
+ if (!db.Inventories.Any(x => x.Id == id))
+ {
+ inventoryDataGridView.Rows[i].Cells[(int)InventoryTableColumns.Id].Value = string.Empty;
+ }
+ }
+ if (actualSalesDataGridView.Rows[i].Cells[(int) SalesTableColumns.Id].EditedFormattedValue.ToString() ==
+ string.Empty) continue;
+ {
+ var id = int.Parse(actualSalesDataGridView.Rows[i].Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString());
+ if (!db.ActualSales.Any(x => x.Id == id))
+ {
+ actualSalesDataGridView.Rows[i].Cells[(int)SalesTableColumns.Id].Value = string.Empty;
+ }
+ }
+ }
}
+ //Save the other bits of data.
+ SaveInvoices(date);
+ SaveWeeklySales(date);
+ SaveTaxable(date);
+ SaveCostAnalysis(date);
+ SaveComments(date);
//If everything went through properly then set the form as not dirty since all changes are saved.
- if (success)
- {
- _isFormDirty = false;
- addRecordButton.Text = @"Update Record";
- Text = @"Modify Record (Current Record: " + _currentActiveDate.ToShortDateString() + @")";
- }
+ _isFormDirty = false;
+ addRecordButton.Text = @"Update Record";
+ Text = @"Modify Record (Current Record: " + _currentActiveDate.ToShortDateString() + @")";
_formRoll = FormRoll.ModifyRecord;
weekEndingCalendar.AddBoldedDate(_currentActiveDate);
weekEndingCalendar.Invalidate();
return success;
}
- ///
- /// Attempts to get the date ID for the date supplied (short date format required, 'Merica!).
- /// Failing that, it will insert the date into the database and return the date ID.
- ///
- /// The date string.
- /// The date ID, otherwise zero (0) on fail.
- private int GetDateId(string date)
+ private void SaveProjections(WeekEndingDate date)
{
- var dbT = new DatabaseTracker();
- var dbW = new DatabaseWriter(dbT.DatabaseConnectionString);
- var dbR = new DatabaseReader();
- var dateId = dbR.RetrieveDateIdByDateString(date, dbT.DatabaseConnectionString);
- //If the ID is zero (0) that means the date isn't in the database so simply insert it.
- if (dateId != 0) return dateId;
- //Try inserting the date string.
- if (dbW.InsertIntoWeekEnding(date))
+ var db = new AdvertisingProfitControlModel();
+ var lastRow = -1;
+ using (var scope = new TransactionScope())
{
- dateId = dbR.RetrieveDateIdByDateString(date, dbT.DatabaseConnectionString);
+ try
+ {
+ //Create the ad special object in-case one is in countered.
+ var adSpecial = new AdSpecial();
+ //Row index, projection object
+ var idNumbers = new Dictionary();
+ //Spin through the Projections DataGridView and build Projection objects.
+ foreach (DataGridViewRow row in projectionsDataGridView.Rows)
+ {
+ //If the row is a new row or is not dirty then continue to the next row if applicable.
+ if (row.IsNewRow) continue;
+ if (!(bool) row.Cells[(int) SalesTableColumns.IsDirty].EditedFormattedValue) continue;
+ //Obtain the ad item.
+ var adItem = new AdItem();
+ //Sadly, LINQ doesn't like calls to the ToString method so we create a temp variable.
+ var adItemName = row.Cells[(int) SalesTableColumns.AdItem].EditedFormattedValue.ToString();
+ //Check to see if this is the ad special row, and if so create the object.
+ if (row.Index == _adSpecialIndex)
+ {
+ adSpecial = GetAdSpecial(adItemName);
+ continue;
+ }
+ //Check to see if the ad item is in the database and if so grab the object for it, otherwise add it.
+ if (db.AdItems.Any(x => x.Name == adItemName))
+ {
+ //Match
+ adItem = db.AdItems.Single(x => x.Name == adItemName);
+ }
+ else
+ {
+ //Not a match
+ adItem.Name = row.Cells[(int) SalesTableColumns.AdItem].EditedFormattedValue.ToString();
+ db.AdItems.Add(adItem);
+ db.SaveChanges();
+ }
+ //Grab the row's attribute if there is one.
+ var rowAttribute = 0;
+ if ((bool) row.Cells[(int) SalesTableColumns.IsHeaderRow].EditedFormattedValue)
+ {
+ rowAttribute = 1;
+ }
+ else if ((bool) row.Cells[(int) SalesTableColumns.IsMemberRow].EditedFormattedValue)
+ {
+ rowAttribute = 2;
+ }
+ var projection = new Projection();
+ //Apply ad special status if there is one.
+ if (_adSpecialIndex != -1 && row.Index > _adSpecialIndex)
+ {
+ projection.FkAdSpecialId = adSpecial.Id;
+ }
+ else
+ {
+ projection.FkAdSpecialId = 0;
+ }
+ //Check for an ID number
+ if (row.Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString() == string.Empty)
+ {
+ //If there isn't one then create a new record and add it to the database.
+ projection.Sold = row.Cells[(int) SalesTableColumns.Sold].EditedFormattedValue.ToString();
+ projection.SalePrice =
+ row.Cells[(int) SalesTableColumns.SalePrice].EditedFormattedValue.ToString();
+ projection.TotalSales =
+ string.IsNullOrWhiteSpace(
+ row.Cells[(int) SalesTableColumns.TotalSales].EditedFormattedValue.ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int) SalesTableColumns.TotalSales].EditedFormattedValue.ToString());
+ projection.Cost =
+ string.IsNullOrWhiteSpace(
+ row.Cells[(int) SalesTableColumns.Cost].EditedFormattedValue.ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int) SalesTableColumns.Cost].EditedFormattedValue.ToString());
+ projection.ProfitReturn =
+ string.IsNullOrWhiteSpace(
+ row.Cells[(int) SalesTableColumns.ProfitReturn].EditedFormattedValue.ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int) SalesTableColumns.ProfitReturn].EditedFormattedValue
+ .ToString());
+ projection.TotalProfitReturn =
+ string.IsNullOrWhiteSpace(
+ row.Cells[(int) SalesTableColumns.TotalProfitReturn].EditedFormattedValue
+ .ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int) SalesTableColumns.TotalProfitReturn].EditedFormattedValue
+ .ToString());
+ projection.FkAdItemId = adItem.Id;
+ projection.RowAttribute = rowAttribute;
+ projection.RowPosition = row.Index + 1;
+ projection.FkDateId = date.Id;
+ db.Projections.Add(projection);
+ idNumbers.Add(row.Index, projection);
+ }
+ else
+ {
+ //If there is one, set the current object to reference the existing record and update.
+ projection = db.Projections.Find(int.Parse(row.Cells[(int) SalesTableColumns.Id].EditedFormattedValue.ToString()));
+ if (projection == null) throw new DbUpdateException("Failed to retrieve Projection record.");
+ projection.Sold = row.Cells[(int) SalesTableColumns.Sold].EditedFormattedValue.ToString();
+ projection.SalePrice =
+ row.Cells[(int) SalesTableColumns.SalePrice].EditedFormattedValue.ToString();
+ projection.TotalSales = string.IsNullOrWhiteSpace(
+ row.Cells[(int) SalesTableColumns.TotalSales].EditedFormattedValue.ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int) SalesTableColumns.TotalSales].EditedFormattedValue.ToString());
+ projection.Cost = string.IsNullOrWhiteSpace(
+ row.Cells[(int) SalesTableColumns.Cost].EditedFormattedValue.ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int) SalesTableColumns.Cost].EditedFormattedValue.ToString());
+ projection.ProfitReturn = string.IsNullOrWhiteSpace(
+ row.Cells[(int) SalesTableColumns.ProfitReturn].EditedFormattedValue.ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int) SalesTableColumns.ProfitReturn].EditedFormattedValue.ToString());
+ projection.TotalProfitReturn = string.IsNullOrWhiteSpace(
+ row.Cells[(int) SalesTableColumns.TotalProfitReturn].EditedFormattedValue.ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int) SalesTableColumns.TotalProfitReturn].EditedFormattedValue
+ .ToString());
+ projection.FkAdItemId = adItem.Id;
+ projection.RowAttribute = rowAttribute;
+ projection.RowPosition = row.Index + 1;
+ }
+ //Update the last row that was done before jumping to the next loop.
+ lastRow = row.Index;
+ }
+ if (lastRow != -1)
+ {
+ db.SaveChanges();
+ //Insert the ID numbers into the respective rows, making the assumption that all the methods will succeed.
+ foreach (var index in idNumbers)
+ {
+ projectionsDataGridView.Rows[index.Key].Cells[(int) SalesTableColumns.Id].Value = index.Value.Id;
+ }
+ informationLabel.Text = @"Updated the Projections table." + Environment.NewLine;
+ }
+ else
+ {
+ informationLabel.Text = @"No changes detected in Projections." + Environment.NewLine;
+ }
+ scope.Complete();
+ }
+ catch (DbUpdateException e)
+ {
+ errorLabel.Text = @"Failed to update Projections: Row " + (lastRow + 1) + @".";
+ LogConsole.WriteToLog(FrmLogConsole.Level.Error, e.Message);
+ throw new TransactionAbortedException("Failed to update Projections." + Environment.NewLine + "Updates to Inventory aborted." + Environment.NewLine + "Updates to Actual Sales aborted." + Environment.NewLine);
+ }
+ }
+ }
+
+ private void SaveInventory(WeekEndingDate date)
+ {
+ var db = new AdvertisingProfitControlModel();
+ var lastRow = -1;
+ using (var scope = new TransactionScope())
+ {
+ try
+ {
+ //Create the ad special object in-case one is in countered.
+ var adSpecial = new AdSpecial();
+ //Row index, inventory object
+ var idNumbers = new Dictionary();
+ //Spin through the Projections DataGridView and build Projection objects.
+ foreach (DataGridViewRow row in inventoryDataGridView.Rows)
+ {
+ //If the row is a new row or is not dirty then continue to the next row if applicable.
+ if (row.IsNewRow) continue;
+ if (!(bool)row.Cells[(int)InventoryTableColumns.IsDirty].EditedFormattedValue) continue;
+ //Obtain the ad item.
+ var adItem = new AdItem();
+ //Sadly, LINQ doesn't like calls to the ToString method so we create a temp variable.
+ var adItemName = row.Cells[(int)InventoryTableColumns.AdItem].EditedFormattedValue.ToString();
+ //Check to see if this is the ad special row, and if so create the object.
+ if (row.Index == _adSpecialIndex)
+ {
+ adSpecial = GetAdSpecial(adItemName);
+ continue;
+ }
+ //Check to see if the ad item is in the database and if so grab the object for it, otherwise add it.
+ if (db.AdItems.Any(x => x.Name == adItemName))
+ {
+ //Match
+ adItem = db.AdItems.Single(x => x.Name == adItemName);
+ }
+ else
+ {
+ //Not a match
+ adItem.Name = row.Cells[(int)InventoryTableColumns.AdItem].EditedFormattedValue.ToString();
+ db.AdItems.Add(adItem);
+ db.SaveChanges();
+ }
+ //Grab the row's attribute if there is one.
+ var rowAttribute = 0;
+ if ((bool)row.Cells[(int)InventoryTableColumns.IsHeaderRow].EditedFormattedValue)
+ {
+ rowAttribute = 1;
+ }
+ else if ((bool)row.Cells[(int)InventoryTableColumns.IsMemberRow].EditedFormattedValue)
+ {
+ rowAttribute = 2;
+ }
+ var inventory = new Inventory();
+ //Apply ad special status if there is one.
+ if (_adSpecialIndex != -1 && row.Index > _adSpecialIndex)
+ {
+ inventory.FkAdSpecialId = adSpecial.Id;
+ }
+ else
+ {
+ inventory.FkAdSpecialId = 0;
+ }
+ //Check for an ID number
+ if (row.Cells[(int)InventoryTableColumns.Id].EditedFormattedValue.ToString() == string.Empty)
+ {
+ //If there isn't one then create a new record and add it to the database.
+ inventory.BeginningInventory =
+ row.Cells[(int) InventoryTableColumns.BeginningInventory].EditedFormattedValue.ToString();
+ inventory.Recieved =
+ row.Cells[(int) InventoryTableColumns.Recieved].EditedFormattedValue.ToString();
+ inventory.TotalInventory =
+ row.Cells[(int) InventoryTableColumns.Total].EditedFormattedValue.ToString();
+ inventory.EndingInventory =
+ row.Cells[(int) InventoryTableColumns.EndingInventory].EditedFormattedValue.ToString();
+ inventory.FkAdItemId = adItem.Id;
+ inventory.RowAttribute = rowAttribute;
+ inventory.RowPosition = row.Index + 1;
+ inventory.FkDateId = date.Id;
+ db.Inventories.Add(inventory);
+ idNumbers.Add(row.Index, inventory);
+ }
+ else
+ {
+ //If there is one, set the current object to reference the existing record and update.
+ inventory = db.Inventories.Find(int.Parse(row.Cells[(int)InventoryTableColumns.Id].EditedFormattedValue.ToString()));
+ if (inventory == null) throw new DbUpdateException("Failed to retrieve Inventory record.");
+ inventory.BeginningInventory =
+ row.Cells[(int)InventoryTableColumns.BeginningInventory].EditedFormattedValue.ToString();
+ inventory.Recieved =
+ row.Cells[(int)InventoryTableColumns.Recieved].EditedFormattedValue.ToString();
+ inventory.TotalInventory =
+ row.Cells[(int)InventoryTableColumns.Total].EditedFormattedValue.ToString();
+ inventory.EndingInventory =
+ row.Cells[(int)InventoryTableColumns.EndingInventory].EditedFormattedValue.ToString();
+ inventory.FkAdItemId = adItem.Id;
+ inventory.RowAttribute = rowAttribute;
+ inventory.RowPosition = row.Index + 1;
+ }
+ //Update the last row that was done before jumping to the next loop.
+ lastRow = row.Index;
+ }
+ if (lastRow != -1)
+ {
+ db.SaveChanges();
+ //Insert the ID numbers into the respective rows, making the assumption that all the methods will succeed.
+ foreach (var index in idNumbers)
+ {
+ inventoryDataGridView.Rows[index.Key].Cells[(int) InventoryTableColumns.Id].Value = index.Value.Id;
+ }
+ informationLabel.Text += @"Updated the Inventory table." + Environment.NewLine;
+ }
+ else
+ {
+ informationLabel.Text += @"No changes detected in Inventory." + Environment.NewLine;
+ }
+ scope.Complete();
+ }
+ catch (DbUpdateException e)
+ {
+ errorLabel.Text = @"Failed to update Inventory: Row " + (lastRow + 1) + @".";
+ LogConsole.WriteToLog(FrmLogConsole.Level.Error, e.Message);
+ throw new TransactionAbortedException("Updates to Projections aborted." + Environment.NewLine + "Failed to update Inventory." + Environment.NewLine + "Updates to Actual Sales aborted." + Environment.NewLine);
+ }
+ }
+ }
+
+ private void SaveActualSales(WeekEndingDate date)
+ {
+ var db = new AdvertisingProfitControlModel();
+ var lastRow = -1;
+ using (var scope = new TransactionScope())
+ {
+ try
+ {
+ //Create the ad special object in-case one is in countered.
+ var adSpecial = new AdSpecial();
+ //Row index, ActualSale object
+ var idNumbers = new Dictionary();
+ //Spin through the Projections DataGridView and build Projection objects.
+ foreach (DataGridViewRow row in actualSalesDataGridView.Rows)
+ {
+ //If the row is a new row or is not dirty then continue to the next row if applicable.
+ if (row.IsNewRow) continue;
+ if (!(bool)row.Cells[(int)SalesTableColumns.IsDirty].EditedFormattedValue) continue;
+ //Obtain the ad item.
+ var adItem = new AdItem();
+ //Sadly, LINQ doesn't like calls to the ToString method so we create a temp variable.
+ var adItemName = row.Cells[(int)SalesTableColumns.AdItem].EditedFormattedValue.ToString();
+ //Check to see if this is the ad special row, and if so create the object.
+ if (row.Index == _adSpecialIndex)
+ {
+ adSpecial = GetAdSpecial(adItemName);
+ continue;
+ }
+ //Check to see if the ad item is in the database and if so grab the object for it, otherwise add it.
+ if (db.AdItems.Any(x => x.Name == adItemName))
+ {
+ //Match
+ adItem = db.AdItems.Single(x => x.Name == adItemName);
+ }
+ else
+ {
+ //Not a match
+ adItem.Name = row.Cells[(int)SalesTableColumns.AdItem].EditedFormattedValue.ToString();
+ db.AdItems.Add(adItem);
+ db.SaveChanges();
+ }
+ //Grab the row's attribute if there is one.
+ var rowAttribute = 0;
+ if ((bool)row.Cells[(int)SalesTableColumns.IsHeaderRow].EditedFormattedValue)
+ {
+ rowAttribute = 1;
+ }
+ else if ((bool)row.Cells[(int)SalesTableColumns.IsMemberRow].EditedFormattedValue)
+ {
+ rowAttribute = 2;
+ }
+ var actualSale = new ActualSale();
+ //Apply ad special status if there is one.
+ if (_adSpecialIndex != -1 && row.Index > _adSpecialIndex)
+ {
+ actualSale.FkAdSpecialId = adSpecial.Id;
+ }
+ else
+ {
+ actualSale.FkAdSpecialId = 0;
+ }
+ //Check for an ID number
+ if (row.Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString() == string.Empty)
+ {
+ //If there isn't one then create a new record and add it to the database.
+ actualSale.Sold = row.Cells[(int)SalesTableColumns.Sold].EditedFormattedValue.ToString();
+ actualSale.SalePrice =
+ row.Cells[(int)SalesTableColumns.SalePrice].EditedFormattedValue.ToString();
+ actualSale.TotalSales =
+ string.IsNullOrWhiteSpace(
+ row.Cells[(int)SalesTableColumns.TotalSales].EditedFormattedValue.ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int)SalesTableColumns.TotalSales].EditedFormattedValue.ToString());
+ actualSale.Cost =
+ string.IsNullOrWhiteSpace(
+ row.Cells[(int)SalesTableColumns.Cost].EditedFormattedValue.ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int)SalesTableColumns.Cost].EditedFormattedValue.ToString());
+ actualSale.ProfitReturn =
+ string.IsNullOrWhiteSpace(
+ row.Cells[(int)SalesTableColumns.ProfitReturn].EditedFormattedValue.ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int)SalesTableColumns.ProfitReturn].EditedFormattedValue
+ .ToString());
+ actualSale.TotalProfitReturn =
+ string.IsNullOrWhiteSpace(
+ row.Cells[(int)SalesTableColumns.TotalProfitReturn].EditedFormattedValue
+ .ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int)SalesTableColumns.TotalProfitReturn].EditedFormattedValue
+ .ToString());
+ actualSale.FkAdItemId = adItem.Id;
+ actualSale.RowAttribute = rowAttribute;
+ actualSale.RowPosition = row.Index + 1;
+ actualSale.FkDateId = date.Id;
+ db.ActualSales.Add(actualSale);
+ idNumbers.Add(row.Index, actualSale);
+ }
+ else
+ {
+ //If there is one, set the current object to reference the existing record and update.
+ actualSale = db.ActualSales.Find(int.Parse(row.Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString()));
+ if (actualSale == null) throw new DbUpdateException("Failed to retrieve Actual Sales record.");
+ actualSale.Sold = row.Cells[(int)SalesTableColumns.Sold].EditedFormattedValue.ToString();
+ actualSale.SalePrice =
+ row.Cells[(int)SalesTableColumns.SalePrice].EditedFormattedValue.ToString();
+ actualSale.TotalSales = string.IsNullOrWhiteSpace(
+ row.Cells[(int)SalesTableColumns.TotalSales].EditedFormattedValue.ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int)SalesTableColumns.TotalSales].EditedFormattedValue.ToString());
+ actualSale.Cost = string.IsNullOrWhiteSpace(
+ row.Cells[(int)SalesTableColumns.Cost].EditedFormattedValue.ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int)SalesTableColumns.Cost].EditedFormattedValue.ToString());
+ actualSale.ProfitReturn = string.IsNullOrWhiteSpace(
+ row.Cells[(int)SalesTableColumns.ProfitReturn].EditedFormattedValue.ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int)SalesTableColumns.ProfitReturn].EditedFormattedValue.ToString());
+ actualSale.TotalProfitReturn = string.IsNullOrWhiteSpace(
+ row.Cells[(int)SalesTableColumns.TotalProfitReturn].EditedFormattedValue.ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int)SalesTableColumns.TotalProfitReturn].EditedFormattedValue
+ .ToString());
+ actualSale.FkAdItemId = -1;//adItem.Id;
+ actualSale.RowAttribute = rowAttribute;
+ actualSale.RowPosition = row.Index + 1;
+ }
+ //Update the last row that was done before jumping to the next loop.
+ lastRow = row.Index;
+ }
+ if (lastRow != -1)
+ {
+ db.SaveChanges();
+ //Insert the ID numbers into the respective rows, making the assumption that all the methods will succeed.
+ foreach (var index in idNumbers)
+ {
+ actualSalesDataGridView.Rows[index.Key].Cells[(int) SalesTableColumns.Id].Value = index.Value.Id;
+ }
+ informationLabel.Text += @"Updated the Actual Sales table." + Environment.NewLine;
+ }
+ else
+ {
+ informationLabel.Text += @"No changes detected in Actual Sales." + Environment.NewLine;
+ }
+ scope.Complete();
+ }
+ catch (DbUpdateException e)
+ {
+ errorLabel.Text = @"Failed to update Actual Sales: Row " + (lastRow + 1) + @".";
+ LogConsole.WriteToLog(FrmLogConsole.Level.Error, e.Message);
+ throw new TransactionAbortedException("Updates to Projections aborted." + Environment.NewLine +
+ "Updates to Inventory aborted." + Environment.NewLine +
+ "Failed to update Actual Sales" + Environment.NewLine);
+ }
+ }
+ }
+
+ private void SaveInvoices(WeekEndingDate date)
+ {
+ var db = new AdvertisingProfitControlModel();
+ var lastRow = -1;
+ using (var scope = new TransactionScope())
+ {
+ try
+ {
+ var idNumbers = new Dictionary();
+ //Spin through the Projections DataGridView and build Projection objects.
+ foreach (DataGridViewRow row in invoicesDataGridView.Rows)
+ {
+ //If the row is a new row or is not dirty then continue to the next row if applicable.
+ if (row.IsNewRow) continue;
+ if (!(bool)row.Cells[(int) InvoiceTableColumns.IsDirty].EditedFormattedValue) continue;
+ //Obtain the ad item.
+ var supplier = new Supplier();
+ //Sadly, LINQ doesn't like calls to the ToString method so we create a temp variable.
+ var supplierName = row.Cells[(int)InvoiceTableColumns.Supplier].EditedFormattedValue.ToString();
+ //Check to see if the ad item is in the database and if so grab the object for it, otherwise add it.
+ if (db.Suppliers.Any(x => x.Name == supplierName))
+ {
+ //Match
+ supplier = db.Suppliers.Single(x => x.Name == supplierName);
+ }
+ else
+ {
+ //Not a match
+ supplier.Name = row.Cells[(int)InvoiceTableColumns.Supplier].EditedFormattedValue.ToString();
+ db.Suppliers.Add(supplier);
+ db.SaveChanges();
+ }
+ var invoice = new Invoice();
+ //Check for an ID number
+ if (row.Cells[(int)InvoiceTableColumns.Id].EditedFormattedValue.ToString() == string.Empty)
+ {
+ //If there isn't one then create a new record and add it to the database.
+ invoice.InvoiceDate = DateTime.Parse(row.Cells[(int)InvoiceTableColumns.InvoiceDate].EditedFormattedValue.ToString());
+ invoice.InvoiceNumber = int.Parse(row.Cells[(int)InvoiceTableColumns.InvoiceNumber].EditedFormattedValue.ToString());
+ invoice.InvoiceNetAmountAtCost =
+ string.IsNullOrWhiteSpace(
+ row.Cells[(int)InvoiceTableColumns.InvoiceNetAmountAtCost].EditedFormattedValue.ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int)InvoiceTableColumns.InvoiceNetAmountAtCost].EditedFormattedValue.ToString());
+ invoice.InvoiceNetAmount =
+ string.IsNullOrWhiteSpace(
+ row.Cells[(int)InvoiceTableColumns.InvoiceNetAmount].EditedFormattedValue.ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int)InvoiceTableColumns.InvoiceNetAmount].EditedFormattedValue.ToString());
+ invoice.InvoiceNote = row.Cells[(int)InvoiceTableColumns.InvoiceNote].EditedFormattedValue.ToString();
+ invoice.FkSupplierId = supplier.Id;
+ invoice.FkDateId = date.Id;
+ db.Invoices.Add(invoice);
+ idNumbers.Add(row.Index, invoice);
+ }
+ else
+ {
+ //If there is one, set the current object to reference the existing record and update.
+ invoice = db.Invoices.Find(int.Parse(row.Cells[(int)InvoiceTableColumns.Id].EditedFormattedValue.ToString()));
+ if (invoice != null)
+ {
+ invoice.InvoiceDate =
+ DateTime.Parse(
+ row.Cells[(int) InvoiceTableColumns.InvoiceDate].EditedFormattedValue.ToString());
+ invoice.InvoiceNumber =
+ int.Parse(
+ row.Cells[(int) InvoiceTableColumns.InvoiceNumber].EditedFormattedValue.ToString
+ ());
+ invoice.InvoiceNetAmountAtCost =
+ string.IsNullOrWhiteSpace(
+ row.Cells[(int) InvoiceTableColumns.InvoiceNetAmountAtCost].EditedFormattedValue
+ .ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int) InvoiceTableColumns.InvoiceNetAmountAtCost]
+ .EditedFormattedValue.ToString());
+ invoice.InvoiceNetAmount =
+ string.IsNullOrWhiteSpace(
+ row.Cells[(int) InvoiceTableColumns.InvoiceNetAmount].EditedFormattedValue
+ .ToString())
+ ? 0
+ : decimal.Parse(
+ row.Cells[(int) InvoiceTableColumns.InvoiceNetAmount].EditedFormattedValue
+ .ToString());
+ invoice.InvoiceNote =
+ row.Cells[(int) InvoiceTableColumns.InvoiceNote].EditedFormattedValue.ToString();
+ invoice.FkSupplierId = supplier.Id;
+ }
+ else
+ {
+ throw new TransactionAbortedException("Failed to retrieve Invoice record");
+ }
+ }
+ //Update the last row that was done before jumping to the next loop.
+ lastRow = row.Index;
+ }
+ if (lastRow != -1)
+ {
+ db.SaveChanges();
+ //Insert the ID numbers into the respective rows, making the assumption that all the methods will succeed.
+ foreach (var index in idNumbers)
+ {
+ invoicesDataGridView.Rows[index.Key].Cells[(int)InvoiceTableColumns.Id].Value = index.Value.Id;
+ invoicesDataGridView.Rows[index.Key].HeaderCell.Style.BackColor = ApplicationColors.EditingSaved;
+ invoicesDataGridView.Rows[index.Key].Cells[(int)InvoiceTableColumns.IsDirty].Value = false;
+ }
+ informationLabel.Text += @"Updated the Invoices table." + Environment.NewLine;
+ }
+ else
+ {
+ informationLabel.Text += @"No changes detected in Invoices." + Environment.NewLine;
+ }
+ scope.Complete();
+ }
+ catch (TransactionAbortedException e)
+ {
+ errorLabel.Text = @"Failed to update Invoices: Row " + (lastRow + 1) + @".";
+ informationLabel.Text += @"Failed to update Invoices." + Environment.NewLine;
+ LogConsole.WriteToLog(FrmLogConsole.Level.Error, e.Message);
+ //Check for the ID numbers to see what is in the database and what isn't.
+ foreach (DataGridViewRow row in inventoryDataGridView.Rows)
+ {
+ if (row.IsNewRow) break;
+ if (row.Cells[(int) InvoiceTableColumns.Id].EditedFormattedValue.ToString() != string.Empty)
+ continue;
+ var id = int.Parse(row.Cells[(int) InvoiceTableColumns.Id].EditedFormattedValue.ToString());
+ if (db.Invoices.Any(x => x.Id == id)) continue;
+ row.Cells[(int) InvoiceTableColumns.Id].Value = string.Empty;
+ row.Cells[(int) InvoiceTableColumns.IsDirty].Value = true;
+ }
+ }
+ }
+ }
+
+ private void SaveWeeklySales(WeekEndingDate date)
+ {
+ if (!isWeeklySalesDirtyCheckBox.Checked)
+ {
+ informationLabel.Text += @"No changes detected to Weekly Sales." + Environment.NewLine;
+ return;
+ }
+ var db = new AdvertisingProfitControlModel();
+ using (var scope = new TransactionScope())
+ {
+ try
+ {
+ var weeklySale = new WeeklySale();
+ //Check for an ID number
+ if (isWeeklySalesDirtyCheckBox.Tag == null)
+ {
+ //If there isn't one then create a new record and add it to the database.
+ weeklySale.Sunday = sundayWeeklySalesTextBox.Text == string.Empty ? 0 : decimal.Parse(sundayWeeklySalesTextBox.Text);
+ weeklySale.Monday = mondayWeeklySalesTextBox.Text == string.Empty ? 0 : decimal.Parse(mondayWeeklySalesTextBox.Text);
+ weeklySale.Tuesday = tuesdayWeeklySalesTextBox.Text == string.Empty ? 0 : decimal.Parse(tuesdayWeeklySalesTextBox.Text);
+ weeklySale.Wednesday = wednesdayWeeklySalesTextBox.Text == string.Empty ? 0 : decimal.Parse(wednesdayWeeklySalesTextBox.Text);
+ weeklySale.Thursday = thursdayWeeklySalesTextBox.Text == string.Empty ? 0 : decimal.Parse(thursdayWeeklySalesTextBox.Text);
+ weeklySale.Friday = fridayWeeklySalesTextBox.Text == string.Empty ? 0 : decimal.Parse(fridayWeeklySalesTextBox.Text);
+ weeklySale.Saturday = saturdayWeeklySalesTextBox.Text == string.Empty ? 0 : decimal.Parse(saturdayWeeklySalesTextBox.Text);
+ weeklySale.TotalSales = totalWeeklySalesTextBox.Text == string.Empty ? 0 : decimal.Parse(totalWeeklySalesTextBox.Text);
+ weeklySale.FkDateId = date.Id;
+ db.WeeklySales.Add(weeklySale);
+ }
+ else
+ {
+ var id = (int) isWeeklySalesDirtyCheckBox.Tag;
+ weeklySale = db.WeeklySales.Single(x => x.Id == id);
+ //If there is one, set the current object to reference the existing record and update.
+ weeklySale.Sunday = sundayWeeklySalesTextBox.Text == string.Empty ? 0 : decimal.Parse(sundayWeeklySalesTextBox.Text);
+ weeklySale.Monday = mondayWeeklySalesTextBox.Text == string.Empty ? 0 : decimal.Parse(mondayWeeklySalesTextBox.Text);
+ weeklySale.Tuesday = tuesdayWeeklySalesTextBox.Text == string.Empty ? 0 : decimal.Parse(tuesdayWeeklySalesTextBox.Text);
+ weeklySale.Wednesday = wednesdayWeeklySalesTextBox.Text == string.Empty ? 0 : decimal.Parse(wednesdayWeeklySalesTextBox.Text);
+ weeklySale.Thursday = thursdayWeeklySalesTextBox.Text == string.Empty ? 0 : decimal.Parse(thursdayWeeklySalesTextBox.Text);
+ weeklySale.Friday = fridayWeeklySalesTextBox.Text == string.Empty ? 0 : decimal.Parse(fridayWeeklySalesTextBox.Text);
+ weeklySale.Saturday = saturdayWeeklySalesTextBox.Text == string.Empty ? 0 : decimal.Parse(saturdayWeeklySalesTextBox.Text);
+ weeklySale.TotalSales = totalWeeklySalesTextBox.Text == string.Empty ? 0 : decimal.Parse(totalWeeklySalesTextBox.Text);
+ }
+ db.SaveChanges();
+ //Insert the ID numbers into the respective rows, making the assumption that all the methods will succeed.
+ isWeeklySalesDirtyCheckBox.Tag = weeklySale.Id;
+ isWeeklySalesDirtyCheckBox.Checked = false;
+ informationLabel.Text += @"Updated Weekly Sales." + Environment.NewLine;
+ scope.Complete();
+ }
+ catch (TransactionAbortedException e)
+ {
+ errorLabel.Text = @"Failed to update Weekly Sales.";
+ informationLabel.Text += @"Failed to update Weekly Sales." + Environment.NewLine;
+ LogConsole.WriteToLog(FrmLogConsole.Level.Error, e.Message);
+ //If the tag contains an object check to see if its in the database, if its not clear the tag out.
+ if (isWeeklySalesDirtyCheckBox.Tag != null)
+ {
+ var id = (int) isWeeklySalesDirtyCheckBox.Tag;
+ if (!db.WeeklySales.Any(x => x.Id == id))
+ {
+ isWeeklySalesDirtyCheckBox.Tag = null;
+ isWeeklySalesDirtyCheckBox.Checked = true;
+ }
+ }
+ }
+ }
+ }
+
+ private void SaveTaxable(WeekEndingDate date)
+ {
+ if (!isTaxableDirtyCheckBox.Checked)
+ {
+ informationLabel.Text += @"No changes detected to Taxable." + Environment.NewLine;
+ return;
+ }
+ var db = new AdvertisingProfitControlModel();
+ using (var scope = new TransactionScope())
+ {
+ try
+ {
+ var taxable = new Taxable();
+ //Check for an ID number
+ if (isTaxableDirtyCheckBox.Tag == null)
+ {
+ //If there isn't one then create a new record and add it to the database.
+ taxable.Sunday = sundayTaxableTextBox.Text == string.Empty ? 0 : decimal.Parse(sundayTaxableTextBox.Text);
+ taxable.Monday = mondayTaxableTextBox.Text == string.Empty ? 0 : decimal.Parse(mondayTaxableTextBox.Text);
+ taxable.Tuesday = tuesdayTaxableTextBox.Text == string.Empty ? 0 : decimal.Parse(tuesdayTaxableTextBox.Text);
+ taxable.Wednesday = wednesdayTaxableTextBox.Text == string.Empty ? 0 : decimal.Parse(wednesdayTaxableTextBox.Text);
+ taxable.Thursday = thursdayTaxableTextBox.Text == string.Empty ? 0 : decimal.Parse(thursdayTaxableTextBox.Text);
+ taxable.Friday = fridayTaxableTextBox.Text == string.Empty ? 0 : decimal.Parse(fridayTaxableTextBox.Text);
+ taxable.Saturday = saturdayTaxableTextBox.Text == string.Empty ? 0 : decimal.Parse(saturdayTaxableTextBox.Text);
+ taxable.Total = totalTaxableTextBox.Text == string.Empty ? 0 : decimal.Parse(totalTaxableTextBox.Text);
+ taxable.FkDateId = date.Id;
+ db.Taxables.Add(taxable);
+ }
+ else
+ {
+ var id = (int)isTaxableDirtyCheckBox.Tag;
+ taxable = db.Taxables.Single(x => x.Id == id);
+ //If there is one, set the current object to reference the existing record and update.
+ taxable.Sunday = sundayTaxableTextBox.Text == string.Empty ? 0 : decimal.Parse(sundayTaxableTextBox.Text);
+ taxable.Monday = mondayTaxableTextBox.Text == string.Empty ? 0 : decimal.Parse(mondayTaxableTextBox.Text);
+ taxable.Tuesday = tuesdayTaxableTextBox.Text == string.Empty ? 0 : decimal.Parse(tuesdayTaxableTextBox.Text);
+ taxable.Wednesday = wednesdayTaxableTextBox.Text == string.Empty ? 0 : decimal.Parse(wednesdayTaxableTextBox.Text);
+ taxable.Thursday = thursdayTaxableTextBox.Text == string.Empty ? 0 : decimal.Parse(thursdayTaxableTextBox.Text);
+ taxable.Friday = fridayTaxableTextBox.Text == string.Empty ? 0 : decimal.Parse(fridayTaxableTextBox.Text);
+ taxable.Saturday = saturdayTaxableTextBox.Text == string.Empty ? 0 : decimal.Parse(saturdayTaxableTextBox.Text);
+ taxable.Total = totalTaxableTextBox.Text == string.Empty ? 0 : decimal.Parse(totalTaxableTextBox.Text);
+ }
+ db.SaveChanges();
+ //Insert the ID numbers into the respective rows, making the assumption that all the methods will succeed.
+ isTaxableDirtyCheckBox.Tag = taxable.Id;
+ isTaxableDirtyCheckBox.Checked = false;
+ informationLabel.Text += @"Updated Taxable." + Environment.NewLine;
+ scope.Complete();
+ }
+ catch (TransactionAbortedException e)
+ {
+ errorLabel.Text = @"Failed to update Taxable.";
+ informationLabel.Text += @"Failed to update Taxable." + Environment.NewLine;
+ LogConsole.WriteToLog(FrmLogConsole.Level.Error, e.Message);
+ //If the tag contains an object check to see if its in the database, if its not clear the tag out.
+ if (isTaxableDirtyCheckBox.Tag != null)
+ {
+ var id = (int)isTaxableDirtyCheckBox.Tag;
+ if (!db.Taxables.Any(x => x.Id == id))
+ {
+ isTaxableDirtyCheckBox.Tag = null;
+ isTaxableDirtyCheckBox.Checked = true;
+ }
+ }
+ }
+ }
+ }
+
+ private void SaveCostAnalysis(WeekEndingDate date)
+ {
+ if (!isCostAnalysisDirtyCheckBox.Checked)
+ {
+ informationLabel.Text += @"No changes detected to Cost Analysis." + Environment.NewLine;
+ return;
+ }
+ var db = new AdvertisingProfitControlModel();
+ using (var scope = new TransactionScope())
+ {
+ try
+ {
+ var costAnalysis = new CostAnalysi();
+ //Check for an ID number
+ if (isCostAnalysisDirtyCheckBox.Tag == null)
+ {
+ //If there isn't one then create a new record and add it to the database.
+ costAnalysis.SalesPerManHour = salesPerManHourTextBox.Text == string.Empty ? 0 : decimal.Parse(salesPerManHourTextBox.Text);
+ costAnalysis.SalaryPercentage = salaryPercentageTextBox.Text == string.Empty ? 0 : decimal.Parse(salaryPercentageTextBox.Text);
+ costAnalysis.SalaryDollar = salaryDollarsTextBox.Text == string.Empty ? 0 : decimal.Parse(salaryDollarsTextBox.Text);
+ costAnalysis.Supplies = suppliesTextBox.Text == string.Empty ? 0 : decimal.Parse(suppliesTextBox.Text);
+ costAnalysis.FkDateId = date.Id;
+ db.CostAnalysis.Add(costAnalysis);
+ }
+ else
+ {
+ var id = (int)isCostAnalysisDirtyCheckBox.Tag;
+ costAnalysis = db.CostAnalysis.Single(x => x.Id == id);
+ //If there is one, set the current object to reference the existing record and update.
+ costAnalysis.SalesPerManHour = salesPerManHourTextBox.Text == string.Empty ? 0 : decimal.Parse(salesPerManHourTextBox.Text);
+ costAnalysis.SalaryPercentage = salaryPercentageTextBox.Text == string.Empty ? 0 : decimal.Parse(salaryPercentageTextBox.Text);
+ costAnalysis.SalaryDollar = salaryDollarsTextBox.Text == string.Empty ? 0 : decimal.Parse(salaryDollarsTextBox.Text);
+ costAnalysis.Supplies = suppliesTextBox.Text == string.Empty ? 0 : decimal.Parse(suppliesTextBox.Text);
+ }
+ db.SaveChanges();
+ //Insert the ID numbers into the respective rows, making the assumption that all the methods will succeed.
+ isCostAnalysisDirtyCheckBox.Tag = costAnalysis.Id;
+ isCostAnalysisDirtyCheckBox.Checked = false;
+ informationLabel.Text += @"Updated Cost Analysis." + Environment.NewLine;
+ scope.Complete();
+ }
+ catch (TransactionAbortedException e)
+ {
+ errorLabel.Text = @"Failed to update Cost Analysis.";
+ informationLabel.Text += @"Failed to update Cost Analysis." + Environment.NewLine;
+ LogConsole.WriteToLog(FrmLogConsole.Level.Error, e.Message);
+ //If the tag contains an object check to see if its in the database, if its not clear the tag out.
+ if (isCostAnalysisDirtyCheckBox.Tag != null)
+ {
+ var id = (int)isCostAnalysisDirtyCheckBox.Tag;
+ if (!db.CostAnalysis.Any(x => x.Id == id))
+ {
+ isCostAnalysisDirtyCheckBox.Tag = null;
+ isCostAnalysisDirtyCheckBox.Checked = true;
+ }
+ }
+ }
+ }
+ }
+
+ private void SaveComments(WeekEndingDate date)
+ {
+ if (!isCommentDirtyCheckBox.Checked)
+ {
+ informationLabel.Text += @"No changes detected for Comments." + Environment.NewLine;
+ return;
+ }
+ var db = new AdvertisingProfitControlModel();
+ using (var scope = new TransactionScope())
+ {
+ try
+ {
+ var note = new Note();
+ //Check for an ID number
+ if (isCommentDirtyCheckBox.Tag == null)
+ {
+ //If there isn't one then create a new record and add it to the database.
+ note.Remark = commentsTextBox.Text;
+ note.FkDateId = date.Id;
+ db.Notes.Add(note);
+ }
+ else
+ {
+ //If there is one, set the current object to reference the existing record and update.
+ var id = (int) isCommentDirtyCheckBox.Tag;
+ note = db.Notes.Single(x => x.Id == id);
+ note.Remark = commentsTextBox.Text;
+ }
+ db.SaveChanges();
+ //Insert the ID numbers into the respective rows, making the assumption that all the methods will succeed.
+ isCommentDirtyCheckBox.Tag = note.Id;
+ isCommentDirtyCheckBox.Checked = false;
+ informationLabel.Text += @"Updated Comments." + Environment.NewLine;
+ scope.Complete();
+ }
+ catch (TransactionAbortedException e)
+ {
+ errorLabel.Text = @"Failed to update Comments.";
+ informationLabel.Text += @"Failed to update Comments." + Environment.NewLine;
+ LogConsole.WriteToLog(FrmLogConsole.Level.Error, e.Message);
+ //If the tag contains an object check to see if its in the database, if its not clear the tag out.
+ if (isCommentDirtyCheckBox.Tag != null)
+ {
+ var id = (int)isCommentDirtyCheckBox.Tag;
+ if (!db.Notes.Any(x => x.Id == id))
+ {
+ isCommentDirtyCheckBox.Tag = null;
+ isCommentDirtyCheckBox.Checked = true;
+ }
+ }
+ }
+ }
+ }
+
+ private static AdSpecial GetAdSpecial(string adSpecialText)
+ {
+ var db = new AdvertisingProfitControlModel();
+ var adSpecial = new AdSpecial();
+ //An ad special does exist so grab its ID from the database.
+ if (db.AdSpecials.Any(x => x.Name == adSpecialText))
+ {
+ //Match found
+ adSpecial = db.AdSpecials.Single(x => x.Name == adSpecialText);
}
else
{
- //The above method reports that it failed to insert the date into the database.
- errorLabel.Text = @"Failed to insert the date '" + date + @"' into the database.";
+ LogConsole.WriteToLog(FrmLogConsole.Level.Error, "Failed to retrieve the ad special ID for '" + adSpecialText + "'.");
}
- return dateId;
- }
-
- private bool SaveInvoices(int dateId, bool displayInformation = true)
- {
- var dbT = new DatabaseTracker();
- var dbW = new DatabaseWriter(dbT.DatabaseConnectionString);
- //Commit the Invoice table to the database.
- var writerStatus = dbW.ProccessInvoiceTable(invoicesDataGridView, dateId, dbT.DatabaseConnectionString);
- if (writerStatus.GetWritingOperationStatus() == WritingOperationStatus.Failed)
- {
- errorLabel.Text = writerStatus.GetErrorMessage();
- return false;
- }
- if (displayInformation) informationLabel.Text += writerStatus.GetErrorMessage() + Environment.NewLine;
- return true;
- }
-
- private bool SaveComments(int dateId, bool displayInformation = true)
- {
- var dbT = new DatabaseTracker();
- var dbW = new DatabaseWriter(dbT.DatabaseConnectionString);
- //TODO: If the comments are null but there is a comment ID, delete the comments from the database.
- if (isCommentDirtyCheckBox.Checked)
- {
- if (isCommentDirtyCheckBox.Tag == null)
- {
- var status = dbW.ProcessComments(commentsTextBox.Text, dateId, dbT.DatabaseConnectionString);
- if (status.Status == WritingOperationStatus.Failed)
- {
- errorLabel.Text = status.ErrorMessage;
- return false;
- }
- if (displayInformation) informationLabel.Text += @"Comment(s) processed successfully." + Environment.NewLine;
- var id = status.Id;
- isCommentDirtyCheckBox.Tag = id;
- isCommentDirtyCheckBox.Text = @"IsCommentDirty (" + id + @")";
- isCommentDirtyCheckBox.Checked = false;
- return true;
- }
- else
- {
- //Check for a null comment box and delete the comment ID from the database.
- //Then if all is successful clear the Tag in the isCommentsDirty check box.
- var status = dbW.ProcessComments(commentsTextBox.Text, dateId, dbT.DatabaseConnectionString, int.Parse(isCommentDirtyCheckBox.Tag.ToString()));
- if (status.Status == WritingOperationStatus.Failed)
- {
- errorLabel.Text = status.ErrorMessage;
- return false;
- }
- isCommentDirtyCheckBox.Checked = false;
- if (displayInformation) informationLabel.Text += @"Comment(s) processed successfully." + Environment.NewLine;
- return true;
- }
- }
- if (displayInformation) informationLabel.Text += @"No changes detected for the comment(s)" + Environment.NewLine;
- return true;
- }
-
- private bool SaveWeeklySales(int dateId, bool displayInformation = true)
- {
- var dbT = new DatabaseTracker();
- var dbW = new DatabaseWriter(dbT.DatabaseConnectionString);
- //Begin checking the Weekly Sales.
- if (isWeeklySalesDirtyCheckBox.Checked)
- {
- //Parse out all the text boxes' values in the weekly sales group.
- var weeklySales = new double[8];
- weeklySales[0] = sundayWeeklySalesTextBox.Text == "" ? 0 : double.Parse(sundayWeeklySalesTextBox.Text);
- weeklySales[1] = mondayWeeklySalesTextBox.Text == "" ? 0 : double.Parse(mondayWeeklySalesTextBox.Text);
- weeklySales[2] = tuesdayWeeklySalesTextBox.Text == "" ? 0 : double.Parse(tuesdayWeeklySalesTextBox.Text);
- weeklySales[3] = wednesdayWeeklySalesTextBox.Text == "" ? 0 : double.Parse(wednesdayWeeklySalesTextBox.Text);
- weeklySales[4] = thursdayWeeklySalesTextBox.Text == "" ? 0 : double.Parse(thursdayWeeklySalesTextBox.Text);
- weeklySales[5] = fridayWeeklySalesTextBox.Text == "" ? 0 : double.Parse(fridayWeeklySalesTextBox.Text);
- weeklySales[6] = saturdayWeeklySalesTextBox.Text == "" ? 0 : double.Parse(saturdayWeeklySalesTextBox.Text);
- weeklySales[7] = totalWeeklySalesTextBox.Text == "" ? 0 : double.Parse(totalWeeklySalesTextBox.Text);
-
- if (isWeeklySalesDirtyCheckBox.Tag == null)
- {
- //Weekly sales is not in the database.
- var status = dbW.ProcessWeeklySales(weeklySales, dateId, dbT.DatabaseConnectionString);
- if (status.Status == WritingOperationStatus.Failed)
- {
- errorLabel.Text = status.ErrorMessage;
- return false;
- }
- if (displayInformation) informationLabel.Text += @"Weekly Sales processed successfully." + Environment.NewLine;
- isWeeklySalesDirtyCheckBox.Tag = status.Id;
- isWeeklySalesDirtyCheckBox.Text = @"IsWeeklySalesDirty (" + status.Id + @")";
- isWeeklySalesDirtyCheckBox.Checked = false;
- return true;
- }
- else
- {
- var status = dbW.ProcessWeeklySales(weeklySales, dateId, dbT.DatabaseConnectionString, int.Parse(isWeeklySalesDirtyCheckBox.Tag.ToString()));
- if (status.Status == WritingOperationStatus.Failed)
- {
- errorLabel.Text = status.ErrorMessage;
- return false;
- }
- isWeeklySalesDirtyCheckBox.Checked = false;
- if (displayInformation) informationLabel.Text += @"Weekly Sales updated successfully." + Environment.NewLine;
- return true;
- }
- }
- if (displayInformation) informationLabel.Text += @"No changes detected for Weekly Sales." + Environment.NewLine;
- return true;
- }
-
- private bool SaveTaxable(int dateId, bool displayInformation = true)
- {
- var dbT = new DatabaseTracker();
- var dbW = new DatabaseWriter(dbT.DatabaseConnectionString);
- //Begin checking the Taxable.
- if (isTaxableDirtyCheckBox.Checked)
- {
- //Parse out all the text boxes' values in the taxable group.
- var taxable = new double[8];
- taxable[0] = sundayTaxableTextBox.Text == "" ? 0 : double.Parse(sundayTaxableTextBox.Text);
- taxable[1] = mondayTaxableTextBox.Text == "" ? 0 : double.Parse(mondayTaxableTextBox.Text);
- taxable[2] = tuesdayTaxableTextBox.Text == "" ? 0 : double.Parse(tuesdayTaxableTextBox.Text);
- taxable[3] = wednesdayTaxableTextBox.Text == "" ? 0 : double.Parse(wednesdayTaxableTextBox.Text);
- taxable[4] = thursdayTaxableTextBox.Text == "" ? 0 : double.Parse(thursdayTaxableTextBox.Text);
- taxable[5] = fridayTaxableTextBox.Text == "" ? 0 : double.Parse(fridayTaxableTextBox.Text);
- taxable[6] = saturdayTaxableTextBox.Text == "" ? 0 : double.Parse(saturdayTaxableTextBox.Text);
- taxable[7] = totalTaxableTextBox.Text == "" ? 0 : double.Parse(totalTaxableTextBox.Text);
-
- if (isTaxableDirtyCheckBox.Tag == null)
- {
- //Taxable is not in the database.
- var status = dbW.ProcessTaxable(taxable, dateId, dbT.DatabaseConnectionString);
- if (status.Status == WritingOperationStatus.Failed)
- {
- errorLabel.Text = status.ErrorMessage;
- return false;
- }
- if (displayInformation) informationLabel.Text += @"Taxable processed successfully." + Environment.NewLine;
- isTaxableDirtyCheckBox.Tag = status.Id;
- isTaxableDirtyCheckBox.Text = @"IsTaxableDirty (" + status.Id + @")";
- return true;
- }
- else
- {
- var status = dbW.ProcessTaxable(taxable, dateId, dbT.DatabaseConnectionString, int.Parse(isTaxableDirtyCheckBox.Tag.ToString()));
- if (status.Status == WritingOperationStatus.Failed)
- {
- errorLabel.Text = status.ErrorMessage;
- return false;
- }
- isTaxableDirtyCheckBox.Checked = false;
- if (displayInformation) informationLabel.Text += @"Taxable updated successfully." + Environment.NewLine;
- return true;
- }
- }
- if (displayInformation) informationLabel.Text += @"No changes detected for Taxable." + Environment.NewLine;
- return true;
- }
-
- private bool SaveCostAnalysis(int dateId, bool displayInformation = true)
- {
- var dbT = new DatabaseTracker();
- var dbW = new DatabaseWriter(dbT.DatabaseConnectionString);
- //Begin checking cost analysis.
- if (isCostAnalysisDirtyCheckBox.Checked)
- {
- //Parse out the cost analysis group values.
- var costAnalysis = new double[4];
- costAnalysis[0] = salesPerManHourTextBox.Text == "" ? 0 : double.Parse(salesPerManHourTextBox.Text);
- costAnalysis[1] = salaryPercentageTextBox.Text == "" ? 0 : double.Parse(salaryPercentageTextBox.Text);
- costAnalysis[2] = salaryDollarsTextBox.Text == "" ? 0 : double.Parse(salaryDollarsTextBox.Text);
- costAnalysis[3] = suppliesTextBox.Text == "" ? 0 : double.Parse(suppliesTextBox.Text);
-
- if (isCostAnalysisDirtyCheckBox.Tag == null)
- {
- //Weekly sales is not in the database.
- var status = dbW.ProcessCostAnalysis(costAnalysis, dateId, dbT.DatabaseConnectionString);
- if (status.Status == WritingOperationStatus.Failed)
- {
- errorLabel.Text = status.ErrorMessage;
- return false;
- }
- if (displayInformation) informationLabel.Text += @"Costs Analysis processed successfully." + Environment.NewLine;
- isCostAnalysisDirtyCheckBox.Tag = status.Id;
- isCostAnalysisDirtyCheckBox.Text = @"IsCostAnalysisDirty (" + status.Id + @")";
- isCostAnalysisDirtyCheckBox.Checked = false;
- return true;
- }
- else
- {
- var status = dbW.ProcessCostAnalysis(costAnalysis, dateId, dbT.DatabaseConnectionString, int.Parse(isCostAnalysisDirtyCheckBox.Tag.ToString()));
- if (status.Status == WritingOperationStatus.Failed)
- {
- errorLabel.Text = status.ErrorMessage;
- return false;
- }
- isCostAnalysisDirtyCheckBox.Checked = false;
- if (displayInformation) informationLabel.Text += @"Cost Analysis updated successfully." + Environment.NewLine;
- return true;
- }
- }
- if (displayInformation) informationLabel.Text += @"No changes made to Cost Analysis." + Environment.NewLine;
- return true;
+ return adSpecial;
}
#endregion
- #region Table Trimming Operations
-
- private TrimmingOperationResult ConstructCleanedSalesTable(string tableName, int dateId, out DataTable newInsertTable, out DataTable updateTable)
- {
- //Create two DataTables one for the new items to be added to the database
- //and one for items that have to be updated.
- //New Sales Table Layout (Based on the Database's Physical Layout)
- //0:Sold 1:SalePrice 2:TotalSales 3:cost 4:ProfitReturn 5:TotalProfitReturn
- //6:FK_AdItemID 7:RowAttribute 8:FK_AdSpecialGroupName (ID) 9:RowPosition (not index based)
- //10:FK_DateID
- newInsertTable = new DataTable(tableName);
- //Update Sales Table Layout (Based on the Database's Physical Layout)
- //0:ID 1:Sold 2:SalePrice 3:TotalSales 4:cost 5:ProfitReturn 6:TotalProfitReturn
- //7:FK_AdItemID 8:RowAttribute 9:FK_AdSpecialGroupName (ID) 10:RowPosition (not index based)
- //11:FK_DateID
- updateTable = new DataTable(tableName);
- //Create a reference to the DataGridView that will be used (either Projections or Actual Sales).
- var dataGridView = tableName == "Projections" ? projectionsDataGridView : actualSalesDataGridView;
- //Construct a list of column names for the projections/actual sales DataGridViews and the inventory DataGirdView.
- string[] saleColumnNames =
- {
- "ID", "Sold", "SalePrice", "TotalSales", "Cost", "ProfitReturn", "TotalProfitReturn", "AdItemID", "RowAttribute", "AdSpecialID", "RowPosition", "DateID"
- };
- foreach (var columnName in saleColumnNames)
- {
- if (columnName == "ID") continue;
- var column = new DataColumn(columnName);
- newInsertTable.Columns.Add(column);
- }
- foreach (var columnName in saleColumnNames)
- {
- var column = new DataColumn(columnName);
- updateTable.Columns.Add(column);
- }
- //Create the database interaction objects.
- var databaseTracker = new DatabaseTracker();
- var databaseReader = new DatabaseReader();
- var databaseWriter = new DatabaseWriter(databaseTracker.DatabaseConnectionString);
- var adSpecialId = 0; //Entries in the database are not allowed to be zero (unique ID wise that is).
- //Grab the ad special ID, assuming there is one.
- if (_adSpecialIndex != -1)
- {
- //An ad special does exist so grab its ID from the database.
- int.TryParse(databaseReader.RetrieveGroupIdByString(dataGridView.Rows[_adSpecialIndex].Cells[(int) SalesTableColumns.AdItem].EditedFormattedValue.ToString(), databaseTracker.DatabaseConnectionString), out adSpecialId);
- }
- //Begin spinning through all the rows in the projections table.
- foreach (DataGridViewRow row in dataGridView.Rows)
- {
- //Always check for new row.
- if (row.IsNewRow) break;
- //Check to see if the current row is the ad special row.
- if (row.Index == _adSpecialIndex)
- {
- continue;
- }
- //Check to see if the row is dirty.
- if (!(bool) row.Cells[(int) SalesTableColumns.IsDirty].EditedFormattedValue)
- {
- //If it is not then continue on to the next row.
- continue;
- }
- //Try grabbing the row's ID number (the number that it is in the database).
- var rowIdNumber = row.Cells[(int) SalesTableColumns.Id].EditedFormattedValue.ToString() == "" ? 0 : int.Parse(row.Cells[(int) SalesTableColumns.Id].EditedFormattedValue.ToString());
- //Grab the ad item ID.
- var adItemId = int.Parse(databaseReader.RetrieveAdItemId(row.Cells[(int) SalesTableColumns.AdItem].EditedFormattedValue.ToString(), databaseTracker.DatabaseConnectionString));
- //If the return value is zero (0) then the ad item is not in the database so try to add it.
- if (adItemId == 0)
- {
- //Add the item to the database.
- adItemId = databaseWriter.InsertNewAdItem(row.Cells[(int) SalesTableColumns.AdItem].EditedFormattedValue.ToString());
- if (adItemId == 0)
- {
- //TODO: Throw an exception, this can not be allowed.
- //AdItemInsertionFailedException
- newInsertTable.Rows.Clear(); //Work around for now
- updateTable.Rows.Clear();
- errorLabel.Text = @"Failed to ad item to database.";
- return TrimmingOperationResult.FailedToTrim;
- }
- }
- //Determine the row's attribute.
- var rowAttribute = 0; //Zero (0) means no grouping, its not a header nor a member.
- if ((bool) row.Cells[(int) SalesTableColumns.IsHeaderRow].EditedFormattedValue && !(bool) row.Cells[(int) SalesTableColumns.IsMemberRow].EditedFormattedValue)
- {
- rowAttribute = 1;
- }
- else if ((bool) row.Cells[(int) SalesTableColumns.IsMemberRow].EditedFormattedValue && !(bool) row.Cells[(int) SalesTableColumns.IsHeaderRow].EditedFormattedValue)
- {
- rowAttribute = 2;
- }
- //Add the values to their respective data table.
- if (rowIdNumber == 0)
- {
- //This table is full of data not in the database so the ID column isn't needed.
- var newRow = new object[11];
- newRow[0] = row.Cells[(int) SalesTableColumns.Sold].EditedFormattedValue.ToString(); //Sold, is string
- newRow[1] = row.Cells[(int) SalesTableColumns.SalePrice].EditedFormattedValue.ToString(); //SalePrice, is string
- newRow[2] = row.Cells[(int) SalesTableColumns.TotalSales].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(row.Cells[(int) SalesTableColumns.TotalSales].EditedFormattedValue.ToString()); //TotalSales, must be a number
- newRow[3] = row.Cells[(int) SalesTableColumns.Cost].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(row.Cells[(int) SalesTableColumns.Cost].EditedFormattedValue.ToString()); //Cost, must be a number
- newRow[4] = row.Cells[(int) SalesTableColumns.ProfitReturn].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(row.Cells[(int) SalesTableColumns.ProfitReturn].EditedFormattedValue.ToString()); //ProfitReturn, must be a number
- newRow[5] = row.Cells[(int) SalesTableColumns.TotalProfitReturn].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(row.Cells[(int) SalesTableColumns.TotalProfitReturn].EditedFormattedValue.ToString()); //TotalProfitReturn, must be a number
- newRow[6] = adItemId;
- newRow[7] = rowAttribute;
- if (_adSpecialIndex != -1 && row.Index > _adSpecialIndex)
- {
- newRow[8] = adSpecialId;
- newRow[9] = row.Index; //"Subtract" one since we don't need to acknowledge the Ad Special Row's existence.
- }
- else
- {
- newRow[8] = 0;
- newRow[9] = row.Index + 1;
- }
- newRow[10] = dateId;
- newInsertTable.Rows.Add(newRow);
- }
- else
- {
- //This table is full of data that is already in the database.
- var newRow = new object[12];
- newRow[0] = rowIdNumber;
- newRow[1] = row.Cells[(int) SalesTableColumns.Sold].EditedFormattedValue.ToString(); //Sold, is string
- newRow[2] = row.Cells[(int) SalesTableColumns.SalePrice].EditedFormattedValue.ToString(); //SalePrice, is string
- newRow[3] = row.Cells[(int) SalesTableColumns.TotalSales].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(row.Cells[(int) SalesTableColumns.TotalSales].EditedFormattedValue.ToString()); //TotalSales, must be a number
- newRow[4] = row.Cells[(int) SalesTableColumns.Cost].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(row.Cells[(int) SalesTableColumns.Cost].EditedFormattedValue.ToString()); //Cost, must be a number
- newRow[5] = row.Cells[(int) SalesTableColumns.ProfitReturn].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(row.Cells[(int) SalesTableColumns.ProfitReturn].EditedFormattedValue.ToString()); //ProfitReturn, must be a number
- newRow[6] = row.Cells[(int) SalesTableColumns.TotalProfitReturn].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(row.Cells[(int) SalesTableColumns.TotalProfitReturn].EditedFormattedValue.ToString()); //TotalProfitReturn, must be a number
- newRow[7] = adItemId;
- newRow[8] = rowAttribute;
- if (_adSpecialIndex != -1 && row.Index > _adSpecialIndex)
- {
- newRow[9] = adSpecialId;
- newRow[10] = row.Index; //"Subtract" one since we don't need to acknowledge the Ad Special Row's existence.
- }
- else
- {
- newRow[9] = 0;
- newRow[10] = row.Index + 1;
- }
- newRow[11] = dateId;
- updateTable.Rows.Add(newRow);
- }
- }
-
- if (newInsertTable.Rows.Count == 0 && updateTable.Rows.Count == 0)
- {
- return TrimmingOperationResult.NoChangesRequired;
- }
- if (newInsertTable.Rows.Count > 0 && updateTable.Rows.Count == 0)
- {
- return TrimmingOperationResult.CreatedNewInsertionTable;
- }
- if (newInsertTable.Rows.Count == 0 && updateTable.Rows.Count > 0)
- {
- return TrimmingOperationResult.CreatedUpdateTable;
- }
- return TrimmingOperationResult.CreatedNewInsertionAndUpdateTables;
- }
-
- private TrimmingOperationResult ConstructCleanedInventoryTable(int dateId, out DataTable newInsertTable, out DataTable updateTable)
- {
- //Create two DataTables one for the new items to be added to the database
- //and one for items that have to be updated.
- //New inventory Table Layout (Based on the Database's Physical Layout)
- //0:Beginning Inventory 1:Received 2:Total Inventory 3:Ending Inventory
- //4:AdItemID 5:RowAttribute 6:GroupID 7:RowPosition 8:DateID
- newInsertTable = new DataTable("Inventory");
- //Update Sales Table Layout (Based on the Database's Physical Layout)
- //0:ID 1:BeginningInventory 2:Received 3:TotalInventory 4:EndingInventory
- //5:AdItemID 6:RowAttribute 7:GroupID 8:RowPosition 9:DateID
- updateTable = new DataTable("Inventory");
- //Construct a list of column names for the projections/actual sales DataGridViews and the inventory DataGirdView.
- string[] saleColumnNames =
- {
- "ID", "Sold", "SalePrice", "TotalSales", "Cost", "ProfitReturn", "TotalProfitReturn", "AdItemID", "RowAttribute", "AdSpecialID", "RowPosition", "DateID"
- };
- foreach (var columnName in saleColumnNames)
- {
- if (columnName == "ID") continue;
- var column = new DataColumn(columnName);
- newInsertTable.Columns.Add(column);
- }
- foreach (var columnName in saleColumnNames)
- {
- var column = new DataColumn(columnName);
- updateTable.Columns.Add(column);
- }
- //Create the database interaction objects.
- var databaseTracker = new DatabaseTracker();
- var databaseReader = new DatabaseReader();
- var databaseWriter = new DatabaseWriter(databaseTracker.DatabaseConnectionString);
- var adSpecialId = 0; //Entries in the database are not allowed to be zero (unique ID wise that is).
- //Grab the ad special ID, assuming there is one.
- if (_adSpecialIndex != -1)
- {
- //An ad special does exist so grab its ID from the database.
- int.TryParse(databaseReader.RetrieveGroupIdByString(inventoryDataGridView.Rows[_adSpecialIndex].Cells[(int) InventoryTableColumns.AdItem].EditedFormattedValue.ToString(), databaseTracker.DatabaseConnectionString), out adSpecialId);
- }
- //Begin spinning through all the rows in the projections table.
- foreach (DataGridViewRow row in inventoryDataGridView.Rows)
- {
- //Always check for new row.
- if (row.IsNewRow) break;
- //Check to see if the current row is the ad special row.
- if (row.Index == _adSpecialIndex)
- {
- //LogConsole.WriteToLog(FrmLogConsole.Level.Verbose, "Ad Special Row found at index " + row.Index + ".");
- continue;
- }
- //Check to see if the row is dirty.
- if (!(bool) row.Cells[(int) InventoryTableColumns.IsDirty].EditedFormattedValue)
- {
- //If it is not then continue on to the next row.
- continue;
- }
- //Try grabbing the row's ID number (the number that it is in the database).
- var rowIdNumber = row.Cells[(int) InventoryTableColumns.Id].EditedFormattedValue.ToString() == "" ? 0 : int.Parse(row.Cells[(int) InventoryTableColumns.Id].EditedFormattedValue.ToString());
- //Grab the ad item ID.
- var adItemId = int.Parse(databaseReader.RetrieveAdItemId(row.Cells[(int) InventoryTableColumns.AdItem].EditedFormattedValue.ToString(), databaseTracker.DatabaseConnectionString));
- //If the return value is zero (0) then the ad item is not in the database so try to add it.
- if (adItemId == 0)
- {
- //Add the item to the database.
- adItemId = databaseWriter.InsertNewAdItem(row.Cells[(int) InventoryTableColumns.AdItem].EditedFormattedValue.ToString());
- if (adItemId == 0)
- {
- //TODO: Throw an exception, this can not be allowed.
- //AdItemInsertionFailedException
- newInsertTable.Rows.Clear(); //Work around for now
- updateTable.Rows.Clear();
- return TrimmingOperationResult.FailedToTrim;
- }
- }
- //Determine the row's attribute.
- var rowAttribute = 0; //Zero (0) means no grouping, its not a header nor a member.
- if ((bool) row.Cells[(int) InventoryTableColumns.IsHeaderRow].EditedFormattedValue && !(bool) row.Cells[(int) InventoryTableColumns.IsMemberRow].EditedFormattedValue)
- {
- rowAttribute = 1;
- }
- else if ((bool) row.Cells[(int) InventoryTableColumns.IsMemberRow].EditedFormattedValue && !(bool) row.Cells[(int) InventoryTableColumns.IsHeaderRow].EditedFormattedValue)
- {
- rowAttribute = 2;
- }
- //Add the values to their respective data table.
- if (rowIdNumber == 0)
- {
- //This table is full of data not in the database so the ID column isn't needed.
- var newRow = new object[9];
- newRow[0] = row.Cells[(int) InventoryTableColumns.BeginningInventory].EditedFormattedValue.ToString(); //Beginning inventory, is string
- newRow[1] = row.Cells[(int) InventoryTableColumns.Recieved].EditedFormattedValue.ToString(); //Received, is string
- newRow[2] = row.Cells[(int) InventoryTableColumns.Total].EditedFormattedValue.ToString(); //Total inventory. is string
- newRow[3] = row.Cells[(int) InventoryTableColumns.EndingInventory].EditedFormattedValue.ToString(); //Ending inventory, is string
- newRow[4] = adItemId;
- newRow[5] = rowAttribute;
- if (_adSpecialIndex != -1 && row.Index > _adSpecialIndex)
- {
- newRow[6] = adSpecialId;
- newRow[7] = row.Index; //"Subtract" one since we don't need to acknowledge the Ad Special Row's existence.
- }
- else
- {
- newRow[6] = 0;
- newRow[7] = row.Index + 1;
- }
- newRow[8] = dateId;
- newInsertTable.Rows.Add(newRow);
- }
- else
- {
- //This table is full of data that is already in the database.
- var newRow = new object[10];
- newRow[0] = rowIdNumber;
- newRow[1] = row.Cells[(int) InventoryTableColumns.BeginningInventory].EditedFormattedValue.ToString(); //Beginning inventory, is string
- newRow[2] = row.Cells[(int) InventoryTableColumns.Recieved].EditedFormattedValue.ToString(); //Received, is string
- newRow[3] = row.Cells[(int) InventoryTableColumns.Total].EditedFormattedValue.ToString(); //Total inventory. is string
- newRow[4] = row.Cells[(int) InventoryTableColumns.EndingInventory].EditedFormattedValue.ToString(); //Ending inventory, is string
- newRow[5] = adItemId;
- newRow[6] = rowAttribute;
- if (_adSpecialIndex != -1 && row.Index > _adSpecialIndex)
- {
- newRow[7] = adSpecialId;
- newRow[8] = row.Index; //"Subtract" one since we don't need to acknowledge the Ad Special Row's existence.
- }
- else
- {
- newRow[7] = 0;
- newRow[8] = row.Index + 1;
- }
- newRow[9] = dateId;
- updateTable.Rows.Add(newRow);
- }
- }
-
- if (newInsertTable.Rows.Count == 0 && updateTable.Rows.Count == 0)
- {
- return TrimmingOperationResult.NoChangesRequired;
- }
- if (newInsertTable.Rows.Count > 0 && updateTable.Rows.Count == 0)
- {
- return TrimmingOperationResult.CreatedNewInsertionTable;
- }
- if (newInsertTable.Rows.Count == 0 && updateTable.Rows.Count > 0)
- {
- return TrimmingOperationResult.CreatedUpdateTable;
- }
- return TrimmingOperationResult.CreatedNewInsertionAndUpdateTables;
- }
-
- #endregion
-
private void addRecordButton_Click(object sender, EventArgs e)
{
SaveRecords();
@@ -4403,7 +4336,7 @@ namespace AdvertsingProfitControl
switch (result)
{
case DialogResult.Yes:
- SaveRecords(false);
+ SaveRecords();
break;
case DialogResult.Cancel:
e.Cancel = true;