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)); }
// the one parameter is the BCeID guid for an individual. static void Main(string[] args) { bool isBackfill = false; bool isSingleQuery = false; string singleQuery = null; if (args.Length > 0) { string arg = args[0]; if (!string.IsNullOrEmpty(arg)) { if (arg.ToLower().Equals("backfill")) { isBackfill = true; Console.Out.WriteLine("Backfill enabled."); } else { isSingleQuery = true; singleQuery = arg; Console.Out.WriteLine("Single query enabled."); } } } // get the environment settings. string bceidServiceSvcid = Environment.GetEnvironmentVariable("BCEID_SERVICE_SVCID"); string bceidServiceUser = Environment.GetEnvironmentVariable("BCEID_SERVICE_USER"); string bceidServicePasswd = Environment.GetEnvironmentVariable("BCEID_SERVICE_PASSWD"); string bceidServiceUrl = Environment.GetEnvironmentVariable("BCEID_SERVICE_URL"); string dynamicsOdataUri = Environment.GetEnvironmentVariable("DYNAMICS_ODATA_URI"); string ssgUsername = Environment.GetEnvironmentVariable("SSG_USERNAME"); string ssgPassword = Environment.GetEnvironmentVariable("SSG_PASSWORD"); string dynamicsNativeOdataUri = Environment.GetEnvironmentVariable("DYNAMICS_NATIVE_ODATA_URI"); BCeIDBusinessQuery bCeIDBusinessQuery = new BCeIDBusinessQuery(bceidServiceSvcid, bceidServiceUser, bceidServicePasswd, bceidServiceUrl); var serviceClientCredentials = new BasicAuthenticationCredentials() { UserName = ssgUsername, Password = ssgPassword }; var _dynamicsClient = new DynamicsClient(new Uri(dynamicsOdataUri), serviceClientCredentials); if (isBackfill) { var contacts = _dynamicsClient.Contacts.Get().Value; foreach (MicrosoftDynamicsCRMcontact contact in contacts) { if (string.IsNullOrEmpty(contact.Emailaddress1)) { string externalId = contact.AdoxioExternalid; if (!string.IsNullOrEmpty(externalId)) { var caller = bCeIDBusinessQuery.ProcessBusinessQuery(externalId); caller.Wait(); Gov.Lclb.Cllb.Interfaces.BCeIDBusiness bceidBusiness = caller.Result; if (bceidBusiness != null) { MicrosoftDynamicsCRMcontact patchRecord = new MicrosoftDynamicsCRMcontact(); if (string.IsNullOrEmpty(contact.Firstname)) { patchRecord.Firstname = bceidBusiness.individualFirstname; } if (string.IsNullOrEmpty(contact.Lastname)) { patchRecord.Lastname = bceidBusiness.individualSurname; } if (string.IsNullOrEmpty(contact.Middlename)) { patchRecord.Middlename = bceidBusiness.individualMiddlename; } if (string.IsNullOrEmpty(contact.Emailaddress1)) { patchRecord.Emailaddress1 = bceidBusiness.contactEmail; } if (string.IsNullOrEmpty(contact.Telephone1)) { patchRecord.Telephone1 = bceidBusiness.contactPhone; } // update the contact. try { _dynamicsClient.Contacts.Update(contact.Contactid, patchRecord); Console.Out.WriteLine("Updated contact " + contact.Firstname + " " + contact.Lastname); } catch (OdataerrorException odee) { Console.Out.WriteLine("Error patching contact"); Console.Out.WriteLine("Request:"); Console.Out.WriteLine(odee.Request.Content); Console.Out.WriteLine("Response:"); Console.Out.WriteLine(odee.Response.Content); } } } } } IList <MicrosoftDynamicsCRMaccount> accounts = null; // now get a list of all the related accounts. try { accounts = _dynamicsClient.Accounts.Get().Value; } catch (OdataerrorException odee) { Console.Out.WriteLine("Error getting accounts"); Console.Out.WriteLine("Request:"); Console.Out.WriteLine(odee.Request.Content); Console.Out.WriteLine("Response:"); Console.Out.WriteLine(odee.Response.Content); } if (accounts != null) { foreach (var account in accounts) { // get the contact. string contactid = account._primarycontactidValue; // only process accounts with missing email address. if (!string.IsNullOrEmpty(contactid) && string.IsNullOrEmpty(account.Emailaddress1)) { var contact = _dynamicsClient.Contacts.GetByKey(contactid); string guid = contact.AdoxioExternalid; if (!string.IsNullOrEmpty(guid)) { var caller = bCeIDBusinessQuery.ProcessBusinessQuery(guid); caller.Wait(); Gov.Lclb.Cllb.Interfaces.BCeIDBusiness bceidBusiness = caller.Result; if (bceidBusiness != null) { MicrosoftDynamicsCRMaccount accountPatchRecord = new MicrosoftDynamicsCRMaccount(); if (string.IsNullOrEmpty(account.Emailaddress1)) { accountPatchRecord.Emailaddress1 = bceidBusiness.contactEmail; } if (string.IsNullOrEmpty(account.Telephone1)) { accountPatchRecord.Telephone1 = bceidBusiness.contactEmail; } if (string.IsNullOrEmpty(account.Address1City)) { accountPatchRecord.Address1City = bceidBusiness.addressCity; } if (string.IsNullOrEmpty(account.Address1Postalcode)) { accountPatchRecord.Address1Postalcode = bceidBusiness.addressPostal; } if (string.IsNullOrEmpty(account.Address1Line1)) { accountPatchRecord.Address1Line1 = bceidBusiness.addressLine1; } if (string.IsNullOrEmpty(account.Address1Line2)) { accountPatchRecord.Address1Line2 = bceidBusiness.addressLine2; } try { _dynamicsClient.Accounts.Update(account.Accountid, accountPatchRecord); Console.Out.WriteLine("Updated account " + account.Name); } catch (OdataerrorException odee) { Console.Out.WriteLine("Error patching account"); Console.Out.WriteLine("Request:"); Console.Out.WriteLine(odee.Request.Content); Console.Out.WriteLine("Response:"); Console.Out.WriteLine(odee.Response.Content); } } } } } } } else if (isSingleQuery) { Console.Out.WriteLine("\"BCEID GUID\",\"Given name\",\"Surname\",\"Email\",\"Phone\",\"Business Number\""); // query BCeID if (!string.IsNullOrEmpty(singleQuery)) { var caller = bCeIDBusinessQuery.ProcessBusinessQuery(singleQuery); caller.Wait(); var result = caller.Result; if (result != null) { Console.Out.WriteLine("\"" + singleQuery + "\",\"" + result.individualFirstname + "\",\"" + result.individualSurname + "\",\"" + result.contactEmail + "\",\"" + result.contactPhone + "\",\"" + result.businessNumber + "\""); } } } else // get all contacts. { // first parse the contacts file. List <string> stringList = new List <string>(); // read from file. /* * string jsonString = File.ReadAllText("filename"); * * var jsonData = JsonConvert.DeserializeObject<GetOKResponseModelModelModelModelModelModelModelModel>(jsonString); * var contacts = jsonData.Value; */ // Get contacts from dynamics. var contacts = _dynamicsClient.Contacts.Get().Value; foreach (var contact in contacts) { stringList.Add(contact.AdoxioExternalid); } Console.Out.WriteLine("\"BCEID GUID\",\"Given name\",\"Surname\",\"Email\",\"Phone\",\"Business Number\""); foreach (string guid in stringList) { // query BCeID if (!string.IsNullOrEmpty(guid)) { var caller = bCeIDBusinessQuery.ProcessBusinessQuery(guid); caller.Wait(); var result = caller.Result; if (result != null) { Console.Out.WriteLine("\"" + guid + "\",\"" + result.individualFirstname + "\",\"" + result.individualSurname + "\",\"" + result.contactEmail + "\",\"" + result.contactPhone + "\",\"" + result.businessNumber + "\""); } } } } }
public async Task <BCeIDBusiness> ProcessBusinessQuery(string guid) { if (String.IsNullOrEmpty(url)) { return(null); } // create the SOAP client //var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); BasicHttpsBinding binding = new BasicHttpsBinding { MaxReceivedMessageSize = int.MaxValue }; binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; binding.CloseTimeout = new TimeSpan(0, 10, 0); EndpointAddress address = new EndpointAddress(url); var client = new BCeIDServiceSoapClient(binding, address); client.ClientCredentials.UserName.UserName = user; client.ClientCredentials.UserName.Password = password; var n_guid = NormalizeGuid(guid); // SOAP request and parameters var myparams = new AccountDetailRequest(); myparams.onlineServiceId = svcid; myparams.requesterUserGuid = n_guid; myparams.requesterAccountTypeCode = BCeIDAccountTypeCode.Business; myparams.userGuid = n_guid; myparams.accountTypeCode = BCeIDAccountTypeCode.Business; try { var response = await client.getAccountDetailAsync(myparams); if (response.code == ResponseCode.Success) { var business = new BCeIDBusiness(); BCeIDAccount account = response.account; business.contactEmail = account.contact.email.value; business.contactPhone = account.contact.telephone.value; business.individualFirstname = account.individualIdentity.name.firstname.value; business.individualMiddlename = account.individualIdentity.name.middleName.value; business.individualOtherMiddlename = account.individualIdentity.name.otherMiddleName.value; business.individualSurname = account.individualIdentity.name.surname.value; business.businessTypeName = account.business.type.name; business.businessTypeDescription = account.business.type.description; business.businessTypeCode = account.business.type.code.ToString(); business.businessTypeOther = account.business.businessTypeOther.value; business.legalName = account.business.legalName.value; business.businessNumber = account.business.businessNumber.value; business.incorporationNumber = account.business.incorporationNumber.value; business.jurisdictionOfIncorporation = account.business.jurisdictionOfIncorporation.value; business.addressLine1 = account.business.address.addressLine1.value; business.addressLine2 = account.business.address.addressLine2.value; business.addressCity = account.business.address.city.value; business.addressProv = account.business.address.province.value; business.addressPostal = account.business.address.postal.value; business.addressCountry = account.business.address.country.value; return(business); } } catch (Exception) { // ignore errors and just return null } return(null); }