示例#1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RentalRequestViewModel" /> class.
        /// </summary>
        /// <param name="id">A system-generated unique identifier for a Request (required).</param>
        /// <param name="project">Project (required).</param>
        /// <param name="localArea">A foreign key reference to the system-generated unique identifier for a Local Area (required).</param>
        /// <param name="status">The status of the Rental Request - whether it in progress, completed or was cancelled. (required).</param>
        /// <param name="districtEquipmentType">A foreign key reference to the system-generated unique identifier for an Equipment Type (required).</param>
        /// <param name="equipmentCount">The number of pieces of the equipment type wanted for hire as part of this request. (required).</param>
        /// <param name="expectedHours">The expected number of rental hours for each piece equipment hired against this request, as provided by the Project Manager making the request..</param>
        /// <param name="expectedStartDate">The expected start date of each piece of equipment hired against this request, as provided by the Project Manager making the request..</param>
        /// <param name="expectedEndDate">The expected end date of each piece of equipment hired against this request, as provided by the Project Manager making the request..</param>
        /// <param name="firstOnRotationList">The first piece of equipment on the rotation list at the time of the creation of the request..</param>
        /// <param name="notes">Notes.</param>
        /// <param name="attachments">Attachments.</param>
        /// <param name="history">History.</param>
        /// <param name="rentalRequestAttachments">RentalRequestAttachments.</param>
        /// <param name="rentalRequestRotationList">RentalRequestRotationList.</param>
        public RentalRequestViewModel(int id, Project project, LocalArea localArea, string status, DistrictEquipmentType districtEquipmentType,
                                      int equipmentCount, int?expectedHours = null, DateTime?expectedStartDate = null, DateTime?expectedEndDate = null,
                                      Equipment firstOnRotationList         = null, List <Note> notes = null, List <Attachment> attachments     = null,
                                      List <History> history = null, List <RentalRequestAttachment> rentalRequestAttachments = null,
                                      List <RentalRequestRotationList> rentalRequestRotationList = null)
        {
            Id                        = id;
            Project                   = project;
            LocalArea                 = localArea;
            Status                    = status;
            DistrictEquipmentType     = districtEquipmentType;
            EquipmentCount            = equipmentCount;
            ExpectedHours             = expectedHours;
            ExpectedStartDate         = expectedStartDate;
            ExpectedEndDate           = expectedEndDate;
            FirstOnRotationList       = firstOnRotationList;
            Notes                     = notes;
            Attachments               = attachments;
            History                   = history;
            RentalRequestAttachments  = rentalRequestAttachments;
            RentalRequestRotationList = rentalRequestRotationList;

            // calculate the Yes Count based on the RentalRequestList
            CalculateYesCount();
        }
示例#2
0
        /// <summary>
        ///  Insert District_Equipment_Type or not according to the rule laid out by HETS-365
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="instance"></param>
        /// <param name="equipRentalRateNo"></param>
        /// <param name="description"></param>
        /// <param name="serviceAreaName"></param>
        /// <param name="addImportMaps"></param>
        private static void AddingDistrictEquipmentTypeInstance(DbAppContext dbContext, EquipType oldObject,
                                                                DistrictEquipmentType instance, float equipRentalRateNo, string description, string serviceAreaName, bool addImportMaps)
        {
            // add the instance (according to the rule of HETS-365)
            List <DistrictEquipmentType> disEquipTypelist = dbContext.DistrictEquipmentTypes
                                                            .Where(x => x.DistrictId == instance.DistrictId)
                                                            .Where(x => x.DistrictEquipmentName.Substring(0, Math.Max(0, x.DistrictEquipmentName.IndexOf(Delim, StringComparison.Ordinal)))
                                                                   .IndexOf(instance.DistrictEquipmentName, StringComparison.Ordinal) >= 0)
                                                            .Include(x => x.EquipmentType)
                                                            .ToList();

            // HETS-365 Step 1
            if (disEquipTypelist.Count == 0)
            {
                instance.DistrictEquipmentName += Delim + description;
                dbContext.DistrictEquipmentTypes.Add(instance);
                if (addImportMaps)
                {
                    ImportUtility.AddImportMap(dbContext, OldTable, oldObject.Equip_Type_Id.ToString(), NewTable, instance.Id);
                }
            }
            else // HETS-365 Step 2
            {
                List <DistrictEquipmentType> list1 = disEquipTypelist
                                                     .FindAll(x => Math.Abs((x.EquipmentType.BlueBookSection ?? 0.1) - equipRentalRateNo) <= ErrowAllowed);

                // HETS-365 Step 2.1
                if (list1.Count > 0 && addImportMaps)
                {
                    ImportUtility.AddImportMap(dbContext, OldTable, oldObject.Equip_Type_Id.ToString(),
                                               NewTable, list1.OrderBy(x => x.Id).FirstOrDefault().Id);
                }

                // check if XML.Description matches any of the HETS.Descriptions
                List <DistrictEquipmentType> list2 = disEquipTypelist
                                                     .FindAll(x => x.DistrictEquipmentName.Substring(x.DistrictEquipmentName.IndexOf(Delim, StringComparison.Ordinal) + Delim.Length)
                                                              .IndexOf(description, StringComparison.Ordinal) >= 0);

                // HETS-365 Step 2.1
                if (list2.Count > 0 && addImportMaps)
                {
                    ImportUtility.AddImportMap(dbContext, OldTable, oldObject.Equip_Type_Id.ToString(),
                                               NewTable, list2.OrderBy(x => x.Id).FirstOrDefault().Id);
                }

                // HETS-365 Step 3
                if (list1.Count == 0 && list2.Count == 0)
                {
                    instance.DistrictEquipmentName += Delim0 + serviceAreaName + Delim + description;
                    dbContext.DistrictEquipmentTypes.Add(instance);

                    if (addImportMaps)
                    {
                        ImportUtility.AddImportMap(dbContext, OldTable, oldObject.Equip_Type_Id.ToString(), NewTable, instance.Id);
                    }
                }
            }
        }
