private void btnSave_Click(object sender, EventArgs e)
        {
            BusyMessage.Show("Saving...", this.FindForm());
            try
            {
                ValidateForm();
                if (!hasError)
                {
                    using (var uow = UnitOfWorkFactory.CreateUnitOfWork())
                    {
                        BaseEntity   selectedStatus       = (BaseEntity)tbStatus.SelectedItem;
                        ModuleStatus selectedModuleStatus = (ModuleStatus)int.Parse(selectedStatus.Id);

                        //ensure client, farm, and field are created
                        var client = clientSelector1.GetOrCreateClientEntity();
                        var farm   = farmSelector1.GetOrCreateFarmEntity(client);
                        var field  = fieldSelector1.GetOrCreateFieldEntity(farm);

                        foreach (var sn in _serialNumbers)
                        {
                            ModuleEntity existingModule = uow.ModuleRepository.FindSingle(x => x.Name == sn, "ModuleHistory");
                            existingModule.ModuleStatus = selectedModuleStatus;
                            existingModule.FieldId      = field.Id;
                            ModuleHistoryEntity historyItem = new ModuleHistoryEntity
                            {
                                Id              = Guid.NewGuid().ToString(),
                                Created         = DateTime.UtcNow,
                                Driver          = existingModule.Driver,
                                TruckID         = existingModule.TruckID,
                                Latitude        = existingModule.Latitude,
                                Longitude       = existingModule.Longitude,
                                ModuleStatus    = existingModule.ModuleStatus,
                                ModuleEventType = ModuleEventType.MANUAL_EDIT
                            };
                            existingModule.ModuleHistory.Add(historyItem);
                            existingModule.SyncedToCloud = false;
                            uow.ModuleRepository.Save(existingModule);
                        }
                        uow.SaveChanges();
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                }
                else
                {
                    this.Activate();
                }
            }
            catch (Exception exc)
            {
                Logging.Logger.Log(exc);
                MessageBox.Show("An error occurred trying to save module.");
            }
            finally
            {
                BusyMessage.Close();
            }
        }
Example #2
0
        private string getHistoryOutputLine(string template, ModuleHistoryEntity doc)
        {
            string outputLine = template.Replace("{Farm}", doc.Module.Field.Farm.Name)
                                .Replace("{Field}", doc.Module.Field.Name)
                                .Replace("{Client}", doc.Module.Field.Farm.Client.Name)
                                .Replace("{ModuleId}", doc.ModuleId)
                                .Replace("{SerialNumber}", doc.Module.Name)
                                .Replace("{LoadNumber}", doc.Module.LoadNumberString)
                                .Replace("{ImportedLoadNumber}", doc.Module.ImportedLoadNumber)
                                .Replace("{Latitude}", doc.Latitude.ToString())
                                .Replace("{Longitude}", doc.Longitude.ToString())
                                .Replace("{TruckID}", doc.TruckID)
                                .Replace("{BridgeID}", doc.BridgeId)
                                .Replace("{BridgeLoadNumber}", doc.BridgeLoadNumber.NullableToString())
                                .Replace("{GinTagLoadNumber}", doc.GinTagLoadNumber)
                                .Replace("{HIDModuleWeight}", doc.Module.HIDModuleWeight.NullableToString())
                                .Replace("{HIDMoisture}", doc.Module.HIDMoisture.NullableToString())
                                .Replace("{HIDFieldArea}", doc.Module.HIDFieldArea.NullableToString())
                                .Replace("{HIDIncrementalArea}", doc.Module.HIDIncrementalArea.NullableToString())
                                .Replace("{HIDDiameter}", doc.Module.HIDDiameter.NullableToString())
                                .Replace("{HIDSeasonTotal}", doc.Module.HIDSeasonTotal.NullableToString())
                                .Replace("{HIDVariety}", doc.Module.HIDVariety)
                                .Replace("{HIDOperator}", doc.Module.HIDOperator)
                                .Replace("{HIDProducerID}", doc.Module.HIDProducerID)

                                .Replace("{HIDGinID}", doc.Module.HIDGinID)
                                .Replace("{HIDMachinePIN}", doc.Module.HIDMachinePIN)
                                .Replace("{HIDDropLat}", doc.Module.HIDDropLat.ToString())
                                .Replace("{HIDDropLong}", doc.Module.HIDDropLong.ToString())
                                .Replace("{HIDWrapLat}", doc.Module.HIDWrapLat.ToString())
                                .Replace("{HIDWrapLong}", doc.Module.HIDWrapLong.ToString())
                                .Replace("{HIDLat}", doc.Module.HIDLat.ToString())
                                .Replace("{HIDLong}", doc.Module.HIDLong.ToString())
                                .Replace("{HIDFieldTotal}", doc.Module.HIDFieldTotal.NullableToString())

                                .Replace("{Driver}", doc.Driver)
                                .Replace("{Status}", doc.StatusName)
                                .Replace("{Notes}", doc.Module.Notes)
                                .Replace("{EventType}", doc.EventName)
                                .Replace("{GMTDate}", doc.Created.ToString("MM/dd/yyyy"))
                                .Replace("{GMTTime}", doc.Created.ToString("HH:mm:ss"))
                                .Replace("{DateAdded}", doc.LocalCreatedTimestamp)
                                .Replace("{DateAddedDate}", doc.Created.ToLocalTime().ToString("MM/dd/yyyy"))
                                .Replace("{DateAddedTime}", doc.Created.ToLocalTime().ToString("HH:mm:ss"));

            return(outputLine);
        }
Example #3
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                ValidateForm();
                if (!hasError)
                {
                    if (dataObj != null && !string.IsNullOrWhiteSpace(dataObj.GinTagLoadNumber) && string.IsNullOrWhiteSpace(tbGinTicketLoadNumber.Text))
                    {
                        if (MessageBox.Show("You have removed the gin ticket load number from this module.  Are you sure you want to save?  This will remove the module from gin ticket load " + dataObj.GinTagLoadNumber + ".", "Confirm", MessageBoxButtons.YesNo) != DialogResult.Yes)
                        {
                            return;
                        }
                    }


                    using (var uow = UnitOfWorkFactory.CreateUnitOfWork()) {
                        var ginLoadId = uow.GinLoadRepository.GetLoadIdForGinTicketNumber(tbGinTicketLoadNumber.Text.Trim());

                        if (string.IsNullOrEmpty(ginLoadId) && !string.IsNullOrWhiteSpace(tbGinTicketLoadNumber.Text))
                        {
                            if (MessageBox.Show("You have entered a gin ticket load number that does not yet have a matching load record from the scale bridge.  Are you sure you want to save? ", "Confirm", MessageBoxButtons.YesNo) != DialogResult.Yes)
                            {
                                return;
                            }
                        }


                        BusyMessage.Show("Saving...", this.FindForm());
                        BaseEntity   selectedStatus       = (BaseEntity)tbStatus.SelectedItem;
                        ModuleStatus selectedModuleStatus = (ModuleStatus)int.Parse(selectedStatus.Id);
                        ModuleEntity existingModule       = null;

                        if (dataObj == null)
                        {
                            existingModule = new ModuleEntity();
                        }
                        else
                        {
                            existingModule = uow.ModuleRepository.GetById(dataObj.Id, "Field.Farm.Client");
                        }

                        //ensure client, farm, and field are created
                        var client = clientSelector1.GetOrCreateClientEntity();
                        var farm   = farmSelector1.GetOrCreateFarmEntity(client);
                        var field  = fieldSelector1.GetOrCreateFieldEntity(farm);


                        string truck  = (cboTruck.SelectedIndex > 0) ? ((BaseEntity)cboTruck.SelectedItem).Name : "";
                        string driver = (cboDriver.SelectedIndex > 0) ? ((BaseEntity)cboDriver.SelectedItem).Name : "";

                        existingModule.Name             = tbSerialNumber.Text.Trim();
                        existingModule.ModuleId         = tbModuleID.Text.Trim();
                        existingModule.FieldId          = field.Id;
                        existingModule.Name             = tbSerialNumber.Text.Trim();
                        existingModule.Driver           = driver;
                        existingModule.TruckID          = truck;
                        existingModule.Latitude         = double.Parse(tbLatitude.Text);
                        existingModule.Longitude        = double.Parse(tbLongitude.Text);
                        existingModule.ModuleStatus     = selectedModuleStatus;
                        existingModule.Notes            = tbNotes.Text.Trim();
                        existingModule.GinLoadId        = ginLoadId;
                        existingModule.GinTagLoadNumber = tbGinTicketLoadNumber.Text.Trim();

                        ModuleHistoryEntity historyItem = new ModuleHistoryEntity
                        {
                            Id              = Guid.NewGuid().ToString(),
                            Created         = DateTime.UtcNow,
                            Driver          = existingModule.Driver,
                            TruckID         = existingModule.TruckID,
                            Latitude        = existingModule.Latitude,
                            Longitude       = existingModule.Longitude,
                            ModuleEventType = ModuleEventType.MANUAL_EDIT
                        };
                        historyItem.ModuleStatus = existingModule.ModuleStatus;
                        existingModule.ModuleHistory.Add(historyItem);
                        existingModule.SyncedToCloud = false;
                        uow.ModuleRepository.Save(existingModule);
                        uow.SaveChanges();

                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                }
                else
                {
                    this.Activate();
                }
            }
            catch (Exception exc)
            {
                Logging.Logger.Log(exc);
                MessageBox.Show("An error occurred trying to save module.");
            }
            finally
            {
                BusyMessage.Close();
            }
        }
