Example #1
0
        private async void MapReportDialog_Shown(object sender, EventArgs e)
        {
            BusyMessage.Show("Loading...", this.FindForm());
            try
            {
                using (var uow = UnitOfWorkFactory.CreateUnitOfWork())
                {
                    mapBrowser.Visible = false;
                    downloaded         = 0;
                    total = 0;
                    modulePoints.Clear();

                    BusyMessage.UpdateMessage("Loading module locations");

                    if (filter.RecentOnly)
                    {
                        modulePoints.AddRange(uow.ModuleRepository.GetModulePoints(filter));
                    }
                    else
                    {
                        modulePoints.AddRange(uow.ModuleRepository.GetModulePointHistory(filter));
                    }

                    BusyMessage.UpdateMessage("Plotting module locations");
                }
            }
            catch (Exception exc)
            {
                Logging.Logger.Log(exc);
                BusyMessage.Close();
            }

            RenderMap();
        }
Example #2
0
 private List <ModuleHistoryEntity> getAllLocationRecordsAsync()
 {
     using (var uow = UnitOfWorkFactory.CreateUnitOfWork())
     {
         BusyMessage.UpdateMessage("Retrieving results");
         var results = uow.ModuleRepository.GetAllMatchingLocations(filterBar.Filter);
         return(results.ToList());
     }
 }