示例#3
0
        /// <summary>
        /// Copy Block item of LocalAreaRotationList item
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="instance"></param>
        /// <param name="systemId"></param>
        private static void CopyToInstance(DbAppContext dbContext, Block oldObject, ref LocalAreaRotationList instance, string systemId)
        {
            if (oldObject.Area_Id <= 0)
            {
                return;
            }

            // add the user specified in oldObject.Modified_By and oldObject.Created_By if not there in the database
            User createdBy = ImportUtility.AddUserFromString(dbContext, oldObject.Created_By, systemId);

            int equipmentTypeId = oldObject.Equip_Type_Id ?? 0;
            int blockNum        = Convert.ToInt32(float.Parse(oldObject.Block_Num == null ? "0.0" : oldObject.Block_Num));

            if (instance == null)
            {
                instance = new LocalAreaRotationList();

                DistrictEquipmentType disEquipType = dbContext.DistrictEquipmentTypes.FirstOrDefault(x => x.Id == equipmentTypeId);
                if (disEquipType != null)
                {
                    instance.DistrictEquipmentType   = disEquipType;
                    instance.DistrictEquipmentTypeId = disEquipType.Id;
                }

                // extract AskNextBlock*Id which is the secondary key of Equip.Id
                int equipId = oldObject.Last_Hired_Equip_Id ?? 0;

                if (dbContext.Equipments.Any(x => x.Id == equipId))
                {
                    switch (blockNum)
                    {
                    case 1:
                        instance.AskNextBlockOpenId = equipId;
                        break;

                    case 2:
                        instance.AskNextBlock1Id = equipId;
                        break;

                    case 3:
                        instance.AskNextBlock2Id = equipId;
                        break;
                    }
                }

                instance.CreateUserid = createdBy.SmUserId;

                if (oldObject.Created_Dt != null)
                {
                    instance.CreateTimestamp = DateTime.ParseExact(oldObject.Created_Dt.Trim().Substring(0, 10), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
                }

                dbContext.LocalAreaRotationLists.Add(instance);
            }
        }
示例#4
0
        private void AdjustRecord(DistrictEquipmentType item)
        {
            if (item != null)
            {
                if (item.District != null)
                {
                    item.District = _context.Districts.FirstOrDefault(a => a.Id == item.District.Id);
                }

                if (item.EquipmentType != null)
                {
                    item.EquipmentType = _context.EquipmentTypes.FirstOrDefault(a => a.Id == item.EquipmentType.Id);
                }
            }
        }
        /// <summary>
        /// Copy xml item to instance (table entries)
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="instance"></param>
        /// <param name="systemId"></param>
        private static void CopyToInstance(DbAppContext dbContext, EquipType oldObject, ref DistrictEquipmentType instance, string systemId)
        {
            if (oldObject.Equip_Type_Id <= 0)
            {
                return;
            }

            // add the user specified in oldObject.Modified_By and oldObject.Created_By if not there in the database
            ImportUtility.AddUserFromString(dbContext, oldObject.Modified_By, systemId);
            User createdBy = ImportUtility.AddUserFromString(dbContext, oldObject.Created_By, systemId);

            if (instance == null)
            {
                instance = new DistrictEquipmentType {
                    Id = oldObject.Equip_Type_Id
                };

                try
                {
                    instance.DistrictEquipmentName = oldObject.Equip_Type_Cd.Length >= 10 ?
                                                     oldObject.Equip_Type_Cd.Substring(0, 10) :
                                                     oldObject.Equip_Type_Cd
                                                     + "-" + (oldObject.Equip_Type_Desc.Length >= 210 ?
                                                              oldObject.Equip_Type_Desc.Substring(0, 210) :
                                                              oldObject.Equip_Type_Desc);
                }
                catch
                {
                    // do nothing
                }

                ServiceArea serviceArea = dbContext.ServiceAreas.FirstOrDefault(x => x.MinistryServiceAreaID == oldObject.Service_Area_Id);

                if (serviceArea != null)
                {
                    int      districtId = serviceArea.DistrictId ?? 0;
                    District dis        = dbContext.Districts.FirstOrDefault(x => x.RegionId == districtId);
                    instance.DistrictId = districtId;
                    instance.District   = dis;
                }

                instance.CreateTimestamp = DateTime.UtcNow;
                instance.CreateUserid    = createdBy.SmUserId;
                dbContext.DistrictEquipmentTypes.Add(instance);
            }
        }
        /// <summary>
        /// Get district equipment type by id
        /// </summary>
        /// <param name="id">id of DistrictEquipmentType to fetch</param>
        /// <response code="200">OK</response>
        /// <response code="404">DistrictEquipmentType not found</response>
        public virtual IActionResult DistrictEquipmentTypesIdGetAsync(int id)
        {
            bool exists = _context.DistrictEquipmentTypes.Any(a => a.Id == id);

            if (exists)
            {
                DistrictEquipmentType result = _context.DistrictEquipmentTypes
                                               .Include(x => x.District)
                                               .Include(x => x.EquipmentType)
                                               .First(a => a.Id == id);

                return(new ObjectResult(new HetsResponse(result)));
            }

            // record not found
            return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
        }
示例#7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="id">id of DistrictEquipmentType to fetch</param>
        /// <param name="item"></param>
        /// <response code="200">OK</response>
        /// <response code="404">DistrictEquipmentType not found</response>
        public virtual IActionResult DistrictEquipmentTypesIdPutAsync(int id, DistrictEquipmentType item)
        {
            AdjustRecord(item);
            var exists = _context.DistrictEquipmentTypes.Any(a => a.Id == id);

            if (exists && id == item.Id)
            {
                _context.DistrictEquipmentTypes.Update(item);
                // Save the changes
                _context.SaveChanges();
                return(new ObjectResult(item));
            }
            else
            {
                // record not found
                return(new StatusCodeResult(404));
            }
        }
示例#8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="item"></param>
        /// <response code="201">DistrictEquipmentType created</response>
        public virtual IActionResult DistrictEquipmentTypesPostAsync(DistrictEquipmentType item)
        {
            AdjustRecord(item);
            var exists = _context.DistrictEquipmentTypes.Any(a => a.Id == item.Id);

            if (exists)
            {
                _context.DistrictEquipmentTypes.Update(item);
            }
            else
            {
                // record not found
                _context.DistrictEquipmentTypes.Add(item);
            }
            // Save the changes
            _context.SaveChanges();
            return(new ObjectResult(item));
        }
        /// <summary>
        /// Update district equipment type
        /// </summary>
        /// <param name="id">id of DistrictEquipmentType to update</param>
        /// <param name="item"></param>
        /// <response code="200">OK</response>
        /// <response code="404">DistrictEquipmentType not found</response>
        public virtual IActionResult DistrictEquipmentTypesIdPutAsync(int id, DistrictEquipmentType item)
        {
            AdjustRecord(item);

            bool exists = _context.DistrictEquipmentTypes.Any(a => a.Id == id);

            if (exists && id == item.Id)
            {
                _context.DistrictEquipmentTypes.Update(item);

                // Save the changes
                _context.SaveChanges();

                return(new ObjectResult(new HetsResponse(item)));
            }

            // record not found
            return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
        }
示例#10
0
        /// <summary>
        /// Delete district equipment type
        /// </summary>
        /// <param name="id">id of DistrictEquipmentType to delete</param>
        /// <response code="200">OK</response>
        /// <response code="404">DistrictEquipmentType not found</response>
        public virtual IActionResult DistrictEquipmentTypesIdDeletePostAsync(int id)
        {
            bool exists = _context.DistrictEquipmentTypes.Any(a => a.Id == id);

            if (exists)
            {
                DistrictEquipmentType item = _context.DistrictEquipmentTypes.First(a => a.Id == id);

                if (item != null)
                {
                    _context.DistrictEquipmentTypes.Remove(item);

                    // Save the changes
                    _context.SaveChanges();
                }

                return(new ObjectResult(new HetsResponse(item)));
            }

            // record not found
            return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
        }
示例#11
0
        /// <summary>
        /// Import Dis(trict) Equip(ment) Type
        /// </summary>
        /// <param name="performContext"></param>
        /// <param name="dbContext"></param>
        /// <param name="fileLocation"></param>
        /// <param name="systemId"></param>
        public static void Import(PerformContext performContext, DbAppContext dbContext, string fileLocation, string systemId)
        {
            // check the start point. If startPoint ==  sigId then it is already completed
            int startPoint = ImportUtility.CheckInterMapForStartPoint(dbContext, OldTableProgress, BCBidImport.SigId);

            if (startPoint == BCBidImport.SigId)    // this means the import job it has done today is complete for all the records in the xml file.
            {
                performContext.WriteLine("*** Importing " + XmlFileName + " is complete from the former process ***");
                return;
            }

            try
            {
                string rootAttr = "ArrayOf" + OldTable;

                // create Processer progress indicator
                performContext.WriteLine("Processing " + OldTable);
                IProgressBar progress = performContext.WriteProgressBar();
                progress.SetValue(0);

                // create serializer and serialize xml file
                XmlSerializer ser          = new XmlSerializer(typeof(EquipType[]), new XmlRootAttribute(rootAttr));
                MemoryStream  memoryStream = ImportUtility.MemoryStreamGenerator(XmlFileName, OldTable, fileLocation, rootAttr);
                EquipType[]   legacyItems  = (EquipType[])ser.Deserialize(memoryStream);

                int ii = startPoint;

                if (startPoint > 0)    // skip the portion already processed
                {
                    legacyItems = legacyItems.Skip(ii).ToArray();
                }

                foreach (EquipType item in legacyItems.WithProgress(progress))
                {
                    string serviceAreaName;

                    // see if we have this one already.
                    ImportMap importMap = dbContext.ImportMaps.FirstOrDefault(x => x.OldTable == OldTable && x.OldKey == item.Equip_Type_Id.ToString());

                    float equipRentalRateNo;
                    try
                    {
                        equipRentalRateNo = (float)Decimal.Parse(item.Equip_Rental_Rate_No, System.Globalization.NumberStyles.Any);
                    }
                    catch
                    {
                        equipRentalRateNo = (float)0.1;
                    }

                    string description;
                    try
                    {
                        description = item.Equip_Type_Desc.Length >= 225 ? item.Equip_Type_Desc.Substring(0, 225) : item.Equip_Type_Desc;
                    }
                    catch
                    {
                        description = "";
                    }

                    // new entry
                    if (importMap == null)
                    {
                        if (item.Equip_Type_Id > 0)
                        {
                            DistrictEquipmentType instance = null;

                            serviceAreaName = CopyToInstance(dbContext, item, ref instance, systemId, equipRentalRateNo);

                            if (serviceAreaName != "ERROR")
                            {
                                AddingDistrictEquipmentTypeInstance(dbContext, item, instance, equipRentalRateNo, description, serviceAreaName, true);
                            }
                        }
                    }
                    else // update
                    {
                        DistrictEquipmentType instance = dbContext.DistrictEquipmentTypes.FirstOrDefault(x => x.Id == importMap.NewKey);

                        if (instance == null) // record was deleted
                        {
                            serviceAreaName = CopyToInstance(dbContext, item, ref instance, systemId, equipRentalRateNo);

                            if (serviceAreaName != "ERROR")
                            {
                                AddingDistrictEquipmentTypeInstance(dbContext, item, instance, equipRentalRateNo, description, serviceAreaName, false);

                                // update the import map
                                importMap.NewKey = instance.Id;
                                dbContext.ImportMaps.Update(importMap);
                            }
                        }
                        else // ordinary update.
                        {
                            serviceAreaName = CopyToInstance(dbContext, item, ref instance, systemId, equipRentalRateNo);

                            if (serviceAreaName != "ERROR")
                            {
                                AddingDistrictEquipmentTypeInstance(dbContext, item, instance, equipRentalRateNo, description, serviceAreaName, false);

                                // touch the import map
                                importMap.LastUpdateTimestamp = DateTime.UtcNow;
                                dbContext.ImportMaps.Update(importMap);
                            }
                        }
                    }

                    // save change to database periodically to avoid frequent writing to the database
                    if (++ii % 250 == 0)
                    {
                        try
                        {
                            ImportUtility.AddImportMapForProgress(dbContext, OldTableProgress, ii.ToString(), BCBidImport.SigId);
                            dbContext.SaveChangesForImport();
                        }
                        catch (Exception e)
                        {
                            performContext.WriteLine("Error saving data " + e.Message);
                        }
                    }
                }

                try
                {
                    performContext.WriteLine("*** Importing " + XmlFileName + " is Done ***");
                    ImportUtility.AddImportMapForProgress(dbContext, OldTableProgress, BCBidImport.SigId.ToString(), BCBidImport.SigId);
                    dbContext.SaveChangesForImport();
                }
                catch (Exception e)
                {
                    performContext.WriteLine("Error saving data " + e.Message);
                }
            }
            catch (Exception e)
            {
                performContext.WriteLine("*** ERROR ***");
                performContext.WriteLine(e.ToString());
            }
        }
示例#12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="id">id of DistrictEquipmentType to fetch</param>
        /// <param name="item"></param>
        /// <response code="200">OK</response>
        /// <response code="404">DistrictEquipmentType not found</response>
        public virtual IActionResult DistrictEquipmentTypesIdPutAsync(int id, DistrictEquipmentType item)
        {
            var result = "";

            return(new ObjectResult(result));
        }
示例#13
0
        /// <summary>
        /// /// <summary>
        /// Copy xml item to instance (table entries)
        /// </summary>
        /// <param name="performContext"></param>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="instance"></param>
        /// <param name="systemId"></param>
        /// <param name="equip_Rental_rate_No"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        static private string CopyToInstance(PerformContext performContext, DbAppContext dbContext, HETSAPI.Import.EquipType oldObject,
                                             ref Models.DistrictEquipmentType instance, string systemId, float equip_Rental_rate_No, string description)
        {
            string serviceAreaName = "";
            bool   isNew           = false;

            if (oldObject.Equip_Type_Id <= 0)
            {
                return(serviceAreaName);
            }

            //Add the user specified in oldObject.Modified_By and oldObject.Created_By if not there in the database
            Models.User modifiedBy = ImportUtility.AddUserFromString(dbContext, oldObject.Modified_By, systemId);
            Models.User createdBy  = ImportUtility.AddUserFromString(dbContext, oldObject.Created_By, systemId);

            if (instance == null)
            {
                isNew       = true;
                instance    = new Models.DistrictEquipmentType();
                instance.Id = oldObject.Equip_Type_Id;
                string typeCode = "";
                try
                {
                    typeCode = oldObject.Equip_Type_Cd.Length >= 20 ? oldObject.Equip_Type_Cd.Substring(0, 20) : oldObject.Equip_Type_Cd;
                }
                catch (Exception e)
                {
                    string ll = e.ToString();
                }

                ServiceArea serviceArea = dbContext.ServiceAreas.FirstOrDefault(x => x.MinistryServiceAreaID == oldObject.Service_Area_Id);
                if (serviceArea != null)
                {
                    serviceAreaName = serviceArea.Name;
                    instance.DistrictEquipmentName = typeCode;

                    int      districtId = serviceArea.DistrictId ?? 0;
                    District dis        = dbContext.Districts.FirstOrDefault(x => x.RegionId == districtId);
                    instance.DistrictId = districtId;
                    instance.District   = dis;
                }

                //    instance.EquipmentType =
                instance.CreateTimestamp = DateTime.UtcNow;
                instance.CreateUserid    = createdBy.SmUserId;
                Models.DistrictEquipmentType dt = new DistrictEquipmentType();
                if (oldObject.Equip_Type_Cd != null)
                {
                    EquipmentType eType = dbContext.EquipmentTypes.FirstOrDefault(x => (Math.Abs((x.BlueBookSection ?? 0.1) - equip_Rental_rate_No)) <= errowAllowed);
                    if (eType == null)
                    {
                        eType = dbContext.EquipmentTypes.FirstOrDefault(x => (Math.Abs((x.BlueBookSection ?? 0.1) - defaultBlueBoxSection)) <= errowAllowed);
                    }
                    //else    //Just in case we need to update the table of EQUIPMENT_TYPE
                    //{
                    //    if (eType.BlueBookRateNumber == 0.0)  // Update etype with BLUE_BOOK_RATE_NUMBER, MAXIMUN
                    //    {
                    //        try
                    //        {
                    //            eType.MaximumHours = (float)Decimal.Parse(oldObject.Max_Hours, System.Globalization.NumberStyles.Any);
                    //        }
                    //        catch (Exception e)
                    //        {
                    //            string ii = e.ToString();
                    //        }
                    //        try
                    //        {
                    //            eType.MaxHoursSub = (float)Decimal.Parse(oldObject.Max_Hours_Sub, System.Globalization.NumberStyles.Any);
                    //        }
                    //        catch (Exception e)
                    //        {
                    //            string ii = e.ToString();
                    //        }
                    //        try
                    //        {
                    //            eType.ExtendHours = (float)Decimal.Parse(oldObject.Extend_Hours, System.Globalization.NumberStyles.Any);
                    //        }
                    //        catch (Exception e)
                    //        {
                    //            string ii = e.ToString();
                    //        }
                    //        eType.LastUpdateTimestamp = DateTime.ParseExact(oldObject.Created_Dt == null ? "1900-01-01" : oldObject.Created_Dt.Trim().Substring(0, 10), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
                    //        eType.LastUpdateUserid = createdBy.SmUserId;
                    //        //Update some content of the Equipment Type
                    //        dbContext.EquipmentTypes.Update(eType);
                    //    }
                    //}
                    instance.EquipmentTypeId = eType.Id;
                }
            }
            return(serviceAreaName);
        }
