/// <summary>
        /// Returns a User based on the guid
        /// </summary>
        /// <param name="context"></param>
        /// <param name="guid"></param>
        /// <returns></returns>
        public static User GetUserBySmUserId(this IDynamicsClient _dynamicsClient, string guid)
        {
            Guid id      = new Guid(guid);
            User user    = null;
            var  contact = _dynamicsClient.GetContactByExternalId(id.ToString());

            if (contact != null)
            {
                user = new User();
                user.FromContact(contact);
            }

            return(user);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Load User from database using their userId and guid
        /// </summary>
        /// <param name="context"></param>
        /// <param name="userId"></param>
        /// <param name="guid"></param>
        /// <returns></returns>
        public static async Task <User> LoadUser(this IDynamicsClient _dynamicsClient, string userId, string guid = null)
        {
            User user = null;
            MicrosoftDynamicsCRMcontact contact = null;
            Guid userGuid;

            if (!string.IsNullOrEmpty(guid))
            {
                user = await _dynamicsClient.GetUserByGuid(guid);
            }

            if (user == null)
            {
                if (Guid.TryParse(userId, out userGuid))
                {
                    user = _dynamicsClient.GetUserBySmUserId(userId);
                }
                else
                { //BC service card login
                    string externalId = GetServiceCardID(userId);
                    contact = _dynamicsClient.GetContactByExternalId(externalId);

                    if (contact != null)
                    {
                        user = new User();
                        user.FromContact(contact);
                    }
                }
            }

            if (user == null)
            {
                return(null);
            }

            if (guid == null)
            {
                return(user);
            }


            if (!user.ContactId.ToString().Equals(guid, StringComparison.OrdinalIgnoreCase))
            {
                // invalid account - guid doesn't match user credential
                return(null);
            }

            return(user);
        }
        /// <summary>
        /// Load User from database using their userId and guid
        /// </summary>
        /// <param name="context"></param>
        /// <param name="userId"></param>
        /// <param name="guid"></param>
        /// <returns></returns>
        public static async Task <User> LoadUser(this IDynamicsClient _dynamicsClient, string userId, IHeaderDictionary Headers, ILogger _logger, string guid = null)
        {
            User user = null;
            MicrosoftDynamicsCRMcontact contact = null;
            Guid userGuid;

            if (!string.IsNullOrEmpty(guid))
            {
                user = await _dynamicsClient.GetUserByGuid(guid);
            }

            if (user == null)
            {
                _logger.LogInformation(">>>> LoadUser for BCEID.");
                if (Guid.TryParse(userId, out userGuid))
                {
                    user = _dynamicsClient.GetUserBySmUserId(userId);
                    if (user != null)
                    {
                        _logger.LogInformation(">>>> LoadUser for BCEID: user != null");
                        // Update the contact with info from Siteminder
                        var contactVM = new Public.ViewModels.Contact();
                        contactVM.CopyHeaderValues(Headers);
                        _logger.LogInformation(">>>> After reading headers: " + Newtonsoft.Json.JsonConvert.SerializeObject(contactVM));
                        MicrosoftDynamicsCRMcontact patchContact = new MicrosoftDynamicsCRMcontact();
                        patchContact.CopyValues(contactVM);
                        try
                        {
                            _dynamicsClient.Contacts.Update(user.ContactId.ToString(), patchContact);
                        }
                        catch (OdataerrorException odee)
                        {
                            _logger.LogError("Error updating Contact");
                            _logger.LogError("Request:");
                            _logger.LogError(odee.Request.Content);
                            _logger.LogError("Response:");
                            _logger.LogError(odee.Response.Content);
                            // fail if we can't create.
                            throw (odee);
                        }
                    }
                }
                else
                { //BC service card login
                    _logger.LogInformation(">>>> LoadUser for BC Services Card.");
                    string externalId = GetServiceCardID(userId);
                    contact = _dynamicsClient.GetContactByExternalId(externalId);

                    if (contact != null)
                    {
                        _logger.LogInformation(">>>> LoadUser for BC Services Card: contact != null");
                        user = new User();
                        user.FromContact(contact);

                        // Update the contact and worker with info from Siteminder
                        var contactVM = new Public.ViewModels.Contact();
                        var workerVm  = new Public.ViewModels.Worker();
                        contactVM.CopyHeaderValues(Headers);
                        workerVm.CopyHeaderValues(Headers);
                        MicrosoftDynamicsCRMcontact patchContact = new MicrosoftDynamicsCRMcontact();

                        patchContact.CopyValuesNoEmailPhone(contactVM);
                        try
                        {
                            _dynamicsClient.Contacts.Update(user.ContactId.ToString(), patchContact);
                        }
                        catch (OdataerrorException odee)
                        {
                            _logger.LogError("Error updating Contact");
                            _logger.LogError("Request:");
                            _logger.LogError(odee.Request.Content);
                            _logger.LogError("Response:");
                            _logger.LogError(odee.Response.Content);
                            // fail if we can't update.
                            throw (odee);
                        }

                        // update worker(s)
                        try
                        {
                            string filter  = $"_adoxio_contactid_value eq {contact.Contactid}";
                            var    workers = _dynamicsClient.Workers.Get(filter: filter).Value;
                            foreach (var item in workers)
                            {
                                MicrosoftDynamicsCRMadoxioWorker patchWorker = new MicrosoftDynamicsCRMadoxioWorker();
                                patchWorker.CopyValuesNoEmailPhone(workerVm);
                                _dynamicsClient.Workers.Update(item.AdoxioWorkerid, patchWorker);
                            }
                        }
                        catch (OdataerrorException odee)
                        {
                            _logger.LogError("Error updating Worker");
                            _logger.LogError("Request:");
                            _logger.LogError(odee.Request.Content);
                            _logger.LogError("Response:");
                            _logger.LogError(odee.Response.Content);
                        }
                    }
                }
            }

            if (user == null)
            {
                return(null);
            }

            if (guid == null)
            {
                return(user);
            }


            if (!user.ContactId.ToString().Equals(guid, StringComparison.OrdinalIgnoreCase))
            {
                // invalid account - guid doesn't match user credential
                return(null);
            }

            return(user);
        }
        public async Task <IActionResult> CreateContact([FromBody] ViewModels.Contact item)
        {
            // get UserSettings from the session
            string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);

            // first check to see that a contact exists.
            string contactSiteminderGuid = userSettings.SiteMinderGuid;

            if (contactSiteminderGuid == null || contactSiteminderGuid.Length == 0)
            {
                _logger.LogDebug(LoggingEvents.Error, "No Contact Siteminder Guid exernal id");
                throw new Exception("Error. No ContactSiteminderGuid exernal id");
            }

            // get the contact record.
            MicrosoftDynamicsCRMcontact userContact = null;

            // see if the contact exists.
            try
            {
                userContact = _dynamicsClient.GetContactByExternalId(contactSiteminderGuid);
                if (userContact != null)
                {
                    throw new Exception("Contact already Exists");
                }
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(LoggingEvents.Error, "Error getting contact by Siteminder Guid.");
                _logger.LogError("Request:");
                _logger.LogError(httpOperationException.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(httpOperationException.Response.Content);
                throw new HttpOperationException("Error getting contact by Siteminder Guid");
            }

            // create a new contact.
            MicrosoftDynamicsCRMcontact contact = new MicrosoftDynamicsCRMcontact();

            contact.CopyValues(item);


            if (userSettings.IsNewUserRegistration)
            {
                // get additional information from the service card headers.
                contact.CopyHeaderValues(_httpContextAccessor);
            }

            contact.AdoxioExternalid = DynamicsExtensions.GetServiceCardID(contactSiteminderGuid);
            try
            {
                contact = await _dynamicsClient.Contacts.CreateAsync(contact);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, $"Error creating contact. ");
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Unknown error creating contact.");
            }

            // if we have not yet authenticated, then this is the new record for the user.
            if (userSettings.IsNewUserRegistration)
            {
                userSettings.ContactId = contact.Contactid.ToString();

                // we can now authenticate.
                if (userSettings.AuthenticatedUser == null)
                {
                    Models.User user = new Models.User();
                    user.Active    = true;
                    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.LogDebug(LoggingEvents.Error, "Invalid user registration.");
                throw new Exception("Invalid user registration.");
            }

            return(new JsonResult(contact.ToViewModel()));
        }
        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));
        }
