public async Task <IActionResult> CreateEstablishment([FromBody] ViewModels.AdoxioEstablishment item) { // create a new legal entity. MicrosoftDynamicsCRMadoxioEstablishment adoxio_establishment = new MicrosoftDynamicsCRMadoxioEstablishment(); // copy received values to Dynamics LegalEntity adoxio_establishment.CopyValues(item); try { adoxio_establishment = await _dynamicsClient.Establishments.CreateAsync(adoxio_establishment); } catch (OdataerrorException odee) { _logger.LogError("Error creating establishment"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new Exception("Unable to create establishment"); } ViewModels.AdoxioEstablishment result = adoxio_establishment.ToViewModel(); return(Json(result)); }
public async Task <IActionResult> DeleteEstablishment(string id) { // get the legal entity. Guid adoxio_establishmentid = new Guid(id); MicrosoftDynamicsCRMadoxioEstablishment establishment = _dynamicsClient.GetEstablishmentById(adoxio_establishmentid); if (establishment == null) { return(new NotFoundResult()); } try { await _dynamicsClient.Establishments.DeleteAsync(adoxio_establishmentid.ToString()); } catch (OdataerrorException odee) { _logger.LogError("Error delete establishment"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new Exception("Unable to delete establishment"); } return(NoContent()); // 204 }
public async Task TestCreateLicenceCredential() { var mockHttp = new MockHttpMessageHandler(); var request = mockHttp.When("http://localhost/lcrb/issue-credential") .Respond("application/json", "[{'sucess': true, 'result': '123-123-123', 'served_by': 'django-83'}]"); var httpClient = new HttpClient(mockHttp); var mock = new Mock <ILogger <VonAgentClient> >(); ILogger <VonAgentClient> logger = mock.Object; var establishment = new MicrosoftDynamicsCRMadoxioEstablishment() { AdoxioName = "Cannabis Establishment" }; MicrosoftDynamicsCRMadoxioLicences licence = new MicrosoftDynamicsCRMadoxioLicences() { AdoxioLicencenumber = "400", AdoxioEstablishment = establishment, AdoxioEffectivedate = DateTime.UtcNow, AdoxioExpirydate = DateTime.Parse("2019-12-27T07:50:11.455516-07:00"), AdoxioEstablishmentaddressstreet = "159 Mary Jane Lane", AdoxioEstablishmentaddresscity = "Victoria", AdoxioEstablishmentaddresspostalcode = "V9A4V1" }; var subject = new VonAgentClient(httpClient, logger, "cannabis", "1", "http://localhost/"); await subject.CreateLicenceCredential(licence, "BC1234567"); Assert.Equal(1, mockHttp.GetMatchCount(request)); }
public List <MicrosoftDynamicsCRMadoxioEstablishment> ObfuscateEstablishments(List <MicrosoftDynamicsCRMadoxioEstablishment> establishments) { List <MicrosoftDynamicsCRMadoxioEstablishment> result = new List <MicrosoftDynamicsCRMadoxioEstablishment>(); foreach (var establishment in establishments) { string firstName = RandomFirstName(); string lastName = RandomLastName(); var newItem = new MicrosoftDynamicsCRMadoxioEstablishment() { AdoxioEstablishmentid = Guid.NewGuid().ToString(), AdoxioName = RandomCompanyName(establishment.AdoxioName), AdoxioAddresscity = establishment.AdoxioAddresscity, AdoxioAddresspostalcode = establishment.AdoxioAddresspostalcode, AdoxioAddressstreet = RandomCompanyName(establishment.AdoxioAddressstreet), AdoxioAlreadyopen = establishment.AdoxioAlreadyopen, AdoxioEmail = RandomEmail(), AdoxioExpectedopendate = establishment.AdoxioExpectedopendate, AdoxioFridayclose = establishment.AdoxioFridayclose, AdoxioFridayopen = establishment.AdoxioFridayopen, AdoxioHasduallicence = establishment.AdoxioHasduallicence, AdoxioIsrural = establishment.AdoxioIsrural, AdoxioIsstandalonepatio = establishment.AdoxioIsstandalonepatio, AdoxioLocatedatwinery = establishment.AdoxioLocatedatwinery, AdoxioLocatedonfirstnationland = establishment.AdoxioLocatedonfirstnationland, AdoxioMailsenttorestaurant = establishment.AdoxioMailsenttorestaurant, AdoxioMondayclose = establishment.AdoxioMondayclose, AdoxioMondayopen = establishment.AdoxioMondayopen, AdoxioOccupantcapacity = establishment.AdoxioOccupantcapacity, AdoxioOccupantload = establishment.AdoxioOccupantload, AdoxioParcelid = establishment.AdoxioParcelid, AdoxioPatronparticipation = establishment.AdoxioPatronparticipation, AdoxioPhone = establishment.AdoxioPhone, AdoxioSaturdayclose = establishment.AdoxioSaturdayclose, AdoxioSaturdayopen = establishment.AdoxioSaturdayopen, AdoxioSendmailtoestablishmentuponapproval = establishment.AdoxioSendmailtoestablishmentuponapproval, AdoxioStandardhours = establishment.AdoxioStandardhours, AdoxioSundayclose = establishment.AdoxioSundayclose, AdoxioSundayopen = establishment.AdoxioSundayopen, AdoxioThursdayclose = establishment.AdoxioThursdayclose, AdoxioThursdayopen = establishment.AdoxioThursdayopen, AdoxioTuesdayclose = establishment.AdoxioTuesdayclose, AdoxioTuesdayopen = establishment.AdoxioTuesdayopen, AdoxioWednesdayclose = establishment.AdoxioWednesdayclose, AdoxioWednesdayopen = establishment.AdoxioWednesdayopen, Statuscode = establishment.Statuscode, Statecode = establishment.Statecode }; EstablishmentMap.Add(establishment.AdoxioEstablishmentid, newItem.AdoxioEstablishmentid); result.Add(newItem); } return(result); }
public async Task <IActionResult> UpdateEstablishment([FromBody] ViewModels.AdoxioEstablishment item, string id) { if (string.IsNullOrEmpty(id) || id != item.id) { return(BadRequest()); } // get the legal entity. Guid adoxio_establishmentid = GuidUtility.SafeGuidConvert(id); MicrosoftDynamicsCRMadoxioEstablishment adoxioEstablishment = _dynamicsClient.GetEstablishmentById(adoxio_establishmentid); if (adoxioEstablishment == null) { return(new NotFoundResult()); } // we are doing a patch, so wipe out the record. adoxioEstablishment = new MicrosoftDynamicsCRMadoxioEstablishment(); // copy values over from the data provided adoxioEstablishment.CopyValues(item); try { await _dynamicsClient.Establishments.UpdateAsync(adoxio_establishmentid.ToString(), adoxioEstablishment); } catch (OdataerrorException odee) { _logger.LogError("Error updating establishment"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new Exception("Unable to update establishment"); } try { adoxioEstablishment = _dynamicsClient.GetEstablishmentById(adoxio_establishmentid); } catch (OdataerrorException odee) { _logger.LogError("Error getting establishment"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new Exception("Unable to get establishment after update"); } return(Json(adoxioEstablishment.ToViewModel())); }
/// <summary> /// Copy values from a Dynamics establishme t entity to a view model. /// </summary> /// <param name="to"></param> /// <param name="from"></param> public static void CopyValues(this MicrosoftDynamicsCRMadoxioEstablishment to, ViewModels.Establishment from) { // Only copy email and phone number if (from.Email != null) { to.AdoxioEmail = from.Email; } if (from.Phone != null) { to.AdoxioPhone = from.Phone; } }
public static MicrosoftDynamicsCRMadoxioEstablishment GetEstablishmentById(this IDynamicsClient _dynamicsClient, Guid id) { MicrosoftDynamicsCRMadoxioEstablishment result = null; try { result = _dynamicsClient.Establishments.GetByKey(id.ToString()); } catch (OdataerrorException) { result = null; } return(result); }
public MicrosoftDynamicsCRMadoxioEstablishment GetEstablishmentById(string id) { MicrosoftDynamicsCRMadoxioEstablishment result = null; string[] expand = { "adoxio_Licencee" }; try { result = Establishments.GetByKey(adoxioEstablishmentid: id, expand: expand); } catch (HttpOperationException) { result = null; } return(result); }
public async Task <IActionResult> CreateEstablishment([FromBody] ViewModels.Establishment item) { // create a new legal entity. MicrosoftDynamicsCRMadoxioEstablishment adoxio_establishment = new MicrosoftDynamicsCRMadoxioEstablishment(); // copy received values to Dynamics LegalEntity adoxio_establishment.CopyValues(item); try { adoxio_establishment = await _dynamicsClient.Establishments.CreateAsync(adoxio_establishment); } catch (HttpOperationException httpOperationException) { _logger.LogError(httpOperationException, "Error creating establishment"); throw new Exception("Unable to create establishment"); } ViewModels.Establishment result = adoxio_establishment.ToViewModel(); return(new JsonResult(result)); }
/// <summary> /// Update entity in adoxio_establishments /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioEstablishmentid'> /// key: adoxio_establishmentid of adoxio_establishment /// </param> /// <param name='body'> /// New property values /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse UpdateWithHttpMessages(this IEstablishments operations, string adoxioEstablishmentid, MicrosoftDynamicsCRMadoxioEstablishment body, Dictionary <string, List <string> > customHeaders = null) { return(operations.UpdateWithHttpMessagesAsync(adoxioEstablishmentid, body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult()); }
/// <summary> /// Update entity in adoxio_establishments /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioEstablishmentid'> /// key: adoxio_establishmentid /// </param> /// <param name='body'> /// New property values /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateAsync(this IEstablishments operations, string adoxioEstablishmentid, MicrosoftDynamicsCRMadoxioEstablishment body, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdateWithHttpMessagesAsync(adoxioEstablishmentid, body, null, cancellationToken).ConfigureAwait(false)).Dispose(); }
/// <summary> /// Copy values from a Dynamics establishme t entity to a view model. /// </summary> /// <param name="to"></param> /// <param name="from"></param> public static void CopyValues(this MicrosoftDynamicsCRMadoxioEstablishment to, ViewModels.AdoxioEstablishment from) { if (to.AdoxioAddresscity != from.Addresscity) { to.AdoxioAddresscity = from.Addresscity; } if (to.AdoxioAddresspostalcode != from.Addresspostalcode) { to.AdoxioAddresspostalcode = from.Addresspostalcode; } if (to.AdoxioAddressstreet != from.Addressstreet) { to.AdoxioAddressstreet = from.Addressstreet; } if (to.AdoxioAlreadyopen != from.Alreadyopen) { to.AdoxioAlreadyopen = from.Alreadyopen; } if (to.AdoxioEmail != from.Email) { to.AdoxioEmail = from.Email; } if (to.AdoxioExpectedopendate != from.Expectedopendate) { to.AdoxioExpectedopendate = from.Expectedopendate; } if (to.AdoxioFridayclose != from.Fridayclose) { to.AdoxioFridayclose = from.Fridayclose; } if (to.AdoxioFridayopen != from.Fridayopen) { to.AdoxioFridayopen = from.Fridayopen; } if (to.AdoxioHasduallicence != from.Hasduallicence) { to.AdoxioHasduallicence = from.Hasduallicence; } if (to.AdoxioIsrural != from.Isrural) { to.AdoxioIsrural = from.Isrural; } if (to.AdoxioIsstandalonepatio != from.Isstandalonepatio) { to.AdoxioIsstandalonepatio = from.Isstandalonepatio; } if (to.AdoxioLocatedatwinery != from.Locatedatwinery) { to.AdoxioLocatedatwinery = from.Locatedatwinery; } if (to.AdoxioLocatedonfirstnationland != from.Locatedonfirstnationland) { to.AdoxioLocatedonfirstnationland = from.Locatedonfirstnationland; } if (to.AdoxioMailsenttorestaurant != from.Mailsenttorestaurant) { to.AdoxioMailsenttorestaurant = from.Mailsenttorestaurant; } if (to.AdoxioMondayclose != from.Mondayclose) { to.AdoxioMondayclose = from.Mondayclose; } if (to.AdoxioMondayopen != from.Mondayopen) { to.AdoxioMondayopen = from.Mondayopen; } if (to.AdoxioName != from.Name) { to.AdoxioName = from.Name; } if (to.AdoxioOccupantcapacity != from.Occupantcapacity) { to.AdoxioOccupantcapacity = from.Occupantcapacity; } if (to.AdoxioOccupantload != from.Occupantload) { to.AdoxioOccupantload = from.Occupantload; } if (to.AdoxioParcelid != from.Parcelid) { to.AdoxioParcelid = from.Parcelid; } if (to.AdoxioPatronparticipation != from.Patronparticipation) { to.AdoxioPatronparticipation = from.Patronparticipation; } if (to.AdoxioPhone != from.Phone) { to.AdoxioPhone = from.Phone; } if (to.AdoxioSaturdayclose != from.Saturdayclose) { to.AdoxioSaturdayclose = from.Saturdayclose; } if (to.AdoxioSaturdayopen != from.Saturdayopen) { to.AdoxioSaturdayopen = from.Saturdayopen; } if (to.AdoxioSendmailtoestablishmentuponapproval != from.Sendmailtoestablishmentuponapproval) { to.AdoxioSendmailtoestablishmentuponapproval = from.Sendmailtoestablishmentuponapproval; } if (to.AdoxioStandardhours != from.Standardhours) { to.AdoxioStandardhours = from.Standardhours; } if (to.AdoxioSundayclose != from.Sundayclose) { to.AdoxioSundayclose = from.Sundayclose; } if (to.AdoxioSundayopen != from.Sundayopen) { to.AdoxioSundayopen = from.Sundayopen; } if (to.AdoxioThursdayclose != from.Thursdayclose) { to.AdoxioThursdayclose = from.Thursdayclose; } if (to.AdoxioThursdayopen != from.Thursdayopen) { to.AdoxioThursdayopen = from.Thursdayopen; } if (to.AdoxioTuesdayclose != from.Tuesdayclose) { to.AdoxioTuesdayclose = from.Tuesdayclose; } if (to.AdoxioTuesdayopen != from.Tuesdayopen) { to.AdoxioTuesdayopen = from.Tuesdayopen; } if (to.AdoxioWednesdayclose != from.Wednesdayclose) { to.AdoxioWednesdayclose = from.Wednesdayclose; } if (to.AdoxioWednesdayopen != from.Wednesdayopen) { to.AdoxioWednesdayopen = from.Wednesdayopen; } if (to.Createdon != from.Createdon) { to.Createdon = from.Createdon; } if (to.Importsequencenumber != from.Importsequencenumber) { to.Importsequencenumber = from.Importsequencenumber; } if (to.Modifiedon != from.Modifiedon) { to.Modifiedon = from.Modifiedon; } if (to.Overriddencreatedon != from.Overriddencreatedon) { to.Overriddencreatedon = from.Overriddencreatedon; } if (to.Statuscode != from.StatusCode) { to.Statuscode = from.StatusCode; } if (to.Statecode != from.StateCode) { to.Statecode = from.StateCode; } if (to.Timezoneruleversionnumber != from.Timezoneruleversionnumber) { to.Timezoneruleversionnumber = from.Timezoneruleversionnumber; } if (to.Utcconversiontimezonecode != from.Utcconversiontimezonecode) { to.Utcconversiontimezonecode = from.Utcconversiontimezonecode; } to.Versionnumber = from.Versionnumber; }
/// <summary> /// Update entity in adoxio_establishments /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioEstablishmentid'> /// key: adoxio_establishmentid /// </param> /// <param name='body'> /// New property values /// </param> public static void Update(this IEstablishments operations, string adoxioEstablishmentid, MicrosoftDynamicsCRMadoxioEstablishment body) { operations.UpdateAsync(adoxioEstablishmentid, body).GetAwaiter().GetResult(); }
/// <summary> /// Add new entity to adoxio_establishments /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// New entity /// </param> /// <param name='prefer'> /// Required in order for the service to return a JSON representation of the /// object. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <MicrosoftDynamicsCRMadoxioEstablishment> CreateAsync(this IEstablishments operations, MicrosoftDynamicsCRMadoxioEstablishment body, string prefer = "return=representation", CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(body, prefer, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
/// <summary> /// Add new entity to adoxio_establishments /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// New entity /// </param> /// <param name='prefer'> /// Required in order for the service to return a JSON representation of the /// object. /// </param> public static MicrosoftDynamicsCRMadoxioEstablishment Create(this IEstablishments operations, MicrosoftDynamicsCRMadoxioEstablishment body, string prefer = "return=representation") { return(operations.CreateAsync(body, prefer).GetAwaiter().GetResult()); }
/// <summary> /// Convert a establishme t entity to a model /// </summary> /// <param name="from"></param> /// <returns></returns> public static MicrosoftDynamicsCRMadoxioEstablishment ToModel(this ViewModels.AdoxioEstablishment from) { MicrosoftDynamicsCRMadoxioEstablishment result = null; if (from != null) { result = new MicrosoftDynamicsCRMadoxioEstablishment(); result.AdoxioEstablishmentid = from.id; result._adoxioLicenceeValue = from._licencee_value.ToString(); result._adoxioLicencetypeidValue = from._licencetypeid_value.ToString(); //result. = from._municipality_value.ToString(); result._adoxioPdjurisdictionValue = from._policejurisdiction_value.ToString(); result._adoxioPrimaryinspectoridValue = from._primaryinspectorid_value.ToString(); result._adoxioTerritoryValue = from._territory_value.ToString(); result._createdbyValue = from._createdby_value.ToString(); result._createdonbehalfbyValue = from._createdonbehalfby_value.ToString(); result._modifiedbyValue = from._modifiedby_value.ToString(); result._modifiedonbehalfbyValue = from._modifiedonbehalfby_value.ToString(); result._owneridValue = from._ownerid_value.ToString(); result._owningbusinessunitValue = from._owningbusinessunit_value.ToString(); result._owningteamValue = from._owningteam_value.ToString(); result._owninguserValue = from._owninguser_value.ToString(); result.AdoxioAddresscity = from.Addresscity; result.AdoxioAddresspostalcode = from.Addresspostalcode; result.AdoxioAddressstreet = from.Addressstreet; result.AdoxioAlreadyopen = from.Alreadyopen; result.AdoxioEmail = from.Email; result.AdoxioExpectedopendate = from.Expectedopendate; result.AdoxioFridayclose = from.Fridayclose; result.AdoxioFridayopen = from.Fridayopen; result.AdoxioHasduallicence = from.Hasduallicence; result.AdoxioIsrural = from.Isrural; result.AdoxioIsstandalonepatio = from.Isstandalonepatio; result.AdoxioLocatedatwinery = from.Locatedatwinery; result.AdoxioLocatedonfirstnationland = from.Locatedonfirstnationland; result.AdoxioMailsenttorestaurant = from.Mailsenttorestaurant; result.AdoxioMondayclose = from.Mondayclose; result.AdoxioMondayopen = from.Mondayopen; result.AdoxioName = from.Name; result.AdoxioOccupantcapacity = from.Occupantcapacity; result.AdoxioOccupantload = from.Occupantload; result.AdoxioParcelid = from.Parcelid; result.AdoxioPatronparticipation = from.Patronparticipation; result.AdoxioPhone = from.Phone; result.AdoxioSaturdayclose = from.Saturdayclose; result.AdoxioSaturdayopen = from.Saturdayopen; result.AdoxioSendmailtoestablishmentuponapproval = from.Sendmailtoestablishmentuponapproval; result.AdoxioStandardhours = from.Standardhours; result.AdoxioSundayclose = from.Sundayclose; result.AdoxioSundayopen = from.Sundayopen; result.AdoxioThursdayclose = from.Thursdayclose; result.AdoxioThursdayopen = from.Thursdayopen; result.AdoxioTuesdayclose = from.Tuesdayclose; result.AdoxioTuesdayopen = from.Tuesdayopen; result.AdoxioWednesdayclose = from.Wednesdayclose; result.AdoxioWednesdayopen = from.Wednesdayopen; result.Createdon = from.Createdon; result.Importsequencenumber = from.Importsequencenumber; result.Modifiedon = from.Modifiedon; result.Overriddencreatedon = from.Overriddencreatedon; result.Statuscode = from.StatusCode; result.Statecode = from.StateCode; result.Timezoneruleversionnumber = from.Timezoneruleversionnumber; result.Utcconversiontimezonecode = from.Utcconversiontimezonecode; result.Versionnumber = from.Versionnumber; } return(result); }
/// <summary> /// Add new entity to adoxio_establishments /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// New entity /// </param> /// <param name='prefer'> /// Required in order for the service to return a JSON representation of the /// object. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse <MicrosoftDynamicsCRMadoxioEstablishment> CreateWithHttpMessages(this IEstablishments operations, MicrosoftDynamicsCRMadoxioEstablishment body, string prefer = "return=representation", Dictionary <string, List <string> > customHeaders = null) { return(operations.CreateWithHttpMessagesAsync(body, prefer, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult()); }
/// <summary> /// Update entity in adoxio_establishments /// </summary> /// <param name='adoxioEstablishmentid'> /// key: adoxio_establishmentid of adoxio_establishment /// </param> /// <param name='body'> /// New property values /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse> UpdateWithHttpMessagesAsync(string adoxioEstablishmentid, MicrosoftDynamicsCRMadoxioEstablishment body, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (adoxioEstablishmentid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "adoxioEstablishmentid"); } if (body == null) { throw new ValidationException(ValidationRules.CannotBeNull, "body"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("adoxioEstablishmentid", adoxioEstablishmentid); tracingParameters.Add("body", body); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "adoxio_establishments({adoxio_establishmentid})").ToString(); _url = _url.Replace("{adoxio_establishmentid}", System.Uri.EscapeDataString(adoxioEstablishmentid)); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (body != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
private async Task GeocodeEstablishment(PerformContext hangfireContext, MicrosoftDynamicsCRMadoxioEstablishment establishment) { if (establishment != null && !string.IsNullOrEmpty(establishment.AdoxioAddresscity)) { string streetAddress = SanitizeStreetAddress(establishment.AdoxioAddressstreet); string address = $"{establishment.AdoxioAddressstreet}, {establishment.AdoxioAddresscity}, BC"; // output format can be xhtml, kml, csv, shpz, geojson, geojsonp, gml var output = _geocoder.GeoCoderAPI.Sites(outputFormat: "json", addressString: address); // if there are any faults try a query based on the LGIN instead of the city. if (output.Features[0].Properties.Faults.Count > 0 && establishment._adoxioLginValue != null) { var lgin = _dynamics.GetLginById(establishment._adoxioLginValue); _logger.LogError($"Unable to find a good match for address {address}, using lgin of {lgin.AdoxioName}"); hangfireContext.WriteLine($"Unable to find a good match for address {address}, using lgin of {lgin.AdoxioName}"); address = $"{establishment.AdoxioAddressstreet}, {lgin.AdoxioName}, BC"; output = _geocoder.GeoCoderAPI.Sites(outputFormat: "json", addressString: address); } // if the LGIN did not provide a good match just default to the specified city. if (output.Features[0].Properties.Faults.Count > 2) { _logger.LogError($"Unable to find a good match for address {address} with city {establishment._adoxioLginValue}, defaulting to just {establishment.AdoxioAddresscity}"); hangfireContext.WriteLine($"Unable to find a good match for address {address} with city {establishment._adoxioLginValue}, defaulting to just {establishment.AdoxioAddresscity}"); output = _geocoder.GeoCoderAPI.Sites(outputFormat: "json", addressString: $"{establishment.AdoxioAddresscity}, BC"); } // get the lat and long for the pin. double?longData = output.Features[0].Geometry.Coordinates[0]; double?latData = output.Features[0].Geometry.Coordinates[1]; // update the establishment. var patchEstablishment = new MicrosoftDynamicsCRMadoxioEstablishment() { AdoxioLongitude = (decimal?)longData, AdoxioLatitude = (decimal?)latData }; try { _dynamics.Establishments.Update(establishment.AdoxioEstablishmentid, patchEstablishment); _logger.LogInformation($"Updated establishment with address {address}"); hangfireContext.WriteLine($"Updated establishment with address {address}"); } catch (HttpOperationException odee) { if (hangfireContext != null) { _logger.LogError("Error updating establishment"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); hangfireContext.WriteLine("Error updating establishment"); hangfireContext.WriteLine("Request:"); hangfireContext.WriteLine(odee.Request.Content); hangfireContext.WriteLine("Response:"); hangfireContext.WriteLine(odee.Response.Content); } // fail if we can't update. throw (odee); } } }