示例#14
0
        /// <summary>
        /// Copy xml item to instance (table entries)
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="equipType"></param>
        /// <param name="systemId"></param>
        /// <param name="maxEquipTypeIndex"></param>
        private static void CopyToInstance(DbAppContext dbContext, EquipType oldObject,
                                           ref DistrictEquipmentType equipType, string systemId, ref int maxEquipTypeIndex)
        {
            try
            {
                if (oldObject.Equip_Type_Id <= 0)
                {
                    return;
                }

                if (equipType != null)
                {
                    return;
                }

                // get the equipment type
                string tempEquipTypeCode = ImportUtility.CleanString(oldObject.Equip_Type_Cd).ToUpper();

                // get the parent equipment type
                EquipmentType type = dbContext.EquipmentTypes.FirstOrDefault(x => x.Name == tempEquipTypeCode);

                if (type == null)
                {
                    throw new ArgumentException(
                              string.Format("Cannot find Equipment Type (Equipment Type Code: {0} | Equipment Type Id: {1})",
                                            tempEquipTypeCode, oldObject.Equip_Type_Id));
                }

                // get the description
                string tempDistrictDescription = ImportUtility.CleanString(oldObject.Equip_Type_Desc);
                tempDistrictDescription = ImportUtility.GetCapitalCase(tempDistrictDescription);

                // add new district equipment type
                int tempId = type.Id;

                equipType = new DistrictEquipmentType
                {
                    Id = ++maxEquipTypeIndex,
                    EquipmentTypeId       = tempId,
                    DistrictEquipmentName = tempDistrictDescription
                };

                // set the district
                ServiceArea serviceArea = dbContext.ServiceAreas.AsNoTracking()
                                          .Include(x => x.District)
                                          .FirstOrDefault(x => x.MinistryServiceAreaID == oldObject.Service_Area_Id);

                if (serviceArea == null)
                {
                    throw new ArgumentException(
                              string.Format("Cannot find Service Area (Service Area Id: {0} | Equipment Type Id: {1})",
                                            oldObject.Service_Area_Id, oldObject.Equip_Type_Id));
                }

                int districtId = serviceArea.District.Id;
                equipType.DistrictId = districtId;

                // save district equipment type record
                equipType.AppCreateUserid        = systemId;
                equipType.AppCreateTimestamp     = DateTime.UtcNow;
                equipType.AppLastUpdateUserid    = systemId;
                equipType.AppLastUpdateTimestamp = DateTime.UtcNow;

                dbContext.DistrictEquipmentTypes.Add(equipType);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - (Old) Equipment Code: " + oldObject.Equip_Type_Cd);
                Debug.WriteLine("***Error*** - Master District Equipment Index: " + maxEquipTypeIndex);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
示例#15
0
        /// <summary>
        /// Import District Equipment Types
        /// </summary>
        /// <param name="performContext"></param>
        /// <param name="dbContext"></param>
        /// <param name="fileLocation"></param>
        /// <param name="systemId"></param>
        public static void Import(PerformContext performContext, DbAppContext dbContext, string fileLocation, string systemId)
        {
            // check the start point. If startPoint ==  sigId then it is already completed
            int startPoint = ImportUtility.CheckInterMapForStartPoint(dbContext, OldTableProgress, BcBidImport.SigId, NewTable);

            if (startPoint == BcBidImport.SigId)    // this means the import job it has done today is complete for all the records in the xml file.
            {
                performContext.WriteLine("*** Importing " + XmlFileName + " is complete from the former process ***");
                return;
            }

            int maxEquipTypeIndex = 0;

            if (dbContext.DistrictEquipmentTypes.Any())
            {
                maxEquipTypeIndex = dbContext.DistrictEquipmentTypes.Max(x => x.Id);
            }

            try
            {
                string rootAttr = "ArrayOf" + OldTable;

                // create Processer progress indicator
                performContext.WriteLine("Processing " + OldTable);
                IProgressBar progress = performContext.WriteProgressBar();
                progress.SetValue(0);

                // create serializer and serialize xml file
                XmlSerializer ser          = new XmlSerializer(typeof(EquipType[]), new XmlRootAttribute(rootAttr));
                MemoryStream  memoryStream = ImportUtility.MemoryStreamGenerator(XmlFileName, OldTable, fileLocation, rootAttr);
                EquipType[]   legacyItems  = (EquipType[])ser.Deserialize(memoryStream);

                int ii = startPoint;

                // skip the portion already processed
                if (startPoint > 0)
                {
                    legacyItems = legacyItems.Skip(ii).ToArray();
                }

                Debug.WriteLine("Importing DistrictEquipmentType Data. Total Records: " + legacyItems.Length);

                foreach (EquipType item in legacyItems.WithProgress(progress))
                {
                    // see if we have this one already
                    ImportMap importMap = dbContext.ImportMaps
                                          .FirstOrDefault(x => x.OldTable == OldTable &&
                                                          x.OldKey == item.Equip_Type_Id.ToString() &&
                                                          x.NewTable == NewTable);

                    // new entry
                    if (importMap == null && item.Equip_Type_Id > 0)
                    {
                        DistrictEquipmentType equipType = null;
                        CopyToInstance(dbContext, item, ref equipType, systemId, ref maxEquipTypeIndex);
                        ImportUtility.AddImportMap(dbContext, OldTable, item.Equip_Type_Id.ToString(), NewTable, equipType.Id);
                    }

                    // save change to database periodically to avoid frequent writing to the database
                    if (ii++ % 250 == 0)
                    {
                        try
                        {
                            dbContext.SaveChangesForImport();
                        }
                        catch (Exception e)
                        {
                            performContext.WriteLine("Error saving data " + e.Message);
                        }
                    }
                }

                try
                {
                    performContext.WriteLine("*** Importing " + XmlFileName + " is Done ***");
                    ImportUtility.AddImportMapForProgress(dbContext, OldTableProgress, BcBidImport.SigId.ToString(), BcBidImport.SigId, NewTable);
                    dbContext.SaveChangesForImport();
                }
                catch (Exception e)
                {
                    string temp = string.Format("Error saving data (DistrictEquipmentTypeIndex: {0}): {1}", maxEquipTypeIndex, e.Message);
                    performContext.WriteLine(temp);
                    throw new DataException(temp);
                }
            }
            catch (Exception e)
            {
                performContext.WriteLine("*** ERROR ***");
                performContext.WriteLine(e.ToString());
                throw;
            }
        }
示例#16
0
 public virtual IActionResult DistrictEquipmentTypesPost([FromBody] DistrictEquipmentType item)
 {
     return(_service.DistrictEquipmentTypesPostAsync(item));
 }
示例#17
0
        /// <summary>
        /// Gets the hash code
        /// </summary>
        /// <returns>Hash code</returns>
        public override int GetHashCode()
        {
            // credit: http://stackoverflow.com/a/263416/677735
            unchecked // Overflow is fine, just wrap
            {
                int hash = 41;

                // Suitable nullity checks
                hash = hash * 59 + Id.GetHashCode();

                if (Project != null)
                {
                    hash = hash * 59 + Project.GetHashCode();
                }

                if (LocalArea != null)
                {
                    hash = hash * 59 + LocalArea.GetHashCode();
                }

                if (Status != null)
                {
                    hash = hash * 59 + Status.GetHashCode();
                }

                if (DistrictEquipmentType != null)
                {
                    hash = hash * 59 + DistrictEquipmentType.GetHashCode();
                }

                hash = hash * 59 + EquipmentCount.GetHashCode();

                if (ExpectedHours != null)
                {
                    hash = hash * 59 + ExpectedHours.GetHashCode();
                }

                if (ExpectedStartDate != null)
                {
                    hash = hash * 59 + ExpectedStartDate.GetHashCode();
                }

                if (ExpectedEndDate != null)
                {
                    hash = hash * 59 + ExpectedEndDate.GetHashCode();
                }

                if (FirstOnRotationList != null)
                {
                    hash = hash * 59 + FirstOnRotationList.GetHashCode();
                }

                if (Notes != null)
                {
                    hash = hash * 59 + Notes.GetHashCode();
                }

                if (Attachments != null)
                {
                    hash = hash * 59 + Attachments.GetHashCode();
                }

                if (History != null)
                {
                    hash = hash * 59 + History.GetHashCode();
                }

                if (RentalRequestAttachments != null)
                {
                    hash = hash * 59 + RentalRequestAttachments.GetHashCode();
                }

                if (RentalRequestRotationList != null)
                {
                    hash = hash * 59 + RentalRequestRotationList.GetHashCode();
                }

                return(hash);
            }
        }
示例#18
0
 public virtual IActionResult DistrictEquipmentTypesIdPut([FromRoute] int id, [FromBody] DistrictEquipmentType item)
 {
     return(_service.DistrictEquipmentTypesIdPutAsync(id, item));
 }
示例#19
0
        /// <summary>
        /// Returns true if RentalRequest instances are equal
        /// </summary>
        /// <param name="other">Instance of RentalRequest to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(RentalRequestViewModel other)
        {
            if (other is null)
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     Id == other.Id ||
                     Id.Equals(other.Id)
                     ) &&
                 (
                     Project == other.Project ||
                     Project != null &&
                     Project.Equals(other.Project)
                 ) &&
                 (
                     LocalArea == other.LocalArea ||
                     LocalArea != null &&
                     LocalArea.Equals(other.LocalArea)
                 ) &&
                 (
                     Status == other.Status ||
                     Status != null &&
                     Status.Equals(other.Status)
                 ) &&
                 (
                     DistrictEquipmentType == other.DistrictEquipmentType ||
                     DistrictEquipmentType != null &&
                     DistrictEquipmentType.Equals(other.DistrictEquipmentType)
                 ) &&
                 (
                     EquipmentCount == other.EquipmentCount ||
                     EquipmentCount.Equals(other.EquipmentCount)
                 ) &&
                 (
                     ExpectedHours == other.ExpectedHours ||
                     ExpectedHours != null &&
                     ExpectedHours.Equals(other.ExpectedHours)
                 ) &&
                 (
                     ExpectedStartDate == other.ExpectedStartDate ||
                     ExpectedStartDate != null &&
                     ExpectedStartDate.Equals(other.ExpectedStartDate)
                 ) &&
                 (
                     ExpectedEndDate == other.ExpectedEndDate ||
                     ExpectedEndDate != null &&
                     ExpectedEndDate.Equals(other.ExpectedEndDate)
                 ) &&
                 (
                     FirstOnRotationList == other.FirstOnRotationList ||
                     FirstOnRotationList != null &&
                     FirstOnRotationList.Equals(other.FirstOnRotationList)
                 ) &&
                 (
                     Notes == other.Notes ||
                     Notes != null &&
                     Notes.SequenceEqual(other.Notes)
                 ) &&
                 (
                     Attachments == other.Attachments ||
                     Attachments != null &&
                     Attachments.SequenceEqual(other.Attachments)
                 ) &&
                 (
                     History == other.History ||
                     History != null &&
                     History.SequenceEqual(other.History)
                 ) &&
                 (
                     RentalRequestAttachments == other.RentalRequestAttachments ||
                     RentalRequestAttachments != null &&
                     RentalRequestAttachments.SequenceEqual(other.RentalRequestAttachments)
                 ) &&
                 (
                     RentalRequestRotationList == other.RentalRequestRotationList ||
                     RentalRequestRotationList != null &&
                     RentalRequestRotationList.SequenceEqual(other.RentalRequestRotationList)
                 ));
        }
