/// <summary>
        /// Get a Account by their Guid
        /// </summary>
        /// <param name="system"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static async Task <MicrosoftDynamicsCRMaccount> GetAccountBySiteminderBusinessGuid(this IDynamicsClient system, string siteminderId)
        {
            // ensure that the siteminderId does not have any dashes.
            string sanitizedSiteminderId = GuidUtility.SanitizeGuidString(siteminderId);

            MicrosoftDynamicsCRMaccount result = null;

            try
            {
                var accountResponse = await system.Accounts.GetAsync(filter : "adoxio_externalid eq '" + sanitizedSiteminderId + "'");

                result = accountResponse.Value.FirstOrDefault();
            }
            catch (Exception)
            {
                result = null;
            }

            // get the primary contact.
            if (result != null && result.Primarycontactid == null && result._primarycontactidValue != null)
            {
                result.Primarycontactid = await system.GetContactById(Guid.Parse(result._primarycontactidValue));
            }

            return(result);
        }
        /// <summary>
        /// Get a contact by their Siteminder ID
        /// </summary>
        /// <param name="system"></param>
        /// <param name="siteminderId"></param>
        /// <returns></returns>
        public static MicrosoftDynamicsCRMcontact GetContactByExternalId(this IDynamicsClient system, string siteminderId)
        {
            string sanitizedSiteminderId       = GuidUtility.SanitizeGuidString(siteminderId);
            MicrosoftDynamicsCRMcontact result = null;
            var contactsResponse = system.Contacts.Get(filter: "adoxio_externalid eq '" + sanitizedSiteminderId + "'");

            result = contactsResponse.Value.FirstOrDefault();
            return(result);
        }
        private bool isBusinessProfileSubmitted(UserSettings userSettings)
        {
            var isSubmitted = false;

            // query the Dynamics system to get the account record.
            if (userSettings.AccountId != null && userSettings.AccountId.Length > 0)
            {
                var accountId = GuidUtility.SanitizeGuidString(userSettings.AccountId);
            }

            return(isSubmitted);
        }
        private async Task <bool> CurrentUserIsLGForApplication(MicrosoftDynamicsCRMadoxioApplication application)
        {
            // get the current user.
            UserSettings userSettings = UserSettings.CreateFromHttpContext(_httpContextAccessor);

            // get user account
            var accountId = GuidUtility.SanitizeGuidString(userSettings.AccountId);
            var account   = await _dynamicsClient.GetAccountByIdAsync(new Guid(accountId));

            // make sure the application and account have matching local government values
            var isLGForApplication = application != null && application._adoxioLocalgovindigenousnationidValue == account._adoxioLginlinkidValue;

            return(isLGForApplication);
        }
Example #5
0
        private async Task <bool> CurrentUserIsLGForApplication(MicrosoftDynamicsCRMadoxioApplication application)
        {
            var temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            var userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);

            // get user account
            var accountId = GuidUtility.SanitizeGuidString(userSettings.AccountId);
            var account   = await _dynamicsClient.GetAccountByIdAsync(new Guid(accountId));

            // make sure the application and account have matching local government values
            var isLGForApplication = application != null && application._adoxioLocalgovindigenousnationidValue == account._adoxioLginlinkidValue;

            return(isLGForApplication);
        }
Example #6
0
        public async Task <IActionResult> GetCurrentAccount()
        {
            _logger.LogInformation(LoggingEvents.HttpGet, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);
            ViewModels.Account result = null;

            // get the current user.
            string       sessionSettings = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings    = JsonConvert.DeserializeObject <UserSettings>(sessionSettings);

            _logger.LogDebug(LoggingEvents.HttpGet, "UserSettings: " + JsonConvert.SerializeObject(userSettings));

            // query the Dynamics system to get the account record.
            if (userSettings.AccountId != null && userSettings.AccountId.Length > 0)
            {
                var accountId = GuidUtility.SanitizeGuidString(userSettings.AccountId);
                MicrosoftDynamicsCRMaccount account = await _dynamicsClient.GetAccountById(new Guid(accountId));

                _logger.LogDebug(LoggingEvents.HttpGet, "Dynamics Account: " + JsonConvert.SerializeObject(account));

                if (account == null)
                {
                    // Sometimes we receive the siteminderbusienssguid instead of the account id.
                    account = await _dynamicsClient.GetAccountBySiteminderBusinessGuid(accountId);

                    if (account == null)
                    {
                        _logger.LogWarning(LoggingEvents.NotFound, "No Account Found.");
                        return(new NotFoundResult());
                    }
                }
                result = account.ToViewModel();
            }
            else
            {
                _logger.LogWarning(LoggingEvents.NotFound, "No Account Found.");
                return(new NotFoundResult());
            }

            _logger.LogDebug(LoggingEvents.HttpGet, "Current Account Result: " +
                             JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            }));
            return(Json(result));
        }
Example #7
0
        private bool isBusinessProfileSubmitted(UserSettings userSettings)
        {
            var isSubmitted = false;

            // query the Dynamics system to get the account record.
            if (userSettings.AccountId != null && userSettings.AccountId.Length > 0)
            {
                var accountId = GuidUtility.SanitizeGuidString(userSettings.AccountId);
                MicrosoftDynamicsCRMaccount account = _dynamicsClient.GetAccountByIdWithChildren(new Guid(accountId));
                _logger.LogDebug(LoggingEvents.HttpGet, "Dynamics Account: " + JsonConvert.SerializeObject(account));

                if (account == null)
                {
                    isSubmitted = account.BcgovSubmitteddate != null;
                }
            }

            return(isSubmitted);
        }
        /// <summary>
        /// Convert a service card ID string into a format that is useful (and fits into Dynamics)
        /// </summary>
        /// <param name="raw"></param>
        /// <returns></returns>
        public static string GetServiceCardID(string raw)
        {
            string result = "";

            if (!string.IsNullOrEmpty(raw))
            {
                var tokens = raw.Split('|');
                if (tokens.Length > 0)
                {
                    result = tokens[0];
                }

                if (!string.IsNullOrEmpty(result))
                {
                    tokens = result.Split(':');
                    result = tokens[tokens.Length - 1];
                }
            }
            result = GuidUtility.SanitizeGuidString(result);
            return(result);
        }
        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));
        }
Example #10
0
        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));
        }