Example #3
0
        private List <ModuleEntity> getRecentModuleDocsAsync()
        {
            List <ModuleEntity> outputDocs = new List <ModuleEntity>();

            using (var uow = UnitOfWorkFactory.CreateUnitOfWork())
            {
                BusyMessage.UpdateMessage("Retrieving results");
                var results = uow.ModuleRepository.GetAllMatchingModules(filterBar.Filter);
                return(results.ToList());
            }
        }
        /*private void btnClearAllData_Click(object sender, EventArgs e)
         * {
         *  if (MessageBox.Show("Are you sure you want to clear all data?  This will delete all data in the system.  Data stored on truck and bridge computers should be cleared on each computer.", "Warning", MessageBoxButtons.YesNo) == DialogResult.Yes)
         *  {
         *      using (var uow = UnitOfWorkFactory.CreateUnitOfWork())
         *      {
         *          uow.TruckRepository.ClearTruckData();
         *          uow.LoadScanRepository.ClearBridgeScanData();
         *          uow.FeederScanRepository.ClearBridgeScanData();
         *      }
         *  }
         * }*/

        private async void btnClearModuleData_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to delete ALL pickup lists, modules, gin loads, bales, and all module location history?", "Warning!", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    using (var uow = UnitOfWorkFactory.CreateUnitOfWork())
                    {
                        BusyMessage.Show("Suspending background sync", this.FindForm());
                        CottonDBMS.EF.Tasks.GinSyncWithCloudTask.Cancel();
                        CottonDBMS.EF.Tasks.GinSyncWithCloudTask.WaitForSyncToFinish();

                        BusyMessage.UpdateMessage("Clearing module data");
                        uow.ModuleRepository.ClearGinModuleData();

                        await CottonDBMS.Cloud.DocumentDBContext.DeleteCollectionAsync();

                        await CottonDBMS.Cloud.DocumentDBContext.CreateCollectionAsync();

                        await CottonDBMS.Cloud.DocumentDBContext.CreateStoredProceduresAsync();

                        var docsToProcess = uow.DocumentsToProcessRepository.GetAll().ToList();
                        uow.DocumentsToProcessRepository.BulkDelete(docsToProcess);

                        uow.ClientRepository.MarkAllDirty();
                        uow.FarmRepository.MarkAllDirty();
                        uow.FieldRepository.MarkAllDirty();
                        uow.TruckRepository.MarkAllDirty();
                        uow.DriverRepository.MarkAllDirty();

                        //reset last sync time to ensure module ownership table is rebuilt
                        uow.SettingsRepository.UpsertSetting(GinAppSettingKeys.LAST_SYNC_TIME, DateTime.UtcNow.AddYears(-1).ToString());

                        uow.SaveChanges();

                        BusyMessage.UpdateMessage("Restarting background sync");
                        CottonDBMS.EF.Tasks.GinSyncWithCloudTask.Reset();

                        BusyMessage.Close();
                    }
                }
                catch (Exception exc)
                {
                    Logging.Logger.Log(exc);
                    BusyMessage.Close();
                    MessageBox.Show("An error occurred clearing data: " + exc.Message);
                }
            }
        }
        private void btnRun_Click(object sender, EventArgs e)
        {
            decimal turnOutRatio    = 0.00M;
            decimal overragePercent = 0.00M;

            if (string.IsNullOrWhiteSpace(txtTurnOutMultiplier.Text) || !decimal.TryParse(txtTurnOutMultiplier.Text, out turnOutRatio) || turnOutRatio < 0.00M || turnOutRatio > 1.00M)
            {
                MessageBox.Show("Please enter a valid turn out as a decimal between 0 and 1.");
                return;
            }

            if (string.IsNullOrWhiteSpace(txtOverrageThreshold.Text) || !decimal.TryParse(txtOverrageThreshold.Text, out overragePercent) || overragePercent < 0.00M || overragePercent > 100.00M)
            {
                MessageBox.Show("Please enter a valid overrage percentage as a decimal between 0 and 100.");
                return;
            }

            List <ModuleEntity> modules = new List <ModuleEntity>();
            List <BaleEntity>   bales   = new List <BaleEntity>();

            int startModuleIndex = int.MaxValue;
            int endModuleIndex   = -1;
            int startBaleIndex   = int.MaxValue;

            //find index of first and last selected module rows
            foreach (DataGridViewRow row in gridViewModules.SelectedRows)
            {
                if (row.Index < startModuleIndex)
                {
                    startModuleIndex = row.Index;
                }

                if (row.Index > endModuleIndex)
                {
                    endModuleIndex = row.Index;
                }
            }

            //get list of modules we are going to accumulate bale weights for
            for (int i = startModuleIndex; i <= endModuleIndex; i++)
            {
                ModuleEntity m = (ModuleEntity)gridViewModules.Rows[i].DataBoundItem;
                m.Bales.Clear(); // need to clear bales because we will be re-assigning
                modules.Add(m);
            }

            //get index of first bale to use as starting point for accumulation
            foreach (DataGridViewRow row in gridViewPBIScans.SelectedRows)
            {
                if (row.Index < startBaleIndex)
                {
                    startBaleIndex = row.Index;
                }
            }

            var firstModule = modules.First();
            var lastModule  = modules.Last();

            //get list of bales we are working with
            for (var i = startBaleIndex; i < gridViewPBIScans.Rows.Count; i++)
            {
                BaleEntity b = (BaleEntity)gridViewPBIScans.Rows[i].DataBoundItem;
                bales.Add(b);
            }

            var firstBale = bales.First();

            if (MessageBox.Show("Accumulation will start with module " + firstModule.Name
                                + " and end with module " + lastModule.Name
                                + ". Lint weight accumulation will begin with bale "
                                + firstBale.PbiNumber + " using a turnout ratio of " + turnOutRatio.ToString() + ". Would you like to continue?  Any previous mappings for this data set will be overwritten.",
                                "Continue?", MessageBoxButtons.YesNo)
                == DialogResult.Yes)
            {
                BusyMessage.Show("Step 1 - Calculating estimated load and module lint turn out.", this.FindForm());

                Task.Run(() =>
                {
                    try
                    {
                        using (IUnitOfWork uow = UnitOfWorkFactory.CreateUnitOfWork())
                        {
                            uow.ModuleRepository.DisableChangeTracking();
                            int moduleCount = 1;
                            foreach (var m in modules)
                            {
                                m.GinLoad.LintWeight = m.GinLoad.NetWeight * turnOutRatio;

                                if (m.HIDModuleWeightLBS.HasValue)
                                {
                                    m.NetSeedCottonWeight = m.HIDModuleWeightLBS.Value;
                                }
                                else if (m.DiameterApproximatedWeight.HasValue)
                                {
                                    m.NetSeedCottonWeight = m.DiameterApproximatedWeight.Value;
                                }
                                else
                                {
                                    m.NetSeedCottonWeight = m.LoadAvgModuleWeight.Value;
                                }
                                m.LintWeight = m.NetSeedCottonWeight * turnOutRatio;
                                uow.GinLoadRepository.QuickUpdate(m.GinLoad, false);
                                uow.ModuleRepository.QuickUpdate(m, false);

                                if (moduleCount % 25 == 0)
                                {
                                    BusyMessage.UpdateMessage("Step 1 - Calculating lint turn out for module " + moduleCount.ToString() + " of " + modules.Count().ToString());
                                }
                                moduleCount++;
                            }
                            BusyMessage.UpdateMessage("Step 1 - Saving lint weight estimates.");
                            uow.SaveChanges();
                        }

                        BusyMessage.UpdateMessage("Step 2 - Accumulating bale lint weights");

                        using (IUnitOfWork uow = UnitOfWorkFactory.CreateUnitOfWork())
                        {
                            uow.ModuleRepository.DisableChangeTracking();
                            uow.BalesRepository.DisableChangeTracking();
                            decimal overrage              = 0.00M;
                            decimal carryOver             = 0.00M;
                            int currentBaleIndex          = 0;
                            decimal accumulatedLintWeight = 0.00M;
                            bool startNewAccumulation     = true;

                            for (int i = 0; i < modules.Count(); i++)
                            {
                                if (i % 25 == 0)
                                {
                                    BusyMessage.UpdateMessage("Step 2 - Accumulating for module " + (i + 1).ToString() + " of " + modules.Count().ToString());
                                }
                                var m = modules[i];
                                startNewAccumulation = false;
                                while (!startNewAccumulation && currentBaleIndex < bales.Count())
                                {
                                    var b = bales[currentBaleIndex];
                                    Logging.Logger.Log("INFO", "Accumulating weight for bale: " + b.PbiNumber);
                                    b.OverrageThreshold = overragePercent;
                                    b.LintTurnout       = turnOutRatio;
                                    if (accumulatedLintWeight + bales[currentBaleIndex].NetWeight + carryOver <= m.LintWeight)
                                    {
                                        Logging.Logger.Log("INFO", "Bale weight under module weight");
                                        //map bale to current module/gin load
                                        accumulatedLintWeight += b.NetWeight + carryOver;
                                        b.ModuleId             = m.Id;
                                        b.Module              = null;
                                        b.ModuleSerialNumber  = m.Name;
                                        b.GinLoadId           = m.GinLoadId;
                                        b.GinTicketLoadNumber = m.GinLoad.GinTagLoadNumber;
                                        b.AccumWeight         = accumulatedLintWeight;
                                        b.OverrageAdjustment  = carryOver;
                                        b.LintTurnout         = turnOutRatio;
                                        carryOver             = 0.00M;
                                        uow.BalesRepository.QuickUpdate(b, true);
                                    }
                                    else
                                    {
                                        startNewAccumulation   = true;
                                        overrage               = accumulatedLintWeight + b.NetWeight - m.LintWeight.Value;
                                        accumulatedLintWeight += b.NetWeight + carryOver;
                                        //if > overrage % of weight belongs to next module map to next and subtract off portion belonging to current
                                        if ((overrage / b.NetWeight) > (1.00M - (overragePercent / 100.00M)))
                                        {
                                            Logging.Logger.Log("INFO", "Bale will be assigned to next module");
                                            int nextModuleIndex = i + 1;
                                            if (nextModuleIndex < modules.Count())
                                            {
                                                Logging.Logger.Log("INFO", "Bale ModuleID: " + b.ModuleId);
                                                b.ModuleId            = modules[nextModuleIndex].Id;
                                                b.Module              = null;
                                                b.ModuleSerialNumber  = modules[nextModuleIndex].Name;
                                                b.GinLoadId           = modules[nextModuleIndex].GinLoadId;
                                                b.GinTicketLoadNumber = modules[nextModuleIndex].GinLoad.GinTagLoadNumber;

                                                //adjust accumulation for next module by subtracting off weight from bale
                                                //applied to current module
                                                carryOver             = 0.00M - (b.NetWeight - overrage);
                                                accumulatedLintWeight = b.NetWeight + carryOver;
                                                b.AccumWeight         = accumulatedLintWeight;
                                                b.OverrageAdjustment  = carryOver;
                                                uow.BalesRepository.QuickUpdate(b, true);
                                                carryOver = 0;
                                            }
                                        }
                                        else //bale belongs to current module
                                        {
                                            Logging.Logger.Log("INFO", "Bale assigned to current module");
                                            b.ModuleId            = m.Id;
                                            b.Module              = null;
                                            b.ModuleSerialNumber  = m.Name;
                                            b.GinLoadId           = m.GinLoadId;
                                            b.GinTicketLoadNumber = m.GinLoad.GinTagLoadNumber;
                                            b.AccumWeight         = accumulatedLintWeight;
                                            b.OverrageAdjustment  = carryOver;
                                            uow.BalesRepository.QuickUpdate(b, true);
                                            carryOver             = overrage;
                                            accumulatedLintWeight = 0.00M;
                                        }
                                    }
                                    if (b.Module != null && b.ModuleId != b.Module.Id)
                                    {
                                        Logging.Logger.Log("INFO", "MISMATCH IDS");
                                    }
                                    currentBaleIndex++;
                                }

                                if (i % 25 == 0) //save every 25 modules
                                {
                                    uow.SaveChanges();
                                }
                            }
                            uow.SaveChanges();
                        }

                        BusyMessage.Close();
                    }
                    catch (Exception exc)
                    {
                        BusyMessage.Close();
                        this.Invoke((MethodInvoker) delegate
                        {
                            MessageBox.Show("An exception occurred: " + exc.Message);
                        });

                        Logging.Logger.Log(exc);
                    }
                });
            }
        }
        private async Task InitializeDataSourcesAsync()
        {
            using (IUnitOfWork uow = UnitOfWorkFactory.CreateUnitOfWork())
            {
                BusyMessage.Show("Checking for Azure database.", this);
                var    settingsRepo = uow.SettingsRepository;
                string endpoint     = settingsRepo.FindSingle(t => t.Key == GinAppSettingKeys.AZURE_DOCUMENTDB_ENDPOINT).Value;
                string key          = settingsRepo.FindSingle(t => t.Key == GinAppSettingKeys.AZURE_DOCUMENTDB_KEY).Value;

                if (endpoint.ToLower().IndexOf("azure.com") >= 0 && !string.IsNullOrEmpty(key))
                {
                    DocumentDBContext.Initialize(endpoint, key);
                    bool exists = await DocumentDBContext.DatabaseExistsAsync();

                    bool createSucceded = true;
                    if (!exists)
                    {
                        BusyMessage.UpdateMessage("Creating Azure document database..");
                        try
                        {
                            await DocumentDBContext.CreateDatabaseAsync();
                        }
                        catch (Exception exc)
                        {
                            Logging.Logger.Log(exc);
                            createSucceded = false;
                            BusyMessage.UpdateMessage("Creating Azure document database failed.");
                            System.Threading.Thread.Sleep(2000);
                        }
                    }

                    if (createSucceded)
                    {
                        exists = await DocumentDBContext.CollectionExistsAsync();

                        if (!exists)
                        {
                            try
                            {
                                BusyMessage.UpdateMessage("Creating Azure document database collections..");
                                await DocumentDBContext.CreateCollectionAsync();

                                createSucceded = true;
                            }
                            catch (Exception exc)
                            {
                                BusyMessage.UpdateMessage("Creating Azure document database collections failed.");
                                System.Threading.Thread.Sleep(2000);
                                Logging.Logger.Log(exc);
                                createSucceded = false;
                            }
                        }
                    }

                    if (createSucceded)
                    {
                        try
                        {
                            await DocumentDBContext.CreateStoredProceduresAsync();
                        }
                        catch (Exception exc)
                        {
                            BusyMessage.UpdateMessage("Creating database stored procedures failed.");
                            System.Threading.Thread.Sleep(2000);
                            Logging.Logger.Log(exc);
                            createSucceded = false;
                        }
                    }

                    DbIntitialized = true;
                    BusyMessage.Close();
                }
                else
                {
                    BusyMessage.Close();
                    DbIntitialized = false;
                    appTabs.TabPages.Remove(tabHome);
                    appTabs.TabPages.Remove(tabFields);
                    appTabs.TabPages.Remove(tabModules);
                    appTabs.TabPages.Remove(tabPickupLists);
                    appTabs.TabPages.Remove(tabClients);
                    appTabs.TabPages.Remove(tabFarms);
                    appTabs.TabPages.Remove(tabTrucks);
                    appTabs.TabPages.Remove(tabDrivers);
                    appTabs.TabPages.Remove(tabReports);
                    appTabs.TabIndex = 0;
                    MessageBox.Show("Azure Document DB connection settings are missing or incorrect.  Please update Azure information in the Settings tab then restart the application.");
                }
            }
        }