Example #4
0
        static void MainTask(string[] args)
        {
            string dir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

            dir = dir.TrimEnd('\\') + "\\" + FolderConstants.ROOT_APP_DATA_FOLDER;

            if (!System.IO.Directory.Exists(dir))
            {
                System.IO.Directory.CreateDirectory(dir);
            }

            CottonDBMS.Logging.Logger.SetLogPath(Environment.CurrentDirectory);

            AppDomain.CurrentDomain.SetData("DataDirectory", dir.TrimEnd('\\'));

            InitializeDataSources();

            Console.WriteLine("Would you like to generate sample data for PBI algorithm? (Y/N)");
            string response = Console.ReadLine();

            if (response.ToUpper() == "Y")
            {
                createPBIData();
                Console.WriteLine("PBI Data generated.  Press enter to exit.");
                Console.ReadLine();
                return;
            }

            string clientStartNumber = "";

            Console.WriteLine("Enter client start number: ");
            clientStartNumber = Console.ReadLine();
            int clientStartNum = 0;

            int.TryParse(clientStartNumber, out clientStartNum);

            Console.WriteLine("Enter number of clients to generate: ");
            string numClientsStr = Console.ReadLine();

            Console.WriteLine("Enter number of farms per client: ");
            string numFarmsPerClientStr = Console.ReadLine();

            Console.WriteLine("Enter number of fields per client: ");
            string numFieldsPerFarmStr = Console.ReadLine();

            Console.WriteLine("Enter number of modules per field: ");
            string numModulesPerFieldStr = Console.ReadLine();

            //Console.WriteLine("Enter number of modules per load: ");
            //string numModulesPerLoad = Console.ReadLine();

            int numClients         = 1;
            int numFarmsPerClient  = 1;
            int numFieldsPerFarm   = 1;
            int numModulesPerField = 1;
            //int numModulesPerLoad = 4;


            double clientFieldLat  = fieldStartLat + (rand.NextDouble() * 1);
            double clientFieldLong = fieldStartLong + (rand.NextDouble() * 1);

            List <ClientEntity> clientsToAdd = new List <ClientEntity>();
            List <ModuleEntity> modulesToAdd = new List <ModuleEntity>();

            int.TryParse(numClientsStr, out numClients);
            int.TryParse(numFarmsPerClientStr, out numFarmsPerClient);
            int.TryParse(numFieldsPerFarmStr, out numFieldsPerFarm);
            int.TryParse(numModulesPerFieldStr, out numModulesPerField);

            string[] drivers = { "John Doe", "Jerry Jones", "E. Smith" };
            string[] trucks  = { "Truck 1", "Truck 2", "Truck 3", "Truck 4" };


            int totalModules = 1;
            int loadNumber   = 1;

            for (int clientIndex = 0; clientIndex < numClients; clientIndex++)
            {
                var client = new ClientEntity();

                client.Name  = string.Format("Client {0}", (clientIndex + clientStartNum));
                client.Farms = new List <FarmEntity>();
                clientsToAdd.Add(client);

                for (int farmCount = 1; farmCount <= numFarmsPerClient; farmCount++)
                {
                    var farm = new FarmEntity();
                    farm.Id     = Guid.NewGuid().ToString();
                    farm.Name   = string.Format("{0} - Farm {1}", client.Name, farmCount);
                    farm.Fields = new List <FieldEntity>();
                    for (int fieldCount = 1; fieldCount <= numFieldsPerFarm; fieldCount++)
                    {
                        DateTime addDate = DateTime.UtcNow.AddDays(rand.Next(30) * -1);
                        var      field   = new FieldEntity();
                        field.Id        = Guid.NewGuid().ToString();
                        field.Name      = string.Format("{0} - Field {1}", farm.Name, fieldCount);
                        field.Modules   = new List <ModuleEntity>();
                        field.Latitude  = clientFieldLat;
                        field.Longitude = clientFieldLong;
                        field.Created   = addDate;
                        farm.Fields.Add(field);

                        totalFields++;

                        int fieldCol = 1;
                        int fieldRow = 1;

                        clientFieldLat  = fieldStartLat + (rand.NextDouble());
                        clientFieldLong = fieldStartLong + (rand.NextDouble());

                        for (int moduleCount = 1; moduleCount <= numModulesPerField; moduleCount++)
                        {
                            ModuleEntity module = new ModuleEntity();
                            module.Id         = Guid.NewGuid().ToString();
                            module.Name       = totalModules.ToString().PadLeft(7, '0');
                            module.FieldId    = field.Id;
                            module.TruckID    = trucks[rand.Next(trucks.Length - 1)];
                            module.Driver     = drivers[rand.Next(drivers.Length - 1)];
                            module.LoadNumber = "2019M" + loadNumber.ToString().PadLeft(7, '0');

                            int weightSelector = rand.Next(1, 4);

                            if (weightSelector == 1) //use module weight
                            {
                                module.HIDDiameter     = rand.Next(225, 240);
                                module.HIDModuleWeight = rand.Next(2200, 2650);
                            }
                            else if (weightSelector == 2) //use diameter
                            {
                                module.HIDDiameter     = rand.Next(225, 240);
                                module.HIDModuleWeight = null;
                            }
                            else
                            {
                                module.HIDDiameter     = null;
                                module.HIDModuleWeight = null;
                            }

                            totalModules++;

                            if (totalModules % 4 == 0)
                            {
                                loadNumber++;
                            }

                            module.Latitude      = clientFieldLat + (fieldRow * fieldLatIncrement);
                            module.Longitude     = clientFieldLong + (fieldCol * fieldLongIncrement);
                            module.ModuleStatus  = ModuleStatus.IN_FIELD;
                            module.Created       = addDate;
                            module.ModuleHistory = new List <ModuleHistoryEntity>();
                            var historyItem = new ModuleHistoryEntity
                            {
                                Id              = Guid.NewGuid().ToString(),
                                Created         = addDate,
                                Driver          = module.Driver,
                                TruckID         = module.TruckID,
                                Latitude        = module.Latitude,
                                Longitude       = module.Longitude,
                                ModuleEventType = ModuleEventType.IMPORTED_FROM_FILE
                            };
                            field.Modules.Add(module);
                            module.ModuleHistory.Add(historyItem);
                            modulesToAdd.Add(module);
                            fieldCol++;
                            if (fieldCol >= 25)
                            {
                                fieldCol = 1;
                                fieldRow++;
                            }
                        }
                    }
                    client.Farms.Add(farm);
                }

                processClients(client, modulesToAdd);

                clientsToAdd.Clear();
                modulesToAdd.Clear();
            }

            createGinLoads();
            createFeederScans();

            Console.WriteLine("Test data generation complete.");
            Console.ReadLine();
        }