Exemplo n.º 6
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));
        }
        /// <summary>
        /// Process Authentication Request
        /// </summary>
        /// <returns></returns>
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            // get siteminder headers
            _logger.LogDebug("Parsing the HTTP headers for SiteMinder authentication credential");

            SiteMinderAuthOptions options = new SiteMinderAuthOptions();
            bool isDeveloperLogin         = false;
            bool isBCSCDeveloperLogin     = false;

            try
            {
                ClaimsPrincipal principal;
                HttpContext     context = Request.HttpContext;

                IConfiguration _configuration = (IConfiguration)context.RequestServices.GetService(typeof(IConfiguration));

                IDynamicsClient _dynamicsClient = (IDynamicsClient)context.RequestServices.GetService(typeof(IDynamicsClient));

                FileManagerClient _fileManagerClient = (FileManagerClient)context.RequestServices.GetService(typeof(FileManagerClient));

                IWebHostEnvironment hostingEnv = (IWebHostEnvironment)context.RequestServices.GetService(typeof(IWebHostEnvironment));

                UserSettings userSettings = new UserSettings();

                if (!string.IsNullOrEmpty(_configuration["FEATURE_DISABLE_LOGIN"]))
                {
                    return(AuthenticateResult.Fail(options.LoginDisabledError));
                }

                string userId                 = null;
                string devCompanyId           = null;
                string siteMinderGuid         = "";
                string siteMinderBusinessGuid = "";
                string siteMinderUserType     = "";

                // **************************************************
                // If this is an Error or Authentiation API - Ignore
                // **************************************************
                string url = context.Request.GetDisplayUrl().ToLower();

                if (url.Contains(".js"))
                {
                    return(AuthenticateResult.NoResult());
                }

                // **************************************************
                // Check if we have a Dev Environment Cookie
                // **************************************************
                if (!hostingEnv.IsProduction())
                {
                    // check for a fake BCeID login in dev mode
                    string temp = context.Request.Cookies[options.DevAuthenticationTokenKey];

                    if (string.IsNullOrEmpty(temp)) // could be an automated test user.
                    {
                        temp = context.Request.Headers["DEV-USER"];
                    }

                    if (!string.IsNullOrEmpty(temp))
                    {
                        if (temp.Contains("::"))
                        {
                            var temp2 = temp.Split("::");
                            userId = temp2[0];
                            if (temp2.Length >= 2)
                            {
                                devCompanyId = temp2[1];
                            }
                            else
                            {
                                devCompanyId = temp2[0];
                            }
                        }
                        else
                        {
                            userId       = temp;
                            devCompanyId = temp;
                        }
                        isDeveloperLogin = true;

                        _logger.LogDebug("Got user from dev cookie = " + userId + ", company = " + devCompanyId);
                    }
                    else
                    {
                        // same set of tests for a BC Services Card dev login
                        temp = context.Request.Cookies[options.DevBCSCAuthenticationTokenKey];

                        if (string.IsNullOrEmpty(temp)) // could be an automated test user.
                        {
                            temp = context.Request.Headers["DEV-BCSC-USER"];
                        }

                        if (!string.IsNullOrEmpty(temp))
                        {
                            userId = temp;
                            isBCSCDeveloperLogin = true;

                            _logger.LogDebug("Got user from dev cookie = " + userId);
                        }
                    }
                }

                // **************************************************
                // Check if the user session is already created
                // **************************************************
                try
                {
                    _logger.LogDebug("Checking user session");
                    userSettings = UserSettings.ReadUserSettings(context);
                    _logger.LogDebug("UserSettings found: " + userSettings.GetJson());
                }
                catch
                {
                    //do nothing
                    _logger.LogDebug("No UserSettings found");
                }

                // is user authenticated - if so we're done
                if ((userSettings.UserAuthenticated && string.IsNullOrEmpty(userId)) ||
                    (userSettings.UserAuthenticated && !string.IsNullOrEmpty(userId) &&
                     !string.IsNullOrEmpty(userSettings.UserId) && userSettings.UserId == userId))
                {
                    _logger.LogDebug("User already authenticated with active session: " + userSettings.UserId);
                    principal = userSettings.AuthenticatedUser.ToClaimsPrincipal(options.Scheme, userSettings.UserType);
                    return(AuthenticateResult.Success(new AuthenticationTicket(principal, null, Options.Scheme)));
                }

                string smgov_userdisplayname = context.Request.Headers["smgov_userdisplayname"];
                if (!string.IsNullOrEmpty(smgov_userdisplayname))
                {
                    userSettings.UserDisplayName = smgov_userdisplayname;
                }

                string smgov_businesslegalname = context.Request.Headers["smgov_businesslegalname"];
                if (!string.IsNullOrEmpty(smgov_businesslegalname))
                {
                    userSettings.BusinessLegalName = smgov_businesslegalname;
                }

                // **************************************************
                // Authenticate based on SiteMinder Headers
                // **************************************************
                _logger.LogDebug("Parsing the HTTP headers for SiteMinder authentication credential");

                // At this point userID would only be set if we are logging in through as a DEV user

                if (string.IsNullOrEmpty(userId))
                {
                    _logger.LogDebug("Getting user data from headers");

                    userId = context.Request.Headers[options.SiteMinderUserNameKey];
                    if (string.IsNullOrEmpty(userId))
                    {
                        userId = context.Request.Headers[options.SiteMinderUniversalIdKey];
                    }

                    siteMinderGuid         = context.Request.Headers[options.SiteMinderUserGuidKey];
                    siteMinderBusinessGuid = context.Request.Headers[options.SiteMinderBusinessGuidKey];
                    siteMinderUserType     = context.Request.Headers[options.SiteMinderUserTypeKey];


                    // **************************************************
                    // Validate credentials
                    // **************************************************
                    if (string.IsNullOrEmpty(userId))
                    {
                        _logger.LogDebug(options.MissingSiteMinderUserIdError);
                        return(AuthenticateResult.Fail(options.MissingSiteMinderGuidError));
                    }

                    if (string.IsNullOrEmpty(siteMinderGuid))
                    {
                        _logger.LogDebug(options.MissingSiteMinderGuidError);
                        return(AuthenticateResult.Fail(options.MissingSiteMinderGuidError));
                    }
                    if (string.IsNullOrEmpty(siteMinderUserType))
                    {
                        _logger.LogDebug(options.MissingSiteMinderUserTypeError);
                        return(AuthenticateResult.Fail(options.MissingSiteMinderUserTypeError));
                    }
                }
                else // DEV user, setup a fake session and SiteMinder headers.
                {
                    if (isDeveloperLogin)
                    {
                        _logger.LogDebug("Generating a Development user");
                        userSettings.BusinessLegalName = devCompanyId + " TestBusiness";
                        userSettings.UserDisplayName   = userId + " TestUser";
                        siteMinderGuid         = GuidUtility.CreateIdForDynamics("contact", userSettings.UserDisplayName).ToString();
                        siteMinderBusinessGuid = GuidUtility.CreateIdForDynamics("account", userSettings.BusinessLegalName).ToString();
                        siteMinderUserType     = "Business";
                    }
                    else if (isBCSCDeveloperLogin)
                    {
                        _logger.LogDebug("Generating a Development BC Services user");
                        userSettings.BusinessLegalName = null;
                        userSettings.UserDisplayName   = userId + " Associate";
                        siteMinderGuid         = GuidUtility.CreateIdForDynamics("bcsc", userSettings.UserDisplayName).ToString();
                        siteMinderBusinessGuid = null;
                        siteMinderUserType     = "VerifiedIndividual";
                    }
                }

                // Previously the code would do a database lookup here.  However there is no backing database for the users table now,
                // so we just do a Dynamics lookup on the siteMinderGuid.

                _logger.LogDebug("Loading user external id = " + siteMinderGuid);
                // 3/18/2020 - Note that LoadUser will now work if there is a match on the guid, as well as a match on name in a case where there is no guid.
                userSettings.AuthenticatedUser = await _dynamicsClient.LoadUser(siteMinderGuid, context.Request.Headers, _logger);

                _logger.LogDebug("After getting authenticated user = "******" (" + userId + ")");
                    return(AuthenticateResult.Fail(options.InactivegDbUserIdError));
                }

                if (userSettings.AuthenticatedUser != null && !String.IsNullOrEmpty(siteMinderUserType))
                {
                    userSettings.AuthenticatedUser.UserType = siteMinderUserType;
                }
                userSettings.UserType = siteMinderUserType;

                // This line gets the various claims for the current user.
                ClaimsPrincipal userPrincipal = userSettings.AuthenticatedUser.ToClaimsPrincipal(options.Scheme, userSettings.UserType);

                // **************************************************
                // Create authenticated user
                // **************************************************
                _logger.LogDebug("Authentication successful: " + userId);
                _logger.LogDebug("Setting identity and creating session for: " + userId);

                // create session info for the current user
                userSettings.UserId                = userId;
                userSettings.UserAuthenticated     = true;
                userSettings.IsNewUserRegistration = userSettings.AuthenticatedUser == null;

                // set other session info
                userSettings.SiteMinderGuid         = siteMinderGuid;
                userSettings.SiteMinderBusinessGuid = siteMinderBusinessGuid;
                _logger.LogDebug("Before getting contact and account ids = " + userSettings.GetJson());

                if (userSettings.AuthenticatedUser != null)
                {
                    userSettings.ContactId = userSettings.AuthenticatedUser.ContactId.ToString();
                    // ensure that the given account has a documents folder.

                    if (siteMinderBusinessGuid != null) // BCeID user
                    {
                        var contact = _dynamicsClient.GetContactByExternalId(userSettings.ContactId);
                        if (contact == null)
                        {
                            // try by other means.
                            var contactVM = new Public.ViewModels.Contact();
                            contactVM.CopyHeaderValues(context.Request.Headers);
                            contact = _dynamicsClient.GetContactByContactVmBlankSmGuid(contactVM);
                        }
                        if (contact != null && contact.Contactid != null)
                        {
                            await CreateContactDocumentLocation(_dynamicsClient, _fileManagerClient, contact);
                        }


                        var account = await _dynamicsClient.GetAccountBySiteminderBusinessGuid(siteMinderBusinessGuid);

                        if (account == null)
                        {
                            // try by other means.
                            account = _dynamicsClient.GetAccountByLegalName(userSettings.BusinessLegalName);
                        }
                        if (account != null && account.Accountid != null)
                        {
                            userSettings.AccountId = account.Accountid;
                            userSettings.AuthenticatedUser.AccountId = Guid.Parse(account.Accountid);

                            // ensure that the given account has a documents folder.
                            await CreateAccountDocumentLocation(_dynamicsClient, _fileManagerClient, account);
                        }
                    }
                }

                if (!hostingEnv.IsProduction() && (isDeveloperLogin || isBCSCDeveloperLogin))
                {
                    _logger.LogDebug("DEV MODE Setting identity and creating session for: " + userId);

                    if (isDeveloperLogin)
                    {
                        userSettings.BusinessLegalName = devCompanyId + " TestBusiness";
                        userSettings.UserDisplayName   = userId + " TestUser";

                        // add generated guids
                        userSettings.SiteMinderBusinessGuid = GuidUtility.CreateIdForDynamics("account", userSettings.BusinessLegalName).ToString();
                        userSettings.SiteMinderGuid         = GuidUtility.CreateIdForDynamics("contact", userSettings.UserDisplayName).ToString();
                    }
                    else if (isBCSCDeveloperLogin)
                    {
                        userSettings.BusinessLegalName = null;
                        userSettings.UserDisplayName   = userId + " Associate";

                        // add generated guids
                        userSettings.SiteMinderBusinessGuid = null;
                        userSettings.SiteMinderGuid         = GuidUtility.CreateIdForDynamics("bcsc", userSettings.UserDisplayName).ToString();
                    }

                    if (userSettings.IsNewUserRegistration)
                    {
                        if (isDeveloperLogin)
                        {
                            // add generated guids
                            // set to null to indicate that the user is still registering the account
                            userSettings.AccountId = null;
                            userSettings.ContactId = null;
                        }
                        else if (isBCSCDeveloperLogin)
                        {
                            // set to null for now
                            userSettings.AccountId = null;
                            userSettings.ContactId = null;
                        }

                        _logger.LogDebug("New user registration:" + userSettings.UserDisplayName);
                        _logger.LogDebug("userSettings.SiteMinderBusinessGuid:" + userSettings.SiteMinderBusinessGuid);
                        _logger.LogDebug("userSettings.SiteMinderGuid:" + userSettings.SiteMinderGuid);
                        _logger.LogDebug("userSettings.AccountId:" + userSettings.AccountId);
                        _logger.LogDebug("userSettings.ContactId:" + userSettings.ContactId);
                    }
                    // Set account ID from authenticated user
                    else if (userSettings.AuthenticatedUser != null)
                    {
                        // populate the business GUID.
                        if (string.IsNullOrEmpty(userSettings.AccountId))
                        {
                            userSettings.AccountId = userSettings.AuthenticatedUser.AccountId.ToString();
                        }
                        if (string.IsNullOrEmpty(userSettings.ContactId))
                        {
                            userSettings.ContactId = userSettings.AuthenticatedUser.ContactId.ToString();
                        }
                        _logger.LogDebug("Returning user:"******"userSettings.AccountId:" + userSettings.AccountId);
                        _logger.LogDebug("userSettings.ContactId:" + userSettings.ContactId);
                    }
                }

                // add the worker settings if it is a new user.
                if (userSettings.IsNewUserRegistration)
                {
                    userSettings.NewWorker = new ViewModels.Worker();
                    userSettings.NewWorker.CopyHeaderValues(context.Request.Headers);

                    userSettings.NewContact = new ViewModels.Contact();
                    userSettings.NewContact.CopyHeaderValues(context.Request.Headers);

                    if (isBCSCDeveloperLogin)
                    {
                        userSettings.NewWorker.firstname  = userId;
                        userSettings.NewWorker.lastname   = "Associate";
                        userSettings.NewContact.firstname = userId;
                        userSettings.NewContact.lastname  = "Associate";
                    }
                }
                else if (siteMinderUserType == "VerifiedIndividual")
                {
                    // Verified individual is from BC Service Card which means it's a worker
                    // Update contact and worker with latest info from BC Service Card
                    MicrosoftDynamicsCRMadoxioWorkerCollection workerCollection = _dynamicsClient.Workers.Get(filter: $"_adoxio_contactid_value eq {userSettings.ContactId}");
                    if (workerCollection.Value.Count > 0)
                    {
                        MicrosoftDynamicsCRMadoxioWorker savedWorker = workerCollection.Value[0];
                        ViewModels.Contact contact = new ViewModels.Contact();
                        contact.CopyHeaderValues(context.Request.Headers);

                        MicrosoftDynamicsCRMcontact savedContact = _dynamicsClient.Contacts.GetByKey(userSettings.ContactId);
                        if (savedContact.Address1Line1 != null && savedContact.Address1Line1 != contact.address1_line1)
                        {
                            MicrosoftDynamicsCRMadoxioPreviousaddress prevAddress = new MicrosoftDynamicsCRMadoxioPreviousaddress()
                            {
                                AdoxioStreetaddress = savedContact.Address1Line1,
                                AdoxioProvstate     = savedContact.Address1Stateorprovince,
                                AdoxioCity          = savedContact.Address1City,
                                AdoxioCountry       = savedContact.Address1Country,
                                AdoxioPostalcode    = savedContact.Address1Postalcode,
                                ContactIdODataBind  = _dynamicsClient.GetEntityURI("contacts", savedContact.Contactid)
                            };
                            _dynamicsClient.Previousaddresses.Create(prevAddress);
                        }


                        _dynamicsClient.Contacts.Update(userSettings.ContactId, contact.ToModel());


                        ViewModels.Worker worker = new ViewModels.Worker();
                        worker.CopyHeaderValues(context.Request.Headers);

                        MicrosoftDynamicsCRMadoxioWorker patchWorker = new MicrosoftDynamicsCRMadoxioWorker()
                        {
                            AdoxioFirstname  = worker.firstname,
                            AdoxioLastname   = worker.lastname,
                            AdoxioMiddlename = worker.middlename
                        };
                        if (worker.gender != 0)
                        {
                            patchWorker.AdoxioGendercode = (int)worker.gender;
                        }

                        _dynamicsClient.Workers.Update(savedWorker.AdoxioWorkerid, patchWorker);

                        var updatedWorker = await _dynamicsClient.GetWorkerByIdWithChildren(savedWorker.AdoxioWorkerid);

                        // only create the worker document location if the FEATURE_NO_WET_SIGNATURE setting is blank
                        if (string.IsNullOrEmpty(_configuration["FEATURE_NO_WET_SIGNATURE"]))
                        {
                            // ensure that the worker has a documents folder.
                            await CreateWorkerDocumentLocation(_dynamicsClient, _fileManagerClient, updatedWorker);
                        }
                    }
                }

                // **************************************************
                // Update user settings
                // **************************************************
                UserSettings.SaveUserSettings(userSettings, context);

                // done!
                principal = userPrincipal;
                return(AuthenticateResult.Success(new AuthenticationTicket(principal, null, Options.Scheme)));
            }
            catch (Exception exception)
            {
                _logger.LogError(exception.Message);
                throw;
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Import responses to Dynamics.
        /// </summary>
        /// <returns></returns>
        private void ImportWorkerRequestsToDynamics(PerformContext hangfireContext, List <WorkerScreeningRequest> requests)
        {
            if (_dynamics == null)
            {
                hangfireContext.WriteLine("Dynamics not configured properly");
                return;
            }
            foreach (WorkerScreeningRequest workerRequest in requests)
            {
                // add data to dynamics.
                // create a Contact which will be bound to the customer id field.
                MicrosoftDynamicsCRMcontact contact = null;

                if (workerRequest.Contact != null)
                {
                    contact = _dynamics.GetContactByExternalId(workerRequest.Contact.ContactId);

                    if (contact == null)
                    {
                        contact = new MicrosoftDynamicsCRMcontact();
                    }

                    contact.Firstname        = workerRequest.Contact.FirstName;
                    contact.Lastname         = workerRequest.Contact.LastName;
                    contact.SpiceDateofbirth = workerRequest.Contact.BirthDate;
                    contact.Emailaddress1    = workerRequest.Contact.Email;
                    if (workerRequest.Contact.Address != null)
                    {
                        contact.Address1Line1           = workerRequest.Contact.Address.AddressStreet1;
                        contact.Address1Line2           = workerRequest.Contact.Address.AddressStreet2;
                        contact.Address1City            = workerRequest.Contact.Address.City;
                        contact.Address1Stateorprovince = workerRequest.Contact.Address.StateProvince;
                        contact.Address1Postalcode      = workerRequest.Contact.Address.Postal;
                        contact.Address1Country         = workerRequest.Contact.Address.Country;
                    }

                    contact.SpiceBcidcardnumber       = workerRequest.BCIdCardNumber;
                    contact.SpiceDriverslicensenumber = int.Parse(workerRequest.DriversLicence);
                    //contact.Externaluseridentifier = workerRequest.RecordIdentifier;
                    contact.Gendercode = (int?)workerRequest.Gender;

                    if (contact.Contactid == null) // new record
                    {
                        contact = _dynamics.Contacts.Create(contact);
                    }
                    else
                    {
                        _dynamics.Contacts.Update(contact.Contactid, contact);
                    }
                }


                MicrosoftDynamicsCRMincident incident = new MicrosoftDynamicsCRMincident();

                incident.SpiceApplicanttype         = 525840001; // Cannabis
                incident.SpiceCannabisapplicanttype = 525840002; // Worker

                // Screenings are Incidents in Dynamics.

                _dynamics.Incidents.Create(incident);
            }
        }