/// <summary> /// Hangfire job to populate CCW data. Only used for a deploy to PROD with a new database. /// </summary> /// <param name="connectionString"></param> /// <param name="Configuration"></param> public static void PopulateCCWJob(string connectionString, string cCW_userId, string cCW_guid, string cCW_directory, string ccwHost) { // sanity check if (connectionString != null && cCW_userId != null && cCW_guid != null && cCW_directory != null && ccwHost != null) { DbContextOptionsBuilder <DbAppContext> options = new DbContextOptionsBuilder <DbAppContext>(); options.UseNpgsql(connectionString); DbAppContext context = new DbAppContext(null, options.Options); // make a database connection and see if there are any records that are missing the CCW link. // we restrict the query to records not updated in the last 6 hours so that the batch process does not repeatedly try a failed record. var data = context.SchoolBuss .FirstOrDefault(x => x.CCWDataId == null && x.LastUpdateTimestamp < DateTime.UtcNow.AddHours(-1)); if (data != null) { // get the data for the request from the result of the database query. string regi = data.ICBCRegistrationNumber; string vin = data.VehicleIdentificationNumber; string plate = data.LicencePlateNumber; // Fetch the record. CCWData cCWData = FetchCCW(ccwHost, regi, vin, plate, cCW_userId, cCW_guid, cCW_directory); data.CCWData = cCWData; // ensure that the record is touched in the database data.LastUpdateTimestamp = DateTime.UtcNow; // save changes. context.SchoolBuss.Update(data); context.SaveChanges(); } } }
/// <summary> /// fetches data from the ICBC CCW system, and constructs a CCWData object from that. Note that it does not perform the insert of that data into the database, only provides JSON data suitable for insertion. If a CCWData record exists in the schoolbus database then the id field will match that record, however all other data will be from the ICBC CCW system. /// </summary> /// <param name="regi">Registration Number (also known as Serial)</param> /// <param name="vin">Vehicle Identification Number</param> /// <param name="plate">License Plate String</param> /// <response code="200">OK</response> /// <response code="404">Vehicle not found in CCW system</response> public virtual IActionResult CcwdataFetchGetAsync(string regi, string vin, string plate) { string cCW_userId = null; string cCW_guid = null; string cCW_directory = null; if (Request.Headers.ContainsKey("SM_UNIVERSALID")) { cCW_userId = Request.Headers["SM_UNIVERSALID"]; } if (Request.Headers.ContainsKey("SMGOV_USERGUID")) { cCW_guid = Request.Headers["SMGOV_USERGUID"]; } if (Request.Headers.ContainsKey("SM_AUTHDIRNAME")) { cCW_directory = Request.Headers["SM_AUTHDIRNAME"]; } string ccwHost = Configuration["CCW_SERVICE_NAME"]; CCWData result = CCWTools.FetchCCW(regi, vin, plate, cCW_userId, cCW_guid, cCW_directory, ccwHost); // return the result, or 404 if no result was found. if (result != null) { return(new ObjectResult(result)); } else { return(new StatusCodeResult(404)); } }
/// <summary> /// /// </summary> /// <remarks>Returns CCWData for a particular Schoolbus</remarks> /// <param name="id">id of SchoolBus to fetch CCWData for</param> /// <response code="200">OK</response> public virtual IActionResult SchoolbusesIdCcwdataGetAsync(int id) { // validate the bus id bool exists = _context.SchoolBuss.Any(a => a.Id == id); if (exists) { SchoolBus schoolbus = _context.SchoolBuss.Where(a => a.Id == id).First(); string regi = schoolbus.ICBCRegistrationNumber; // get CCW data for this bus. // could be none. // validate the bus id bool ccw_exists = _context.CCWDatas.Any(a => a.ICBCRegistrationNumber == regi); if (ccw_exists) { var result = _context.CCWDatas.Where(a => a.ICBCRegistrationNumber == regi).First(); return(new ObjectResult(result)); } else { // record not found CCWData[] nodata = new CCWData[0]; return(new ObjectResult(nodata)); } } else { // record not found return(new StatusCodeResult(404)); } }
public async Task PopulateCCWJob() { await Task.CompletedTask; var enableCcwCreate = (_configuration["ENABLE_HANGFIRE_CREATE"] ?? "N").ToUpperInvariant() == "Y"; if (!enableCcwCreate) { return; } // sanity check if (_userId != null && _userGuid != null && _userDir != null) { // make a database connection and see if there are any records that are missing the CCW link. // we restrict the query to records not updated in the last 6 hours so that the batch process does not repeatedly try a failed record. var data = _context.SchoolBuss .FirstOrDefault(x => x.CCWDataId == null && x.LastUpdateTimestamp < DateTime.UtcNow.AddHours(-6)); if (data == null) { return; } data.LastUpdateTimestamp = DateTime.UtcNow; // get the data for the request from the result of the database query. string regi = data.ICBCRegistrationNumber; string vin = data.VehicleIdentificationNumber; string plate = data.LicencePlateNumber; // Fetch the record. CCWData cCWData = _ccwDataService.GetCCW(regi, plate, vin, _userId, _userGuid, _userDir); if (cCWData == null) { _logger.LogInformation($"[Hangfire] PopulateCCWJob - No data from CCW for regi: {regi} vin: {vin}, plate: {plate}."); _context.SaveChanges(); _logger.LogInformation($"[Hangfire] PopulateCCWJob - Updated bus record timestamp with the ID {data.Id}."); return; } data.CCWData = cCWData; // ensure that the record is touched in the database _context.SaveChanges(); _logger.LogInformation($"[Hangfire] PopulateCCWJob - Saved bus record with the ID {data.Id}."); } }
/// <summary> /// fetches data from the ICBC CCW system, and constructs a CCWData object from that. Note that it does not perform the insert of that data into the database, only provides JSON data suitable for insertion. If a CCWData record exists in the schoolbus database then the id field will match that record, however all other data will be from the ICBC CCW system. /// </summary> /// <param name="regi">Registration Number (also known as Serial)</param> /// <param name="vin">Vehicle Identification Number</param> /// <param name="plate">License Plate String</param> /// <response code="200">OK</response> /// <response code="404">Vehicle not found in CCW system</response> public virtual IActionResult CcwdataFetchGetAsync(string regi, string vin, string plate) { var(userId, guid, directory) = User.GetUserInfo(); CCWData result = GetCCW(regi, plate, vin, userId, guid, directory); if (result != null) { return(new ObjectResult(result)); } else { return(new StatusCodeResult(404)); } }
/// <summary> /// Hangfire job to refresh existing data. /// </summary> /// <param name="connectionString"></param> /// <param name="Configuration"></param> public static void UpdateCCWJob(string connectionString, string cCW_userId, string cCW_guid, string cCW_directory, string ccwHost) { // sanity check if (connectionString != null && cCW_userId != null && cCW_guid != null && cCW_directory != null && ccwHost != null) { // make a database connection and see if there are any records that need to be updated. DbContextOptionsBuilder <DbAppContext> options = new DbContextOptionsBuilder <DbAppContext>(); options.UseNpgsql(connectionString); DbAppContext context = new DbAppContext(null, options.Options); // first get a few metrics. we only want to update a max of 1% the database per day. int databaseTotal = context.CCWDatas.Count(); int dailyTotal = context.CCWDatas .Where(x => x.LastUpdateTimestamp < DateTime.UtcNow.AddDays(-1)) .Select(x => x) .Count(); if (databaseTotal > 0 && dailyTotal < databaseTotal / 100) { // make a database connection and see if there are any records that are missing the CCW link. var data = context.CCWDatas .OrderBy(x => x.LastUpdateTimestamp) .FirstOrDefault(x => x.LastUpdateTimestamp < DateTime.UtcNow.AddDays(-1)); if (data != null) { // get the data for the request from the result of the database query. string regi = data.ICBCRegistrationNumber; string vin = data.ICBCVehicleIdentificationNumber; // plate is excluded from the batch update because it can be shared. string plate = null; // Fetch the record. CCWData cCWData = FetchCCW(regi, vin, plate, cCW_userId, cCW_guid, cCW_directory, ccwHost); if (cCWData == null) // fetch did not work, but we don't want it to fire again, so update the timestamp. { // ensure that the record is touched in the database data.LastUpdateTimestamp = DateTime.UtcNow; context.CCWDatas.Update(data); context.SaveChanges(); } } } } }
/// <summary> /// /// </summary> /// <param name="id">id of CCWData to fetch</param> /// <param name="item"></param> /// <response code="200">OK</response> /// <response code="404">CCWData not found</response> public virtual IActionResult CcwdataIdPutAsync(int id, CCWData item) { var exists = _context.CCWDatas.Any(a => a.Id == id); if (exists && id == item.Id) { _context.CCWDatas.Update(item); // Save the changes _context.SaveChanges(); return(new ObjectResult(item)); } else { // record not found return(new StatusCodeResult(404)); } }
public virtual IActionResult CcwdataPost([FromBody] CCWData item) { return(this._service.CcwdataPostAsync(item)); }
public virtual IActionResult CcwdataIdPut([FromRoute] int id, [FromBody] CCWData item) { return(this._service.CcwdataIdPutAsync(id, item)); }
/// <summary> /// /// </summary> /// <param name="item"></param> /// <response code="201">CCWData created</response> public virtual IActionResult CcwdataPostAsync(CCWData item) { _context.CCWDatas.Add(item); _context.SaveChanges(); return(new ObjectResult(item)); }
public async Task UpdateCCWJob() { await Task.CompletedTask; var enableCcwUpdate = (_configuration["ENABLE_HANGFIRE_UPDATE"] ?? "N").ToUpperInvariant() == "Y"; if (!enableCcwUpdate) { return; } // sanity check if (_userId != null && _userGuid != null && _userDir != null) { int maxUpdateCount = _context.CCWDatas .Count(x => x.LastUpdateTimestamp > DateTime.UtcNow.AddDays(-1)); if (maxUpdateCount > 500) { _logger.LogInformation($"[Hangfire] UpdateCCWJob - Today's max update count({maxUpdateCount}) reached."); return; } // make a database connection and see if there are any records that are missing the CCW link. var data = _context.CCWDatas .OrderBy(x => x.LastUpdateTimestamp) .FirstOrDefault(x => x.LastUpdateTimestamp < DateTime.UtcNow.AddDays(-1)); if (data == null) { return; } // get the data for the request from the result of the database query. string regi = data.ICBCRegistrationNumber; string vin = data.ICBCVehicleIdentificationNumber; // plate is excluded from the batch update because it can be shared. string plate = null; // Fetch the record. this FetchCCW actually updates CCWData too. Refer to CCW microservice CCWData cCWData = _ccwDataService.GetCCW(regi, plate, vin, _userId, _userGuid, _userDir); data.LastUpdateTimestamp = DateTime.UtcNow; // fetch did not work, but we don't want it to fire again, so update the timestamp. if (cCWData == null) { _logger.LogInformation($"[Hangfire] UpdateCCWJob - No data from CCW for regi: {regi} vin: {vin}, plate: {plate}."); _context.SaveChanges(); _logger.LogInformation($"[Hangfire] UpdateCCWJob - Updated bus record timestamp with the ID {data.Id}."); return; } //update records in SchoolBus table bool exists = _context.SchoolBuss.Any(x => x.CCWDataId == cCWData.Id); if (exists) { var bus = _context.SchoolBuss.First(a => a.CCWDataId == cCWData.Id); if (cCWData.ICBCRegistrationNumber != null && bus.ICBCRegistrationNumber != null && !cCWData.ICBCRegistrationNumber.Equals(bus.ICBCRegistrationNumber)) { bus.ICBCRegistrationNumber = cCWData.ICBCRegistrationNumber; } if (cCWData.ICBCVehicleIdentificationNumber != null && bus.VehicleIdentificationNumber != null && !cCWData.ICBCVehicleIdentificationNumber.Equals(bus.VehicleIdentificationNumber)) { bus.VehicleIdentificationNumber = cCWData.ICBCVehicleIdentificationNumber; } if (cCWData.ICBCLicencePlateNumber != null && bus.LicencePlateNumber != null && !cCWData.ICBCLicencePlateNumber.Equals(bus.LicencePlateNumber)) { bus.LicencePlateNumber = cCWData.ICBCLicencePlateNumber; } _context.SaveChanges(); _logger.LogInformation($"[Hangfire] UpdateCCWJob - Saved bus record with the ID {data.Id}."); } } await Task.CompletedTask; }
public CCWData GetCCW(string regi, string plate, string vin, string userId, string guid, string directory) { // check we have the right headers. if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(guid) || string.IsNullOrEmpty(directory)) { return(null); } var batchUser = _configuration.GetValue <string>("CCW_USER_ID"); var logPrefix = batchUser == userId ? "[Hangfire]" : ""; // 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) { _logger.LogInformation($"{logPrefix} Exception occured parsing registration number {regi}."); } vehicle = _ccwService.GetBCVehicleForRegistrationNumber(regi, userId, guid, directory); } if (vehicle == null && plate != null) // check the plate. { vehicle = _ccwService.GetBCVehicleForLicensePlateNumber(plate, userId, guid, directory); } if (vehicle == null && vin != null) // check the vin. { vehicle = _ccwService.GetBCVehicleForSerialNumber(vin, userId, guid, directory); } if (vehicle == null) { return(null); } string icbcRegistrationNumber = vehicle.registrationNumber; CCWData ccwdata = null; if (_context.CCWDatas.Any(x => x.ICBCRegistrationNumber == icbcRegistrationNumber)) { ccwdata = _context.CCWDatas.First(x => x.ICBCRegistrationNumber == icbcRegistrationNumber); _logger.LogInformation($"{logPrefix} Found CCW record for Registration # " + ccwdata.ICBCRegistrationNumber); } else { _logger.LogInformation($"{logPrefix} Creating new CCW 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"; ClientOrganization clientOrganization = _ccwService.GetCurrentClientOrganization(ccwdata.NSCClientNum, organizationNameCode, userId, guid, directory); if (clientOrganization != null) { foundNSCData = true; ccwdata.NSCCarrierConditions = clientOrganization.nscInformation.carrierStatus; ccwdata.NSCCarrierName = clientOrganization.displayName; ccwdata.NSCCarrierSafetyRating = clientOrganization.nscInformation.safetyRating; } // now try the individual service if there was no match. if (foundNSCData == false) { ClientIndividual clientIndividual = _ccwService.GetCurrentClientIndividual(ccwdata.NSCClientNum, organizationNameCode, userId, guid, directory); if (clientIndividual != null) { foundNSCData = true; ccwdata.NSCCarrierConditions = clientIndividual.nscInformation.carrierStatus; ccwdata.NSCCarrierName = clientIndividual.displayName; ccwdata.NSCCarrierSafetyRating = clientIndividual.nscInformation.safetyRating; } } } if (ccwdata.Id > 0) { var bus = _context.SchoolBuss.FirstOrDefault(x => x.CCWDataId == ccwdata.Id); var changes = _context.GetChanges(ccwdata, "DateFetched"); if (bus != null && changes.Count > 0) { var ccwNotification = (new CCWNotification { HasBeenViewed = false, }); bus.CCWNotifications.Add(ccwNotification); foreach (var change in changes) { ccwNotification.CCWNotificationDetails.Add(new CCWNotificationDetail { ColName = change.ColName, ColDescription = change.ColDescription, ValueFrom = change.ValueFrom, ValueTo = change.ValueTo }); } } } else { _context.Add(ccwdata); } _logger.LogInformation($"{logPrefix} CCW data has been added/updated."); _context.SaveChanges(); return(ccwdata); }
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)); } }
/// <summary> /// Fetch CCW data from the microservice /// </summary> /// <param name="Configuration"></param> /// <param name="regi"></param> /// <param name="vin"></param> /// <param name="plate"></param> /// <param name="cCW_userId"></param> /// <param name="cCW_guid"></param> /// <param name="cCW_directory"></param> /// <param name="ccwHost"></param> /// <returns></returns> public static CCWData FetchCCW(string regi, string vin, string plate, string cCW_userId, string cCW_guid, string cCW_directory, string ccwHost) { CCWData result = null; Dictionary <string, string> parametersToAdd = new Dictionary <string, string>(); if (regi != null) { // first convert the regi to a number. int tempRegi; bool parsed = int.TryParse(regi, out tempRegi); if (parsed) { regi = tempRegi.ToString(); } parametersToAdd.Add("regi", regi); } if (vin != null) { parametersToAdd.Add("vin", vin); } if (plate != null) { parametersToAdd.Add("plate", plate); } var targetUrl = ccwHost + "/api/CCW/GetCCW"; string newUri = QueryHelpers.AddQueryString(targetUrl, parametersToAdd); // call the microservice try { HttpClient client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, newUri); request.Headers.Clear(); // transfer over the request headers. request.Headers.Add("SM_UNIVERSALID", cCW_userId); request.Headers.Add("SMGOV_USERGUID", cCW_guid); request.Headers.Add("SM_AUTHDIRNAME", cCW_directory); Task <HttpResponseMessage> responseTask = client.SendAsync(request); responseTask.Wait(); HttpResponseMessage response = responseTask.Result; if (response.StatusCode == HttpStatusCode.OK) // success { var stringtask = response.Content.ReadAsStringAsync(); stringtask.Wait(); // parse as JSON. string jsonString = stringtask.Result; result = JsonConvert.DeserializeObject <CCWData>(jsonString); } } catch (Exception e) { result = null; } return(result); }
/// <summary> /// fetches data from the ICBC CCW system, and constructs a CCWData object from that. Note that it does not perform the insert of that data into the database, only provides JSON data suitable for insertion. If a CCWData record exists in the schoolbus database then the id field will match that record, however all other data will be from the ICBC CCW system. /// </summary> /// <param name="regi">Registration Number (also known as Serial)</param> /// <param name="vin">Vehicle Identification Number</param> /// <param name="plate">License Plate String</param> /// <response code="200">OK</response> /// <response code="404">Vehicle not found in CCW system</response> public virtual IActionResult CcwdataFetchGetAsync(string regi, string vin, string plate) { CCWData result = null; string ccwHost = Configuration["CCW_SERVICE_NAME"]; // construct the query string Dictionary <string, string> parametersToAdd = new Dictionary <string, string>(); if (regi != null) { // first convert the regi to a number. int tempRegi; bool parsed = int.TryParse(regi, out tempRegi); if (parsed) { regi = tempRegi.ToString(); } parametersToAdd.Add("regi", regi); } if (vin != null) { parametersToAdd.Add("vin", vin); } if (plate != null) { parametersToAdd.Add("plate", plate); } var targetUrl = ccwHost + "/api/CCW/GetCCW"; string newUri = QueryHelpers.AddQueryString(targetUrl, parametersToAdd); // call the microservice try { HttpClient client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, newUri); request.Headers.Clear(); // transfer over the request headers. foreach (var item in Request.Headers) { string key = item.Key; string value = item.Value; request.Headers.Add(key, value); } Task <HttpResponseMessage> responseTask = client.SendAsync(request); responseTask.Wait(); HttpResponseMessage response = responseTask.Result; if (response.StatusCode == HttpStatusCode.OK) // success { var stringtask = response.Content.ReadAsStringAsync(); stringtask.Wait(); // parse as JSON. string jsonString = stringtask.Result; result = JsonConvert.DeserializeObject <CCWData>(jsonString); } } catch (Exception e) { result = null; } // return the result, or 404 if no result was found. if (result != null) { return(new ObjectResult(result)); } else { return(new StatusCodeResult(404)); } }
/// <summary> /// Adjust a SchoolBus item to ensure child object data is in place correctly /// </summary> /// <param name="item"></param> private void AdjustSchoolBus(SchoolBus item) { if (item != null) { if (item.SchoolBusOwner != null) { int school_bus_owner_id = item.SchoolBusOwner.Id; bool school_bus_owner_exists = _context.SchoolBusOwners.Any(a => a.Id == school_bus_owner_id); if (school_bus_owner_exists) { SchoolBusOwner school_bus_owner = _context.SchoolBusOwners.First(a => a.Id == school_bus_owner_id); item.SchoolBusOwner = school_bus_owner; } else // invalid data { item.SchoolBusOwner = null; } } // adjust District. if (item.District != null) { int district_id = item.District.Id; var district_exists = _context.ServiceAreas.Any(a => a.Id == district_id); if (district_exists) { District district = _context.Districts.First(a => a.Id == district_id); item.District = district; } else { item.District = null; } } // adjust school district if (item.SchoolDistrict != null) { int schoolDistrict_id = item.SchoolDistrict.Id; bool schoolDistrict_exists = _context.SchoolDistricts.Any(a => a.Id == schoolDistrict_id); if (schoolDistrict_exists) { SchoolDistrict school_district = _context.SchoolDistricts.First(a => a.Id == schoolDistrict_id); item.SchoolDistrict = school_district; } else // invalid data { item.SchoolDistrict = null; } } // adjust home city if (item.HomeTerminalCity != null) { int city_id = item.HomeTerminalCity.Id; bool city_exists = _context.Cities.Any(a => a.Id == city_id); if (city_exists) { City city = _context.Cities.First(a => a.Id == city_id); item.HomeTerminalCity = city; } else // invalid data { item.HomeTerminalCity = null; } } // adjust inspector if (item.Inspector != null) { int inspector_id = item.Inspector.Id; bool inspector_exists = _context.Users.Any(a => a.Id == inspector_id); if (inspector_exists) { User inspector = _context.Users.First(a => a.Id == inspector_id); item.Inspector = inspector; } else // invalid data { item.Inspector = null; } } // adjust CCWData if (item.CCWData != null) { int ccwdata_id = item.CCWData.Id; bool ccwdata_exists = _context.CCWDatas.Any(a => a.Id == ccwdata_id); if (ccwdata_exists) { CCWData ccwdata = _context.CCWDatas.First(a => a.Id == ccwdata_id); item.CCWData = ccwdata; } else // invalid data { item.CCWData = null; } } } }
/// <summary> /// Setup the test. /// </summary> public CCWDataModelTests() { instance = new CCWData(); }