Example #7
0
        private void generatePDFAsync(string outputFilename)
        {
            //apply filters to get all records using paging - streaming records into a temporary database table
            BusyMessage.Show("Downloading data...", this.FindForm());
            try
            {
                Document      mDoc   = new Document();
                Table         table  = new Table();
                int           record = 1;
                int           total  = 0;
                StringBuilder sb     = new StringBuilder(32000);
                if (filterBar.Filter.RecentOnly)
                {
                    using (StreamWriter sr = new StreamWriter(outputFilename, false))
                    {
                        var      outputDocs = getRecentModuleDocsAsync();
                        string[] headers    = { "Client:3cm", "Farm:2.8cm", "Field:3cm", "Serial:2.2cm", "Load:1.30cm", "Gin Tkt Load:1.50cm", "Latitude:3.15cm", "Longitude:3.15cm", "TruckID:1.5cm", "Driver:1.75cm", "Status:1.4cm", "Timestamp:2.0cm" };
                        string[] columns    = { "{Client}", "{Farm}", "{Field}", "{SerialNumber}", "{LoadNumber}", "{GinTagLoadNumber}", "{Latitude}", "{Longitude}", "{TruckID}", "{Driver}", "{Status}", "{DateAdded}" };

                        setupPdf(mDoc, headers, ref table, tbReportTitle.Text);
                        total = outputDocs.Count();

                        foreach (var d in outputDocs)
                        {
                            BusyMessage.UpdateMessage(string.Format("Building Row {0} of {1}", record, total));

                            List <string> values = new List <string>();
                            foreach (var v in columns)
                            {
                                values.Add(getOutputLine(v, d));
                            }
                            addPdfRow(mDoc, values.ToArray(), table);
                            record++;
                        }
                    }
                }
                else
                {
                    using (StreamWriter sr = new StreamWriter(outputFilename, false))
                    {
                        var      historyDocs = getAllLocationRecordsAsync();
                        string[] headers     = { "Client:2.5cm", "Farm:2.0cm", "Field:2.5cm", "Serial:2.2cm", "Load:1.30cm", "Gin ticket load:1.50cm", "Latitude:3.15cm", "Longitude:3.15cm", "TruckID:1.5cm", "Driver:1.75cm", "Status:1.2cm", "Event:1.75cm", "Timestamp:2.0cm" };
                        string[] columns     = { "{Client}", "{Farm}", "{Field}", "{SerialNumber}", "{LoadNumber}", "{GinTagLoadNumber}", "{Latitude}", "{Longitude}", "{TruckID}", "{Driver}", "{Status}", "{EventType}", "{DateAdded}" };

                        setupPdf(mDoc, headers, ref table, tbReportTitle.Text);
                        total = historyDocs.Count();
                        foreach (var d in historyDocs)
                        {
                            BusyMessage.UpdateMessage(string.Format("Building Row {0} of {1}", record, total));
                            List <string> values = new List <string>();
                            foreach (var v in columns)
                            {
                                values.Add(getHistoryOutputLine(v, d));
                            }
                            addPdfRow(mDoc, values.ToArray(), table);
                            record++;
                        }
                    }
                }

                if (total > 10000)
                {
                    BusyMessage.Close();
                    MessageBox.Show("Too many records to render to a single PDF.  Please add additional filter criteria to reduce the number of included records.");
                    return;
                }
                else
                {
                    BusyMessage.UpdateMessage("Rendering PDF");
                    var pdfRenderer = new MigraDoc.Rendering.PdfDocumentRenderer(false);
                    pdfRenderer.Document = mDoc;
                    pdfRenderer.RenderDocument();
                    pdfRenderer.PdfDocument.Save(outputFilename);
                    System.Diagnostics.Process.Start(outputFilename);
                }
            }
            catch (Exception exc)
            {
                Logging.Logger.Log(exc);
                MessageBox.Show(exc.Message);
            }
            BusyMessage.Close();
        }