示例#20
0
        /// <summary>
        /// Copy Block item of LocalAreaRotationList item
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="rotationList"></param>
        /// <param name="systemId"></param>
        /// <param name="maxBlockIndex"></param>
        private static void CopyToInstance(DbAppContext dbContext, Block oldObject, ref LocalAreaRotationList rotationList,
                                           string systemId, ref int maxBlockIndex)
        {
            try
            {
                bool isNew = false;

                if (oldObject.Area_Id <= 0)
                {
                    return; // ignore these records
                }

                if (oldObject.Equip_Type_Id <= 0)
                {
                    return; // ignore these records
                }

                if (oldObject.Last_Hired_Equip_Id <= 0)
                {
                    return; // ignore these records
                }

                // ***********************************************
                // we only need records from the current fiscal
                // so ignore all others
                // ***********************************************
                DateTime fiscalStart;
                DateTime fiscalEnd;

                if (DateTime.UtcNow.Month == 1 || DateTime.UtcNow.Month == 2 || DateTime.UtcNow.Month == 3)
                {
                    fiscalEnd = new DateTime(DateTime.UtcNow.Year, 3, 31);
                }
                else
                {
                    fiscalEnd = new DateTime(DateTime.UtcNow.AddYears(1).Year, 3, 31);
                }

                if (DateTime.UtcNow.Month == 1 || DateTime.UtcNow.Month == 2 || DateTime.UtcNow.Month == 3)
                {
                    fiscalStart = new DateTime(DateTime.UtcNow.AddYears(-1).Year, 4, 1);
                }
                else
                {
                    fiscalStart = new DateTime(DateTime.UtcNow.Year, 4, 1);
                }

                string tempRecordDate = oldObject.Created_Dt;

                if (string.IsNullOrEmpty(tempRecordDate))
                {
                    return; // ignore if we don't have a created date
                }

                if (!string.IsNullOrEmpty(tempRecordDate))
                {
                    DateTime?recordDate = ImportUtility.CleanDateTime(tempRecordDate);

                    if (recordDate == null ||
                        recordDate < fiscalStart ||
                        recordDate > fiscalEnd)
                    {
                        return; // ignore this record - it is outside of the current fiscal year
                    }
                }

                // ***********************************************
                // get the area record
                // ***********************************************
                string tempOldAreaId = oldObject.Area_Id.ToString();

                ImportMap mapArea = dbContext.ImportMaps.AsNoTracking()
                                    .FirstOrDefault(x => x.OldKey == tempOldAreaId &&
                                                    x.OldTable == ImportLocalArea.OldTable &&
                                                    x.NewTable == ImportLocalArea.NewTable);

                if (mapArea == null)
                {
                    throw new DataException(string.Format("Area Id cannot be null (BlockIndex: {0})", maxBlockIndex));
                }

                LocalArea area = dbContext.LocalAreas.AsNoTracking()
                                 .FirstOrDefault(x => x.Id == mapArea.NewKey);

                if (area == null)
                {
                    throw new ArgumentException(string.Format("Cannot locate Local Area record (Local Area Id: {0})", tempOldAreaId));
                }

                // ***********************************************
                // get the equipment type record
                // ***********************************************
                string tempOldEquipTypeId = oldObject.Equip_Type_Id.ToString();

                ImportMap mapEquipType = dbContext.ImportMaps.AsNoTracking()
                                         .FirstOrDefault(x => x.OldKey == tempOldEquipTypeId &&
                                                         x.OldTable == ImportDistrictEquipmentType.OldTable &&
                                                         x.NewTable == ImportDistrictEquipmentType.NewTable);

                if (mapEquipType == null)
                {
                    throw new DataException(string.Format("Equipment Type Id cannot be null (BlockIndex: {0})", maxBlockIndex));
                }

                DistrictEquipmentType equipmentType = dbContext.DistrictEquipmentTypes.AsNoTracking()
                                                      .FirstOrDefault(x => x.Id == mapEquipType.NewKey);

                if (equipmentType == null)
                {
                    throw new ArgumentException(string.Format("Cannot locate District Equipment Type record (Equipment Type Id: {0})", tempOldEquipTypeId));
                }

                // ***********************************************
                // see if a record already exists
                // ***********************************************
                rotationList = dbContext.LocalAreaRotationLists
                               .FirstOrDefault(x => x.LocalAreaId == area.Id &&
                                               x.DistrictEquipmentTypeId == equipmentType.Id);

                if (rotationList == null)
                {
                    isNew = true;

                    // create new list
                    rotationList = new LocalAreaRotationList
                    {
                        Id                      = ++maxBlockIndex,
                        LocalAreaId             = area.Id,
                        DistrictEquipmentTypeId = equipmentType.Id,
                        AppCreateUserid         = systemId,
                        AppCreateTimestamp      = DateTime.UtcNow
                    };
                }
                else
                {
                    // record already exists - just testing updates
                    Debug.WriteLine("Record Id: " + rotationList.Id);
                }

                // ***********************************************
                // get the equipment record
                // ***********************************************
                string tempOldEquipId = oldObject.Last_Hired_Equip_Id.ToString();

                ImportMap mapEquip = dbContext.ImportMaps.AsNoTracking()
                                     .FirstOrDefault(x => x.OldKey == tempOldEquipId &&
                                                     x.OldTable == ImportEquip.OldTable &&
                                                     x.NewTable == ImportEquip.NewTable);

                if (mapEquip == null)
                {
                    throw new DataException(string.Format("Equipment Id cannot be null (BlockIndex: {0})", maxBlockIndex));
                }

                Equipment equipment = dbContext.Equipments.AsNoTracking()
                                      .FirstOrDefault(x => x.Id == mapEquip.NewKey);

                if (equipment == null)
                {
                    throw new ArgumentException(string.Format("Cannot locate Equipment record (Equipment Id: {0})", tempOldEquipId));
                }

                // ***********************************************
                // update the "Ask Next" values
                // ***********************************************
                float?blockNum = ImportUtility.GetFloatValue(oldObject.Block_Num);

                if (blockNum == null)
                {
                    throw new DataException(string.Format("Block Number cannot be null (BlockIndex: {0}", maxBlockIndex));
                }

                // extract AskNextBlock*Id which is the secondary key of Equip.Id
                switch (blockNum)
                {
                case 1:
                    rotationList.AskNextBlock1Id        = equipment.Id;
                    rotationList.AskNextBlock1Seniority = equipment.Seniority;
                    break;

                case 2:
                    rotationList.AskNextBlock2Id        = equipment.Id;
                    rotationList.AskNextBlock2Seniority = equipment.Seniority;
                    break;

                case 3:
                    rotationList.AskNextBlockOpenId = equipment.Id;
                    break;
                }

                // ***********************************************
                // update or create equipment
                // ***********************************************
                equipment.AppLastUpdateUserid    = systemId;
                equipment.AppLastUpdateTimestamp = DateTime.UtcNow;

                if (isNew)
                {
                    dbContext.LocalAreaRotationLists.Add(rotationList);
                }
                else
                {
                    dbContext.LocalAreaRotationLists.Update(rotationList);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - Master Block Index: " + maxBlockIndex);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
示例#21
0
        /// <summary>
        /// Copy Block item of LocalAreaRotationList item
        /// </summary>
        /// <param name="performContext"></param>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="instance"></param>
        /// <param name="systemId"></param>
        /// <param name="oldUniqueId"></param>
        static private void CopyToInstance(PerformContext performContext, DbAppContext dbContext, HETSAPI.Import.Block oldObject,
                                           ref Models.LocalAreaRotationList instance, string systemId, string oldUniqueId)
        {
            bool isNew = false;

            if (oldObject.Area_Id <= 0)
            {
                return;
            }

            //Add the user specified in oldObject.Modified_By and oldObject.Created_By if not there in the database
            Models.User modifiedBy = ImportUtility.AddUserFromString(dbContext, "", systemId);
            Models.User createdBy  = ImportUtility.AddUserFromString(dbContext, oldObject.Created_By, systemId);

            int areaId          = oldObject.Area_Id ?? 0;
            int equipmentTypeId = oldObject.Equip_Type_Id ?? 0;
            int blockNum        = Convert.ToInt32(float.Parse(oldObject.Block_Num == null ? "0.0" : oldObject.Block_Num));
            int cyclekNum       = Convert.ToInt32(float.Parse(oldObject.Cycle_Num == null ? "0.0" : oldObject.Cycle_Num));
            int maxCycle        = Convert.ToInt32(float.Parse(oldObject.Max_Cycle == null ? "0.0" : oldObject.Max_Cycle));
            int lastHiredEqupId = oldObject.Last_Hired_Equip_Id ?? 0;

            if (instance == null)
            {
                isNew    = true;
                instance = new Models.LocalAreaRotationList();
                // instance.ProjectId = oldObject.Reg_Dump_Trk;
                DistrictEquipmentType disEquipType = dbContext.DistrictEquipmentTypes.FirstOrDefault(x => x.Id == equipmentTypeId);
                if (disEquipType != null)
                {
                    instance.DistrictEquipmentType   = disEquipType;
                    instance.DistrictEquipmentTypeId = disEquipType.Id;
                }

                // Extract AskNextBlock*Id which is the secondary key of Equip.Id
                int equipId = oldObject.Last_Hired_Equip_Id ?? 0;
                if (dbContext.Equipments.Any(x => x.Id == equipId))
                {
                    switch (blockNum)
                    {
                    case 1:
                        instance.AskNextBlockOpenId = equipId;
                        break;

                    case 2:
                        instance.AskNextBlock1Id = equipId;
                        break;

                    case 3:
                        instance.AskNextBlock2Id = equipId;
                        break;

                    default:
                        break;
                    }
                }

                instance.CreateUserid = createdBy.SmUserId;
                if (oldObject.Created_Dt != null)
                {
                    instance.CreateTimestamp = DateTime.ParseExact(oldObject.Created_Dt.Trim().Substring(0, 10), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
                }

                dbContext.LocalAreaRotationLists.Add(instance);
            }
            else
            {
                // Updating the existing instance - but how to locate it? There is(are) no unique key(s) for that
            }
        }
示例#22
0
        /// <summary>
        /// Import District Equipment Types
        /// </summary>
        /// <param name="performContext"></param>
        /// <param name="dbContext"></param>
        /// <param name="fileLocation"></param>
        /// <param name="systemId"></param>
        public static void Import(PerformContext performContext, DbAppContext dbContext, string fileLocation, string systemId)
        {
            // check the start point. If startPoint ==  sigId then it is already completed
            int startPoint = ImportUtility.CheckInterMapForStartPoint(dbContext, OldTableProgress, BCBidImport.SigId);

            if (startPoint == BCBidImport.SigId)    // this means the import job it has done today is complete for all the records in the xml file.
            {
                performContext.WriteLine("*** Importing " + XmlFileName + " is complete from the former process ***");
                return;
            }

            try
            {
                string rootAttr = "ArrayOf" + OldTable;

                //Create Processer progress indicator
                performContext.WriteLine("Processing " + OldTable);
                IProgressBar progress = performContext.WriteProgressBar();
                progress.SetValue(0);

                // create serializer and serialize xml file
                XmlSerializer ser          = new XmlSerializer(typeof(EquipType[]), new XmlRootAttribute(rootAttr));
                MemoryStream  memoryStream = ImportUtility.MemoryStreamGenerator(XmlFileName, OldTable, fileLocation, rootAttr);
                EquipType[]   legacyItems  = (EquipType[])ser.Deserialize(memoryStream);

                int ii = 0;

                foreach (EquipType item in legacyItems.WithProgress(progress))
                {
                    // see if we have this one already
                    ImportMap importMap = dbContext.ImportMaps.FirstOrDefault(x => x.OldTable == OldTable && x.OldKey == item.Equip_Type_Id.ToString());

                    // new entry
                    if (importMap == null)
                    {
                        if (item.Equip_Type_Id > 0)
                        {
                            DistrictEquipmentType instance = null;
                            CopyToInstance(dbContext, item, ref instance, systemId);
                            ImportUtility.AddImportMap(dbContext, OldTable, item.Equip_Type_Id.ToString(), NewTable, instance.Id);
                        }
                    }
                    else // update
                    {
                        DistrictEquipmentType instance = dbContext.DistrictEquipmentTypes.FirstOrDefault(x => x.Id == importMap.NewKey);
                        if (instance == null) // record was deleted
                        {
                            CopyToInstance(dbContext, item, ref instance, systemId);

                            // update the import map
                            importMap.NewKey = instance.Id;
                            dbContext.ImportMaps.Update(importMap);
                        }
                        else // ordinary update
                        {
                            CopyToInstance(dbContext, item, ref instance, systemId);

                            // touch the import map
                            importMap.LastUpdateTimestamp = DateTime.UtcNow;
                            dbContext.ImportMaps.Update(importMap);
                        }
                    }

                    // save change to database periodically to avoid frequent writing to the database
                    if (ii++ % 250 == 0)
                    {
                        try
                        {
                            dbContext.SaveChangesForImport();
                        }
                        catch (Exception e)
                        {
                            performContext.WriteLine("Error saving data " + e.Message);
                        }
                    }
                }

                try
                {
                    performContext.WriteLine("*** Importing " + XmlFileName + " is Done ***");
                    ImportUtility.AddImportMapForProgress(dbContext, OldTableProgress, BCBidImport.SigId.ToString(), BCBidImport.SigId);
                    dbContext.SaveChangesForImport();
                }
                catch (Exception e)
                {
                    performContext.WriteLine("Error saving data " + e.Message);
                }
            }
            catch (Exception e)
            {
                performContext.WriteLine("*** ERROR ***");
                performContext.WriteLine(e.ToString());
            }
        }
示例#23
0
        /// <summary>
        /// Map data
        /// </summary>
        /// <param name="performContext"></param>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="instance"></param>
        /// <param name="systemId"></param>
        private static void CopyToInstance(PerformContext performContext, DbAppContext dbContext, Equip oldObject, ref Equipment instance, string systemId)
        {
            if (oldObject.Equip_Id <= 0)
            {
                return;
            }

            //Add the user specified in oldObject.Modified_By and oldObject.Created_By if not there in the database
            User modifiedBy = ImportUtility.AddUserFromString(dbContext, oldObject.Modified_By, systemId);
            User createdBy  = ImportUtility.AddUserFromString(dbContext, oldObject.Created_By, systemId);

            if (instance == null)
            {
                instance = new Equipment
                {
                    Id          = oldObject.Equip_Id,
                    ArchiveCode = oldObject.Archive_Cd == null
                        ? ""
                        : new string(oldObject.Archive_Cd.Take(50).ToArray()),
                    ArchiveReason = oldObject.Archive_Reason == null
                        ? ""
                        : new string(oldObject.Archive_Reason.Take(2048).ToArray()),
                    LicencePlate = oldObject.Licence == null ? "" : new string(oldObject.Licence.Take(20).ToArray())
                };

                if (oldObject.Approved_Dt != null)
                {
                    instance.ApprovedDate = DateTime.ParseExact(oldObject.Approved_Dt.Trim().Substring(0, 10), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
                }

                if (oldObject.Received_Dt != null)
                {
                    instance.ReceivedDate = DateTime.ParseExact(oldObject.Received_Dt.Trim().Substring(0, 10), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
                }

                if (oldObject.Comment != null)
                {
                    instance.Notes = new List <Note>();

                    Note note = new Note
                    {
                        Text = new string(oldObject.Comment.Take(2048).ToArray()),
                        IsNoLongerRelevant = true
                    };

                    instance.Notes.Add(note);
                }

                if (oldObject.Area_Id != null)
                {
                    LocalArea area = dbContext.LocalAreas.FirstOrDefault(x => x.Id == oldObject.Area_Id);
                    if (area != null)
                    {
                        instance.LocalArea = area;
                    }
                }

                if (oldObject.Equip_Type_Id != null)
                {
                    //Equipment_TYPE_ID is copied to the table of HET_DISTRICT_DISTRICT_TYPE as key
                    DistrictEquipmentType equipType = dbContext.DistrictEquipmentTypes.FirstOrDefault(x => x.Id == oldObject.Equip_Type_Id);

                    if (equipType != null)
                    {
                        instance.DistrictEquipmentType   = equipType;
                        instance.DistrictEquipmentTypeId = oldObject.Equip_Type_Id;
                    }
                }

                instance.EquipmentCode = oldObject.Equip_Cd == null ? "" : new string(oldObject.Equip_Cd.Take(25).ToArray());
                instance.Model         = oldObject.Model == null ? "" : new string(oldObject.Model.Take(50).ToArray());
                instance.Make          = oldObject.Make == null ? "" : new string(oldObject.Make.Take(50).ToArray());
                instance.Year          = oldObject.Year == null ? "" : new string(oldObject.Year.Take(15).ToArray());
                instance.Operator      = oldObject.Operator == null ? "" : new string(oldObject.Operator.Take(255).ToArray());
                instance.SerialNumber  = oldObject.Serial_Num == null ? "" : new string(oldObject.Serial_Num.Take(100).ToArray());
                instance.Status        = oldObject.Status_Cd == null ? "" : new string(oldObject.Status_Cd.Take(50).ToArray());

                if (oldObject.Pay_Rate != null)
                {
                    try
                    {
                        instance.PayRate = float.Parse(oldObject.Pay_Rate.Trim());
                    }
                    catch
                    {
                        instance.PayRate = (float)0.0;
                    }
                }

                if (instance.Seniority != null)
                {
                    try
                    {
                        instance.Seniority = float.Parse(oldObject.Seniority.Trim());
                    }
                    catch
                    {
                        instance.Seniority = (float)0.0;
                    }
                }

                // find the owner which is referenced in the equipment of the xml file entry Through ImportMaps because owner_ID is not prop_ID
                ImportMap map = dbContext.ImportMaps.FirstOrDefault(x => x.OldTable == ImportOwner.OldTable && x.OldKey == oldObject.Owner_Popt_Id.ToString());

                if (map != null)
                {
                    Models.Owner owner = dbContext.Owners.FirstOrDefault(x => x.Id == map.NewKey);
                    if (owner != null)
                    {
                        instance.Owner = owner;
                        Contact con = dbContext.Contacts.FirstOrDefault(x => x.Id == owner.PrimaryContactId);

                        // update owner contact address
                        if (con != null)
                        {
                            try
                            {
                                con.Address1   = oldObject.Addr1;
                                con.Address2   = oldObject.Addr2;
                                con.City       = oldObject.City;
                                con.PostalCode = oldObject.Postal;
                                con.Province   = "BC";
                                dbContext.Contacts.Update(con);
                            }
                            catch (Exception e)
                            {
                                performContext.WriteLine("Error mapping data " + e.Message);
                            }
                        }
                    }
                }

                if (oldObject.Seniority != null)
                {
                    try
                    {
                        instance.Seniority = float.Parse(oldObject.Seniority.Trim());
                    }
                    catch
                    {
                        instance.Seniority = (float)0.0;
                    }
                }

                if (oldObject.Num_Years != null)
                {
                    try
                    {
                        instance.YearsOfService = float.Parse(oldObject.Num_Years.Trim());
                    }
                    catch
                    {
                        instance.YearsOfService = (float)0.0;
                    }
                }

                if (oldObject.Block_Num != null)
                {
                    try
                    {
                        instance.BlockNumber = decimal.ToInt32(Decimal.Parse(oldObject.Block_Num, System.Globalization.NumberStyles.Float));
                    }
                    catch
                    {
                        // do nothing
                    }
                }

                if (oldObject.Size != null)
                {
                    try
                    {
                        instance.Size = oldObject.Size;
                    }
                    catch
                    {
                        // do nothing
                    }
                }

                if (oldObject.YTD1 != null && oldObject.YTD2 != null && oldObject.YTD3 != null)
                {
                    try
                    {
                        instance.ServiceHoursLastYear = (float)Decimal.Parse(oldObject.YTD1, System.Globalization.NumberStyles.Any);
                    }
                    catch
                    {
                        instance.ServiceHoursLastYear = (float)0.0;
                    }
                    try
                    {
                        instance.ServiceHoursTwoYearsAgo   = (float)Decimal.Parse(oldObject.YTD2, System.Globalization.NumberStyles.Any);
                        instance.ServiceHoursThreeYearsAgo = (float)Decimal.Parse(oldObject.YTD3, System.Globalization.NumberStyles.Any);
                    }
                    catch
                    {
                        instance.ServiceHoursTwoYearsAgo   = (float)0.0;
                        instance.ServiceHoursThreeYearsAgo = (float)0.0;
                    }
                }

                instance.CreateTimestamp = DateTime.UtcNow;
                instance.CreateUserid    = createdBy.SmUserId;
                dbContext.Equipments.Add(instance);
            }
            else
            {
                instance = dbContext.Equipments.First(x => x.Id == oldObject.Equip_Id);
                instance.LastUpdateUserid = modifiedBy.SmUserId;

                try
                {
                    instance.LastUpdateUserid    = modifiedBy.SmUserId;
                    instance.LastUpdateTimestamp = DateTime.ParseExact(oldObject.Modified_Dt.Trim().Substring(0, 10), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
                }
                catch (Exception e)
                {
                    performContext.WriteLine("Error mapping data " + e.Message);
                }

                dbContext.Equipments.Update(instance);
            }
        }
示例#24
0
        /// <summary>
        /// Create or update district equipment type
        /// </summary>
        /// <param name="id">id of DistrictEquipmentType to update (o to create)</param>
        /// <param name="item"></param>
        /// <response code="200">OK</response>
        /// <response code="404">DistrictEquipmentType not found</response>
        public virtual IActionResult DistrictEquipmentTypesIdPostAsync(int id, DistrictEquipmentType item)
        {
            if (id != item.Id)
            {
                // record not found
                return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
            }

            // add or update contact
            if (item.Id > 0)
            {
                bool exists = _context.DistrictEquipmentTypes.Any(a => a.Id == id);

                if (!exists)
                {
                    // record not found
                    return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
                }

                // get record
                DistrictEquipmentType equipment = _context.DistrictEquipmentTypes.First(x => x.Id == id);

                equipment.DistrictEquipmentName = item.DistrictEquipmentName;

                if (item.District != null)
                {
                    equipment.DistrictId = item.District.Id;
                }
                else
                {
                    equipment.District = null;
                }

                if (item.EquipmentType != null)
                {
                    equipment.EquipmentTypeId = item.EquipmentType.Id;
                }
                else
                {
                    equipment.EquipmentType = null;
                }
            }
            else
            {
                // get child records
                AdjustRecord(item);

                _context.DistrictEquipmentTypes.Add(item);
            }

            // Save the changes
            _context.SaveChanges();

            // get the id (in the case of new records)
            id = item.Id;

            // return the updated record
            DistrictEquipmentType result = _context.DistrictEquipmentTypes.AsNoTracking()
                                           .Include(x => x.District)
                                           .ThenInclude(y => y.Region)
                                           .Include(x => x.EquipmentType)
                                           .First(a => a.Id == id);

            return(new ObjectResult(new HetsResponse(result)));
        }
示例#25
0
        /// <summary>
        /// Test the creation of the rotation list, a side effect of rental request record creation.
        /// </summary>
        public async Task TestRotationListNonDumpTruck()
        {
            string initialName = "InitialName";

            // create a temporary region.
            var    request = new HttpRequestMessage(HttpMethod.Post, "/api/regions");
            Region region  = new Region();

            region.Name = initialName;

            request.Content = new StringContent(region.ToJson(), Encoding.UTF8, "application/json");

            var response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            // parse as JSON.
            string jsonString = await response.Content.ReadAsStringAsync();

            region = JsonConvert.DeserializeObject <Region>(jsonString);

            request = new HttpRequestMessage(HttpMethod.Post, "/api/districts");

            // create a new District
            District district = new District();

            district.Id     = 0;
            district.Name   = initialName;
            district.Region = region;
            jsonString      = district.ToJson();
            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
            response        = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            // parse as JSON.
            jsonString = await response.Content.ReadAsStringAsync();

            district = JsonConvert.DeserializeObject <District>(jsonString);

            // create a new Service Area
            request = new HttpRequestMessage(HttpMethod.Post, "/api/serviceareas");
            ServiceArea serviceArea = new ServiceArea();

            serviceArea.Id       = 0;
            serviceArea.Name     = initialName;
            serviceArea.District = district;
            jsonString           = serviceArea.ToJson();
            request.Content      = new StringContent(jsonString, Encoding.UTF8, "application/json");
            response             = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            // parse as JSON.
            jsonString = await response.Content.ReadAsStringAsync();

            serviceArea = JsonConvert.DeserializeObject <ServiceArea>(jsonString);

            // create a new Local Area
            request = new HttpRequestMessage(HttpMethod.Post, "/api/localAreas");
            LocalArea localArea = new LocalArea();

            localArea.Id = 0;
            localArea.LocalAreaNumber = 1234;
            localArea.ServiceArea     = serviceArea;
            jsonString      = localArea.ToJson();
            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
            response        = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            // parse as JSON.
            jsonString = await response.Content.ReadAsStringAsync();

            localArea = JsonConvert.DeserializeObject <LocalArea>(jsonString);

            // create a new Equipment Type
            request = new HttpRequestMessage(HttpMethod.Post, "/api/equipmentTypes");

            // create a new equipment type
            EquipmentType equipmentType = new EquipmentType();

            equipmentType.Id             = 0;
            equipmentType.Name           = initialName;
            equipmentType.IsDumpTruck    = false;
            equipmentType.NumberOfBlocks = 2;

            jsonString      = equipmentType.ToJson();
            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
            response        = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            // parse as JSON.
            jsonString = await response.Content.ReadAsStringAsync();

            equipmentType = JsonConvert.DeserializeObject <EquipmentType>(jsonString);

            request = new HttpRequestMessage(HttpMethod.Post, "/api/districtEquipmentTypes");

            // create a new District Equipment Type
            DistrictEquipmentType districtEquipmentType = new DistrictEquipmentType();

            districtEquipmentType.Id = 0;
            districtEquipmentType.DistrictEquipmentName = initialName;
            districtEquipmentType.District      = district;
            districtEquipmentType.EquipmentType = equipmentType;
            jsonString      = districtEquipmentType.ToJson();
            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
            response        = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            // parse as JSON.
            jsonString = await response.Content.ReadAsStringAsync();

            districtEquipmentType = JsonConvert.DeserializeObject <DistrictEquipmentType>(jsonString);

            // create equipment.
            int numberEquipment = 75;

            Equipment[] testEquipment = new Equipment[numberEquipment];
            int         blockCount    = 0;
            int         currentBlock  = 1;

            for (int i = 0; i < numberEquipment; i++)
            {
                testEquipment[i]                       = new Equipment();
                testEquipment[i].LocalArea             = localArea;
                testEquipment[i].DistrictEquipmentType = districtEquipmentType;
                testEquipment[i].Seniority             = (numberEquipment - i + 1) * 1.05F;
                testEquipment[i].IsSeniorityOverridden = true;
                testEquipment[i].BlockNumber           = currentBlock;
                testEquipment[i]                       = CreateEquipment(testEquipment[i]);
                ++blockCount;
                if (blockCount >= 10 && currentBlock < 2)
                {
                    currentBlock++;
                    blockCount = 0;
                }

                // avoid database problems due to too many requests
                System.Threading.Thread.Sleep(200);
            }

            // Now create the rental request.
            request = new HttpRequestMessage(HttpMethod.Post, "/api/rentalrequests");
            RentalRequest rentalRequest = new RentalRequest();

            rentalRequest.Status                = initialName;
            rentalRequest.LocalArea             = localArea;
            rentalRequest.DistrictEquipmentType = districtEquipmentType;

            jsonString      = rentalRequest.ToJson();
            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
            response        = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            // parse as JSON.
            jsonString = await response.Content.ReadAsStringAsync();

            rentalRequest = JsonConvert.DeserializeObject <RentalRequest>(jsonString);
            // get the id
            var id = rentalRequest.Id;

            // do a get.
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/rentalrequests/" + id);
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            // parse as JSON.
            jsonString = await response.Content.ReadAsStringAsync();

            rentalRequest = JsonConvert.DeserializeObject <RentalRequest>(jsonString);

            // should be the same number of equipment.
            Assert.Equal(rentalRequest.RentalRequestRotationList.Count, numberEquipment);

            // do a delete.
            request  = new HttpRequestMessage(HttpMethod.Post, "/api/rentalrequests/" + id + "/delete");
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            // should get a 404 if we try a get now.
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/rentalrequests/" + id);
            response = await _client.SendAsync(request);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            // remove equipment.

            for (int i = 0; i < numberEquipment; i++)
            {
                request  = new HttpRequestMessage(HttpMethod.Post, "/api/equipment/" + testEquipment[i].Id + "/delete");
                response = await _client.SendAsync(request);

                response.EnsureSuccessStatusCode();

                // should get a 404 if we try a get now.
                request  = new HttpRequestMessage(HttpMethod.Get, "/api/equipment/" + testEquipment[i].Id);
                response = await _client.SendAsync(request);

                Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            }

            // now remove the other temporary objects.

            // districtEquipmentType
            request  = new HttpRequestMessage(HttpMethod.Post, "/api/districtEquipmentTypes/" + districtEquipmentType.Id + "/delete");
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/districtEquipmentTypes/" + districtEquipmentType.Id);
            response = await _client.SendAsync(request);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            // equipmentType
            request  = new HttpRequestMessage(HttpMethod.Post, "/api/equipmentTypes/" + equipmentType.Id + "/delete");
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/equipmentTypes/" + equipmentType.Id);
            response = await _client.SendAsync(request);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            // localArea
            request  = new HttpRequestMessage(HttpMethod.Post, "/api/localAreas/" + localArea.Id + "/delete");
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/localAreas/" + localArea.Id);
            response = await _client.SendAsync(request);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            // Service Area
            request  = new HttpRequestMessage(HttpMethod.Post, "/api/serviceareas/" + serviceArea.Id + "/delete");
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/serviceareas/" + serviceArea.Id);
            response = await _client.SendAsync(request);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            // District
            request  = new HttpRequestMessage(HttpMethod.Post, "/api/districts/" + district.Id + "/delete");
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/districts/" + district.Id);
            response = await _client.SendAsync(request);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            // Region
            request  = new HttpRequestMessage(HttpMethod.Post, "/api/regions/" + region.Id + "/delete");
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/regions/" + region.Id);
            response = await _client.SendAsync(request);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
        }
示例#26
0
        /// <summary>
        /// Map data
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="equipment"></param>
        /// <param name="systemId"></param>
        /// <param name="maxEquipmentIndex"></param>
        private static void CopyToInstance(DbAppContext dbContext, Equip oldObject, ref Equipment equipment, string systemId, ref int maxEquipmentIndex)
        {
            try
            {
                if (oldObject.Equip_Id <= 0)
                {
                    return;
                }

                equipment = new Equipment {
                    Id = ++maxEquipmentIndex
                };

                // there is a problem with 1 equipment record
                // Per BC Bid - the correct Owner Id should be: 8786195
                if (oldObject.Equip_Id == 19165)
                {
                    oldObject.Owner_Popt_Id = 8786195;
                }

                // ***********************************************
                // set the equipment status
                // ***********************************************
                string tempArchive = oldObject.Archive_Cd;
                string tempStatus  = oldObject.Status_Cd.Trim();

                if (tempArchive == "Y")
                {
                    // archived!
                    equipment.ArchiveCode   = "Y";
                    equipment.ArchiveDate   = DateTime.UtcNow;
                    equipment.ArchiveReason = "Imported from BC Bid";
                    equipment.Status        = "Archived";

                    string tempArchiveReason = ImportUtility.CleanString(oldObject.Archive_Reason);

                    if (!string.IsNullOrEmpty(tempArchiveReason))
                    {
                        equipment.ArchiveReason = ImportUtility.GetUppercaseFirst(tempArchiveReason);
                    }
                }
                else
                {
                    equipment.ArchiveCode   = "N";
                    equipment.ArchiveDate   = null;
                    equipment.ArchiveReason = null;
                    equipment.Status        = tempStatus == "A" ? "Approved" : "Unapproved";
                    equipment.StatusComment = string.Format("Imported from BC Bid ({0})", tempStatus);
                }

                // ***********************************************
                // set equipment attributes
                // ***********************************************
                string tempLicense = ImportUtility.CleanString(oldObject.Licence).ToUpper();

                if (!string.IsNullOrEmpty(tempLicense))
                {
                    equipment.LicencePlate = tempLicense;
                }

                equipment.ApprovedDate = ImportUtility.CleanDateTime(oldObject.Approved_Dt);

                DateTime?tempReceivedDate = ImportUtility.CleanDateTime(oldObject.Received_Dt);

                if (tempReceivedDate != null)
                {
                    equipment.ReceivedDate = (DateTime)tempReceivedDate;
                }
                else
                {
                    if (equipment.ArchiveCode == "N" && equipment.Status == "Approved")
                    {
                        throw new DataException(string.Format("Received Date cannot be null (EquipmentIndex: {0}", maxEquipmentIndex));
                    }
                }

                // equipment code
                string tempEquipmentCode = ImportUtility.CleanString(oldObject.Equip_Cd).ToUpper();

                if (!string.IsNullOrEmpty(tempEquipmentCode))
                {
                    equipment.EquipmentCode = tempEquipmentCode;
                }
                else
                {
                    if (equipment.ArchiveCode == "N" && equipment.Status == "Approved")
                    {
                        throw new DataException(string.Format("Equipment Code cannot be null (EquipmentIndex: {0}", maxEquipmentIndex));
                    }
                }

                // pay rate
                float?tempPayRate = ImportUtility.GetFloatValue(oldObject.Pay_Rate);

                if (tempPayRate != null)
                {
                    equipment.PayRate = tempPayRate;
                }

                // ***********************************************
                // make, model, year, etc.
                // ***********************************************
                string tempMake = ImportUtility.CleanString(oldObject.Make);

                if (!string.IsNullOrEmpty(tempMake))
                {
                    tempMake       = ImportUtility.GetCapitalCase(tempMake);
                    equipment.Make = tempMake;
                }

                // model
                string tempModel = ImportUtility.CleanString(oldObject.Model).ToUpper();

                if (!string.IsNullOrEmpty(tempModel))
                {
                    equipment.Model = tempModel;
                }

                // year
                string tempYear = ImportUtility.CleanString(oldObject.Year);

                if (!string.IsNullOrEmpty(tempYear))
                {
                    equipment.Year = tempYear;
                }

                // size
                string tempSize = ImportUtility.CleanString(oldObject.Size);

                if (!string.IsNullOrEmpty(tempSize))
                {
                    tempSize = ImportUtility.GetCapitalCase(tempSize);

                    equipment.Size = tempSize;
                }

                // serial number
                string tempSerialNumber = ImportUtility.CleanString(oldObject.Serial_Num).ToUpper();

                if (!string.IsNullOrEmpty(tempSerialNumber))
                {
                    equipment.SerialNumber = tempSerialNumber;
                }

                // operator
                string tempOperator = ImportUtility.CleanString(oldObject.Operator);

                if (!string.IsNullOrEmpty(tempOperator))
                {
                    equipment.Operator = tempOperator ?? null;
                }

                // ***********************************************
                // add comment into the notes field
                // ***********************************************
                string tempComment = ImportUtility.CleanString(oldObject.Comment);

                if (!string.IsNullOrEmpty(tempComment))
                {
                    tempComment = ImportUtility.GetUppercaseFirst(tempComment);

                    Note note = new Note
                    {
                        Text = tempComment,
                        IsNoLongerRelevant = false
                    };

                    if (equipment.Notes == null)
                    {
                        equipment.Notes = new List <Note>();
                    }

                    equipment.Notes.Add(note);
                }

                // ***********************************************
                // add equipment to the correct area
                // ***********************************************
                if (oldObject.Area_Id != null)
                {
                    LocalArea area = dbContext.LocalAreas.AsNoTracking()
                                     .FirstOrDefault(x => x.LocalAreaNumber == oldObject.Area_Id);

                    if (area != null)
                    {
                        int tempAreaId = area.Id;
                        equipment.LocalAreaId = tempAreaId;
                    }
                }

                if (equipment.LocalAreaId == null && equipment.ArchiveCode == "N" && equipment.Status == "Approved")
                {
                    throw new DataException(string.Format("Local Area cannot be null (EquipmentIndex: {0}", maxEquipmentIndex));
                }

                // ***********************************************
                // set the equipment type
                // ***********************************************
                if (oldObject.Equip_Type_Id != null)
                {
                    // get the new id for the "District" Equipment Type
                    string tempEquipmentTypeId = oldObject.Equip_Type_Id.ToString();

                    ImportMap equipMap = dbContext.ImportMaps.AsNoTracking()
                                         .FirstOrDefault(x => x.OldTable == ImportDistrictEquipmentType.OldTable &&
                                                         x.OldKey == tempEquipmentTypeId &&
                                                         x.NewTable == ImportDistrictEquipmentType.NewTable);

                    if (equipMap != null)
                    {
                        DistrictEquipmentType distEquipType = dbContext.DistrictEquipmentTypes.FirstOrDefault(x => x.Id == equipMap.NewKey);

                        if (distEquipType != null)
                        {
                            int tempEquipmentId = distEquipType.Id;
                            equipment.DistrictEquipmentTypeId = tempEquipmentId;
                        }

                        // is this a dump truck?
                        if (!string.IsNullOrEmpty(oldObject.Reg_Dump_Trk) && oldObject.Reg_Dump_Trk == "Y")
                        {
                            // update the equipment type record -> IsDumpTruck = True
                            EquipmentType equipType = dbContext.EquipmentTypes.FirstOrDefault(x => x.Id == distEquipType.EquipmentTypeId);

                            if (equipType != null)
                            {
                                equipType.IsDumpTruck = true;
                                dbContext.EquipmentTypes.Update(equipType);
                            }
                        }
                    }
                }

                if (equipment.DistrictEquipmentTypeId == null && equipment.ArchiveCode == "N" && equipment.Status == "Approved")
                {
                    throw new DataException(string.Format("Equipment Type cannot be null (EquipmentIndex: {0}", maxEquipmentIndex));
                }

                // ***********************************************
                // set the equipment owner
                // ***********************************************
                ImportMap ownerMap = dbContext.ImportMaps.AsNoTracking()
                                     .FirstOrDefault(x => x.OldTable == ImportOwner.OldTable &&
                                                     x.OldKey == oldObject.Owner_Popt_Id.ToString());

                if (ownerMap != null)
                {
                    Models.Owner owner = dbContext.Owners.FirstOrDefault(x => x.Id == ownerMap.NewKey);

                    if (owner != null)
                    {
                        int tempOwnerId = owner.Id;
                        equipment.OwnerId = tempOwnerId;

                        // set address fields on the owner record
                        if (string.IsNullOrEmpty(owner.Address1))
                        {
                            string tempAddress1 = ImportUtility.CleanString(oldObject.Addr1);
                            tempAddress1 = ImportUtility.GetCapitalCase(tempAddress1);

                            string tempAddress2 = ImportUtility.CleanString(oldObject.Addr2);
                            tempAddress2 = ImportUtility.GetCapitalCase(tempAddress2);

                            string tempCity = ImportUtility.CleanString(oldObject.City);
                            tempCity = ImportUtility.GetCapitalCase(tempCity);

                            owner.Address1   = tempAddress1;
                            owner.Address2   = tempAddress2;
                            owner.City       = tempCity;
                            owner.PostalCode = ImportUtility.CleanString(oldObject.Postal).ToUpper();
                            owner.Province   = "BC";

                            dbContext.Owners.Update(owner);
                        }
                    }
                }

                if (equipment.OwnerId == null && equipment.ArchiveCode != "Y")
                {
                    throw new DataException(string.Format("Owner cannot be null (EquipmentIndex: {0}", maxEquipmentIndex));
                }

                // ***********************************************
                // set seniority and hours
                // ***********************************************
                float?tempSeniority = ImportUtility.GetFloatValue(oldObject.Seniority);
                equipment.Seniority = tempSeniority ?? 0.0F;

                float?tempYearsOfService = ImportUtility.GetFloatValue(oldObject.Num_Years);
                equipment.YearsOfService = tempYearsOfService ?? 0.0F;

                int?tempBlockNumber = ImportUtility.GetIntValue(oldObject.Block_Num);
                equipment.BlockNumber = tempBlockNumber ?? null;

                float?tempServiceHoursLastYear = ImportUtility.GetFloatValue(oldObject.YTD1);
                equipment.ServiceHoursLastYear = tempServiceHoursLastYear ?? 0.0F;

                float?tempServiceHoursTwoYearsAgo = ImportUtility.GetFloatValue(oldObject.YTD2);
                equipment.ServiceHoursTwoYearsAgo = tempServiceHoursTwoYearsAgo ?? 0.0F;

                float?tempServiceHoursThreeYearsAgo = ImportUtility.GetFloatValue(oldObject.YTD3);
                equipment.ServiceHoursThreeYearsAgo = tempServiceHoursThreeYearsAgo ?? 0.0F;

                // ***********************************************
                // set last verified date (default to March 31, 2018)
                // ***********************************************
                equipment.LastVerifiedDate = DateTime.Parse("2018-03-31 0:00:01");

                // ***********************************************
                // create equipment
                // ***********************************************
                equipment.AppCreateUserid        = systemId;
                equipment.AppCreateTimestamp     = DateTime.UtcNow;
                equipment.AppLastUpdateUserid    = systemId;
                equipment.AppLastUpdateTimestamp = DateTime.UtcNow;

                dbContext.Equipments.Add(equipment);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - Equipment Code: " + equipment.EquipmentCode);
                Debug.WriteLine("***Error*** - Master Equipment Index: " + maxEquipmentIndex);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
示例#27
0
 /// <summary>
 /// Setup the test.
 /// </summary>
 public EquipmentTypeModelTests()
 {
     instance = new DistrictEquipmentType();
 }
示例#28
0
        /// <summary>
        /// Copy xml item to instance (table entries)
        /// Output is ServiceArea name
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="instance"></param>
        /// <param name="systemId"></param>
        /// <param name="equipRentalRateNo"></param>
        /// <returns></returns>
        private static string CopyToInstance(DbAppContext dbContext, EquipType oldObject, ref DistrictEquipmentType instance, string systemId, float equipRentalRateNo)
        {
            string serviceAreaName = "";

            if (oldObject.Equip_Type_Id <= 0)
            {
                return(serviceAreaName);
            }

            // add the user specified in oldObject.Modified_By and oldObject.Created_By if not there in the database
            User createdBy = ImportUtility.AddUserFromString(dbContext, oldObject.Created_By, systemId);

            if (instance == null)
            {
                instance = new DistrictEquipmentType {
                    Id = oldObject.Equip_Type_Id
                };

                string typeCode = "";

                try
                {
                    typeCode = oldObject.Equip_Type_Cd.Length >= 20 ? oldObject.Equip_Type_Cd.Substring(0, 20) : oldObject.Equip_Type_Cd;
                }
                catch
                {
                    // do nothing
                }

                ServiceArea serviceArea = dbContext.ServiceAreas.FirstOrDefault(x => x.MinistryServiceAreaID == oldObject.Service_Area_Id);

                if (serviceArea != null)
                {
                    serviceAreaName = serviceArea.Name;
                    instance.DistrictEquipmentName = typeCode;

                    int      districtId = serviceArea.DistrictId ?? 0;
                    District dis        = dbContext.Districts.FirstOrDefault(x => x.RegionId == districtId);

                    if (dis != null)
                    {
                        instance.DistrictId = districtId;
                        instance.District   = dis;
                    }
                    else
                    {
                        // the District Id is not in the database
                        // (happens when the production data does not include district Other than "Lower Mainland" or all the districts)
                        return("ERROR");
                    }
                }

                instance.CreateTimestamp = DateTime.UtcNow;
                instance.CreateUserid    = createdBy.SmUserId;

                if (oldObject.Equip_Type_Cd != null)
                {
                    EquipmentType eType = dbContext.EquipmentTypes.FirstOrDefault(x => (Math.Abs((x.BlueBookSection ?? 0.1) - equipRentalRateNo)) <= ErrowAllowed);

                    if (eType == null)
                    {
                        eType = dbContext.EquipmentTypes.FirstOrDefault(x => (Math.Abs((x.BlueBookSection ?? 0.1) - DefaultBlueBoxSection)) <= ErrowAllowed);
                    }

                    if (eType != null)
                    {
                        instance.EquipmentTypeId = eType.Id;
                    }
                }
            }

            return(serviceAreaName);
        }