Beispiel #1
0
 private void AdjustRecord(EquipmentAttachment item)
 {
     if (item != null && item.Equipment != null)
     {
         item.Equipment = _context.Equipments.FirstOrDefault(a => a.Id == item.Equipment.Id);
     }
 }
Beispiel #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="item"></param>
        /// <response code="201">Equipment Attachment created</response>
        public virtual IActionResult EquipmentAttachmentsPostAsync(EquipmentAttachment item)
        {
            if (item != null)
            {
                AdjustRecord(item);

                bool exists = _context.Equipments.Any(a => a.Id == item.Id);
                if (exists)
                {
                    _context.EquipmentAttachments.Update(item);
                }
                else
                {
                    // record not found
                    _context.EquipmentAttachments.Add(item);
                }
                // Save the changes
                _context.SaveChanges();
                int item_id = item.Id;
                var result  = _context.EquipmentAttachments
                              .Include(x => x.Equipment)
                              .First(a => a.Id == item_id);

                return(new ObjectResult(result));
            }
            else
            {
                // record not found
                return(new StatusCodeResult(404));
            }
        }
Beispiel #3
0
        /// <summary>
        /// Create equipment attachments
        /// </summary>
        /// <param name="item"></param>
        /// <response code="200">Equipment Attachment created</response>
        public virtual IActionResult EquipmentAttachmentsPostAsync(EquipmentAttachment item)
        {
            if (item != null)
            {
                AdjustRecord(item);

                bool exists = _context.Equipments.Any(a => a.Id == item.Id);

                if (exists)
                {
                    _context.EquipmentAttachments.Update(item);
                }
                else
                {
                    // record not found
                    _context.EquipmentAttachments.Add(item);
                }

                // Save the changes
                _context.SaveChanges();

                int itemId = item.Id;

                EquipmentAttachment result = _context.EquipmentAttachments
                                             .Include(x => x.Equipment)
                                             .First(a => a.Id == itemId);

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

            // record not found
            return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
        }
        public async Task <EquipmentAttachmentViewModel> AddEquipmentAttachmentAsync(User user, AddEquipmentAttachmentFormModel equipmentAttachmentForm)
        {
            try
            {
                Equipment equipment = null;
                equipment = _context.Equipments.FirstOrDefault(c => c.Id == equipmentAttachmentForm.EquipmentId);
                if (equipment != null)
                {
                    var isDuplicateEquipmentAtt = _context.EquipmentAttachments.Any(c => c.EquipmentId == equipmentAttachmentForm.EquipmentId && c.EquipmentAttachmentName == equipmentAttachmentForm.EquipmentAttachmentName && c.EquipmentAttachmentType == equipmentAttachmentForm.EquipmentAttachmentType);
                    if (!isDuplicateEquipmentAtt)
                    {
                        var equipmentAtt = new EquipmentAttachment()
                        {
                            Description             = equipmentAttachmentForm.Description,
                            EquipmentAttachmentName = equipmentAttachmentForm.EquipmentAttachmentName.ToLower(),
                            EquipmentAttachmentType = equipmentAttachmentForm.EquipmentAttachmentType,
                            EquipmentId             = equipmentAttachmentForm.EquipmentId,
                        };
                        if (equipmentAttachmentForm.UploadFileId != null)
                        {
                            var fileAddress = _context.FileAddresses.Find(equipmentAttachmentForm.UploadFileId);

                            if (fileAddress is null)
                            {
                                throw new ExperienceManagementGlobalException(IssueServiceErrors.NotExistFileAddressError);
                            }
                            equipmentAtt.FileId   = fileAddress.FileId;
                            equipmentAtt.FileSize = fileAddress.FileSize;
                            equipmentAtt.FileType = fileAddress.FileType;
                        }
                        await _context.EquipmentAttachments.AddAsync(equipmentAtt);

                        await _context.SaveChangesAsync();

                        return(new EquipmentAttachmentViewModel()
                        {
                            EquipmentAttachmentId = equipmentAtt.Id,
                            CreationDate = equipmentAtt.CreationDate,
                            Description = equipmentAtt.Description,
                            EquipmentAttachmentName = equipmentAtt.EquipmentAttachmentName,
                            EquipmentId = equipmentAtt.EquipmentId,
                            EquipmentAttachmentType = equipmentAtt.EquipmentAttachmentType,
                            FileId = equipmentAtt.FileId,
                            FileSize = equipmentAtt.FileSize,
                            FileType = equipmentAtt.FileType
                        });
                    }
                    throw new ExperienceManagementGlobalException(EquipmentServiceErrors.AddDuplicateEquipmentAttachmentError);
                }
                throw new ExperienceManagementGlobalException(EquipmentServiceErrors.EditEquipmentNotExistError);
            }
            catch (Exception ex)
            {
                throw new ExperienceManagementGlobalException(EquipmentServiceErrors.AddEquipmentAttachmentError, ex);
            }
        }
Beispiel #5
0
 private void AdjustRecord(EquipmentAttachment item)
 {
     if (item != null)
     {
         // Adjust the record to allow it to be updated / inserted
         if (item.Equipment != null)
         {
             item.Equipment = _context.Equipments.FirstOrDefault(a => a.Id == item.Equipment.Id);
         }
     }
 }
 public void ShowObject(object keyValue)
 {
     if (keyValue == null)
     {
         _equipmentAttachment = new EquipmentAttachment()
         {
             EquipmentId = Equipment.EquipmentId
         };
         attachmentBindingSource.DataSource = _equipmentAttachment;
         _newMode = true;
     }
 }
Beispiel #7
0
        private void gridControl3_Click(object sender, EventArgs e)
        {
            if (attachmentGridView.SelectedRowsCount > 0)
            {
                var selected = (EquipmentAttachment)attachmentGridView.GetRow((int)attachmentGridView.GetSelectedRows().GetValue(0));
                if (null != selected)
                {
                    _selectedAttachment         = selected;
                    btnRead.Enabled             = true;
                    btnDeleteAttachment.Enabled = true;
                }
            }

            AuthorizeForm();
        }
        /// <summary>
        /// Get equipment attachment by id
        /// </summary>
        /// <param name="id">id of Equipment to fetch</param>
        /// <response code="200">OK</response>
        /// <response code="404">Equipment not found</response>
        public virtual IActionResult EquipmentAttachmentsIdGetAsync(int id)
        {
            bool exists = _context.EquipmentAttachments.Any(a => a.Id == id);

            if (exists)
            {
                EquipmentAttachment result = _context.EquipmentAttachments
                                             .Include(x => x.Equipment)
                                             .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))));
        }
        /// <summary>
        /// Map data
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="instance"></param>
        /// <param name="equips"></param>
        /// <param name="systemId"></param>
        private static void CopyToInstance(DbAppContext dbContext, EquipAttach oldObject, ref EquipmentAttachment instance,
                                           List <Equipment> equips, 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 createdBy = ImportUtility.AddUserFromString(dbContext, oldObject.Created_By, systemId);

            if (instance == null)
            {
                instance = new EquipmentAttachment();
                int equipId = oldObject.Equip_Id ?? -1;

                Equipment equipment = equips.FirstOrDefault(x => x.Id == equipId);
                if (equipment != null)
                {
                    instance.Equipment   = equipment;
                    instance.EquipmentId = equipment.Id;
                }

                instance.Description = oldObject.Attach_Desc == null ? "" : oldObject.Attach_Desc;
                instance.TypeName    = (oldObject.Attach_Seq_Num ?? -1).ToString();

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

                instance.CreateUserid = createdBy.SmUserId;

                dbContext.EquipmentAttachments.Add(instance);
            }
            else
            {
                instance = dbContext.EquipmentAttachments
                           .First(x => x.EquipmentId == oldObject.Equip_Id && x.TypeName == (oldObject.Attach_Seq_Num ?? -2).ToString());
                instance.LastUpdateUserid    = systemId;
                instance.LastUpdateTimestamp = DateTime.UtcNow;
                dbContext.EquipmentAttachments.Update(instance);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Delete equipment attachment
        /// </summary>
        /// <param name="id">id of Equipment to delete</param>
        /// <response code="200">OK</response>
        public virtual IActionResult EquipmentAttachmentsIdDeletePostAsync(int id)
        {
            bool exists = _context.EquipmentAttachments.Any(a => a.Id == id);

            if (exists)
            {
                EquipmentAttachment item = _context.EquipmentAttachments.First(a => a.Id == id);

                _context.EquipmentAttachments.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))));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="id">id of EquipmentAttachment to fetch</param>
        /// <param name="item"></param>
        /// <response code="200">OK</response>
        /// <response code="404">EquipmentAttachment not found</response>
        public virtual IActionResult EquipmentAttachmentsIdPutAsync(int id, EquipmentAttachment item)
        {
            var result = "";

            return(new ObjectResult(result));
        }
