public async Task <IActionResult> UpdateDynamicsLegalEntity([FromBody] ViewModels.AdoxioLegalEntity item, string id) { if (id != item.id) { return(BadRequest()); } // get the legal entity. Guid adoxio_legalentityid = new Guid(id); MicrosoftDynamicsCRMadoxioLegalentity adoxioLegalEntity = await _dynamicsClient.GetLegalEntityById(adoxio_legalentityid); if (adoxioLegalEntity == null) { return(new NotFoundResult()); } // we are doing a patch, so wipe out the record. adoxioLegalEntity = new MicrosoftDynamicsCRMadoxioLegalentity(); // copy values over from the data provided adoxioLegalEntity.CopyValues(item); await _dynamicsClient.Legalentities.UpdateAsync(adoxio_legalentityid.ToString(), adoxioLegalEntity); adoxioLegalEntity = await _dynamicsClient.GetLegalEntityById(adoxio_legalentityid); return(Json(adoxioLegalEntity.ToViewModel())); }
public async Task <IActionResult> CreateDynamicsShareholderLegalEntity([FromBody] ViewModels.AdoxioLegalEntity item) { if (item == null) { return(BadRequest()); } var adoxioLegalEntity = new MicrosoftDynamicsCRMadoxioLegalentity(); adoxioLegalEntity.CopyValues(item); if (item.isShareholder == true && item.isindividual != true) { var account = new MicrosoftDynamicsCRMaccount(); account.Name = item.name; account.AdoxioAccounttype = (int)Adoxio_accounttypecodes.Shareholder; account.AdoxioBusinesstype = (int)Enum.ToObject(typeof(Gov.Lclb.Cllb.Public.ViewModels.Adoxio_applicanttypecodes), item.legalentitytype); account = await _dynamicsClient.Accounts.CreateAsync(account); adoxioLegalEntity.AdoxioAccountValueODataBind = _dynamicsClient.GetEntityURI("accounts", account.Accountid); } else { adoxioLegalEntity.AdoxioAccountValueODataBind = _dynamicsClient.GetEntityURI("accounts", item.account.id); } adoxioLegalEntity.AdoxioLegalEntityOwnedODataBind = _dynamicsClient.GetEntityURI("adoxio_legalentities", item.parentLegalEntityId); adoxioLegalEntity = await _dynamicsClient.Adoxiolegalentities.CreateAsync(adoxioLegalEntity); return(Json(adoxioLegalEntity.ToViewModel())); }
public async Task <IActionResult> DeleteDynamicsAccount(string id) { // verify the currently logged in user has access to this account Guid accountId = new Guid(id); if (!CurrentUserHasAccessToAccount(accountId)) { return(new NotFoundResult()); } // get the account MicrosoftDynamicsCRMaccount account = await _dynamicsClient.GetAccountById(accountId); if (account == null) { return(new NotFoundResult()); } // delete the associated LegalEntity MicrosoftDynamicsCRMadoxioLegalentity legalentity = await _dynamicsClient.GetAdoxioLegalentityByAccountId(accountId); if (legalentity != null) { _dynamicsClient.Adoxiolegalentities.Delete(legalentity.AdoxioLegalentityid); } await _dynamicsClient.Accounts.DeleteAsync(accountId.ToString()); return(NoContent()); // 204 }
public async Task <IActionResult> GetDynamicsLegalEntity(string id) { ViewModels.AdoxioLegalEntity result = null; // query the Dynamics system to get the legal entity record. if (string.IsNullOrEmpty(id)) { return(new NotFoundResult()); } else { // get the current user. string temp = _httpContextAccessor.HttpContext.Session.GetString("UserSettings"); UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp); Guid adoxio_legalentityid = new Guid(id); MicrosoftDynamicsCRMadoxioLegalentity adoxioLegalEntity = await _dynamicsClient.GetLegalEntityById(adoxio_legalentityid); //prevent getting legal entity data if the user is not associated with the account if (adoxioLegalEntity == null || !DynamicsExtensions.CurrentUserHasAccessToAccount(new Guid(adoxioLegalEntity._adoxioAccountValue), _httpContextAccessor, _dynamicsClient)) { return(new NotFoundResult()); } result = adoxioLegalEntity.ToViewModel(); } return(Json(result)); }
public async Task <IActionResult> DeleteDynamicsLegalEntity(string id) { // get the legal entity. Guid adoxio_legalentityid = new Guid(id); MicrosoftDynamicsCRMadoxioLegalentity legalEntity = await _dynamicsClient.GetLegalEntityById(adoxio_legalentityid); if (legalEntity == null) { return(new NotFoundResult()); } try { await _dynamicsClient.Legalentities.DeleteAsync(adoxio_legalentityid.ToString()); } catch (HttpOperationException httpOperationException) { _logger.LogError(httpOperationException, $"Error deleting legal entity: {httpOperationException.Request.Content} Response: {httpOperationException.Response.Content}"); } catch (Exception e) { _logger.LogError(e, $"Unexpected Exception while deleting legal entity"); } return(NoContent()); // 204 }
public async Task <IActionResult> GetApplicantDynamicsLegalEntity() { ViewModels.AdoxioLegalEntity result = null; // get the current user. string temp = _httpContextAccessor.HttpContext.Session.GetString("UserSettings"); UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp); // check that the session is setup correctly. userSettings.Validate(); // query the Dynamics system to get the legal entity record. MicrosoftDynamicsCRMadoxioLegalentity legalEntity = null; _logger.LogError("Find legal entity for applicant = " + userSettings.AccountId.ToString()); legalEntity = _dynamicsClient.GetAdoxioLegalentityByAccountId(Guid.Parse(userSettings.AccountId)); if (legalEntity == null) { return(new NotFoundResult()); } // fix the account. result = legalEntity.ToViewModel(); if (result.account == null) { MicrosoftDynamicsCRMaccount account = await _dynamicsClient.GetAccountById(Guid.Parse(userSettings.AccountId)); result.account = account.ToViewModel(); } return(Json(result)); }
public async Task <IActionResult> DeleteDynamicsLegalEntity(string id) { // get the legal entity. Guid adoxio_legalentityid = new Guid(id); MicrosoftDynamicsCRMadoxioLegalentity legalEntity = await _dynamicsClient.GetLegalEntityById(adoxio_legalentityid); if (legalEntity == null) { return(new NotFoundResult()); } try { await _dynamicsClient.Legalentities.DeleteAsync(adoxio_legalentityid.ToString()); } catch (OdataerrorException odee) { _logger.LogError("Error deleting legal entity"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new Exception("Unable to delete legal entity"); } return(NoContent()); // 204 }
public static MicrosoftDynamicsCRMadoxioLegalentity GetAdoxioLegalentityByAccountId(this IDynamicsClient _dynamicsClient, Guid id) { MicrosoftDynamicsCRMadoxioLegalentity result = null; string accountFilter = "_adoxio_account_value eq " + id.ToString(); IEnumerable <MicrosoftDynamicsCRMadoxioLegalentity> legalEntities = _dynamicsClient.Legalentities.Get(filter: accountFilter).Value; result = legalEntities.FirstOrDefault(); return(result); }
/// <summary> /// Convert a Dynamics Legal Entity to a ViewModel /// </summary> public static ViewModels.AdoxioLegalEntity ToViewModel(this MicrosoftDynamicsCRMadoxioLegalentity adoxio_legalentity) { ViewModels.AdoxioLegalEntity result = null; if (adoxio_legalentity != null) { result = new ViewModels.AdoxioLegalEntity(); if (adoxio_legalentity.AdoxioLegalentityid != null) { result.id = adoxio_legalentity.AdoxioLegalentityid.ToString(); } if (adoxio_legalentity._adoxioAccountValue != null) { result.accountId = adoxio_legalentity._adoxioAccountValue; } result.commonnonvotingshares = adoxio_legalentity.AdoxioCommonnonvotingshares; result.commonvotingshares = adoxio_legalentity.AdoxioCommonvotingshares; result.dateofbirth = adoxio_legalentity.AdoxioDateofbirth; result.firstname = adoxio_legalentity.AdoxioFirstname; result.interestpercentage = (decimal?)adoxio_legalentity.AdoxioInterestpercentage; // convert from int to bool. result.isindividual = (adoxio_legalentity.AdoxioIsindividual != null && adoxio_legalentity.AdoxioIsindividual != 0); result.lastname = adoxio_legalentity.AdoxioLastname; if (adoxio_legalentity.AdoxioLegalentitytype != null) { result.legalentitytype = (Adoxio_applicanttypecodes)adoxio_legalentity.AdoxioLegalentitytype; } result.middlename = adoxio_legalentity.AdoxioMiddlename; result.name = adoxio_legalentity.AdoxioName; result.email = adoxio_legalentity.AdoxioEmail; result.isPartner = (adoxio_legalentity.AdoxioIspartner == true); result.isShareholder = (adoxio_legalentity.AdoxioIsshareholder == true); // result.isTrustee = adoxio_legalentity.AdoxioIstrustee; // result.isOwner = adoxio_legalentity.AdoxioIsowner; result.isDirector = (adoxio_legalentity.AdoxioIsdirector == true); result.isOfficer = (adoxio_legalentity.AdoxioIsofficer == true); result.isSeniorManagement = (adoxio_legalentity.AdoxioIsseniormanagement == true); result.preferrednonvotingshares = adoxio_legalentity.AdoxioPreferrednonvotingshares; result.preferredvotingshares = adoxio_legalentity.AdoxioPreferredvotingshares; // convert from int to bool. result.sameasapplyingperson = (adoxio_legalentity.AdoxioSameasapplyingperson != null && adoxio_legalentity.AdoxioSameasapplyingperson != 0); result.dateofappointment = adoxio_legalentity.AdoxioDateofappointment; // populate the account. if (adoxio_legalentity.AdoxioAccount != null) { result.account = adoxio_legalentity.AdoxioAccount.ToViewModel(); } } return(result); }
/// <summary> /// Copy values from View Model to Dynamics legal entity /// </summary> /// <param name="to"></param> /// <param name="from"></param> public static void CopyValues(this MicrosoftDynamicsCRMadoxioLegalentity to, LegalEntity from) { to.AdoxioCommonnonvotingshares = from.commonnonvotingshares; to.AdoxioCommonvotingshares = from.commonvotingshares; to.AdoxioDateofbirth = from.dateofbirth; to.AdoxioFirstname = from.firstname; to.AdoxioInterestpercentage = from.interestpercentage; to.AdoxioIsindividual = (from.isindividual != null && (bool)from.isindividual) ? 1 : 0; to.AdoxioLastname = from.lastname; to.AdoxioIstrustee = from.IsTrustee; if (from.legalentitytype != null) { to.AdoxioLegalentitytype = (int?)from.legalentitytype; } if (from.partnerType != null) { to.AdoxioPartnertype = (int?)from.partnerType; } to.AdoxioMiddlename = from.middlename; to.AdoxioName = from.name; to.AdoxioIspartner = from.isPartner; to.AdoxioIsshareholder = from.isShareholder; to.AdoxioIstrustee = false; to.AdoxioIsdirector = from.isDirector; to.AdoxioIsofficer = from.isOfficer; to.AdoxioIsseniormanagement = from.isSeniorManagement; to.AdoxioIsowner = from.isOwner; to.AdoxioIskeypersonnel = from.isKeyPersonnel; to.AdoxioPreferrednonvotingshares = from.preferrednonvotingshares; to.AdoxioPreferredvotingshares = from.preferredvotingshares; to.AdoxioSameasapplyingperson = (from.sameasapplyingperson != null && (bool)from.sameasapplyingperson) ? 1 : 0; to.AdoxioEmail = from.email; to.AdoxioDateofappointment = from.dateofappointment; to.AdoxioDateofsharesissued = from.dateIssued; to.AdoxioJobtitle = from.jobTitle; to.AdoxioNumberofmembers = from.NumberOfMembers; to.AdoxioAnnualmembershipfee = from.AnnualMembershipFee; to.AdoxioTotalshares = from.TotalShares; // Assigning the account this way throws exception: // System.InvalidOperationException: Collection was modified; enumeration operation may not execute. //if (from.account.id != null) //{ // // fetch the account from Dynamics. // var getAccountTask = _system.GetAccountById(null, Guid.Parse(from.account.id)); // getAccountTask.Wait(); // to.Adoxio_Account= getAccountTask.Result; //} to.AdoxioDateemailsent = from.securityAssessmentEmailSentOn; }
public async Task <IActionResult> DeleteDynamicsLegalEntity(string id) { // get the legal entity. Guid adoxio_legalentityid = new Guid(id); MicrosoftDynamicsCRMadoxioLegalentity legalEntity = await _dynamicsClient.GetLegalEntityById(adoxio_legalentityid); if (legalEntity == null) { return(new NotFoundResult()); } await _dynamicsClient.Adoxiolegalentities.DeleteAsync(adoxio_legalentityid.ToString()); return(NoContent()); // 204 }
public async Task <IActionResult> UpdateDynamicsLegalEntity([FromBody] ViewModels.LegalEntity item, string id) { if (id != item.id) { return(BadRequest()); } // get the legal entity. Guid adoxio_legalentityid = new Guid(id); MicrosoftDynamicsCRMadoxioLegalentity adoxioLegalEntity = await _dynamicsClient.GetLegalEntityById(adoxio_legalentityid); if (adoxioLegalEntity == null) { return(new NotFoundResult()); } // we are doing a patch, so wipe out the record. adoxioLegalEntity = new MicrosoftDynamicsCRMadoxioLegalentity(); // copy values over from the data provided adoxioLegalEntity.CopyValues(item); try { _dynamicsClient.Legalentities.Update(adoxio_legalentityid.ToString(), adoxioLegalEntity); } catch (HttpOperationException httpOperationException) { _logger.LogError(httpOperationException, $"Error updating legal entity: {httpOperationException.Request.Content} Response: {httpOperationException.Response.Content}"); } catch (Exception e) { _logger.LogError(e, $"Unexpected Exception while updating legal entity"); } adoxioLegalEntity = await _dynamicsClient.GetLegalEntityById(adoxio_legalentityid); return(new JsonResult(adoxioLegalEntity.ToViewModel())); }
/// <summary> /// Copy values from View Model to Dynamics legal entity /// </summary> /// <param name="to"></param> /// <param name="from"></param> public static void CopyValues(this MicrosoftDynamicsCRMadoxioLegalentity to, ViewModels.AdoxioLegalEntity from) { to.AdoxioCommonnonvotingshares = from.commonnonvotingshares; to.AdoxioCommonvotingshares = from.commonvotingshares; to.AdoxioDateofbirth = from.dateofbirth; to.AdoxioFirstname = from.firstname; to.AdoxioInterestpercentage = (double?)from.interestpercentage; to.AdoxioIsindividual = (from.isindividual != null && (bool)from.isindividual) ? 1 : 0; to.AdoxioLastname = from.lastname; if (from.legalentitytype != null) { to.AdoxioLegalentitytype = (int?)from.legalentitytype; } to.AdoxioMiddlename = from.middlename; to.AdoxioName = from.name; to.AdoxioIspartner = from.isPartner; to.AdoxioIsshareholder = from.isShareholder; to.AdoxioIstrustee = false; to.AdoxioIsdirector = from.isDirector; to.AdoxioIsofficer = from.isOfficer; to.AdoxioIsseniormanagement = from.isSeniorManagement; to.AdoxioIsowner = false; to.AdoxioPreferrednonvotingshares = from.preferrednonvotingshares; to.AdoxioPreferredvotingshares = from.preferredvotingshares; to.AdoxioSameasapplyingperson = (from.sameasapplyingperson != null && (bool)from.sameasapplyingperson) ? 1 : 0; to.AdoxioEmail = from.email; to.AdoxioDateofappointment = from.dateofappointment; // Assigning the account this way throws exception: // System.InvalidOperationException: Collection was modified; enumeration operation may not execute. //if (from.account.id != null) //{ // // fetch the account from Dynamics. // var getAccountTask = _system.GetAccountById(null, Guid.Parse(from.account.id)); // getAccountTask.Wait(); // to.Adoxio_Account= getAccountTask.Result; //} // adoxio_dateemailsent }
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 async Task <IActionResult> CreateDynamicsAccount([FromBody] ViewModels.Account item) { ViewModels.Account result = null; Boolean updateIfNull = true; // get UserSettings from the session string temp = _httpContextAccessor.HttpContext.Session.GetString("UserSettings"); UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp); // get account Siteminder GUID string accountSiteminderGuid = userSettings.SiteMinderBusinessGuid; if (accountSiteminderGuid == null || accountSiteminderGuid.Length == 0) { throw new Exception("Oops no accountSiteminderGuid exernal id"); } // first check to see that a contact exists. string contactSiteminderGuid = userSettings.SiteMinderGuid; if (contactSiteminderGuid == null || contactSiteminderGuid.Length == 0) { throw new Exception("Oops no ContactSiteminderGuid exernal id"); } // get BCeID record for the current user //var bceidBusiness = await _bceid.ProcessBusinessQuery("44437132CF6B4E919FE6FBFC5594FC44"); var bceidBusiness = await _bceid.ProcessBusinessQuery(userSettings.SiteMinderGuid); // get the contact record. MicrosoftDynamicsCRMcontact userContact = null; // see if the contact exists. userContact = await _dynamicsClient.GetContactBySiteminderGuid(contactSiteminderGuid); if (userContact == null) { // create the user contact record. userContact = new MicrosoftDynamicsCRMcontact(); // Adoxio_externalid is where we will store the guid from siteminder. userContact.AdoxioExternalid = contactSiteminderGuid; userContact.Fullname = userSettings.UserDisplayName; userContact.Nickname = userSettings.UserDisplayName; userContact.Employeeid = 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); if (account == null) // do a deep create. create 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.Adoxio_applicanttypecodes), item.businessType, true); // ensure that we create an account for the current user. account.AdoxioExternalid = accountSiteminderGuid; account.Primarycontactid = userContact; account.AdoxioAccounttype = (int)Adoxio_accounttypecodes.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(Adoxio_applicanttypecodes), item.businessType, true); var legalEntity = new MicrosoftDynamicsCRMadoxioLegalentity() { AdoxioAccount = account, AdoxioName = item.name, AdoxioIsindividual = 0, AdoxioIsapplicant = true }; string legalEntityString = JsonConvert.SerializeObject(legalEntity); _logger.LogError("Legal Entity Before --> " + legalEntityString); legalEntity = await _dynamicsClient.Adoxiolegalentities.CreateAsync(legalEntity); 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.LogError("Legal Entity After --> " + legalEntityString); } else // it is a new user only. { userContact = await _dynamicsClient.Contacts.CreateAsync(userContact); } // always patch 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("Error binding contact to account"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); } // 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.SmUserId = userSettings.UserId; userSettings.AuthenticatedUser = user; } userSettings.IsNewUserRegistration = false; string userSettingsString = JsonConvert.SerializeObject(userSettings); _logger.LogError("AccountController --> " + userSettingsString); // add the user to the session. _httpContextAccessor.HttpContext.Session.SetString("UserSettings", userSettingsString); } else { throw new Exception("Oops not a new user registration"); } //account.accountId = id; result = account.ToViewModel(); return(Json(result)); }
/// <summary> /// Update entity in adoxio_legalentities /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioLegalentityid'> /// key: adoxio_legalentityid /// </param> /// <param name='body'> /// New property values /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateAsync(this IAdoxiolegalentities operations, string adoxioLegalentityid, MicrosoftDynamicsCRMadoxioLegalentity body, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdateWithHttpMessagesAsync(adoxioLegalentityid, body, null, cancellationToken).ConfigureAwait(false)).Dispose(); }
/// <summary> /// Update entity in adoxio_legalentities /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioLegalentityid'> /// key: adoxio_legalentityid /// </param> /// <param name='body'> /// New property values /// </param> public static void Update(this IAdoxiolegalentities operations, string adoxioLegalentityid, MicrosoftDynamicsCRMadoxioLegalentity body) { operations.UpdateAsync(adoxioLegalentityid, body).GetAwaiter().GetResult(); }
/// <summary> /// Add new entity to adoxio_legalentities /// </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 <MicrosoftDynamicsCRMadoxioLegalentity> CreateAsync(this IAdoxiolegalentities operations, MicrosoftDynamicsCRMadoxioLegalentity 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_legalentities /// </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 MicrosoftDynamicsCRMadoxioLegalentity Create(this IAdoxiolegalentities operations, MicrosoftDynamicsCRMadoxioLegalentity body, string prefer = "return=representation") { return(operations.CreateAsync(body, prefer).GetAwaiter().GetResult()); }
/// <summary> /// Add new entity to adoxio_legalentities /// </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 <MicrosoftDynamicsCRMadoxioLegalentity> CreateWithHttpMessages(this ILegalentities operations, MicrosoftDynamicsCRMadoxioLegalentity body, string prefer = "return=representation", Dictionary <string, List <string> > customHeaders = null) { return(operations.CreateWithHttpMessagesAsync(body, prefer, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult()); }
public List <MicrosoftDynamicsCRMadoxioLegalentity> ObfuscateLegalEntities(List <MicrosoftDynamicsCRMadoxioLegalentity> legalEntities) { List <MicrosoftDynamicsCRMadoxioLegalentity> result = new List <MicrosoftDynamicsCRMadoxioLegalentity>(); foreach (var legalEntity in legalEntities) { string firstName = RandomFirstName(); string lastName = RandomLastName(); var newItem = new MicrosoftDynamicsCRMadoxioLegalentity() { AdoxioLegalentityid = Guid.NewGuid().ToString(), AdoxioCommonnonvotingshares = legalEntity.AdoxioCommonnonvotingshares, AdoxioCommonvotingshares = legalEntity.AdoxioCommonvotingshares, AdoxioDateofbirth = RandomDateInPast(), AdoxioFirstname = firstName, AdoxioLastname = lastName, AdoxioInterestpercentage = legalEntity.AdoxioInterestpercentage, AdoxioIsindividual = legalEntity.AdoxioIsindividual, AdoxioLegalentitytype = legalEntity.AdoxioLegalentitytype, AdoxioPartnertype = legalEntity.AdoxioPartnertype, AdoxioName = firstName + " " + lastName, AdoxioEmail = RandomEmail(), AdoxioIspartner = legalEntity.AdoxioIspartner, AdoxioIsapplicant = legalEntity.AdoxioIsapplicant, AdoxioIsshareholder = legalEntity.AdoxioIsshareholder, AdoxioIsdirector = legalEntity.AdoxioIsdirector, AdoxioIsofficer = legalEntity.AdoxioIsofficer, AdoxioIsseniormanagement = legalEntity.AdoxioIsseniormanagement, AdoxioPreferrednonvotingshares = legalEntity.AdoxioPreferrednonvotingshares, AdoxioPreferredvotingshares = legalEntity.AdoxioPreferredvotingshares, AdoxioSameasapplyingperson = legalEntity.AdoxioSameasapplyingperson }; if (legalEntity._adoxioAccountValue != null) { newItem.AdoxioAccount = new MicrosoftDynamicsCRMaccount() { Accountid = AccountMap[legalEntity._adoxioAccountValue] }; } if (legalEntity._adoxioShareholderaccountidValue != null) { newItem.AdoxioShareholderAccountID = new MicrosoftDynamicsCRMaccount() { Accountid = AccountMap[legalEntity._adoxioShareholderaccountidValue] }; } // parent legal entity if (legalEntity._adoxioLegalentityownedValue != null) { newItem.AdoxioLegalEntityOwned = new MicrosoftDynamicsCRMadoxioLegalentity() { AdoxioLegalentityid = legalEntity._adoxioLegalentityownedValue }; } if (legalEntity.AdoxioDateemailsent != null) { newItem.AdoxioDateemailsent = RandomDateInPast(); } if (legalEntity.AdoxioDateofappointment != null) { newItem.AdoxioDateofappointment = RandomDateInPast(); } LegalEntityMap.Add(legalEntity.AdoxioLegalentityid, newItem.AdoxioLegalentityid); result.Add(newItem); } // second pass to fix the parent child relationship for legalEntities foreach (var legalEntity in result) { if (legalEntity.AdoxioLegalEntityOwned != null) { legalEntity.AdoxioLegalEntityOwned.AdoxioLegalentityid = LegalEntityMap[legalEntity.AdoxioLegalEntityOwned.AdoxioLegalentityid]; } } return(result); }
public async Task <IActionResult> SendConsentRequests(string id, [FromBody] List <string> recipientIds) { // start by getting the record for the current legal entity. // get the current user. string temp = _httpContextAccessor.HttpContext.Session.GetString("UserSettings"); UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp); // check that the session is setup correctly. userSettings.Validate(); var userAccount = await _dynamicsClient.GetAccountById(Guid.Parse(userSettings.AccountId)); MicrosoftDynamicsCRMadoxioLegalentity userLegalentity = _dynamicsClient.GetAdoxioLegalentityByAccountId(Guid.Parse(userSettings.AccountId)); // get the legal entity. Guid adoxio_legalentityid = new Guid(id); // TODO verify that this is the current user's legal entity var adoxioLegalEntity = await _dynamicsClient.GetLegalEntityById(adoxio_legalentityid); // now get each of the supplied ids and send an email to them. foreach (string recipientId in recipientIds) { Guid recipientIdGuid = new Guid(recipientId); // TODO verify that each recipient is part of the current user's user set // TODO switch over to new AuthAPI framework var recipientEntity = await _dynamicsClient.GetLegalEntityById(recipientIdGuid); string email = recipientEntity.AdoxioEmail; string firstname = recipientEntity.AdoxioFirstname; string lastname = recipientEntity.AdoxioLastname; string confirmationEmailLink = GetConsentLink(email, recipientId, id); string bclogo = Configuration["BASE_URI"] + Configuration["BASE_PATH"] + "/assets/bc-logo.svg"; /* send the user an email confirmation. */ string body = "<img src='" + bclogo + "'/><br><h2>Security Screening and Financial Integrity Checks</h2>" + "<p>" + "Dear " + firstname + " " + lastname + "," + "</p>" + "<p>" + "An application from " + "[TBD Company Name]" + " has been submitted for a non-medical retail cannabis licence in British Columbia. " + "As a " + "[TBD Position]" + " of " + "[TBD Company Name]" + " you are required to authorize a security screening — including criminal and police record checks—" + "and financial integrity checks as part of the application process. " + "</p>" + "<p>" + "Where you reside will determine how you are able to authorize the security screening." + "</p>" + "<p><strong>B.C. Residents</strong></p>" + "<p>" + "Residents of B.C. require a Photo B.C. Services Card to login to the application. A Services Card " + "verifies your identity, and has enhanced levels of security making the card more secure and helps protect your privacy." + "</p>" + "<p>" + "If you don’t have a B.C. Services Card, or haven’t activated it for online login, visit the B.C. Services Card website to find how to get a card." + "</p>" + "<p>" + "After you receive your verified Photo B.C. Services Card, login through this unique link:" + "</p>" + "<p><a href='" + confirmationEmailLink + "'>" + confirmationEmailLink + "</a></p>" + "<p><strong>Out of Province Residents</strong></p>" + "<p>TBD</p>" + "<p><strong>Residents Outside of Canada</strong></p>" + "<p>TBD</p>" + "<p>If you have any questions about the security authorization, contact [email protected]</p>" + "<p>Do not reply to this email address</p>"; // send the email. SmtpClient client = new SmtpClient(Configuration["SMTP_HOST"]); // Specify the message content. MailMessage message = new MailMessage("*****@*****.**", email); message.Subject = "BC LCLB Cannabis Licensing Security Consent"; message.Body = body; message.IsBodyHtml = true; client.Send(message); // save the consent link and the fact that the email has been sent MicrosoftDynamicsCRMadoxioLegalentity patchEntity = new MicrosoftDynamicsCRMadoxioLegalentity(); patchEntity.AdoxioDateemailsent = DateTime.Now; // patch the record. try { await _dynamicsClient.Legalentities.UpdateAsync(adoxioLegalEntity.AdoxioLegalentityid, patchEntity); } catch (OdataerrorException odee) { _logger.LogError("Error updating date email sent."); _logger.LogError(odee.Request.RequestUri.ToString()); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); } } return(NoContent()); // 204 }
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())); }
public async Task <IActionResult> CreateDynamicsLegalEntity([FromBody] ViewModels.AdoxioLegalEntity item) { // create a new legal entity. MicrosoftDynamicsCRMadoxioLegalentity adoxioLegalEntity = new MicrosoftDynamicsCRMadoxioLegalentity(); // get the current user. string temp = _httpContextAccessor.HttpContext.Session.GetString("UserSettings"); UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp); // check that the session is setup correctly. userSettings.Validate(); // copy received values to Dynamics LegalEntity adoxioLegalEntity.CopyValues(item); try { adoxioLegalEntity = await _dynamicsClient.Legalentities.CreateAsync(adoxioLegalEntity); } catch (OdataerrorException odee) { _logger.LogError("Error creating legal entity"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new Exception("Unable to create legal entity"); } // setup navigation properties. MicrosoftDynamicsCRMadoxioLegalentity patchEntity = new MicrosoftDynamicsCRMadoxioLegalentity(); Guid accountId = Guid.Parse(userSettings.AccountId); var userAccount = await _dynamicsClient.GetAccountById(accountId); patchEntity.AdoxioAccountValueODataBind = _dynamicsClient.GetEntityURI("accounts", accountId.ToString()); // patch the record. try { await _dynamicsClient.Legalentities.UpdateAsync(adoxioLegalEntity.AdoxioLegalentityid, patchEntity); } catch (OdataerrorException odee) { _logger.LogError("Error patching legal entity"); _logger.LogError(odee.Request.RequestUri.ToString()); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); } // TODO take the default for now from the parent account's legal entity record // TODO likely will have to re-visit for shareholders that are corporations/organizations MicrosoftDynamicsCRMadoxioLegalentity tempLegalEntity = _dynamicsClient.GetAdoxioLegalentityByAccountId(Guid.Parse(userSettings.AccountId)); if (tempLegalEntity != null) { Guid tempLegalEntityId = Guid.Parse(tempLegalEntity.AdoxioLegalentityid); // see https://msdn.microsoft.com/en-us/library/mt607875.aspx patchEntity = new MicrosoftDynamicsCRMadoxioLegalentity(); patchEntity.AdoxioLegalEntityOwnedODataBind = _dynamicsClient.GetEntityURI("adoxio_legalentities", tempLegalEntityId.ToString()); // patch the record. try { await _dynamicsClient.Legalentities.UpdateAsync(adoxioLegalEntity.AdoxioLegalentityid, patchEntity); } catch (OdataerrorException odee) { _logger.LogError("Error adding LegalEntityOwned reference to legal entity"); _logger.LogError(odee.Request.RequestUri.ToString()); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); } } return(Json(adoxioLegalEntity.ToViewModel())); }
/// <summary> /// Update entity in adoxio_legalentities /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioLegalentityid'> /// key: adoxio_legalentityid of adoxio_legalentity /// </param> /// <param name='body'> /// New property values /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse UpdateWithHttpMessages(this ILegalentities operations, string adoxioLegalentityid, MicrosoftDynamicsCRMadoxioLegalentity body, Dictionary <string, List <string> > customHeaders = null) { return(operations.UpdateWithHttpMessagesAsync(adoxioLegalentityid, body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult()); }
/// <summary> /// Update entity in adoxio_legalentities /// </summary> /// <param name='adoxioLegalentityid'> /// key: adoxio_legalentityid /// </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="OdataerrorException"> /// 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 adoxioLegalentityid, MicrosoftDynamicsCRMadoxioLegalentity body, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (adoxioLegalentityid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "adoxioLegalentityid"); } 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("adoxioLegalentityid", adoxioLegalentityid); 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_legalentities({adoxio_legalentityid})").ToString(); _url = _url.Replace("{adoxio_legalentityid}", System.Uri.EscapeDataString(adoxioLegalentityid)); // 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 OdataerrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Odataerror _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Odataerror>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } 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> /// Convert a Dynamics Legal Entity to a ViewModel /// </summary> public static ViewModels.LegalEntity ToViewModel(this MicrosoftDynamicsCRMadoxioLegalentity adoxio_legalentity) { ViewModels.LegalEntity result = null; if (adoxio_legalentity != null) { result = new ViewModels.LegalEntity(); if (adoxio_legalentity.AdoxioLegalentityid != null) { result.id = adoxio_legalentity.AdoxioLegalentityid.ToString(); } if (adoxio_legalentity._adoxioAccountValue != null) { result.accountId = adoxio_legalentity._adoxioAccountValue; } if (adoxio_legalentity._adoxioShareholderaccountidValue != null) { result.shareholderAccountId = adoxio_legalentity._adoxioShareholderaccountidValue; } result.parentLegalEntityId = adoxio_legalentity._adoxioLegalentityownedValue; result.commonnonvotingshares = adoxio_legalentity.AdoxioCommonnonvotingshares; result.commonvotingshares = adoxio_legalentity.AdoxioCommonvotingshares; result.dateofbirth = adoxio_legalentity.AdoxioDateofbirth; result.firstname = adoxio_legalentity.AdoxioFirstname; if (adoxio_legalentity.AdoxioInterestpercentage != null) { result.interestpercentage = Convert.ToDecimal(adoxio_legalentity.AdoxioInterestpercentage); } // convert from int to bool. result.isindividual = (adoxio_legalentity.AdoxioIsindividual != null && adoxio_legalentity.AdoxioIsindividual != 0); result.lastname = adoxio_legalentity.AdoxioLastname; if (adoxio_legalentity.AdoxioLegalentitytype != null) { result.legalentitytype = (AdoxioApplicantTypeCodes)adoxio_legalentity.AdoxioLegalentitytype; } if (adoxio_legalentity.AdoxioPartnertype != null) { result.partnerType = (AdoxioPartnerType)adoxio_legalentity.AdoxioPartnertype; } result.middlename = adoxio_legalentity.AdoxioMiddlename; result.name = adoxio_legalentity.AdoxioName; result.email = adoxio_legalentity.AdoxioEmail; result.isPartner = (adoxio_legalentity.AdoxioIspartner == true); result.isApplicant = (adoxio_legalentity.AdoxioIsapplicant == true); result.isShareholder = (adoxio_legalentity.AdoxioIsshareholder == true); // result.isTrustee = adoxio_legalentity.AdoxioIstrustee; result.isDirector = (adoxio_legalentity.AdoxioIsdirector == true); result.isOfficer = (adoxio_legalentity.AdoxioIsofficer == true); result.isSeniorManagement = (adoxio_legalentity.AdoxioIsseniormanagement == true); result.isOwner = (adoxio_legalentity.AdoxioIsowner == true); result.isKeyPersonnel = (adoxio_legalentity.AdoxioIskeypersonnel == true); result.preferrednonvotingshares = adoxio_legalentity.AdoxioPreferrednonvotingshares; result.preferredvotingshares = adoxio_legalentity.AdoxioPreferredvotingshares; // convert from int to bool. result.sameasapplyingperson = (adoxio_legalentity.AdoxioSameasapplyingperson != null && adoxio_legalentity.AdoxioSameasapplyingperson != 0); result.dateofappointment = adoxio_legalentity.AdoxioDateofappointment; result.dateIssued = adoxio_legalentity.AdoxioDateofsharesissued; result.securityAssessmentEmailSentOn = adoxio_legalentity.AdoxioDateemailsent; result.jobTitle = adoxio_legalentity.AdoxioJobtitle; // populate the account. if (adoxio_legalentity.AdoxioAccount != null) { result.account = adoxio_legalentity.AdoxioAccount.ToViewModel(); } } return(result); }