/// <summary> /// Copy values from a Dynamics legal entity to another one /// </summary> /// <param name="to"></param> /// <param name="from"></param> public static void CopyValues(this MicrosoftDynamicsCRMadoxioTiedhouseconnection to, ViewModels.TiedHouseConnection from) { to.AdoxioTiedhouseconnectionid = from.id; to.AdoxioCorpconnectionfederalproducer = from.CorpConnectionFederalProducer; to.AdoxioCorpconnectionfederalproducerdetails = from.CorpConnectionFederalProducerDetails; to.AdoxioFamilymemberfederalproducer = from.FamilyMemberFederalProducer; to.AdoxioFamilymemberfederalproducerdetails = from.FamilyMemberFederalProducerDetails; to.AdoxioFederalproducerconnectiontocorp = from.FederalProducerConnectionToCorp; to.AdoxioFederalproducerconnectiontocorpdetails = from.FederalProducerConnectionToCorpDetails; to.AdoxioIsconnection = from.IsConnection; to.AdoxioPartnersconnectionfederalproducer = from.PartnersConnectionFederalProducer; to.AdoxioPartnersconnectionfederalproducerdetails = from.PartnersConnectionFederalProducerDetails; to.AdoxioPercentageofownership = from.PercentageofOwnership; to.AdoxioShare20plusconnectionproducer = from.Share20PlusConnectionProducer; to.AdoxioShare20plusconnectionproducerdetails = from.Share20PlusConnectionProducerDetails; to.AdoxioShare20plusfamilyconnectionproducer = from.Share20PlusFamilyConnectionProducer; to.AdoxioShare20plusfamilyconnectionproducerdetail = from.Share20PlusFamilyConnectionProducerDetail; to.AdoxioSharetype = from.ShareType; to.AdoxioSocietyconnectionfederalproducer = from.SocietyConnectionFederalProducer; to.AdoxioSocietyconnectionfederalproducerdetails = from.SocietyConnectionFederalProducerDetails; to.AdoxioConnectiontype = (int?)from.ConnectionType; to.AdoxioCrsconnectiontomarketer = (int?)from.CrsConnectionToMarketer; to.AdoxioCrsconnectiontomarketerdetails = from.CrsConnectionToMarketerDetails; to.AdoxioMarketerconnectiontocrs = (int?)from.MarketerConnectionToCrs; to.AdoxioMarketerconnectiontocrsdetails = from.MarketerConnectionToCrsDetails; to.AdoxioInconnectiontofederalproducer = (int?)from.INConnectionToFederalProducer; to.AdoxioInconnectiontofederalproducerdetails = from.INConnectionToFederalProducerDetails; }
/// <summary> /// Convert a Dynamics Legal Entity to a ViewModel /// </summary> public static ViewModels.TiedHouseConnection ToViewModel(this MicrosoftDynamicsCRMadoxioTiedhouseconnection tiedHouse) { ViewModels.TiedHouseConnection result = null; if (tiedHouse != null) { result = new ViewModels.TiedHouseConnection(); if (tiedHouse.AdoxioTiedhouseconnectionid != null) { result.id = tiedHouse.AdoxioTiedhouseconnectionid.ToString(); } result.CorpConnectionFederalProducer = tiedHouse.AdoxioCorpconnectionfederalproducer; result.CorpConnectionFederalProducerDetails = tiedHouse.AdoxioCorpconnectionfederalproducerdetails; result.FamilyMemberFederalProducer = tiedHouse.AdoxioFamilymemberfederalproducer; result.FamilyMemberFederalProducerDetails = tiedHouse.AdoxioFamilymemberfederalproducerdetails; result.FederalProducerConnectionToCorp = tiedHouse.AdoxioFederalproducerconnectiontocorp; result.FederalProducerConnectionToCorpDetails = tiedHouse.AdoxioFederalproducerconnectiontocorpdetails; result.IsConnection = tiedHouse.AdoxioIsconnection; result.PartnersConnectionFederalProducer = tiedHouse.AdoxioPartnersconnectionfederalproducer; result.PartnersConnectionFederalProducerDetails = tiedHouse.AdoxioPartnersconnectionfederalproducerdetails; result.PercentageofOwnership = tiedHouse.AdoxioPercentageofownership; result.Share20PlusConnectionProducer = tiedHouse.AdoxioShare20plusconnectionproducer; result.Share20PlusConnectionProducerDetails = tiedHouse.AdoxioShare20plusconnectionproducerdetails; result.Share20PlusFamilyConnectionProducer = tiedHouse.AdoxioShare20plusfamilyconnectionproducer; result.Share20PlusFamilyConnectionProducerDetail = tiedHouse.AdoxioShare20plusfamilyconnectionproducerdetail; result.ShareType = tiedHouse.AdoxioSharetype; result.SocietyConnectionFederalProducer = tiedHouse.AdoxioSocietyconnectionfederalproducer; result.SocietyConnectionFederalProducerDetails = tiedHouse.AdoxioSocietyconnectionfederalproducerdetails; } return(result); }
public ActionResult AddTiedHouseConnection([FromBody] ViewModels.TiedHouseConnection item, string accountId) { if (item == null) { return(BadRequest()); } var tiedHouse = new MicrosoftDynamicsCRMadoxioTiedhouseconnection(); // copy values over from the data provided tiedHouse.CopyValues(item); tiedHouse.AccountODataBind = _dynamicsClient.GetEntityURI("accounts", accountId); try { tiedHouse = _dynamicsClient.Tiedhouseconnections.Create(tiedHouse); } catch (HttpOperationException httpOperationException) { tiedHouse.AdoxioTiedhouseconnectionid = _dynamicsClient.GetCreatedRecord(httpOperationException, null); if (string.IsNullOrEmpty(tiedHouse.AdoxioTiedhouseconnectionid)) { _logger.LogError(httpOperationException, "Error creating tiedhouse connection "); throw new Exception("Error creating tiedhouse connection"); } } catch (Exception e) { _logger.LogError(e, "Error creating tiedhouse connection"); throw new Exception("Error creating tiedhouse connection"); } return(new JsonResult(tiedHouse.ToViewModel())); }
public ActionResult AddTiedHouseConnection([FromBody] ViewModels.TiedHouseConnection item, string accountId) { if (item == null) { return(BadRequest()); } var tiedHouse = new MicrosoftDynamicsCRMadoxioTiedhouseconnection(); // copy values over from the data provided tiedHouse.CopyValues(item); tiedHouse.AccountODataBind = _dynamicsClient.GetEntityURI("accounts", accountId); try { tiedHouse = _dynamicsClient.Tiedhouseconnections.Create(tiedHouse); } catch (OdataerrorException odee) { tiedHouse.AdoxioTiedhouseconnectionid = _dynamicsClient.GetCreatedRecord(odee, null); if (string.IsNullOrEmpty(tiedHouse.AdoxioTiedhouseconnectionid)) { _logger.LogError("Error creating tiedhouse connection"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new Exception("Unable to update tied house connections"); } } return(Json(tiedHouse.ToViewModel())); }
public async Task <IActionResult> CreateDynamicsShareholderLegalEntity([FromBody] ViewModels.AdoxioLegalEntity item) { if (item == null) { return(BadRequest()); } var adoxioLegalEntity = new MicrosoftDynamicsCRMadoxioLegalentity(); adoxioLegalEntity.CopyValues(item); if (item.isindividual != true) { var account = new MicrosoftDynamicsCRMaccount(); account.Name = item.name; if (item.isShareholder == true) { account.AdoxioAccounttype = (int)AdoxioAccountTypeCodes.Shareholder; } else if (item.isPartner == true) { account.AdoxioAccounttype = (int)AdoxioAccountTypeCodes.Partner; } account.AdoxioBusinesstype = (int)Enum.ToObject(typeof(Gov.Lclb.Cllb.Public.ViewModels.AdoxioApplicantTypeCodes), item.legalentitytype); account = await _dynamicsClient.Accounts.CreateAsync(account); //create tied house under account var tiedHouse = new MicrosoftDynamicsCRMadoxioTiedhouseconnection() { }; tiedHouse.AccountODataBind = _dynamicsClient.GetEntityURI("accounts", account.Accountid); adoxioLegalEntity.AdoxioShareholderAccountODataBind = _dynamicsClient.GetEntityURI("accounts", account.Accountid); var res = await _dynamicsClient.Tiedhouseconnections.CreateAsync(tiedHouse); } adoxioLegalEntity.AdoxioAccountValueODataBind = _dynamicsClient.GetEntityURI("accounts", item.account.id); adoxioLegalEntity.AdoxioLegalEntityOwnedODataBind = _dynamicsClient.GetEntityURI("adoxio_legalentities", item.parentLegalEntityId); adoxioLegalEntity = await _dynamicsClient.Legalentities.CreateAsync(adoxioLegalEntity); return(Json(adoxioLegalEntity.ToViewModel())); }
/// <summary> /// Convert a Dynamics Legal Entity to a ViewModel /// </summary> public static TiedHouseConnection ToViewModel(this MicrosoftDynamicsCRMadoxioTiedhouseconnection tiedHouse) { TiedHouseConnection result = null; if (tiedHouse != null) { result = new TiedHouseConnection(); if (tiedHouse.AdoxioTiedhouseconnectionid != null) { result.id = tiedHouse.AdoxioTiedhouseconnectionid; } result.CorpConnectionFederalProducer = tiedHouse.AdoxioCorpconnectionfederalproducer; result.CorpConnectionFederalProducerDetails = tiedHouse.AdoxioCorpconnectionfederalproducerdetails; result.FamilyMemberFederalProducer = tiedHouse.AdoxioFamilymemberfederalproducer; result.FamilyMemberFederalProducerDetails = tiedHouse.AdoxioFamilymemberfederalproducerdetails; result.FederalProducerConnectionToCorp = tiedHouse.AdoxioFederalproducerconnectiontocorp; result.FederalProducerConnectionToCorpDetails = tiedHouse.AdoxioFederalproducerconnectiontocorpdetails; result.IsConnection = tiedHouse.AdoxioIsconnection; result.PartnersConnectionFederalProducer = tiedHouse.AdoxioPartnersconnectionfederalproducer; result.PartnersConnectionFederalProducerDetails = tiedHouse.AdoxioPartnersconnectionfederalproducerdetails; result.PercentageofOwnership = tiedHouse.AdoxioPercentageofownership; result.Share20PlusConnectionProducer = tiedHouse.AdoxioShare20plusconnectionproducer; result.Share20PlusConnectionProducerDetails = tiedHouse.AdoxioShare20plusconnectionproducerdetails; result.Share20PlusFamilyConnectionProducer = tiedHouse.AdoxioShare20plusfamilyconnectionproducer; result.Share20PlusFamilyConnectionProducerDetail = tiedHouse.AdoxioShare20plusfamilyconnectionproducerdetail; result.ShareType = tiedHouse.AdoxioSharetype; result.SocietyConnectionFederalProducer = tiedHouse.AdoxioSocietyconnectionfederalproducer; result.SocietyConnectionFederalProducerDetails = tiedHouse.AdoxioSocietyconnectionfederalproducerdetails; result.LiquorFinancialInterest = tiedHouse.AdoxioLiquorfinancialinterest; result.LiquorFinancialInterestDetails = tiedHouse.AdoxioLiquorfinancialinterestdetails; result.ConnectionType = (TiedHouseConnectionType?)tiedHouse.AdoxioConnectiontype; result.CrsConnectionToMarketer = (MarketerYesNo?)tiedHouse.AdoxioCrsconnectiontomarketer; result.CrsConnectionToMarketerDetails = tiedHouse.AdoxioCrsconnectiontomarketerdetails; result.MarketerConnectionToCrs = (MarketerYesNo?)tiedHouse.AdoxioMarketerconnectiontocrs; result.MarketerConnectionToCrsDetails = tiedHouse.AdoxioMarketerconnectiontocrsdetails; result.INConnectionToFederalProducer = (MarketerYesNo?)tiedHouse.AdoxioInconnectiontofederalproducer; result.INConnectionToFederalProducerDetails = tiedHouse.AdoxioInconnectiontofederalproducerdetails; } return(result); }
public async Task <IActionResult> UpdateTiedHouse([FromBody] ViewModels.TiedHouseConnection item, string id) { if (item == null || id != item.id) { return(BadRequest()); } // get the legal entity. Guid tiedHouseId = new Guid(id); MicrosoftDynamicsCRMadoxioTiedhouseconnection res = await _dynamicsClient.GetTiedHouseConnectionById(tiedHouseId); if (res == null) { return(new NotFoundResult()); } // we are doing a patch, so wipe out the record. var tiedHouse = new MicrosoftDynamicsCRMadoxioTiedhouseconnection(); // copy values over from the data provided tiedHouse.CopyValues(item); try { await _dynamicsClient.AdoxioTiedhouseconnections.UpdateAsync(tiedHouseId.ToString(), tiedHouse); } catch (OdataerrorException odee) { _logger.LogError("Error updating tied house connections"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new Exception("Unable to update tied house connections"); } return(Json(tiedHouse.ToViewModel())); }
/// <summary> /// Update entity in adoxio_tiedhouseconnections /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioTiedhouseconnectionid'> /// key: adoxio_tiedhouseconnectionid /// </param> /// <param name='body'> /// New property values /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateAsync(this IAdoxioTiedhouseconnections operations, string adoxioTiedhouseconnectionid, MicrosoftDynamicsCRMadoxioTiedhouseconnection body, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdateWithHttpMessagesAsync(adoxioTiedhouseconnectionid, body, null, cancellationToken).ConfigureAwait(false)).Dispose(); }
/// <summary> /// Update entity in adoxio_tiedhouseconnections /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioTiedhouseconnectionid'> /// key: adoxio_tiedhouseconnectionid /// </param> /// <param name='body'> /// New property values /// </param> public static void Update(this IAdoxioTiedhouseconnections operations, string adoxioTiedhouseconnectionid, MicrosoftDynamicsCRMadoxioTiedhouseconnection body) { operations.UpdateAsync(adoxioTiedhouseconnectionid, body).GetAwaiter().GetResult(); }
/// <summary> /// Add new entity to adoxio_tiedhouseconnections /// </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 <MicrosoftDynamicsCRMadoxioTiedhouseconnection> CreateAsync(this IAdoxioTiedhouseconnections operations, MicrosoftDynamicsCRMadoxioTiedhouseconnection 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_tiedhouseconnections /// </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 MicrosoftDynamicsCRMadoxioTiedhouseconnection Create(this IAdoxioTiedhouseconnections operations, MicrosoftDynamicsCRMadoxioTiedhouseconnection body, string prefer = "return=representation") { return(operations.CreateAsync(body, prefer).GetAwaiter().GetResult()); }
/// <summary> /// Update entity in adoxio_tiedhouseconnections /// </summary> /// <param name='adoxioTiedhouseconnectionid'> /// key: adoxio_tiedhouseconnectionid of adoxio_tiedhouseconnection /// </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 adoxioTiedhouseconnectionid, MicrosoftDynamicsCRMadoxioTiedhouseconnection body, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (adoxioTiedhouseconnectionid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "adoxioTiedhouseconnectionid"); } 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("adoxioTiedhouseconnectionid", adoxioTiedhouseconnectionid); 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_tiedhouseconnections({adoxio_tiedhouseconnectionid})").ToString(); _url = _url.Replace("{adoxio_tiedhouseconnectionid}", System.Uri.EscapeDataString(adoxioTiedhouseconnectionid)); // 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); }
/// <summary> /// Update entity in adoxio_tiedhouseconnections /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioTiedhouseconnectionid'> /// key: adoxio_tiedhouseconnectionid of adoxio_tiedhouseconnection /// </param> /// <param name='body'> /// New property values /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse UpdateWithHttpMessages(this ITiedhouseconnections operations, string adoxioTiedhouseconnectionid, MicrosoftDynamicsCRMadoxioTiedhouseconnection body, Dictionary <string, List <string> > customHeaders = null) { return(operations.UpdateWithHttpMessagesAsync(adoxioTiedhouseconnectionid, body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult()); }
/// <summary> /// Add new entity to adoxio_tiedhouseconnections /// </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 <MicrosoftDynamicsCRMadoxioTiedhouseconnection> CreateWithHttpMessages(this ITiedhouseconnections operations, MicrosoftDynamicsCRMadoxioTiedhouseconnection body, string prefer = "return=representation", Dictionary <string, List <string> > customHeaders = null) { return(operations.CreateWithHttpMessagesAsync(body, prefer, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult()); }
public async Task <IActionResult> CreateDynamicsAccount([FromBody] ViewModels.Account item) { _logger.LogInformation(LoggingEvents.HttpPost, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name); _logger.LogDebug(LoggingEvents.HttpPost, "Account parameters: " + JsonConvert.SerializeObject(item)); ViewModels.Account result = null; bool updateIfNull = true; Guid tryParseOutGuid; bool createContact = true; // get UserSettings from the session string temp = _httpContextAccessor.HttpContext.Session.GetString("UserSettings"); UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp); _logger.LogDebug(LoggingEvents.HttpPost, "UserSettings: " + JsonConvert.SerializeObject(userSettings)); // get account Siteminder GUID string accountSiteminderGuid = userSettings.SiteMinderBusinessGuid; if (accountSiteminderGuid == null || accountSiteminderGuid.Length == 0) { _logger.LogError(LoggingEvents.Error, "No account Siteminder Guid exernal id"); throw new Exception("Error. No accountSiteminderGuid exernal id"); } // first check to see that a contact exists. string contactSiteminderGuid = userSettings.SiteMinderGuid; if (contactSiteminderGuid == null || contactSiteminderGuid.Length == 0) { _logger.LogError(LoggingEvents.Error, "No Contact Siteminder Guid exernal id"); throw new Exception("Error. No ContactSiteminderGuid exernal id"); } // get BCeID record for the current user Gov.Lclb.Cllb.Interfaces.BCeIDBusiness bceidBusiness = await _bceid.ProcessBusinessQuery(userSettings.SiteMinderGuid); var cleanNumber = BusinessNumberSanitizer.SanitizeNumber(bceidBusiness?.businessNumber); if (cleanNumber != null) { bceidBusiness.businessNumber = cleanNumber; } _logger.LogDebug(LoggingEvents.HttpGet, "BCeId business: " + JsonConvert.SerializeObject(bceidBusiness)); // get the contact record. MicrosoftDynamicsCRMcontact userContact = null; // see if the contact exists. try { userContact = _dynamicsClient.GetContactByExternalId(contactSiteminderGuid); createContact = false; } catch (OdataerrorException odee) { _logger.LogError(LoggingEvents.Error, "Error getting contact by Siteminder Guid."); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new OdataerrorException("Error getting contact by Siteminder Guid"); } if (userContact == null) { // create the user contact record. userContact = new MicrosoftDynamicsCRMcontact(); // Adoxio_externalid is where we will store the guid from siteminder. string sanitizedContactSiteminderId = GuidUtility.SanitizeGuidString(contactSiteminderGuid); userContact.AdoxioExternalid = sanitizedContactSiteminderId; userContact.Fullname = userSettings.UserDisplayName; userContact.Nickname = userSettings.UserDisplayName; if (Guid.TryParse(userSettings.UserId, out tryParseOutGuid)) // BCeid id goes here { userContact.Employeeid = userSettings.UserId; } else // Store the BC service card id here { userContact.Externaluseridentifier = userSettings.UserId; } if (bceidBusiness != null) { // set contact according to item userContact.Firstname = bceidBusiness.individualFirstname; userContact.Middlename = bceidBusiness.individualMiddlename; userContact.Lastname = bceidBusiness.individualSurname; userContact.Emailaddress1 = bceidBusiness.contactEmail; userContact.Telephone1 = bceidBusiness.contactPhone; } else { userContact.Firstname = userSettings.UserDisplayName.GetFirstName(); userContact.Lastname = userSettings.UserDisplayName.GetLastName(); } userContact.Statuscode = 1; } // this may be an existing account, as this service is used during the account confirmation process. MicrosoftDynamicsCRMaccount account = await _dynamicsClient.GetAccountBySiteminderBusinessGuid(accountSiteminderGuid); _logger.LogDebug(LoggingEvents.HttpGet, "Account by siteminder business guid: " + JsonConvert.SerializeObject(account)); if (account == null) // do a deep create. create 3 objects at once. { _logger.LogDebug(LoggingEvents.HttpGet, "Account is null. Do a deep create of 3 objects at once."); // create a new account account = new MicrosoftDynamicsCRMaccount(); account.CopyValues(item, updateIfNull); // business type must be set only during creation, not in update (removed from copyValues() ) account.AdoxioBusinesstype = (int)Enum.Parse(typeof(ViewModels.AdoxioApplicantTypeCodes), item.businessType, true); // ensure that we create an account for the current user. // by convention we strip out any dashes present in the guid, and force it to uppercase. string sanitizedAccountSiteminderId = GuidUtility.SanitizeGuidString(accountSiteminderGuid); account.AdoxioExternalid = sanitizedAccountSiteminderId; account.Primarycontactid = userContact; account.AdoxioAccounttype = (int)AdoxioAccountTypeCodes.Applicant; if (bceidBusiness != null) { account.Emailaddress1 = bceidBusiness.contactEmail; account.Telephone1 = bceidBusiness.contactPhone; account.Address1City = bceidBusiness.addressCity; account.Address1Postalcode = bceidBusiness.addressPostal; account.Address1Line1 = bceidBusiness.addressLine1; account.Address1Line2 = bceidBusiness.addressLine2; account.Address1Postalcode = bceidBusiness.addressPostal; } // sets Business type with numerical value found in Adoxio_applicanttypecodes // using account.businessType which is set in bceid-confirmation.component.ts account.AdoxioBusinesstype = (int)Enum.Parse(typeof(AdoxioApplicantTypeCodes), item.businessType, true); var legalEntity = new MicrosoftDynamicsCRMadoxioLegalentity() { AdoxioAccount = account, AdoxioName = item.name, AdoxioIsindividual = 0, AdoxioIsapplicant = true, AdoxioLegalentitytype = account.AdoxioBusinesstype }; string legalEntityString = JsonConvert.SerializeObject(legalEntity); _logger.LogDebug("Legal Entity before creation in dynamics --> " + legalEntityString); try { legalEntity = await _dynamicsClient.Adoxiolegalentities.CreateAsync(legalEntity); } catch (OdataerrorException odee) { string legalEntityId = _dynamicsClient.GetCreatedRecord(odee, null); if (!string.IsNullOrEmpty(legalEntityId) && Guid.TryParse(legalEntityId, out Guid legalEntityGuid)) { legalEntity = await _dynamicsClient.GetLegalEntityById(legalEntityGuid); } else { _logger.LogError(LoggingEvents.Error, "Error creating legal entity."); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new OdataerrorException("Error creating legal entitiy"); } } account.Accountid = legalEntity._adoxioAccountValue; // fetch the account and get the created contact. if (legalEntity.AdoxioAccount == null) { legalEntity.AdoxioAccount = await _dynamicsClient.GetAccountById(Guid.Parse(account.Accountid)); } if (legalEntity.AdoxioAccount.Primarycontactid == null) { legalEntity.AdoxioAccount.Primarycontactid = await _dynamicsClient.GetContactById(Guid.Parse(legalEntity.AdoxioAccount._primarycontactidValue)); } userContact.Contactid = legalEntity.AdoxioAccount._primarycontactidValue; legalEntityString = JsonConvert.SerializeObject(legalEntity); _logger.LogDebug("Legal Entity after creation in dynamics --> " + legalEntityString); var tiedHouse = new MicrosoftDynamicsCRMadoxioTiedhouseconnection() { }; tiedHouse.AccountODataBind = _dynamicsClient.GetEntityURI("accounts", account.Accountid); try { tiedHouse = await _dynamicsClient.AdoxioTiedhouseconnections.CreateAsync(tiedHouse); } catch (OdataerrorException odee) { string tiedHouseId = _dynamicsClient.GetCreatedRecord(odee, null); if (string.IsNullOrEmpty(tiedHouseId)) { _logger.LogError(LoggingEvents.Error, "Error creating Tied house connection."); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new OdataerrorException("Error creating Tied house connection."); } } catch (Exception e) { _logger.LogError(e.Message); } } else // it is a new user only. { if (createContact) { _logger.LogDebug(LoggingEvents.HttpGet, "Account is NOT null. Only a new user."); try { userContact = await _dynamicsClient.Contacts.CreateAsync(userContact); } catch (OdataerrorException odee) { string contactId = _dynamicsClient.GetCreatedRecord(odee, null); if (!string.IsNullOrEmpty(contactId) && Guid.TryParse(contactId, out Guid contactGuid)) { userContact = await _dynamicsClient.GetContactById(contactGuid); } else { _logger.LogError(LoggingEvents.Error, "Error creating contact"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new OdataerrorException("Error creating contact"); } } } } // always patch the userContact so it relates to the account. _logger.LogDebug(LoggingEvents.Save, "Patching the userContact so it relates to the account."); // parent customer id relationship will be created using the method here: //https://msdn.microsoft.com/en-us/library/mt607875.aspx MicrosoftDynamicsCRMcontact patchUserContact = new MicrosoftDynamicsCRMcontact(); patchUserContact.ParentCustomerIdAccountODataBind = _dynamicsClient.GetEntityURI("accounts", account.Accountid); try { await _dynamicsClient.Contacts.UpdateAsync(userContact.Contactid, patchUserContact); } catch (OdataerrorException odee) { _logger.LogError(LoggingEvents.Error, "Error binding contact to account"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new OdataerrorException("Error binding contact to account"); } // if we have not yet authenticated, then this is the new record for the user. if (userSettings.IsNewUserRegistration) { userSettings.AccountId = account.Accountid.ToString(); userSettings.ContactId = userContact.Contactid.ToString(); // we can now authenticate. if (userSettings.AuthenticatedUser == null) { Models.User user = new Models.User(); user.Active = true; user.AccountId = Guid.Parse(userSettings.AccountId); user.ContactId = Guid.Parse(userSettings.ContactId); user.UserType = userSettings.UserType; user.SmUserId = userSettings.UserId; userSettings.AuthenticatedUser = user; } userSettings.IsNewUserRegistration = false; string userSettingsString = JsonConvert.SerializeObject(userSettings); _logger.LogDebug("userSettingsString --> " + userSettingsString); // add the user to the session. _httpContextAccessor.HttpContext.Session.SetString("UserSettings", userSettingsString); _logger.LogDebug("user added to session. "); } else { _logger.LogError(LoggingEvents.Error, "Invalid user registration."); throw new Exception("Invalid user registration."); } //account.accountId = id; result = account.ToViewModel(); _logger.LogDebug(LoggingEvents.HttpPost, "result: " + JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore })); return(Json(result)); }
public IActionResult CreateDynamicsShareholderLegalEntity([FromBody] ViewModels.LegalEntity item) { if (item == null) { return(BadRequest()); } MicrosoftDynamicsCRMadoxioLegalentity adoxioLegalEntity = new MicrosoftDynamicsCRMadoxioLegalentity(); adoxioLegalEntity.CopyValues(item); if (item.isindividual != true) { var account = new MicrosoftDynamicsCRMaccount(); account.Name = item.name; if (item.isShareholder == true) { account.AdoxioAccounttype = (int)AdoxioAccountTypeCodes.Shareholder; } else if (item.isPartner == true) { account.AdoxioAccounttype = (int)AdoxioAccountTypeCodes.Partner; } if (item.legalentitytype != null) { account.AdoxioBusinesstype = (int)Enum.ToObject(typeof(Gov.Lclb.Cllb.Public.ViewModels.AdoxioApplicantTypeCodes), item.legalentitytype); } try { account = _dynamicsClient.Accounts.Create(account); } catch (HttpOperationException httpOperationException) { _logger.LogError(httpOperationException, $"Error creating account: {httpOperationException.Request.Content} Response: {httpOperationException.Response.Content}"); } catch (Exception e) { _logger.LogError(e, $"Unexpected Exception while creating tied house connection"); } //create tied house under account var tiedHouse = new MicrosoftDynamicsCRMadoxioTiedhouseconnection() { AccountODataBind = _dynamicsClient.GetEntityURI("accounts", account.Accountid) }; adoxioLegalEntity.AdoxioShareholderAccountODataBind = _dynamicsClient.GetEntityURI("accounts", account.Accountid); try { _dynamicsClient.Tiedhouseconnections.Create(tiedHouse); } catch (HttpOperationException httpOperationException) { _logger.LogError(httpOperationException, $"Error creating tied house connection"); } catch (Exception e) { _logger.LogError(e, $"Unexpected Exception while creating tied house connection"); } } adoxioLegalEntity.AdoxioAccountValueODataBind = _dynamicsClient.GetEntityURI("accounts", item.account.id); adoxioLegalEntity.AdoxioLegalEntityOwnedODataBind = _dynamicsClient.GetEntityURI("adoxio_legalentities", item.parentLegalEntityId); try { adoxioLegalEntity = _dynamicsClient.Legalentities.Create(adoxioLegalEntity); } catch (HttpOperationException httpOperationException) { _logger.LogError(httpOperationException, $"Error creating legal entity: {httpOperationException.Request.Content} Response: {httpOperationException.Response.Content}"); } catch (Exception e) { _logger.LogError(e, $"Unexpected Exception while creating legal entity"); } return(new JsonResult(adoxioLegalEntity.ToViewModel())); }