public async Task <IActionResult> CreateAccount([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; // 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"); } // validate contact Siteminder GUID 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.Jag.PillPressRegistry.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)); MicrosoftDynamicsCRMcontact userContact = null; // see if the contact exists. try { userContact = _dynamicsClient.GetContactByExternalId(contactSiteminderGuid); } 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.Externaluseridentifier = sanitizedContactSiteminderId; userContact.BcgovBceiduserguid = sanitizedContactSiteminderId; userContact.Fullname = userSettings.UserDisplayName; userContact.Nickname = userSettings.UserDisplayName; // ENABLE FOR BC SERVICE CARD SUPPORT /* * if (! Guid.TryParse(userSettings.UserId, out tryParseOutGuid)) * { * 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; userContact.BcgovBceid = bceidBusiness.userId; userContact.BcgovBceidemail = bceidBusiness.contactEmail; } else { userContact.Firstname = userSettings.UserDisplayName.GetFirstName(); userContact.Lastname = userSettings.UserDisplayName.GetLastName(); } userContact.Statuscode = 1; _logger.LogDebug(LoggingEvents.HttpGet, "Account is NOT null. Only a new user."); try { userContact = await _dynamicsClient.Contacts.CreateAsync(userContact); } catch (OdataerrorException odee) { _logger.LogError(LoggingEvents.Error, "Error creating user contact."); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new OdataerrorException("Error creating user contact."); } } // 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) { _logger.LogDebug(LoggingEvents.HttpGet, "Creating account"); // create a new account account = new MicrosoftDynamicsCRMaccount(); account.CopyValues(item); // business type must be set only during creation, not in update (removed from copyValues() ) // by convention we strip out any dashes present in the guid, and force it to uppercase. string sanitizedAccountSiteminderId = GuidUtility.SanitizeGuidString(accountSiteminderGuid); account.BcgovBceid = sanitizedAccountSiteminderId; UpdateContacts(item); // For Pill Press the Primary Contact is not set to default to the first user. if (item.primaryContact != null && !(string.IsNullOrEmpty(item.primaryContact.id))) { // add as a reference. account.PrimaryContactidODataBind = _dynamicsClient.GetEntityURI("contacts", item.primaryContact.id); } // Additional Contact if (item.additionalContact != null && !(string.IsNullOrEmpty(item.additionalContact.id))) { // add as a reference. account.AdditionalContactODataBind = _dynamicsClient.GetEntityURI("contacts", item.additionalContact.id); } if (bceidBusiness != null) { account.Name = bceidBusiness.legalName; account.BcgovDoingbusinessasname = bceidBusiness.legalName; account.Emailaddress1 = bceidBusiness.contactEmail; account.Telephone1 = bceidBusiness.contactPhone; // do not set the address from BCeID for Pill Press. /* * account.Address1City = bceidBusiness.addressCity; * account.Address1Postalcode = bceidBusiness.addressPostal; * account.Address1Line1 = bceidBusiness.addressLine1; * account.Address1Line2 = bceidBusiness.addressLine2; * account.Address1Postalcode = bceidBusiness.addressPostal; */ } else // likely a dev login. { account.Name = userSettings.BusinessLegalName; account.BcgovDoingbusinessasname = userSettings.BusinessLegalName; } // set the Province and Country if they are not set. if (string.IsNullOrEmpty(account.Address1Stateorprovince)) { account.Address1Stateorprovince = "British Columbia"; } if (string.IsNullOrEmpty(account.Address1Country)) { account.Address1Country = "Canada"; } string accountString = JsonConvert.SerializeObject(account); _logger.LogDebug("Account before creation in dynamics --> " + accountString); try { account = await _dynamicsClient.Accounts.CreateAsync(account); } catch (OdataerrorException odee) { _logger.LogError(LoggingEvents.Error, "Error creating Account."); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new OdataerrorException("Error creating Account"); } // create a document location await CreateAccountDocumentLocation(account); // populate child elements. account = _dynamicsClient.GetAccountByIdWithChildren(Guid.Parse(account.Accountid)); accountString = JsonConvert.SerializeObject(accountString); _logger.LogDebug("Account Entity after creation in dynamics --> " + accountString); } // 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; } // create the bridge entity for the BCeID user _dynamicsClient.CreateBusinessContactLink(_logger, userSettings.ContactId, userSettings.AccountId, null, (int?)ContactTypeCodes.BCeID, "BCeID"); 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."); } // create the business contact links. if (item.primaryContact != null) { _dynamicsClient.CreateBusinessContactLink(_logger, item.primaryContact.id, account.Accountid, null, (int?)ContactTypeCodes.Primary, item.primaryContact.title); } if (item.additionalContact != null) { _dynamicsClient.CreateBusinessContactLink(_logger, item.additionalContact.id, account.Accountid, null, (int?)ContactTypeCodes.Additional, item.additionalContact.title); } //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 <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; business.userId = account.userId.value; return(business); } } catch (Exception) { // ignore errors and just return null } return(null); }