/// <summary> /// Create bulk owner records /// </summary> /// <param name="items"></param> /// <response code="201">Owner created</response> public virtual IActionResult OwnersBulkPostAsync(Owner[] items) { if (items == null) { return(new BadRequestResult()); } foreach (Owner item in items) { AdjustRecord(item); // determine if this is an insert or an update bool exists = _context.Owners.Any(a => a.Id == item.Id); if (exists) { _context.Update(item); } else { _context.Add(item); } } // save the changes _context.SaveChanges(); return(new NoContentResult()); }
/// <summary> /// Add user to a role /// </summary> /// <remarks>Adds a role to a user</remarks> /// <param name="id">id of User to update</param> /// <param name="item"></param> /// <response code="200">Role created for user</response> public virtual IActionResult UsersIdRolesPostAsync(int id, UserRoleViewModel item) { bool exists = _context.Users.Any(x => x.Id == id); // record not found if (!exists) { return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)))); } // check the role id bool roleExists = _context.Roles.Any(x => x.Id == item.RoleId); // record not found if (!roleExists) { return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)))); } User user = _context.Users .Include(x => x.District) .Include(x => x.UserRoles) .ThenInclude(y => y.Role) .ThenInclude(z => z.RolePermissions) .ThenInclude(z => z.Permission) .First(x => x.Id == id); if (user.UserRoles == null) { user.UserRoles = new List <UserRole>(); } // create a new UserRole based on the view model. UserRole userRole = new UserRole(); Role role = _context.Roles.First(x => x.Id == item.RoleId); userRole.Role = role; userRole.EffectiveDate = item.EffectiveDate; userRole.ExpiryDate = item.ExpiryDate; if (!user.UserRoles.Contains(userRole)) { user.UserRoles.Add(userRole); } _context.Update(user); _context.SaveChanges(); return(new StatusCodeResult(200)); }
public IActionResult like(string id) { var post = _context.Posts.Find(id); if (post == null) { return(NotFound()); } post.Likes = post.Likes + 1; //try //{ _context.Update(post); _context.SaveChanges(); //} //catch (DbUpdateConcurrencyException) //{ // if (!EmployeeExists(employee.ID)) // { // return NotFound(); // } // else // { // throw; // } //} return(new ObjectResult(post)); }
/// <summary> /// Create bulk rental request attachment records /// </summary> /// <param name="items"></param> /// <response code="201">Rental Request Attachment created</response> public virtual IActionResult RentalrequestattachmentsBulkPostAsync(RentalRequestAttachment[] items) { if (items == null) { return(new BadRequestResult()); } foreach (RentalRequestAttachment item in items) { // determine if this is an insert or an update bool exists = _context.LookupLists.Any(a => a.Id == item.Id); if (exists) { _context.Update(item); } else { _context.Add(item); } } // save the changes _context.SaveChanges(); return(new NoContentResult()); }
/// <summary> /// Create bulk area rottion list records /// </summary> /// <param name="items"></param> /// <response code="201">DumpTruck created</response> public virtual IActionResult LocalarearotationlistsBulkPostAsync(LocalAreaRotationList[] items) { if (items == null) { return(new BadRequestResult()); } foreach (LocalAreaRotationList item in items) { // determine if this is an insert or an update bool exists = _context.LocalAreaRotationLists.Any(a => a.Id == item.Id); if (exists) { _context.Update(item); } else { _context.Add(item); } } // Save the changes _context.SaveChanges(); return(new NoContentResult()); }
/// <summary> /// Create bulk dumptruck records /// </summary> /// <param name="items"></param> /// <response code="201">DumpTruck created</response> public virtual IActionResult DumptrucksBulkPostAsync(DumpTruck[] items) { if (items == null) { return(new BadRequestResult()); } foreach (DumpTruck item in items) { // determine if this is an insert or an update bool exists = _context.DumpTrucks.Any(a => a.Id == item.Id); if (exists) { _context.Update(item); } else { _context.Add(item); } } // Save the changes _context.SaveChanges(); return(new NoContentResult()); }
/// <summary> /// /// </summary> /// <remarks>Replaces an Project's Contacts</remarks> /// <param name="id">id of Project to replace Contacts for</param> /// <param name="items">Replacement Project contacts.</param> /// <response code="200">OK</response> public virtual IActionResult ProjectsIdContactsPutAsync(int id, Contact[] items) { var exists = _context.Projects.Any(a => a.Id == id); if (exists && items != null) { Project project = _context.Projects .Include(x => x.District.Region) .Include(x => x.Notes) .Include(x => x.Attachments) .Include(x => x.History) .Include(x => x.Contacts) .First(x => x.Id == id); // adjust the incoming list. for (int i = 0; i < items.Count(); i++) { Contact item = items[i]; if (item != null) { bool contact_exists = _context.Contacts.Any(x => x.Id == item.Id); if (contact_exists) { items[i] = _context.Contacts .First(x => x.Id == item.Id); } else { _context.Add(item); items[i] = item; } } } // remove contacts that are no longer attached. foreach (Contact contact in project.Contacts) { if (contact != null && !items.Any(x => x.Id == contact.Id)) { _context.Remove(contact); } } // replace Contacts. project.Contacts = items.ToList(); _context.Update(project); _context.SaveChanges(); return(new ObjectResult(items)); } else { // record not found return(new StatusCodeResult(404)); } }
/// <summary> /// Update contacts associated with a project /// </summary> /// <remarks>Replaces an Project's Contacts</remarks> /// <param name="id">id of Project to replace Contacts for</param> /// <param name="items">Replacement Project contacts.</param> /// <response code="200">OK</response> public virtual IActionResult ProjectsIdContactsPutAsync(int id, Contact[] items) { bool exists = _context.Projects.Any(a => a.Id == id); if (exists && items != null) { Project project = _context.Projects .Include(x => x.District.Region) .Include(x => x.Notes) .Include(x => x.Attachments) .Include(x => x.History) .Include(x => x.Contacts) .First(x => x.Id == id); // adjust the incoming list for (int i = 0; i < items.Count(); i++) { Contact item = items[i]; if (item != null) { bool contactExists = _context.Contacts.Any(x => x.Id == item.Id); if (contactExists) { items[i] = _context.Contacts .First(x => x.Id == item.Id); } else { _context.Add(item); items[i] = item; } } } // remove contacts that are no longer attached foreach (Contact contact in project.Contacts) { if (contact != null && items.All(x => x.Id != contact.Id)) { _context.Remove(contact); } } // replace contacts project.Contacts = items.ToList(); _context.Update(project); _context.SaveChanges(); return(new ObjectResult(new HetsResponse(items))); } // record not found return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration)))); }
/// <summary> /// /// </summary> /// <param name="id">id of Inspection to delete</param> /// <param name="isAdmin">is current user has permission of ADMIN</param> /// /// <response code="200">OK</response> /// <response code="404">Inspection not found</response> public virtual IActionResult InspectionsIdDeletePostAsync(int id, bool isAdmin) { var exists = _context.Inspections.Any(a => a.Id == id); if (exists) { var item = _context.Inspections.Include(x => x.SchoolBus).First(a => a.Id == id); // Delete Inspection has special behavior. // By design, an Inspector is only able to delete an Inspection 24 hours after it has been entered. // Also, the related Schoolbus will be updated with the value of the PreviousNextInspectionDate and PreviousNextInspectionType fields. // first check to see if we are allowed to delete. if (item.CreatedDate > DateTime.UtcNow.AddDays(-1) || isAdmin) { // update the Schoolbus record. if (item.SchoolBus != null) { int schoolbusId = item.SchoolBus.Id; bool schoolbus_exists = _context.SchoolBuss.Any(x => x.Id == schoolbusId); if (schoolbus_exists) { SchoolBus schoolbus = _context.SchoolBuss.First(x => x.Id == schoolbusId); schoolbus.NextInspectionDate = item.PreviousNextInspectionDate; schoolbus.NextInspectionTypeCode = item.PreviousNextInspectionTypeCode; _context.Update(schoolbus); } } _context.Inspections.Remove(item); // Save the changes _context.SaveChanges(); return(new ObjectResult(item)); } else { // forbidden return(new StatusCodeResult(403)); } } else { // record not found return(new StatusCodeResult(404)); } }
/// <summary> /// /// </summary> /// <param name="id">id of Inspection to delete</param> /// <response code="200">OK</response> /// <response code="404">Inspection not found</response> public virtual IActionResult InspectionsIdDeletePostAsync(int id) { // Delete Inspection has special behavior. // By design, an Inspector is only able to delete an Inspection 24 hours after it has been entered. // Admin user still can delete it any time. // Also, the related Schoolbus will be updated with the value of the PreviousNextInspectionDate and PreviousNextInspectionType fields. if (!_context.Inspections.Any(a => a.Id == id)) { return(new StatusCodeResult(404)); } var item = _context.Inspections.Include(x => x.SchoolBus).First(a => a.Id == id); if (item.CreatedDate <= DateTime.UtcNow.AddDays(-1) && !User.IsSystemAdmin()) { return(new StatusCodeResult(403)); } // update the Schoolbus record. if (item.SchoolBus != null) { int schoolbusId = item.SchoolBus.Id; bool schoolbus_exists = _context.SchoolBuss.Any(x => x.Id == schoolbusId); if (schoolbus_exists) { SchoolBus schoolbus = _context.SchoolBuss.First(x => x.Id == schoolbusId); schoolbus.NextInspectionDate = item.PreviousNextInspectionDate; schoolbus.NextInspectionTypeCode = item.PreviousNextInspectionTypeCode; _context.Update(schoolbus); } } _context.Inspections.Remove(item); // Save the changes _context.SaveChanges(); return(new ObjectResult(item)); }
/// <summary> /// /// </summary> /// <remarks>Updates the active set of groups for a user</remarks> /// <param name="id">id of User to update</param> /// <param name="items"></param> /// <response code="200">OK</response> /// <response code="404">User not found</response> public virtual IActionResult UsersIdGroupsPutAsync(int id, GroupMembershipViewModel[] items) { bool exists = _context.Users.Any(x => x.Id == id); if (exists) { User user = _context.Users .Include(x => x.District) .Include(x => x.GroupMemberships) .ThenInclude(y => y.Group) .Include(x => x.UserRoles) .ThenInclude(y => y.Role) .ThenInclude(z => z.RolePermissions) .ThenInclude(z => z.Permission) .First(x => x.Id == id); if (user.GroupMemberships == null) { user.GroupMemberships = new List <GroupMembership>(); } else { // existing data, clear it. foreach (var groupMembership in user.GroupMemberships) { if (_context.GroupMemberships.Any(x => x.Id == groupMembership.Id)) { GroupMembership delete = _context.GroupMemberships.First(x => x.Id == groupMembership.Id); _context.Remove(delete); } } user.GroupMemberships.Clear(); } foreach (var item in items) { if (item != null) { // check the role id bool group_exists = _context.Groups.Any(x => x.Id == item.GroupId); if (group_exists) { // create a new UserRole based on the view model. GroupMembership groupMembership = new GroupMembership(); Group group = _context.Groups.First(x => x.Id == item.GroupId); groupMembership.Group = group; groupMembership.User = user; _context.Add(groupMembership); if (!user.GroupMemberships.Contains(groupMembership)) { user.GroupMemberships.Add(groupMembership); } } } } _context.Update(user); _context.SaveChanges(); return(new StatusCodeResult(201)); } else { return(new StatusCodeResult(400)); } }
public virtual IActionResult GetCCW([FromQuery] string regi, [FromQuery] string plate, [FromQuery] string vin) { // check we have the right headers. if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(guid) || string.IsNullOrEmpty(directory)) { return(new UnauthorizedResult()); } // Check for the following data: // 1. registration // 2. plate // 3. decal VehicleDescription vehicle = null; if (regi != null) { // format the regi. try { int registration = int.Parse(regi); // zero padded, 8 digits regi = registration.ToString("D8"); } catch (Exception e) { _logger.LogInformation("Exception occured parsing registration number " + regi); } try { vehicle = _service.GetBCVehicleForRegistrationNumber(regi, userId, guid, directory); } catch (Exception e) { vehicle = null; } } if (vehicle == null && plate != null) // check the plate. { try { vehicle = _service.GetBCVehicleForLicensePlateNumber(plate, userId, guid, directory); } catch (Exception e) { vehicle = null; } } if (vehicle == null && vin != null) // check the vin. { try { vehicle = _service.GetBCVehicleForSerialNumber(vin, userId, guid, directory); } catch (Exception e) { vehicle = null; } } if (vehicle == null) { return(new StatusCodeResult(404)); // Can't find the vehicle. } else { string icbcRegistrationNumber = vehicle.registrationNumber; CCWData ccwdata = null; bool existing = false; if (_context.CCWDatas.Any(x => x.ICBCRegistrationNumber == icbcRegistrationNumber)) { ccwdata = _context.CCWDatas.First(x => x.ICBCRegistrationNumber == icbcRegistrationNumber); existing = true; _logger.LogInformation("Found record for Registration # " + ccwdata.ICBCRegistrationNumber); } else { _logger.LogInformation("Creating new record"); ccwdata = new CCWData(); } // update the ccw record. ccwdata.ICBCBody = vehicle.bodyCode; ccwdata.ICBCColour = vehicle.colour; ccwdata.ICBCCVIPDecal = vehicle.inspectionDecalNumber; ccwdata.ICBCCVIPExpiry = vehicle.inspectionExpiryDate; ccwdata.ICBCFleetUnitNo = SanitizeInt(vehicle.fleetUnitNumber); ccwdata.ICBCFuel = vehicle.fuelTypeDescription; ccwdata.ICBCGrossVehicleWeight = SanitizeInt(vehicle.grossVehicleWeight); ccwdata.ICBCMake = vehicle.make; ccwdata.ICBCModel = vehicle.model; ccwdata.ICBCGrossVehicleWeight = SanitizeInt(vehicle.grossVehicleWeight); ccwdata.ICBCModelYear = SanitizeInt(vehicle.modelYear); ccwdata.ICBCNetWt = SanitizeInt(vehicle.netWeight); ccwdata.ICBCNotesAndOrders = vehicle.cvipDataFromLastInspection; ccwdata.ICBCOrderedOn = vehicle.firstOpenOrderDate; ccwdata.ICBCRateClass = vehicle.rateClass; ccwdata.ICBCRebuiltStatus = vehicle.statusCode; ccwdata.ICBCRegistrationNumber = vehicle.registrationNumber; ccwdata.ICBCRegOwnerAddr1 = vehicle.owner.mailingAddress1; ccwdata.ICBCRegOwnerAddr2 = vehicle.owner.mailingAddress2; ccwdata.ICBCRegOwnerCity = vehicle.owner.mailingAddress3; ccwdata.ICBCRegOwnerName = vehicle.owner.name1; ccwdata.ICBCRegOwnerPODL = vehicle.principalOperatorDlNum; ccwdata.ICBCRegOwnerPostalCode = vehicle.owner.postalCode; ccwdata.ICBCRegOwnerProv = vehicle.owner.mailingAddress4; ccwdata.ICBCRegOwnerRODL = vehicle.owner.driverLicenseNumber; ccwdata.ICBCSeatingCapacity = SanitizeInt(vehicle.seatingCapacity); ccwdata.ICBCVehicleType = vehicle.vehicleType + " - " + vehicle.vehicleTypeDescription; ccwdata.ICBCVehicleIdentificationNumber = vehicle.serialNumber; ccwdata.NSCPlateDecal = vehicle.decalNumber; ccwdata.NSCPolicyEffectiveDate = vehicle.policyStartDate; ccwdata.NSCPolicyExpiryDate = vehicle.policyExpiryDate; ccwdata.NSCPolicyStatus = vehicle.policyStatus + " - " + vehicle.policyStatusDescription; // policyAquiredCurrentStatusDate is the preferred field, however it is often null. if (vehicle.policyAcquiredCurrentStatusDate != null) { ccwdata.NSCPolicyStatusDate = vehicle.policyAcquiredCurrentStatusDate; } else if (vehicle.policyTerminationDate != null) { ccwdata.NSCPolicyStatusDate = vehicle.policyTerminationDate; } else if (vehicle.policyReplacedOnDate != null) { ccwdata.NSCPolicyStatusDate = vehicle.policyReplacedOnDate; } else if (vehicle.policyStartDate != null) { ccwdata.NSCPolicyStatusDate = vehicle.policyStartDate; } if (vehicle.owner != null) { ccwdata.ICBCRegOwnerRODL = vehicle.owner.driverLicenseNumber; } ccwdata.ICBCLicencePlateNumber = vehicle.policyNumber; // these fields are the same. ccwdata.NSCPolicyNumber = vehicle.policyNumber; ccwdata.NSCClientNum = vehicle.nscNumber; ccwdata.DateFetched = DateTime.UtcNow; // get the nsc client organization data. bool foundNSCData = false; if (!string.IsNullOrEmpty(ccwdata.NSCPolicyNumber)) { string organizationNameCode = "LE"; try { ClientOrganization clientOrganization = _service.GetCurrentClientOrganization(ccwdata.NSCClientNum, organizationNameCode, userId, guid, directory); foundNSCData = true; ccwdata.NSCCarrierConditions = clientOrganization.nscInformation.carrierStatus; ccwdata.NSCCarrierName = clientOrganization.displayName; ccwdata.NSCCarrierSafetyRating = clientOrganization.nscInformation.safetyRating; } catch (AggregateException ae) { _logger.LogInformation("Aggregate Exception occured during GetCurrentClientOrganization"); ae.Handle((x) => { if (x is FaultException <CVSECommonException> ) // From the web service. { _logger.LogDebug("CVSECommonException:"); FaultException <CVSECommonException> fault = (FaultException <CVSECommonException>)x; _logger.LogDebug("errorId: {0}", fault.Detail.errorId); _logger.LogDebug("errorMessage: {0}", fault.Detail.errorMessage); _logger.LogDebug("systemError: {0}", fault.Detail.systemError); return(true); } return(true); // ignore other exceptions }); } catch (Exception e) { _logger.LogInformation("Unknown Error retrieving NSC data."); } // now try the individual service if there was no match. if (foundNSCData == false) { try { ClientIndividual clientIndividual = _service.GetCurrentClientIndividual(ccwdata.NSCClientNum, organizationNameCode, userId, guid, directory); foundNSCData = true; ccwdata.NSCCarrierConditions = clientIndividual.nscInformation.carrierStatus; ccwdata.NSCCarrierName = clientIndividual.displayName; ccwdata.NSCCarrierSafetyRating = clientIndividual.nscInformation.safetyRating; } catch (AggregateException ae) { _logger.LogInformation("Aggregate Exception occured during GetCurrentClientIndividual"); ae.Handle((x) => { if (x is FaultException <CVSECommonException> ) // From the web service. { _logger.LogDebug("CVSECommonException:"); FaultException <CVSECommonException> fault = (FaultException <CVSECommonException>)x; _logger.LogDebug("errorId: {0}", fault.Detail.errorId); _logger.LogDebug("errorMessage: {0}", fault.Detail.errorMessage); _logger.LogDebug("systemError: {0}", fault.Detail.systemError); return(true); } return(true); // ignore other exceptions }); } catch (Exception e) { _logger.LogInformation("Unknown Error retrieving Individual NSC data."); } } } if (ccwdata.Id > 0) { _context.Update(ccwdata); } else { _context.Add(ccwdata); } _context.SaveChanges(); return(new ObjectResult(ccwdata)); } }