Example #5
0
        private static void createFeederScans()
        {
            //create feeder scan for each load
            DateTime currentModuleScan = new DateTime(2019, 9, 15, 8, 0, 0);

            currentModuleScan = currentModuleScan.ToUniversalTime();


            int feederToBaleMaxMinutes = 10;
            int feedetToBaleMinMunutes = 4;
            int minBaleWeight          = 475;
            int maxBaleWeight          = 510;
            int minModuleTurnout       = 39;
            int maxModuleTurnout       = 45;
            int lastBaleNumber         = 0;

            try
            {
                //get each load in order
                using (var uow = UnitOfWorkFactory.CreateUnitOfWork())
                {
                    var loads = uow.GinLoadRepository.GetAll(new string[] { "Modules.ModuleHistory" }).OrderBy(x => x.ScaleBridgeLoadNumber);
                    foreach (var l in loads)
                    {
                        Console.WriteLine("CREATING SCANS FOR LOAD: " + l.GinTagLoadNumber);
                        foreach (var affectedModule in l.Modules)
                        {
                            affectedModule.ModuleStatus = ModuleStatus.ON_FEEDER;
                            affectedModule.LastBridgeId = "BRIDGE2";
                            Console.WriteLine("CURRENT FEEDER SCAN TIME: " + currentModuleScan.ToString("MM/dd/yyyy HH:mm:ss"));
                            ModuleHistoryEntity historyItem = new ModuleHistoryEntity();
                            historyItem.Id               = Guid.NewGuid().ToString();
                            historyItem.Created          = currentModuleScan;
                            historyItem.Driver           = "";
                            historyItem.TruckID          = "";
                            historyItem.BridgeId         = "BRIDGE2";
                            historyItem.ModuleId         = affectedModule.Id;
                            historyItem.Latitude         = affectedModule.Latitude;
                            historyItem.Longitude        = affectedModule.Longitude;
                            historyItem.GinTagLoadNumber = affectedModule.GinTagLoadNumber;

                            if (!string.IsNullOrEmpty(affectedModule.BridgeLoadNumber))
                            {
                                historyItem.BridgeLoadNumber = int.Parse(affectedModule.BridgeLoadNumber);
                            }
                            else
                            {
                                historyItem.BridgeLoadNumber = null;
                            }

                            affectedModule.ModuleHistory.Add(historyItem);
                            historyItem.ModuleStatus     = ModuleStatus.ON_FEEDER;
                            historyItem.ModuleStatus     = affectedModule.ModuleStatus;
                            historyItem.ModuleEventType  = ModuleEventType.BRIDGE_SCAN;
                            affectedModule.SyncedToCloud = false;
                            uow.ModuleRepository.Save(affectedModule);
                            uow.SaveChanges();

                            //create PBI scans for module
                            decimal accumulatedWeight    = 0.00M;
                            decimal currentModuleTurnout = Convert.ToDecimal(rand.Next(minModuleTurnout, maxModuleTurnout)) / 100.00M;

                            decimal selectedWeight = 0.00M;

                            if (affectedModule.HIDModuleWeightLBS.HasValue)
                            {
                                selectedWeight = affectedModule.HIDModuleWeightLBS.Value;
                            }
                            else if (affectedModule.DiameterApproximatedWeight.HasValue)
                            {
                                selectedWeight = affectedModule.DiameterApproximatedWeight.Value;
                            }
                            else
                            {
                                selectedWeight = affectedModule.LoadAvgModuleWeight.Value;
                            }

                            decimal  currentModuleLintWeight = selectedWeight * currentModuleTurnout;
                            DateTime currentPBIScanTime      = currentModuleScan.AddMinutes(rand.Next(feedetToBaleMinMunutes, feederToBaleMaxMinutes));
                            currentPBIScanTime = currentPBIScanTime.AddSeconds(rand.Next(1, 30));
                            while (accumulatedWeight < currentModuleLintWeight)
                            {
                                lastBaleNumber++;
                                var affectedBale = new BaleEntity();
                                affectedBale.Id            = Guid.NewGuid().ToString();
                                affectedBale.Name          = int.Parse(affectedModule.Name).ToString().PadLeft(5, '0') + lastBaleNumber.ToString().PadLeft(6, '0').ToString();
                                affectedBale.PbiNumber     = affectedBale.Name;
                                affectedBale.Created       = currentPBIScanTime;
                                affectedBale.SyncedToCloud = false;

                                affectedBale.WeightFromScale = rand.Next(minBaleWeight, maxBaleWeight);
                                affectedBale.TareWeight      = 3.0M;
                                affectedBale.ScanNumber      = lastBaleNumber;
                                affectedBale.SyncedToCloud   = false;
                                affectedBale.NetWeight       = affectedBale.WeightFromScale - affectedBale.TareWeight;

                                accumulatedWeight += affectedBale.NetWeight;

                                if (accumulatedWeight > currentModuleLintWeight) //only apply weight to equal lint weight
                                {
                                    affectedBale.NetWeight = affectedBale.NetWeight - (accumulatedWeight - currentModuleLintWeight);

                                    if (rand.Next(10) > 5)
                                    {
                                        affectedBale.NetWeight += rand.Next(1, 3);
                                    }
                                    else
                                    {
                                        affectedBale.NetWeight -= rand.Next(1, 3);
                                    }

                                    affectedBale.WeightFromScale = affectedBale.NetWeight + 3.0M;
                                }
                                Console.WriteLine("CREATING PBI: " + affectedBale.PbiNumber + " " + affectedBale.Created.ToString("MM/dd/yyyy HH:mm:ss"));
                                uow.BalesRepository.Add(affectedBale);

                                currentPBIScanTime = currentPBIScanTime.AddMinutes(rand.Next(1, 3));
                            }
                            uow.SaveChanges();
                            //set next module scan half way between last module scan and current pbi scan
                            var timeSpan = currentPBIScanTime.Subtract(currentModuleScan);
                            currentModuleScan = currentPBIScanTime.AddSeconds(feedetToBaleMinMunutes * 60 / 2 * -1);
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
            }
        }
Example #6
0
        private static void createPBIData()
        {
            FieldEntity  field  = null;
            ModuleEntity module = null;

            using (var uow = UnitOfWorkFactory.CreateUnitOfWork())
            {
                #region Create Modules and Gin Loads
                var client = new ClientEntity();
                client.Name  = "PBI TEST CLIENT";
                client.Farms = new List <FarmEntity>();

                var farm = new FarmEntity();
                farm.Id     = Guid.NewGuid().ToString();
                farm.Name   = "PBI TEST FARM";
                farm.Fields = new List <FieldEntity>();

                field           = new FieldEntity();
                field.Id        = Guid.NewGuid().ToString();
                field.Name      = "PBI TEST FIELD";
                field.Modules   = new List <ModuleEntity>();
                field.Latitude  = 0.00;
                field.Longitude = 0.00;
                field.Created   = DateTime.UtcNow;
                farm.Fields.Add(field);

                client.Farms.Add(farm);
                uow.ClientRepository.Save(client);
                uow.SaveChanges();
            }

            //add modules from CSV file
            string   fileName       = "C:\\Users\\mbohn\\Documents\\PBI_TestData.csv";
            string[] moduleContents = System.IO.File.ReadAllLines(fileName);

            List <GinLoadEntity> ginLoadEntities = new List <GinLoadEntity>();
            int bridgeLoadNumber = 0;
            for (int moduleCount = 1; moduleCount < moduleContents.Length; moduleCount++)
            {
                var fields = moduleContents[moduleCount].Split(',');
                using (var uow = UnitOfWorkFactory.CreateUnitOfWork())
                {
                    module                 = new ModuleEntity();
                    module.Id              = Guid.NewGuid().ToString();
                    module.Name            = fields[0];
                    module.FieldId         = field.Id;
                    module.TruckID         = "";
                    module.Driver          = "";
                    module.LoadNumber      = fields[3];
                    module.HIDDiameter     = Decimal.Parse(fields[1]) * 2.54M;
                    module.HIDModuleWeight = Decimal.Parse(fields[2]) * 0.453592M;

                    module.Latitude      = 0.00;
                    module.Longitude     = 0.00;
                    module.ModuleStatus  = ModuleStatus.IN_FIELD;
                    module.Created       = DateTime.UtcNow;
                    module.ModuleHistory = new List <ModuleHistoryEntity>();
                    var historyItem = new ModuleHistoryEntity
                    {
                        Id              = Guid.NewGuid().ToString(),
                        Created         = DateTime.UtcNow,
                        Driver          = module.Driver,
                        TruckID         = module.TruckID,
                        Latitude        = module.Latitude,
                        Longitude       = module.Longitude,
                        ModuleEventType = ModuleEventType.IMPORTED_FROM_FILE
                    };
                    module.FieldId = field.Id;
                    module.ModuleHistory.Add(historyItem);
                    uow.ModuleRepository.Add(module);
                    uow.SaveChanges();

                    if (!ginLoadEntities.Any(g => g.GinTagLoadNumber == module.LoadNumber))
                    {
                        //create gin load
                        var affectedGinLoad = new GinLoadEntity();
                        ginLoadEntities.Add(affectedGinLoad);
                        affectedGinLoad.Created       = DateTime.UtcNow;
                        affectedGinLoad.SyncedToCloud = false;

                        affectedGinLoad.Name                  = module.LoadNumber;
                        affectedGinLoad.GinTagLoadNumber      = module.LoadNumber;
                        affectedGinLoad.ScaleBridgeLoadNumber = bridgeLoadNumber++;
                        affectedGinLoad.NetWeight             = Convert.ToDecimal(fields[4]);
                        affectedGinLoad.GrossWeight           = affectedGinLoad.NetWeight + 8200;
                        affectedGinLoad.SplitWeight1          = affectedGinLoad.NetWeight;
                        affectedGinLoad.SplitWeight2          = 0.00M;

                        affectedGinLoad.ScaleBridgeId         = "BRIDGE1";
                        affectedGinLoad.ScaleBridgeLoadNumber = ginLoadEntities.Count();
                        affectedGinLoad.Source        = InputSource.GIN;
                        affectedGinLoad.SyncedToCloud = false;
                        affectedGinLoad.TruckID       = "TRUCK1";
                        affectedGinLoad.YardLocation  = "SOMEWHERE";
                        affectedGinLoad.SubmittedBy   = "TEST HARNESS";

                        //add client/farm/field information
                        affectedGinLoad.FieldId = field.Id;
                        uow.GinLoadRepository.Save(affectedGinLoad);
                        uow.SaveChanges();

                        module.GinTagLoadNumber = affectedGinLoad.GinTagLoadNumber;
                        module.GinLoadId        = affectedGinLoad.Id;
                    }
                    else
                    {
                        var load = ginLoadEntities.Single(g => g.GinTagLoadNumber == module.LoadNumber);
                        module.GinTagLoadNumber = load.GinTagLoadNumber;
                        module.GinLoadId        = load.Id;
                    }

                    //create feeder scan of module
                    module.ModuleStatus = ModuleStatus.ON_FEEDER;
                    module.LastBridgeId = "BRIDGE2";
                    // uow.ModuleRepository.Save(module);
                    //uow.SaveChanges();
                    Console.WriteLine("CREATING FEEDER SCAN FOR MODULE : " + module.Name);
                    ModuleHistoryEntity feederHistoryItem = new ModuleHistoryEntity();
                    feederHistoryItem.Id               = Guid.NewGuid().ToString();
                    feederHistoryItem.Created          = DateTime.Parse(fields[5] + " " + fields[6]).ToUniversalTime();
                    feederHistoryItem.Created          = feederHistoryItem.Created.AddSeconds(int.Parse(fields[7]));
                    feederHistoryItem.Driver           = "";
                    feederHistoryItem.TruckID          = "";
                    feederHistoryItem.BridgeId         = "BRIDGE2";
                    feederHistoryItem.ModuleId         = module.Id;
                    feederHistoryItem.Latitude         = module.Latitude;
                    feederHistoryItem.Longitude        = module.Longitude;
                    feederHistoryItem.GinTagLoadNumber = module.GinTagLoadNumber;

                    if (!string.IsNullOrEmpty(module.BridgeLoadNumber))
                    {
                        feederHistoryItem.BridgeLoadNumber = bridgeLoadNumber;
                    }
                    else
                    {
                        feederHistoryItem.BridgeLoadNumber = null;
                    }

                    module.ModuleHistory.Add(feederHistoryItem);
                    feederHistoryItem.ModuleStatus    = ModuleStatus.ON_FEEDER;
                    feederHistoryItem.ModuleStatus    = module.ModuleStatus;
                    feederHistoryItem.ModuleEventType = ModuleEventType.BRIDGE_SCAN;
                    module.SyncedToCloud = false;
                    uow.ModuleRepository.Save(module);
                    uow.SaveChanges();
                }
            }

            #endregion

            #region Create PBIs
            using (var uow = UnitOfWorkFactory.CreateUnitOfWork())
            {
                string   pbiFileName = "C:\\Users\\mbohn\\Documents\\PBI_Test_Bales.csv";
                string[] pbiLines    = System.IO.File.ReadAllLines(pbiFileName);
                for (int lineCount = 1; lineCount < pbiLines.Length; lineCount++)
                {
                    string line         = pbiLines[lineCount];
                    var    pbiFields    = line.Split(',');
                    var    affectedBale = new BaleEntity();
                    affectedBale.Id              = Guid.NewGuid().ToString();
                    affectedBale.Name            = pbiFields[0];
                    affectedBale.PbiNumber       = pbiFields[0];
                    affectedBale.Created         = DateTime.Parse(pbiFields[1] + " " + pbiFields[2]).ToUniversalTime();
                    affectedBale.Created         = affectedBale.Created.AddMilliseconds(lineCount);
                    affectedBale.SyncedToCloud   = false;
                    affectedBale.NetWeight       = decimal.Parse(pbiFields[3]);
                    affectedBale.WeightFromScale = affectedBale.NetWeight + 3.0M;
                    affectedBale.TareWeight      = 3.0M;
                    affectedBale.ScanNumber      = lineCount;
                    affectedBale.SyncedToCloud   = false;
                    affectedBale.NetWeight       = decimal.Parse(pbiFields[3]);
                    Console.WriteLine("CREATING PBI: " + affectedBale.PbiNumber + " " + affectedBale.Created.ToString("MM/dd/yyyy HH:mm:ss"));
                    uow.BalesRepository.Add(affectedBale);
                }
                uow.SaveChanges();
            }
            #endregion
        }
Example #7
0
        private static void createGinLoads()
        {
            int currentGinTagNumber = 5000;
            int bridgeLoad          = 0;

            System.Random rand = new Random(55);
            using (IUnitOfWork uow = UnitOfWorkFactory.CreateUnitOfWork())
            {
                var fields = uow.FieldRepository.GetAll().OrderBy(x => x.Created).ToList();

                foreach (var field in fields)
                {
                    Console.WriteLine("CREATING LOADS FOR FIELD: " + field.Name);
                    var modules = uow.ModuleRepository.FindMatching(m => m.FieldId == field.Id, new string[] { "ModuleHistory" }).ToArray();

                    int           loadModuleCount = 0;
                    GinLoadEntity affectedGinLoad = null;
                    for (var i = 0; i < modules.Count(); i++)
                    {
                        if (loadModuleCount == 0 || loadModuleCount == 4)
                        {
                            loadModuleCount = 0;
                            bridgeLoad++;
                            currentGinTagNumber++;
                            Console.WriteLine("CREATING LOAD: " + currentGinTagNumber.ToString());
                            //break modules up into loads of 4
                            affectedGinLoad               = new GinLoadEntity();
                            affectedGinLoad.Created       = DateTime.UtcNow;
                            affectedGinLoad.SyncedToCloud = false;

                            affectedGinLoad.Name             = currentGinTagNumber.ToString();
                            affectedGinLoad.GinTagLoadNumber = currentGinTagNumber.ToString();

                            affectedGinLoad.NetWeight    = Convert.ToDecimal(rand.Next(18000, 20300));
                            affectedGinLoad.GrossWeight  = affectedGinLoad.NetWeight + 8200;
                            affectedGinLoad.SplitWeight1 = affectedGinLoad.NetWeight;
                            affectedGinLoad.SplitWeight2 = 0.00M;

                            affectedGinLoad.ScaleBridgeId         = "BRIDGE1";
                            affectedGinLoad.ScaleBridgeLoadNumber = bridgeLoad;
                            affectedGinLoad.Source        = InputSource.GIN;
                            affectedGinLoad.SyncedToCloud = false;

                            affectedGinLoad.TruckID = "TRUCK1";

                            affectedGinLoad.YardLocation = "SOMEWHERE";
                            affectedGinLoad.SubmittedBy  = "TEST HARNESS";

                            //add client/farm/field information
                            affectedGinLoad.FieldId = field.Id;
                            uow.GinLoadRepository.Save(affectedGinLoad);
                            uow.SaveChanges();
                        }


                        var module = modules[i];
                        module.Updated = DateTime.UtcNow;

                        //update module with scan information and link to load
                        module.TruckID      = affectedGinLoad.TruckID;
                        module.LastBridgeId = "BRIDGE1";
                        module.GinLoadId    = affectedGinLoad.Id;

                        if (string.IsNullOrEmpty(module.FirstBridgeId))
                        {
                            module.FirstBridgeId = "BRIDGE1";
                        }

                        module.GinTagLoadNumber = affectedGinLoad.GinTagLoadNumber;
                        module.ClassingModuleId = "";
                        module.ModuleStatus     = ModuleStatus.AT_GIN;

                        ModuleHistoryEntity historyItem = new ModuleHistoryEntity();
                        historyItem.Id               = Guid.NewGuid().ToString();
                        historyItem.Created          = DateTime.UtcNow;//moduleScan.ScanTime.HasValue ? moduleScan.ScanTime.Value : DateTime.UtcNow;
                        historyItem.Driver           = "";
                        historyItem.TruckID          = "TRUCK1";
                        historyItem.BridgeId         = "BRIDGE1";
                        historyItem.BridgeLoadNumber = bridgeLoad;
                        historyItem.GinTagLoadNumber = affectedGinLoad.GinTagLoadNumber;
                        historyItem.Name             = affectedGinLoad.GinTagLoadNumber;
                        historyItem.ModuleStatus     = ModuleStatus.AT_GIN;
                        historyItem.Latitude         = module.Latitude;
                        historyItem.Longitude        = module.Longitude;
                        historyItem.ModuleEventType  = ModuleEventType.BRIDGE_SCAN;
                        historyItem.SyncedToCloud    = false;
                        historyItem.ModuleId         = module.Id;
                        module.ModuleHistory.Add(historyItem);
                        uow.ModuleRepository.Save(module);
                        // uow.SaveChanges();

                        loadModuleCount++;
                    }
                    uow.SaveChanges();
                }
            }
        }
Example #8
0
        private static void processClients(ClientEntity client, List <ModuleEntity> modulesToAdd)
        {
            using (var uow = UnitOfWorkFactory.CreateUnitOfWork())
            {
                Console.WriteLine("Creating client: " + client.Name);
                clientCount++;

                //generate history records for modules
                int yardCol = 1;
                int yardRow = 1;
                foreach (var module in modulesToAdd)
                {
                    int stage = 2; // rand.Next(1, 5);

                    if (stage >= 2)
                    {
                        ModuleHistoryEntity pickupItem = new ModuleHistoryEntity
                        {
                            Id              = Guid.NewGuid().ToString(),
                            Created         = module.Created.AddDays(2),
                            Driver          = module.Driver,
                            TruckID         = module.TruckID,
                            Latitude        = module.Latitude,
                            Longitude       = module.Longitude,
                            ModuleEventType = ModuleEventType.LOADED,
                            ModuleStatus    = ModuleStatus.PICKED_UP
                        };
                        module.ModuleStatus = ModuleStatus.PICKED_UP;
                        module.ModuleHistory.Add(pickupItem);
                    }

                    if (stage >= 3)
                    {
                        ModuleHistoryEntity atGinItem = new ModuleHistoryEntity
                        {
                            Id              = Guid.NewGuid().ToString(),
                            Created         = module.Created.AddDays(4),
                            Driver          = module.Driver,
                            TruckID         = module.TruckID,
                            Latitude        = yardLat + fieldLatIncrement * yardRow,
                            Longitude       = yardLong + fieldLongIncrement * yardCol,
                            ModuleEventType = ModuleEventType.UNLOADED,
                            ModuleStatus    = ModuleStatus.AT_GIN
                        };

                        yardCol++;
                        if (yardCol > 50)
                        {
                            yardCol = 1;
                            yardRow++;
                        }

                        module.ModuleStatus = ModuleStatus.AT_GIN;
                        module.ModuleHistory.Add(atGinItem);
                    }

                    if (stage >= 4)
                    {
                        ModuleHistoryEntity loadedAtGinYard = new ModuleHistoryEntity
                        {
                            Id              = Guid.NewGuid().ToString(),
                            Created         = module.Created.AddDays(6),
                            Driver          = module.Driver,
                            TruckID         = module.TruckID,
                            Latitude        = yardLat + fieldLatIncrement * yardRow,
                            Longitude       = yardLong + fieldLongIncrement * yardCol,
                            ModuleEventType = ModuleEventType.LOADED,
                            ModuleStatus    = ModuleStatus.AT_GIN
                        };

                        yardCol++;
                        if (yardCol > 25)
                        {
                            yardCol = 1;
                            yardRow++;
                        }

                        ModuleHistoryEntity unloadedAtFeeder = new ModuleHistoryEntity
                        {
                            Id              = Guid.NewGuid().ToString(),
                            Created         = module.Created.AddDays(6).AddMinutes(10),
                            Driver          = module.Driver,
                            TruckID         = module.TruckID,
                            Latitude        = feederLat,
                            Longitude       = feederLong,
                            ModuleEventType = ModuleEventType.UNLOADED,
                            ModuleStatus    = ModuleStatus.ON_FEEDER
                        };

                        module.ModuleStatus = ModuleStatus.ON_FEEDER;
                        module.ModuleHistory.Add(loadedAtGinYard);
                        module.ModuleHistory.Add(unloadedAtFeeder);
                    }
                }

                Console.WriteLine("Creating test modules...");
                //await CloudDataProvider.ModulesRepository.BulkCreateAsync(modulesToAdd, 250);
                uow.ClientRepository.Save(client);
                uow.SaveChanges();
            }
        }
 internal static ModuleHistoryModule ToModel(this ModuleHistoryEntity entity) => new ModuleHistoryModule
 {
     Time   = entity.Time.FormatDateTime(FormatPattern.FullDateTimeWithDayOfWeek),
     Change = entity.Change
 };
        private bool processRow(CSVRow row, CSVFileParser parser, string filename)
        {
            try
            {
                using (var uow = UnitOfWorkFactory.CreateUnitOfWork())
                {
                    //create a new module document
                    ModuleEntity doc = new ModuleEntity();
                    doc.Name = row.GetColumnValue(serialNumberColIndex);
                    string clientName = row.GetColumnValue(clientColIndex);
                    string farmName   = row.GetColumnValue(farmColIndex);
                    string fieldName  = row.GetColumnValue(fieldColIndex);
                    doc.ImportedLoadNumber = row.GetColumnValue(loadColIndex);
                    doc.Driver             = row.GetColumnValue(driverColIndex);
                    doc.TruckID            = row.GetColumnValue(truckColIndex);
                    doc.Latitude           = row.GetDoubleColumnValue(latitudeColIndex);
                    doc.Longitude          = row.GetDoubleColumnValue(longitudeColIndex);
                    doc.Notes            = row.GetColumnValue(commentsColIndex);
                    doc.GinTagLoadNumber = row.GetColumnValue(ginTicketColIndex).TrimStart('0');
                    doc.ModuleId         = row.GetColumnValue(moduleIdColIndex);

                    doc.HIDDiameter        = row.GetDecimalColumnValueNullabe(hidDiameterIndex);
                    doc.HIDFieldArea       = row.GetDecimalColumnValueNullabe(hidFieldArea);
                    doc.HIDIncrementalArea = row.GetDecimalColumnValueNullabe(hidIncrementalAreaIndex);
                    doc.HIDModuleWeight    = row.GetDecimalColumnValueNullabe(hidModuleWeightIndex);
                    doc.HIDMoisture        = row.GetDecimalColumnValueNullabe(hidMoistureIndex);
                    doc.HIDOperator        = row.GetColumnValue(hidOperatorIndex);
                    doc.HIDProducerID      = row.GetColumnValue(hidProducerIDIndex);
                    doc.HIDGMTDate         = row.GetColumnValue(hidGMTDateIndex);
                    doc.HIDGMTTime         = row.GetColumnValue(hidGMTTimeIndex);

                    DateTime ts = DateTime.Now;

                    if (DateTime.TryParse(doc.HIDGMTDate + " " + doc.HIDGMTTime, out ts))
                    {
                        doc.HIDTimestamp = ts;
                    }
                    else
                    {
                        doc.HIDTimestamp = null;
                    }

                    doc.HIDSeasonTotal = row.GetIntColumnValueNullabe(hidSeasonTotalIndex);
                    doc.HIDFieldTotal  = row.GetIntColumnValueNullabe(hidFieldTotalIndex);
                    doc.HIDVariety     = row.GetColumnValue(hidVarietyIndex);

                    doc.HIDLat        = row.GetDoubleColumnValue(latitudeColIndex);
                    doc.HIDLong       = row.GetDoubleColumnValue(longitudeColIndex);
                    doc.HIDDropLat    = row.GetDoubleColumnValue(hidDropLat);
                    doc.HIDDropLong   = row.GetDoubleColumnValue(hidDropLong);
                    doc.HIDWrapLat    = row.GetDoubleColumnValue(hidWrapLat);
                    doc.HIDWrapLong   = row.GetDoubleColumnValue(hidWrapLon);
                    doc.HIDGinID      = row.GetColumnValue(hidGinID);
                    doc.HIDMachinePIN = row.GetColumnValue(hidMachinePIN);

                    doc.GinTagLoadNumber = row.GetColumnValue(ginTicketColIndex).TrimStart('0');

                    doc.Name = doc.Name.Trim();

                    string clientID = row.GetColumnValue(clientIDColIndex);
                    string farmID   = row.GetColumnValue(farmIDColIndex);
                    string fieldID  = row.GetColumnValue(fieldIDColIndex);

                    ModuleEventType eventType = ModuleEventType.IMPORTED_FROM_FILE;
                    DateTime        created   = DateTime.Now;
                    if (filename.ToLower().Contains("transmission"))
                    {
                        eventType = ModuleEventType.IMPORTED_FROM_RFID_MODULESCAN;
                        if (!DateTime.TryParse(row.GetColumnValue(timestampIndex), out created))
                        {
                            if (doc.HIDTimestamp.HasValue)
                            {
                                created = doc.HIDTimestamp.Value;
                            }
                        }
                        else
                        {
                            created = created.ToUniversalTime();
                        }
                    }
                    else
                    {
                        eventType = ModuleEventType.IMPORTED_FROM_HID;
                        if (doc.HIDTimestamp.HasValue)
                        {
                            created = doc.HIDTimestamp.Value;
                        }
                    }

                    ModuleHistoryEntity historyItem = new ModuleHistoryEntity
                    {
                        Id               = Guid.NewGuid().ToString(),
                        Created          = created,
                        Driver           = doc.Driver,
                        TruckID          = doc.TruckID,
                        BridgeId         = string.Empty,
                        BridgeLoadNumber = null,
                        GinTagLoadNumber = doc.GinTagLoadNumber,
                        Latitude         = doc.Latitude,
                        Longitude        = doc.Longitude,
                        ModuleEventType  = eventType
                    };
                    doc.ModuleHistory.Add(historyItem);

                    //determine if serial number exists if so skip
                    bool canSave   = !string.IsNullOrWhiteSpace(doc.Name) && !existingSerialNumbers.ContainsKey(doc.Name);
                    bool canUpdate = !string.IsNullOrWhiteSpace(doc.Name) && existingSerialNumbers.ContainsKey(doc.Name);

                    if (canSave)
                    {
                        existingSerialNumbers.Add(doc.Name, true);
                        ClientEntity existingClient = uow.ClientRepository.FindSingle(c => c.Name == clientName.Trim(), "Farms.Fields");
                        FarmEntity   existingFarm   = null;
                        FieldEntity  existingField  = null;

                        if (existingClient == null)
                        {
                            //add client/farm/field and module
                            if (!string.IsNullOrWhiteSpace(clientName))
                            {
                                existingClient       = new ClientEntity();
                                existingClient.Farms = new List <FarmEntity>();
                                existingClient.Name  = clientName.Trim();
                                uow.ClientRepository.CreateWithID(existingClient, clientID);
                            }
                            else
                            {
                                Logging.Logger.Log("INFO", string.Format("Cannot save client for new module with SN {0} - name is empty.", doc.Name));
                                return(false);
                            }
                        }

                        existingFarm = uow.FarmRepository.FindSingle(f => f.Name == farmName.Trim() && f.ClientId == existingClient.Id);

                        if (existingFarm == null)
                        {
                            var canSaveFarm = !(string.IsNullOrWhiteSpace(farmName));

                            if (!canSaveFarm)
                            {
                                Logging.Logger.Log("INFO", string.Format("Cannot save farm {0} for new module with SN {1} - name empty or duplicate farm already exists for another client.", doc.FarmName, doc.Name));
                                return(false);
                            }
                            else
                            {
                                //add farm/field to client
                                existingFarm          = new FarmEntity();
                                existingFarm.Fields   = new List <FieldEntity>();
                                existingFarm.Name     = farmName.Trim();
                                existingFarm.ClientId = existingClient.Id;
                                uow.FarmRepository.CreateWithID(existingFarm, farmID);
                            }
                        }

                        existingField = uow.FieldRepository.FindSingle(f => f.Name.Trim() == fieldName.Trim() && f.FarmId == existingFarm.Id);

                        if (existingField == null)
                        {
                            if (!string.IsNullOrWhiteSpace(fieldName))
                            {
                                existingField           = new FieldEntity();
                                existingField.Name      = fieldName.Trim();
                                existingField.Latitude  = 0.00;
                                existingField.Longitude = 0.00;
                                existingField.FarmId    = existingFarm.Id;
                                uow.FieldRepository.CreateWithID(existingField, fieldID);
                            }
                            else
                            {
                                Logging.Logger.Log("INFO", string.Format("Cannot save field for new module with SN {0} - field name empty.", doc.Name));
                                return(false);
                            }
                        }

                        if (uow.SettingsRepository.CoordsAtFeeder(doc.Latitude, doc.Longitude))
                        {
                            doc.ModuleStatus = ModuleStatus.ON_FEEDER;
                        }
                        else if (uow.SettingsRepository.CoordsOnGinYard(doc.Latitude, doc.Longitude))
                        {
                            doc.ModuleStatus = ModuleStatus.AT_GIN;
                        }
                        else
                        {
                            doc.ModuleStatus = ModuleStatus.IN_FIELD; //change status back to field
                        }

                        historyItem.ModuleStatus = doc.ModuleStatus;
                        doc.FieldId       = existingField.Id;
                        doc.SyncedToCloud = false; // Added 5/23
                        uow.ModuleRepository.Save(doc);
                        uow.SaveChanges();
                        return(true);
                    }
                    else if (canUpdate)
                    {
                        var affectedModule = uow.ModuleRepository.FindSingle(x => x.Name == doc.Name, "ModuleHistory");
                        affectedModule.Latitude  = doc.Latitude;
                        affectedModule.Longitude = doc.Longitude;
                        if (uow.SettingsRepository.CoordsAtFeeder(doc.Latitude, doc.Longitude))
                        {
                            affectedModule.ModuleStatus = ModuleStatus.ON_FEEDER;
                        }
                        else if (uow.SettingsRepository.CoordsOnGinYard(doc.Latitude, doc.Longitude))
                        {
                            affectedModule.ModuleStatus = ModuleStatus.AT_GIN;
                        }
                        else
                        {
                            affectedModule.ModuleStatus = ModuleStatus.IN_FIELD; //change status back to field
                        }
                        if (!string.IsNullOrWhiteSpace(doc.ImportedLoadNumber))
                        {
                            affectedModule.ImportedLoadNumber = doc.ImportedLoadNumber;
                        }

                        historyItem.ModuleStatus = affectedModule.ModuleStatus;
                        affectedModule.ModuleHistory.Add(historyItem);
                        affectedModule.SyncedToCloud = false;
                        uow.ModuleRepository.Save(affectedModule);
                        uow.SaveChanges();
                        return(true);
                    }
                    else
                    {
                        Logging.Logger.Log("INFO", "Cannot save empty or duplicate serial number: " + doc.Name);
                        return(false);
                    }
                }
            }
            catch (Exception exc)
            {
                Logging.Logger.Log(exc);
                return(false);
            }
        }