Beispiel #12
0
        /// <summary>
        /// Import Equipment Attachments
        /// </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 maxEquipAttachIndex = 0;

            if (dbContext.EquipmentAttachments.Any())
            {
                maxEquipAttachIndex = dbContext.EquipmentAttachments.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(EquipAttach[]), new XmlRootAttribute(rootAttr));
                MemoryStream  memoryStream = ImportUtility.MemoryStreamGenerator(XmlFileName, OldTable, fileLocation, rootAttr);
                EquipAttach[] legacyItems  = (EquipAttach[])ser.Deserialize(memoryStream);

                int ii = startPoint;

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

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

                foreach (EquipAttach item in legacyItems.WithProgress(progress))
                {
                    // see if we have this one already. We used old combine because item.Equip_Id is not unique
                    string    oldKeyCombined = (item.Equip_Id ?? 0 * 100 + item.Attach_Seq_Num ?? 0).ToString();
                    ImportMap importMap      = dbContext.ImportMaps.FirstOrDefault(x => x.OldTable == OldTable && x.OldKey == oldKeyCombined);

                    // new entry
                    if (importMap == null && item.Equip_Id > 0)
                    {
                        EquipmentAttachment instance = null;
                        CopyToInstance(dbContext, item, ref instance, systemId, ref maxEquipAttachIndex);
                        ImportUtility.AddImportMap(dbContext, OldTable, oldKeyCombined, NewTable, instance.Id);
                    }

                    // save change to database periodically to avoid frequent writing to the database
                    if (++ii % 1000 == 0)
                    {
                        try
                        {
                            ImportUtility.AddImportMapForProgress(dbContext, OldTableProgress, ii.ToString(), BcBidImport.SigId, NewTable);
                            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 (EquipmentAttachmentIndex: {0}): {1}", maxEquipAttachIndex, e.Message);
                    performContext.WriteLine(temp);
                    throw new DataException(temp);
                }
            }
            catch (Exception e)
            {
                performContext.WriteLine("*** ERROR ***");
                performContext.WriteLine(e.ToString());
                throw;
            }
        }
 public virtual IActionResult EquipmentAttachmentsIdPut([FromRoute] int id, [FromBody] EquipmentAttachment item)
 {
     return(_service.EquipmentAttachmentsIdPutAsync(id, item));
 }
 public virtual IActionResult EquipmentAttachmentsPost([FromBody] EquipmentAttachment item)
 {
     return(_service.EquipmentAttachmentsPostAsync(item));
 }
 /// <summary>
 /// Setup the test.
 /// </summary>
 public EquipmentAttachmentModelTests()
 {
     instance = new EquipmentAttachment();
 }
        /// <summary>
        /// Import Equipment Attachments
        /// </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(EquipAttach[]), new XmlRootAttribute(rootAttr));
                MemoryStream  memoryStream = ImportUtility.MemoryStreamGenerator(XmlFileName, OldTable, fileLocation, rootAttr);
                EquipAttach[] legacyItems  = (EquipAttach[])ser.Deserialize(memoryStream);

                // use this list to save a trip to query database in each iteration
                List <Equipment> equips = dbContext.Equipments
                                          .Include(x => x.DumpTruck)
                                          .Include(x => x.DistrictEquipmentType)
                                          .ToList();

                int ii = startPoint;

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

                foreach (EquipAttach item in legacyItems.WithProgress(progress))
                {
                    // see if we have this one already. We used old combine because item.Equip_Id is not unique
                    string    oldKeyCombined = (item.Equip_Id ?? 0 * 100 + item.Attach_Seq_Num ?? 0).ToString();
                    ImportMap importMap      = dbContext.ImportMaps.FirstOrDefault(x => x.OldTable == OldTable && x.OldKey == oldKeyCombined);

                    // new entry
                    if (importMap == null)
                    {
                        if (item.Equip_Id > 0)
                        {
                            EquipmentAttachment instance = null;
                            CopyToInstance(dbContext, item, ref instance, equips, systemId);
                            ImportUtility.AddImportMap(dbContext, OldTable, oldKeyCombined, NewTable, instance.Id);
                        }
                    }
                    else // update
                    {
                        EquipmentAttachment instance = dbContext.EquipmentAttachments.FirstOrDefault(x => x.Id == importMap.NewKey);

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

                            // update the import map.
                            importMap.NewKey = instance.Id;
                            dbContext.ImportMaps.Update(importMap);
                        }
                        else // ordinary update.
                        {
                            CopyToInstance(dbContext, item, ref instance, equips, 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 % 1000 == 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());
            }
        }
        /// <summary>
        /// Integration test for EquipmentAttachments
        /// </summary>
        public async void TestEquipmentAttachmentsBasic()
        {
            string initialName = "InitialName";
            string changedName = "ChangedName";
            // first test the POST.
            var request = new HttpRequestMessage(HttpMethod.Post, "/api/equipmentAttachments");

            // create a new object.
            EquipmentAttachment equipmentattachment = new EquipmentAttachment();

            equipmentattachment.Description = initialName;
            string jsonString = equipmentattachment.ToJson();

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

            var response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

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

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

            // change the name
            equipmentattachment.Description = changedName;

            // now do an update.
            request         = new HttpRequestMessage(HttpMethod.Put, "/api/equipmentAttachments/" + id);
            request.Content = new StringContent(equipmentattachment.ToJson(), Encoding.UTF8, "application/json");
            response        = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

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

            response.EnsureSuccessStatusCode();

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

            equipmentattachment = JsonConvert.DeserializeObject <EquipmentAttachment>(jsonString);

            // verify the change went through.
            Assert.Equal(equipmentattachment.Description, changedName);

            // do a delete.
            request  = new HttpRequestMessage(HttpMethod.Post, "/api/equipmentAttachments/" + 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/equipmentAttachments/" + id);
            response = await _client.SendAsync(request);

            Assert.Equal(response.StatusCode, HttpStatusCode.NotFound);
        }
Beispiel #18
0
        /// <summary>
        /// Map data
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="equipAttach"></param>
        /// <param name="systemId"></param>
        /// <param name="maxEquipAttachIndex"></param>
        private static void CopyToInstance(DbAppContext dbContext, EquipAttach oldObject, ref EquipmentAttachment equipAttach,
                                           string systemId, ref int maxEquipAttachIndex)
        {
            try
            {
                if (oldObject.Equip_Id <= 0)
                {
                    return;
                }

                equipAttach = new EquipmentAttachment {
                    Id = ++maxEquipAttachIndex
                };

                // ************************************************
                // get the imported equipment record map
                // ************************************************
                string tempId = oldObject.Equip_Id.ToString();

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

                if (map == null)
                {
                    return; // ignore and move to the next record
                }

                // ************************************************
                // get the equipment record
                // ************************************************
                Equipment equipment = dbContext.Equipments.AsNoTracking()
                                      .FirstOrDefault(x => x.Id == map.NewKey);

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

                // ************************************************
                // set the equipment attachment attributes
                // ************************************************
                int tempEquipmentId = equipment.Id;
                equipAttach.EquipmentId = tempEquipmentId;

                string tempDescription = ImportUtility.CleanString(oldObject.Attach_Desc);

                if (string.IsNullOrEmpty(tempDescription))
                {
                    return;                                        // don't add blank attachments
                }
                tempDescription         = ImportUtility.GetCapitalCase(tempDescription);
                equipAttach.Description = tempDescription;

                if (oldObject.Attach_Seq_Num != null)
                {
                    string tempSequence = oldObject.Attach_Seq_Num.ToString();
                    equipAttach.TypeName = tempSequence;
                }

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

                dbContext.EquipmentAttachments.Add(equipAttach);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - Equipment Attachment: " + equipAttach.Description);
                Debug.WriteLine("***Error*** - Master Equipment Attachment Index: " + maxEquipAttachIndex);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }