コード例 #1
0
        public async Task <IActionResult> GetContact(string id)
        {
            ViewModels.Contact result = null;

            if (!string.IsNullOrEmpty(id))
            {
                Guid contactId = Guid.Parse(id);
                // query the Dynamics system to get the contact record.
                MicrosoftDynamicsCRMcontact contact = await _dynamicsClient.GetContactById(contactId);

                if (contact != null)
                {
                    result = contact.ToViewModel();
                }
                else
                {
                    return(new NotFoundResult());
                }
            }
            else
            {
                return(BadRequest());
            }

            return(new JsonResult(result));
        }
コード例 #2
0
        public IActionResult GetContact(string id)
        {
            ViewModels.Contact result = null;

            if (!string.IsNullOrEmpty(id) && Guid.TryParse(id, out Guid contactId))
            {
                // query the Dynamics system to get the contact record.
                MicrosoftDynamicsCRMcontact contact = _dynamicsClient.GetContactById(contactId);

                if (contact != null)
                {
                    result = contact.ToViewModel();
                }
                else
                {
                    return(new NotFoundResult());
                }
            }
            else
            {
                return(BadRequest());
            }

            return(Json(result));
        }
コード例 #3
0
        private async Task <bool> CanAccessEntity(string entityName, string entityId)
        {
            var result = false;
            var id     = Guid.Parse(entityId);

            switch (entityName.ToLower())
            {
            case "application":
                var application = await _dynamicsClient.GetApplicationById(id);

                result = application != null && CurrentUserHasAccessToApplicationOwnedBy(application._adoxioApplicantValue);
                break;

            case "contact":
                var contact = await _dynamicsClient.GetContactById(id);

                result = contact != null && CurrentUserHasAccessToContactOwnedBy(contact.Contactid);
                break;

            case "worker":
                var worker = await _dynamicsClient.GetWorkerById(id);

                result = worker != null && CurrentUserHasAccessToContactOwnedBy(worker._adoxioContactidValue);
                break;

            default:
                break;
            }
            return(result);
        }
コード例 #4
0
        public static void CreateEntitySharePointDocumentLocation(this IDynamicsClient _dynamicsClient, string entityName, string entityId, string folderName, string name)
        {
            switch (entityName.ToLower())
            {
            case "account":
                var account = _dynamicsClient.GetAccountById(entityId);
                _dynamicsClient.CreateAccountDocumentLocation(account, folderName, name);
                break;

            case "application":
                var application = _dynamicsClient.GetApplicationByIdWithChildren(entityId).GetAwaiter().GetResult();
                _dynamicsClient.CreateApplicationDocumentLocation(application, folderName, name);
                break;

            case "contact":
                var contact = _dynamicsClient.GetContactById(entityId).GetAwaiter().GetResult();
                _dynamicsClient.CreateContactDocumentLocation(contact, folderName, name);
                break;

            case "worker":
                var worker = _dynamicsClient.GetWorkerByIdWithChildren(entityId).GetAwaiter().GetResult();
                _dynamicsClient.CreateWorkerDocumentLocation(worker, folderName, name);
                break;

            case "event":
                var eventEntity = _dynamicsClient.GetEventByIdWithChildren(entityId);
                _dynamicsClient.CreateEventDocumentLocation(eventEntity, folderName, name);
                break;

            case "licence":
                var licenceEntity = _dynamicsClient.GetLicenceByIdWithChildren(entityId);
                _dynamicsClient.CreateLicenceDocumentLocation(licenceEntity, folderName, name);
                break;
            }
        }
コード例 #5
0
        public static async Task <string> GetFolderName(string entityName, string entityId, IDynamicsClient _dynamicsClient)
        {
            var folderName = "";

            switch (entityName.ToLower())
            {
            case "account":
                var account = await _dynamicsClient.GetAccountById(Guid.Parse(entityId));

                folderName = GetAccountFolderName(account);
                break;

            case "application":
                var application = await _dynamicsClient.GetApplicationById(Guid.Parse(entityId));

                folderName = GetApplicationFolderName(application);
                break;

            case "contact":
                var contact = await _dynamicsClient.GetContactById(Guid.Parse(entityId));

                folderName = GetContactFolderName(contact);
                break;

            case "worker":
                var worker = await _dynamicsClient.GetWorkerById(Guid.Parse(entityId));

                folderName = GetWorkerFolderName(worker);
                break;

            default:
                break;
            }
            return(folderName);
        }
コード例 #6
0
        /// <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);
        }
コード例 #7
0
        /// <summary>
        /// Get a Account by their Guid
        /// </summary>
        /// <param name="system"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static async Task <MicrosoftDynamicsCRMaccount> GetAccountById(this IDynamicsClient system, Guid id)
        {
            MicrosoftDynamicsCRMaccount result;

            try
            {
                // fetch from Dynamics.
                result = await system.Accounts.GetByKeyAsync(id.ToString());
            }
            catch (Gov.Lclb.Cllb.Interfaces.Models.OdataerrorException)
            {
                result = null;
            }

            // get the primary contact.
            if (result != null && result.Primarycontactid == null && result._primarycontactidValue != null)
            {
                try
                {
                    result.Primarycontactid = await system.GetContactById(Guid.Parse(result._primarycontactidValue));
                }
                catch (Gov.Lclb.Cllb.Interfaces.Models.OdataerrorException)
                {
                    result.Primarycontactid = null;
                }
            }
            return(result);
        }
コード例 #8
0
        public static async Task <MicrosoftDynamicsCRMaccount> GetAccountByLegalName(this IDynamicsClient system, string legalName)
        {
            legalName = legalName.Replace("'", "''");

            MicrosoftDynamicsCRMaccount result = null;

            try
            {
                var accountResponse = await system.Accounts.GetAsync(filter : $"name eq '{legalName}'");

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

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

            return(result);
        }
コード例 #9
0
        /// <summary>
        /// Get a Account by their Guid
        /// </summary>
        /// <param name="system"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static MicrosoftDynamicsCRMaccount GetAccountByIdWithChildren(this IDynamicsClient system, Guid id)
        {
            List <string> expand = new List <string>()
            {
                "primarycontactid",
                "bcgov_AdditionalContact",
                "Account_SharepointDocumentLocation"
            };

            MicrosoftDynamicsCRMaccount result;

            try
            {
                // fetch from Dynamics.
                result = system.Accounts.GetByKey(accountid: id.ToString(), expand: expand);
            }
            catch (OdataerrorException)
            {
                result = null;
            }

            // get the primary contact.
            if (result != null && result.Primarycontactid == null && result._primarycontactidValue != null)
            {
                try
                {
                    result.Primarycontactid = system.GetContactById(Guid.Parse(result._primarycontactidValue));
                }
                catch (OdataerrorException)
                {
                    result.Primarycontactid = null;
                }
            }
            return(result);
        }
コード例 #10
0
        public async Task <IActionResult> CreateAlias([FromBody] ViewModels.Alias item)
        {
            if (item?.contact?.id == null || item?.worker?.id == null)
            {
                return(BadRequest());
            }

            // for association with current user
            string       userJson     = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(userJson);

            MicrosoftDynamicsCRMadoxioAlias alias = new MicrosoftDynamicsCRMadoxioAlias();

            // copy received values to Dynamics Application
            alias.CopyValues(item);
            try
            {
                alias = _dynamicsClient.Aliases.Create(alias);
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError("Error creating application");
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
                // fail if we can't create.
                throw (odee);
            }


            MicrosoftDynamicsCRMadoxioAlias patchAlias = new MicrosoftDynamicsCRMadoxioAlias();

            // set contact and worker associations
            try
            {
                var worker = _dynamicsClient.GetWorkerById(Guid.Parse(item.worker.id));
                patchAlias.WorkerIdODataBind = _dynamicsClient.GetEntityURI("adoxio_workers", item.worker.id);

                var contact = _dynamicsClient.GetContactById(Guid.Parse(item.contact.id));
                patchAlias.ContactIdODataBind = _dynamicsClient.GetEntityURI("contacts", item.contact.id);

                await _dynamicsClient.Aliases.UpdateAsync(alias.AdoxioAliasid, patchAlias);
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError("Error updating application");
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
                // fail if we can't create.
                throw (odee);
            }

            return(Json(alias.ToViewModel()));
        }
コード例 #11
0
ファイル: FileController.cs プロジェクト: bcgov/pssg-cscp-vsd
        private async Task <bool> CanAccessEntity(string entityName, string entityId)
        {
            var result = false;
            var id     = Guid.Parse(entityId);

            switch (entityName.ToLower())
            {
            //TODO - add logic for other entity types.
            case "contact":
                var contact = _dynamicsClient.GetContactById(id);
                result = contact != null && CurrentUserHasAccessToContactOwnedBy(contact.Contactid);
                break;

            default:
                break;
            }
            return(result);
        }
コード例 #12
0
        /// <summary>
        /// Returns the folder name for a given entity
        /// </summary>
        /// <param name="entityName"></param>
        /// <param name="entityId"></param>
        /// <param name="getFromDocumentLocation"></param>
        /// <param name="_dynamicsClient"></param>
        /// <returns></returns>
        public static async Task <string> GetFolderName(this IDynamicsClient _dynamicsClient, string entityName, string entityId, bool getFromDocumentLocation = true)
        {
            string folderName = null;

            if (getFromDocumentLocation)
            {
                folderName = _dynamicsClient.GetEntitySharePointDocumentLocation(entityName, entityId);
            }

            if (folderName == null)
            {
                switch (entityName.ToLower())
                {
                case "account":
                    var account = await _dynamicsClient.GetAccountByIdAsync(Guid.Parse(entityId)).ConfigureAwait(true);

                    folderName = account.GetDocumentFolderName();
                    break;

                case "application":
                    var application = await _dynamicsClient.GetApplicationById(Guid.Parse(entityId)).ConfigureAwait(true);

                    folderName = application.GetDocumentFolderName();
                    break;

                case "contact":
                    var contact = await _dynamicsClient.GetContactById(Guid.Parse(entityId)).ConfigureAwait(true);

                    folderName = contact.GetDocumentFolderName();
                    break;

                case "worker":
                    var worker = await _dynamicsClient.GetWorkerById(Guid.Parse(entityId)).ConfigureAwait(true);

                    folderName = worker.GetDocumentFolderName();
                    break;

                case "event":
                    var eventEntity = _dynamicsClient.GetEventById(Guid.Parse(entityId));
                    folderName = eventEntity.GetDocumentFolderName();
                    break;

                case "licence":
                    var licenceEntity = _dynamicsClient.GetLicenceById(Guid.Parse(entityId));
                    folderName = licenceEntity.GetDocumentFolderName();
                    break;

                case "specialevent":
                    var entity = _dynamicsClient.GetSpecialEventById(entityId);
                    folderName = entity.GetDocumentFolderName();
                    break;
                }
            }

            return(folderName);
        }
コード例 #13
0
        /// <summary>
        /// Returns true if the current user can access the entity
        /// </summary>
        /// <param name="entityName"></param>
        /// <param name="entityId"></param>
        /// <param name="isDelete">Some access rules are different for deletes</param>
        /// <returns></returns>
        private async Task <bool> CanAccessEntity(string entityName, string entityId, bool isDelete = false)
        {
            var result = false;
            var id     = Guid.Parse(entityId);

            switch (entityName.ToLower())
            {
            case "account":
                var account = await _dynamicsClient.GetAccountByIdAsync(id).ConfigureAwait(true);

                result = account != null && CurrentUserHasAccessToAccount(account.Accountid);
                break;

            case "application":
                var application = await _dynamicsClient.GetApplicationById(id).ConfigureAwait(true);

                result = application != null && CurrentUserHasAccessToAccount(application._adoxioApplicantValue);
                var allowLGAccess = await CurrentUserIsLGForApplication(application);

                result = result || allowLGAccess && !isDelete;
                break;

            case "contact":
                var contact = await _dynamicsClient.GetContactById(id).ConfigureAwait(true);

                result = contact != null && CurrentUserHasAccessToContactOwnedBy(contact.Contactid);
                break;

            case "worker":
                var worker = await _dynamicsClient.GetWorkerById(id).ConfigureAwait(true);

                result = worker != null && CurrentUserHasAccessToContactOwnedBy(worker._adoxioContactidValue);
                break;

            case "event":
                var eventEntity = _dynamicsClient.GetEventById(id);
                result = eventEntity != null && CurrentUserHasAccessToAccount(eventEntity._adoxioAccountValue);
                break;
            }
            return(result);
        }
コード例 #14
0
        public void Execute(IDynamicsClient _dynamicsClient, BCeIDBusinessQuery _bceidQuery)
        {
            // first find bad accounts
            string filter = "accountnumber eq '' or accountnumber eq null";

            try
            {
                var badAccounts = _dynamicsClient.Accounts.Get().Value;

                Console.Out.WriteLine($"Found {badAccounts.Count} accounts missing the BN9 Account Number.");
                Console.Out.WriteLine($"Account ID - Account Name - Account Siteminder ID - BN9");
                foreach (var badAccount in badAccounts)
                {
                    if (string.IsNullOrEmpty(badAccount._primarycontactidValue))
                    {
                        Console.Out.WriteLine($"{badAccount.Accountid} - {badAccount.Name} - {badAccount.AdoxioExternalid} - no primary contact.");
                    }
                    else
                    {
                        // get the primary contact external id.
                        var contact = _dynamicsClient.GetContactById(badAccount._primarycontactidValue).GetAwaiter().GetResult();

                        if (contact == null || string.IsNullOrEmpty(contact.AdoxioExternalid))
                        {
                            Console.Out.WriteLine($"{badAccount.Accountid} - {badAccount.Name} - {badAccount.AdoxioExternalid} - no primary contact user identifier.");
                        }
                        else
                        {
                            // get the BN9.
                            string bn9 = "";
                            try
                            {
                                var result = _bceidQuery.ProcessBusinessQuery(contact.AdoxioExternalid).GetAwaiter().GetResult();
                                bn9 = result.businessNumber;
                                Console.Out.WriteLine("** Found BN9");
                                Console.Out.WriteLine($"{badAccount.Accountid} - {badAccount.Name} - {badAccount.AdoxioExternalid} - {bn9} - {result.incorporationNumber}");
                            }
                            catch (Exception e)
                            {
                                Console.Out.WriteLine("ERROR during get BCEID");
                                Console.Out.WriteLine(e.Message);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("Error getting bad accounts.");
                Console.Out.WriteLine(e.Message);
            }
        }
コード例 #15
0
        private async Task <bool> CanAccessEntity(string entityName, string entityId)
        {
            var result = false;
            var id     = Guid.Parse(entityId);

            switch (entityName.ToLower())
            {
            case "incident":
                var application = _dynamicsClient.GetApplicationById(id);
                result = application != null && CurrentUserHasAccessToApplicationOwnedBy(application._customeridValue);
                break;

            case "contact":
                var contact = _dynamicsClient.GetContactById(id);
                result = contact != null && CurrentUserHasAccessToContactOwnedBy(contact.Contactid);
                break;

            default:
                break;
            }
            return(result);
        }
コード例 #16
0
        /// <summary>
        /// Get a Account by their Guid
        /// </summary>
        /// <param name="system"></param>
        /// <param name="distributedCache"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static async Task <MicrosoftDynamicsCRMaccount> GetAccountBySiteminderBusinessGuid(this IDynamicsClient system, string siteminderId)
        {
            MicrosoftDynamicsCRMaccount result = null;
            var accountResponse = await system.Accounts.GetAsync(filter : "adoxio_externalid eq '" + siteminderId + "'");

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

            return(result);
        }
コード例 #17
0
        /// <summary>
        /// Returns a User based on the guid
        /// </summary>
        /// <param name="context"></param>
        /// <param name="guid"></param>
        /// <returns></returns>
        public static async Task <User> GetUserByGuid(this IDynamicsClient _dynamicsClient, string guid)
        {
            Guid id      = new Guid(guid);
            User user    = null;
            var  contact = await _dynamicsClient.GetContactById(id);

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

            return(user);
        }
コード例 #18
0
        public async Task <IActionResult> CreateAlias([FromBody] ViewModels.Alias item)
        {
            if (item?.contact?.id == null || item?.worker?.id == null)
            {
                return(BadRequest());
            }

            // get the current user.
            UserSettings userSettings = UserSettings.CreateFromHttpContext(_httpContextAccessor);

            MicrosoftDynamicsCRMadoxioAlias alias = new MicrosoftDynamicsCRMadoxioAlias();

            // copy received values to Dynamics Application
            alias.CopyValues(item);
            try
            {
                alias = _dynamicsClient.Aliases.Create(alias);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error creating application");
                // fail if we can't create.
                throw (httpOperationException);
            }


            MicrosoftDynamicsCRMadoxioAlias patchAlias = new MicrosoftDynamicsCRMadoxioAlias();

            // set contact and worker associations
            try
            {
                var worker = _dynamicsClient.GetWorkerById(Guid.Parse(item.worker.id));
                patchAlias.WorkerIdODataBind = _dynamicsClient.GetEntityURI("adoxio_workers", item.worker.id);

                var contact = _dynamicsClient.GetContactById(Guid.Parse(item.contact.id));
                patchAlias.ContactIdODataBind = _dynamicsClient.GetEntityURI("contacts", item.contact.id);

                await _dynamicsClient.Aliases.UpdateAsync(alias.AdoxioAliasid, patchAlias);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error updating application");
                // fail if we can't create.
                throw (httpOperationException);
            }

            return(new JsonResult(alias.ToViewModel()));
        }
        public async Task <IActionResult> CreateAddress([FromBody] ViewModels.PreviousAddress item)
        {
            // for association with current user
            string       userJson     = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(userJson);

            MicrosoftDynamicsCRMadoxioPreviousaddress address = new MicrosoftDynamicsCRMadoxioPreviousaddress();

            // copy received values to Dynamics Application
            address.CopyValues(item);
            try
            {
                address = _dynamicsClient.Previousaddresses.Create(address);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error creating application");
                // fail if we can't create.
                throw (httpOperationException);
            }


            MicrosoftDynamicsCRMadoxioPreviousaddress patchAddress = new MicrosoftDynamicsCRMadoxioPreviousaddress();

            // set contact and worker associations
            try
            {
                var contact = _dynamicsClient.GetContactById(Guid.Parse(item.contactId));
                patchAddress.ContactIdODataBind = _dynamicsClient.GetEntityURI("contacts", item.contactId);

                if (item.workerId != null)
                {
                    var worker = _dynamicsClient.GetWorkerById(Guid.Parse(item.workerId));
                    patchAddress.WorkerIdODataBind = _dynamicsClient.GetEntityURI("adoxio_workers", item.workerId);
                }

                await _dynamicsClient.Previousaddresses.UpdateAsync(address.AdoxioPreviousaddressid, patchAddress);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error updating application");
                // fail if we can't create.
                throw (httpOperationException);
            }

            return(new JsonResult(address.ToViewModel()));
        }
コード例 #20
0
        public async static Task <Application> ToViewModel(this MicrosoftDynamicsCRMadoxioApplication dynamicsApplication, IDynamicsClient dynamicsClient)
        {
            Application applicationVM = new ViewModels.Application()
            {
                Name      = dynamicsApplication.AdoxioName,
                JobNumber = dynamicsApplication.AdoxioJobnumber,
                //get establishment name and address
                EstablishmentName              = dynamicsApplication.AdoxioEstablishmentpropsedname,
                EstablishmentAddressStreet     = dynamicsApplication.AdoxioEstablishmentaddressstreet,
                EstablishmentAddressCity       = dynamicsApplication.AdoxioEstablishmentaddresscity,
                EstablishmentAddressPostalCode = dynamicsApplication.AdoxioEstablishmentaddresspostalcode,
                EstablishmentAddress           = dynamicsApplication.AdoxioEstablishmentaddressstreet
                                                 + ", " + dynamicsApplication.AdoxioEstablishmentaddresscity
                                                 + " " + dynamicsApplication.AdoxioEstablishmentaddresspostalcode,
                EstablishmentPhone   = dynamicsApplication.AdoxioEstablishmentphone,
                EstablishmentEmail   = dynamicsApplication.AdoxioEstablishmentemail,
                FederalProducerNames = dynamicsApplication.AdoxioFederalproducernames,

                ServicehHoursStandardHours = dynamicsApplication.AdoxioServicehoursstandardhours,
                ServiceHoursSundayOpen     = (ServiceHours?)dynamicsApplication.AdoxioServicehourssundayopen,
                ServiceHoursSundayClose    = (ServiceHours?)dynamicsApplication.AdoxioServicehourssundayclose,
                ServiceHoursMondayOpen     = (ServiceHours?)dynamicsApplication.AdoxioServicehoursmondayopen,
                ServiceHoursMondayClose    = (ServiceHours?)dynamicsApplication.AdoxioServicehoursmondayclose,
                ServiceHoursTuesdayOpen    = (ServiceHours?)dynamicsApplication.AdoxioServicehourstuesdayopen,
                ServiceHoursTuesdayClose   = (ServiceHours?)dynamicsApplication.AdoxioServicehourstuesdayclose,
                ServiceHoursWednesdayOpen  = (ServiceHours?)dynamicsApplication.AdoxioServicehourswednesdayopen,
                ServiceHoursWednesdayClose = (ServiceHours?)dynamicsApplication.AdoxioServicehourswednesdayclose,
                ServiceHoursThursdayOpen   = (ServiceHours?)dynamicsApplication.AdoxioServicehoursthursdayopen,
                ServiceHoursThursdayClose  = (ServiceHours?)dynamicsApplication.AdoxioServicehoursthursdayclose,
                ServiceHoursFridayOpen     = (ServiceHours?)dynamicsApplication.AdoxioServicehoursfridayopen,
                ServiceHoursFridayClose    = (ServiceHours?)dynamicsApplication.AdoxioServicehoursfridayclose,
                ServiceHoursSaturdayOpen   = (ServiceHours?)dynamicsApplication.AdoxioServicehourssaturdayopen,
                ServiceHoursSaturdayClose  = (ServiceHours?)dynamicsApplication.AdoxioServicehourssaturdayclose,

                RenewalCriminalOffenceCheck     = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalcriminaloffencecheck,
                RenewalUnreportedSaleOfBusiness = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalunreportedsaleofbusiness,
                RenewalBusinessType             = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalbusinesstype,
                RenewalTiedhouse            = (ValueNotChanged?)dynamicsApplication.AdoxioRenewaltiedhouse,
                RenewalOrgLeadership        = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalorgleadership,
                Renewalkeypersonnel         = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalkeypersonnel,
                RenewalShareholders         = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalshareholders,
                RenewalOutstandingFines     = (ValueNotChanged?)dynamicsApplication.AdoxioRenewaloutstandingfines,
                RenewalBranding             = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalbranding,
                RenewalSignage              = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalsignage,
                RenewalEstablishmentAddress = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalestablishmentaddress,
                RenewalValidInterest        = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalvalidinterest,
                RenewalZoning            = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalzoning,
                RenewalFloorPlan         = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalfloorplan,
                RenewalSiteMap           = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalsitemap,
                TiedhouseFederalInterest = (ValueNotChanged?)dynamicsApplication.AdoxioRenewaltiedhousefederalinterest,



                AuthorizedToSubmit = dynamicsApplication.AdoxioAuthorizedtosubmit,
                SignatureAgreement = dynamicsApplication.AdoxioSignatureagreement,

                LicenceFeeInvoicePaid = (dynamicsApplication.AdoxioLicencefeeinvoicepaid != null && dynamicsApplication.AdoxioLicencefeeinvoicepaid == true),

                // set a couple of read-only flags to indicate status
                IsPaid = (dynamicsApplication.AdoxioPaymentrecieved != null && (bool)dynamicsApplication.AdoxioPaymentrecieved),

                IndigenousNationId = dynamicsApplication._adoxioLocalgovindigenousnationidValue,

                //get parcel id
                EstablishmentParcelId = dynamicsApplication.AdoxioEstablishmentparcelid,

                //get additional property info
                AdditionalPropertyInformation = dynamicsApplication.AdoxioAdditionalpropertyinformation,
                AdoxioInvoiceId = dynamicsApplication._adoxioInvoiceValue,

                PaymentReceivedDate = dynamicsApplication.AdoxioPaymentreceiveddate,
                Description1        = dynamicsApplication.AdoxioDescription1,

                //get contact details
                ContactPersonFirstName = dynamicsApplication.AdoxioContactpersonfirstname,
                ContactPersonLastName  = dynamicsApplication.AdoxioContactpersonlastname,
                ContactPersonRole      = dynamicsApplication.AdoxioRole,
                ContactPersonEmail     = dynamicsApplication.AdoxioEmail,
                ContactPersonPhone     = dynamicsApplication.AdoxioContactpersonphone,

                //get record audit info
                CreatedOn  = dynamicsApplication.Createdon,
                ModifiedOn = dynamicsApplication.Modifiedon,

                //store opening
                IsReadyWorkers                  = dynamicsApplication.AdoxioIsreadyworkers,
                IsReadyNameBranding             = dynamicsApplication.AdoxioIsreadynamebranding,
                IsReadyDisplays                 = dynamicsApplication.AdoxioIsreadydisplays,
                IsReadyIntruderAlarm            = dynamicsApplication.AdoxioIsreadyintruderalarm,
                IsReadyFireAlarm                = dynamicsApplication.AdoxioIsreadyfirealarm,
                IsReadyLockedCases              = dynamicsApplication.AdoxioIsreadylockedcases,
                IsReadyLockedStorage            = dynamicsApplication.AdoxioIsreadylockedstorage,
                IsReadyPerimeter                = dynamicsApplication.AdoxioIsreadyperimeter,
                IsReadyRetailArea               = dynamicsApplication.AdoxioIsreadyretailarea,
                IsReadyStorage                  = dynamicsApplication.AdoxioIsreadystorage,
                IsReadyExtranceExit             = dynamicsApplication.AdoxioIsreadyentranceexit,
                IsReadySurveillanceNotice       = dynamicsApplication.AdoxioIsreadysurveillancenotice,
                IsReadyProductNotVisibleOutside = dynamicsApplication.AdoxioIsreadyproductnotvisibleoutside,
                Establishmentopeningdate        = dynamicsApplication.AdoxioEstablishmentopeningdate,
                IsReadyValidInterest            = dynamicsApplication.AdoxioIsreadyvalidinterest,
            };


            // id
            if (dynamicsApplication.AdoxioApplicationid != null)
            {
                applicationVM.Id = dynamicsApplication.AdoxioApplicationid.ToString();
            }

            if (dynamicsApplication.Statuscode != null)
            {
                applicationVM.ApplicationStatus = (AdoxioApplicationStatusCodes)dynamicsApplication.Statuscode;
            }

            if (dynamicsApplication.AdoxioApplicanttype != null)
            {
                applicationVM.ApplicantType = (AdoxioApplicantTypeCodes)dynamicsApplication.AdoxioApplicanttype;
            }

            //get applying person from Contact entity
            if (dynamicsApplication._adoxioApplyingpersonValue != null)
            {
                Guid applyingPersonId = Guid.Parse(dynamicsApplication._adoxioApplyingpersonValue);
                var  contact          = await dynamicsClient.GetContactById(applyingPersonId);

                applicationVM.ApplyingPerson = contact.Fullname;
            }
            if (dynamicsApplication._adoxioApplicantValue != null)
            {
                var applicant = await dynamicsClient.GetAccountById(Guid.Parse(dynamicsApplication._adoxioApplicantValue));

                applicationVM.Applicant = applicant.ToViewModel();
            }

            //get license type from Adoxio_licencetype entity
            if (dynamicsApplication._adoxioLicencetypeValue != null)
            {
                Guid adoxio_licencetypeId = Guid.Parse(dynamicsApplication._adoxioLicencetypeValue);
                var  adoxio_licencetype   = dynamicsClient.GetAdoxioLicencetypeById(adoxio_licencetypeId);
                applicationVM.LicenseType = adoxio_licencetype.AdoxioName;
            }

            if (dynamicsApplication.AdoxioAppchecklistfinaldecision != null)
            {
                applicationVM.AppChecklistFinalDecision = (AdoxioFinalDecisionCodes)dynamicsApplication.AdoxioAppchecklistfinaldecision;
            }

            //get payment info
            if (dynamicsApplication.AdoxioInvoicetrigger != null && dynamicsApplication.AdoxioInvoicetrigger == 1)
            {
                applicationVM.AdoxioInvoiceTrigger = GeneralYesNo.Yes;
                applicationVM.IsSubmitted          = true;
            }
            else
            {
                applicationVM.AdoxioInvoiceTrigger = GeneralYesNo.No;
                applicationVM.IsSubmitted          = false;
            }

            if (dynamicsApplication.AdoxioLicenceFeeInvoice != null)
            {
                applicationVM.LicenceFeeInvoice = dynamicsApplication.AdoxioLicenceFeeInvoice.ToViewModel();
            }

            if (dynamicsApplication.AdoxioAssignedLicence != null)
            {
                applicationVM.AssignedLicence = dynamicsApplication.AdoxioAssignedLicence.ToViewModel(dynamicsClient);
            }

            if (dynamicsApplication.AdoxioApplicationTypeId != null)
            {
                applicationVM.ApplicationType = dynamicsApplication.AdoxioApplicationTypeId.ToViewModel();
            }
            if (dynamicsApplication.AdoxioApplicationAdoxioTiedhouseconnectionApplication != null)
            {
                var tiedHouse = dynamicsApplication.AdoxioApplicationAdoxioTiedhouseconnectionApplication.FirstOrDefault();
                if (tiedHouse != null)
                {
                    applicationVM.TiedHouse = tiedHouse.ToViewModel();
                }
            }

            applicationVM.PrevPaymentFailed = (dynamicsApplication._adoxioInvoiceValue != null) && (!applicationVM.IsSubmitted);

            return(applicationVM);
        }
コード例 #21
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));
        }
コード例 #22
0
        /// <summary>
        /// Returns the SharePoint document Location for a given entity record
        /// </summary>
        /// <param name="entityName"></param>
        /// <param name="entityId"></param>
        /// <returns></returns>
        public static string GetEntitySharePointDocumentLocation(this IDynamicsClient _dynamicsClient, string entityName, string entityId)
        {
            string result = null;
            var    id     = Guid.Parse(entityId);

            try
            {
                switch (entityName.ToLower())
                {
                case "account":
                    var account         = _dynamicsClient.GetAccountById(entityId);
                    var accountLocation = account.AccountSharepointDocumentLocation.FirstOrDefault();
                    if (accountLocation != null && !string.IsNullOrEmpty(accountLocation.Relativeurl))
                    {
                        result = accountLocation.Relativeurl;
                    }
                    break;

                case "application":
                    var application         = _dynamicsClient.GetApplicationByIdWithChildren(entityId).GetAwaiter().GetResult();
                    var applicationLocation = application.AdoxioApplicationSharePointDocumentLocations.FirstOrDefault();
                    if (applicationLocation != null && !string.IsNullOrEmpty(applicationLocation.Relativeurl))
                    {
                        result = applicationLocation.Relativeurl;
                    }
                    break;

                case "contact":
                    var contact         = _dynamicsClient.GetContactById(entityId).GetAwaiter().GetResult();
                    var contactLocation = contact.ContactSharePointDocumentLocations.FirstOrDefault();
                    if (contactLocation != null && !string.IsNullOrEmpty(contactLocation.Relativeurl))
                    {
                        result = contactLocation.Relativeurl;
                    }
                    break;

                case "worker":
                    var worker         = _dynamicsClient.GetWorkerByIdWithChildren(entityId).GetAwaiter().GetResult();
                    var workerLocation = worker.AdoxioWorkerSharePointDocumentLocations.FirstOrDefault();
                    if (workerLocation != null && !string.IsNullOrEmpty(workerLocation.Relativeurl))
                    {
                        result = workerLocation.Relativeurl;
                    }
                    break;

                case "event":
                    var eventEntity   = _dynamicsClient.GetEventByIdWithChildren(entityId);
                    var eventLocation = eventEntity.AdoxioEventSharePointDocumentLocations.FirstOrDefault();
                    if (eventLocation != null && !string.IsNullOrEmpty(eventLocation.Relativeurl))
                    {
                        result = eventLocation.Relativeurl;
                    }
                    break;

                case "licence":
                    var licenceEntity   = _dynamicsClient.GetLicenceByIdWithChildren(entityId);
                    var licenceLocation = licenceEntity.AdoxioLicencesSharePointDocumentLocations.FirstOrDefault();
                    if (licenceLocation != null && !string.IsNullOrEmpty(licenceLocation.Relativeurl))
                    {
                        result = licenceLocation.Relativeurl;
                    }
                    break;
                }
            }
            catch (ArgumentNullException)
            {
                return(null);
            }
            return(result);
        }
コード例 #23
0
        public async static Task <ViewModels.Application> ToViewModel(this MicrosoftDynamicsCRMadoxioApplication dynamicsApplication, IDynamicsClient dynamicsClient, IMemoryCache cache, ILogger logger)
        {
            ViewModels.Application applicationVM = new ViewModels.Application()
            {
                Name      = dynamicsApplication.AdoxioName,
                JobNumber = dynamicsApplication.AdoxioJobnumber,
                //get establishment name and address
                EstablishmentName              = dynamicsApplication.AdoxioEstablishmentpropsedname,
                EstablishmentAddressStreet     = dynamicsApplication.AdoxioEstablishmentaddressstreet,
                EstablishmentAddressCity       = dynamicsApplication.AdoxioEstablishmentaddresscity,
                EstablishmentAddressPostalCode = dynamicsApplication.AdoxioEstablishmentaddresspostalcode,
                EstablishmentAddress           = dynamicsApplication.AdoxioEstablishmentaddressstreet
                                                 + ", " + dynamicsApplication.AdoxioEstablishmentaddresscity
                                                 + " " + dynamicsApplication.AdoxioEstablishmentaddresspostalcode,
                EstablishmentPhone    = dynamicsApplication.AdoxioEstablishmentphone,
                EstablishmentEmail    = dynamicsApplication.AdoxioEstablishmentemail,
                FederalProducerNames  = dynamicsApplication.AdoxioFederalproducernames,
                IsApplicationComplete = (GeneralYesNo?)dynamicsApplication.AdoxioIsapplicationcomplete,

                RenewalCriminalOffenceCheck     = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalcriminaloffencecheck,
                RenewalUnreportedSaleOfBusiness = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalunreportedsaleofbusiness,
                RenewalBusinessType             = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalbusinesstype,
                RenewalTiedhouse            = (ValueNotChanged?)dynamicsApplication.AdoxioRenewaltiedhouse,
                RenewalOrgLeadership        = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalorgleadership,
                Renewalkeypersonnel         = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalkeypersonnel,
                RenewalShareholders         = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalshareholders,
                RenewalOutstandingFines     = (ValueNotChanged?)dynamicsApplication.AdoxioRenewaloutstandingfines,
                RenewalBranding             = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalbranding,
                RenewalSignage              = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalsignage,
                RenewalEstablishmentAddress = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalestablishmentaddress,
                RenewalValidInterest        = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalvalidinterest,
                RenewalZoning            = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalzoning,
                RenewalFloorPlan         = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalfloorplan,
                RenewalSiteMap           = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalsitemap,
                TiedhouseFederalInterest = (ValueNotChanged?)dynamicsApplication.AdoxioRenewaltiedhousefederalinterest,
                RenewalDUI        = (ValueNotChanged?)dynamicsApplication.AdoxioRenewaldui,
                RenewalThirdParty = (ValueNotChanged?)dynamicsApplication.AdoxioRenewalthirdparty,

                AuthorizedToSubmit = dynamicsApplication.AdoxioAuthorizedtosubmit,
                SignatureAgreement = dynamicsApplication.AdoxioSignatureagreement,

                LicenceFeeInvoicePaid = (dynamicsApplication.AdoxioLicencefeeinvoicepaid != null && dynamicsApplication.AdoxioLicencefeeinvoicepaid == true),

                // set a couple of read-only flags to indicate status
                IsPaid = (dynamicsApplication.AdoxioPaymentrecieved != null && (bool)dynamicsApplication.AdoxioPaymentrecieved),

                IndigenousNationId   = dynamicsApplication._adoxioLocalgovindigenousnationidValue,
                PoliceJurisdictionId = dynamicsApplication._adoxioPolicejurisdictionidValue,

                //get parcel id
                EstablishmentParcelId = dynamicsApplication.AdoxioEstablishmentparcelid,

                //get additional property info
                AdditionalPropertyInformation = dynamicsApplication.AdoxioAdditionalpropertyinformation,
                AdoxioInvoiceId = dynamicsApplication._adoxioInvoiceValue,

                PaymentReceivedDate = dynamicsApplication.AdoxioPaymentreceiveddate,
                Description1        = dynamicsApplication.AdoxioDescription1,
                Description2        = dynamicsApplication.AdoxioDescription2,

                //get contact details
                ContactPersonFirstName = dynamicsApplication.AdoxioContactpersonfirstname,
                ContactPersonLastName  = dynamicsApplication.AdoxioContactpersonlastname,
                ContactPersonRole      = dynamicsApplication.AdoxioRole,
                ContactPersonEmail     = dynamicsApplication.AdoxioEmail,
                ContactPersonPhone     = dynamicsApplication.AdoxioContactpersonphone,

                //get record audit info
                CreatedOn  = dynamicsApplication.Createdon,
                ModifiedOn = dynamicsApplication.Modifiedon,

                //store opening
                IsReadyWorkers                  = dynamicsApplication.AdoxioIsreadyworkers,
                IsReadyNameBranding             = dynamicsApplication.AdoxioIsreadynamebranding,
                IsReadyDisplays                 = dynamicsApplication.AdoxioIsreadydisplays,
                IsReadyIntruderAlarm            = dynamicsApplication.AdoxioIsreadyintruderalarm,
                IsReadyFireAlarm                = dynamicsApplication.AdoxioIsreadyfirealarm,
                IsReadyLockedCases              = dynamicsApplication.AdoxioIsreadylockedcases,
                IsReadyLockedStorage            = dynamicsApplication.AdoxioIsreadylockedstorage,
                IsReadyPerimeter                = dynamicsApplication.AdoxioIsreadyperimeter,
                IsReadyRetailArea               = dynamicsApplication.AdoxioIsreadyretailarea,
                IsReadyStorage                  = dynamicsApplication.AdoxioIsreadystorage,
                IsReadyExtranceExit             = dynamicsApplication.AdoxioIsreadyentranceexit,
                IsReadySurveillanceNotice       = dynamicsApplication.AdoxioIsreadysurveillancenotice,
                IsReadyProductNotVisibleOutside = dynamicsApplication.AdoxioIsreadyproductnotvisibleoutside,
                IsLocatedInGroceryStore         = dynamicsApplication.AdoxioIslocatedingrocerystore,
                Establishmentopeningdate        = dynamicsApplication.AdoxioEstablishmentopeningdate,
                IsReadyValidInterest            = dynamicsApplication.AdoxioIsreadyvalidinterest,

                IsHasPatio = dynamicsApplication.AdoxioIshaspatio,

                // LgInName
                LGNameOfOfficial         = dynamicsApplication.AdoxioLgnameofofficial,
                LGTitlePosition          = dynamicsApplication.AdoxioLgtitleposition,
                LGContactPhone           = dynamicsApplication.AdoxioLgcontactphone,
                LGContactEmail           = dynamicsApplication.AdoxioLgcontactemail,
                LGDecisionSubmissionDate = dynamicsApplication.AdoxioLgdecisionsubmissiondate,
                LgInName           = dynamicsApplication?.AdoxioLocalgovindigenousnationid?.AdoxioName,
                LGApprovalDecision = (LGDecision?)dynamicsApplication.AdoxioLgapprovaldecision,
                LgZoning           = (Zoning?)dynamicsApplication.AdoxioLgzoning,
                LGDecisionComments = dynamicsApplication.AdoxioLgdecisioncomments,

                // Catering fields.

                PreviousApplicationDetails = dynamicsApplication.AdoxioPreviouslicenceapplicationdetails,

                LiquorIndustryConnectionsDetails = dynamicsApplication.AdoxioLiquorindustryconnectionsdetails,

                OtherBusinessesDetails = dynamicsApplication.AdoxioOtherbusinesssamelocationdetails,
                ServiceAreas           = new List <CapacityArea>(),
                OutsideAreas           = new List <CapacityArea>(),
                CapacityArea           = new List <CapacityArea>(),

                // Manufacturing fields

                IsPackaging = dynamicsApplication.AdoxioIspackaging,

                MfgAcresOfFruit           = dynamicsApplication.AdoxioMfgacresoffruit,
                MfgAcresOfGrapes          = dynamicsApplication.AdoxioMfgacresofgrapes,
                MfgAcresOfHoney           = dynamicsApplication.AdoxioMfgacresofhoney,
                MfgMeetsProductionMinimum = dynamicsApplication.AdoxioMfgmeetsproductionminimum,
                MfgStepBlending           = dynamicsApplication.AdoxioMfgstepblending,
                MfgStepCrushing           = dynamicsApplication.AdoxioMfgstepcrushing,
                MfgStepFiltering          = dynamicsApplication.AdoxioMfgstepfiltering,
                MfgStepSecFermOrCarb      = dynamicsApplication.AdoxioMfgstepsecfermorcarb,
                IsOwnerBusiness           = dynamicsApplication.AdoxioIsownerbusiness,
                HasValidInterest          = dynamicsApplication.AdoxioIsownerhasvalidinterest,
                WillHaveValidInterest     = dynamicsApplication.AdoxioIsownerwillhavevalidinterest,
                ZoningStatus = dynamicsApplication.AdoxioZoningstatus,


                PidList             = dynamicsApplication.AdoxioPidlist,
                IsPermittedInZoning = dynamicsApplication.AdoxioIspermittedinzoning,

                // Manufacturing structural change fields

                PatioCompDescription          = dynamicsApplication.AdoxioPatiocompdescription,
                PatioLocationDescription      = dynamicsApplication.AdoxioPatiolocationdescription,
                PatioAccessDescription        = dynamicsApplication.AdoxioPatioaccessdescription,
                PatioIsLiquorCarried          = dynamicsApplication.AdoxioPatioisliquorcarried,
                PatioLiquorCarriedDescription = dynamicsApplication.AdoxioPatioliquorcarrieddescription,
                PatioAccessControlDescription = dynamicsApplication.AdoxioPatioaccesscontroldescription,
                IsAlr           = dynamicsApplication.AdoxioProposedestablishmentisalr.HasValue && (bool)dynamicsApplication.AdoxioProposedestablishmentisalr,
                HasCoolerAccess = dynamicsApplication.AdoxioHascooleraccess.HasValue && (bool)dynamicsApplication.AdoxioHascooleraccess
            };


            // mfg fields

            if (dynamicsApplication.AdoxioMfgpipedinproduct != null)
            {
                applicationVM.MfgPipedInProduct = (YesNoNotApplicable?)dynamicsApplication.AdoxioMfgpipedinproduct;
            }
            if (dynamicsApplication.AdoxioMfgbrewpubonsite != null)
            {
                applicationVM.MfgBrewPubOnSite = (YesNoNotApplicable?)dynamicsApplication.AdoxioMfgbrewpubonsite;
            }
            if (dynamicsApplication.AdoxioMfgusesneutralgrainspirits != null)
            {
                applicationVM.MfgUsesNeutralGrainSpirits = (YesNoNotApplicable)dynamicsApplication.AdoxioMfgusesneutralgrainspirits;
            }


            if (dynamicsApplication.AdoxioLocatedabovedescription != null)
            {
                applicationVM.LocatedAboveDescription = dynamicsApplication.AdoxioLocatedabovedescription;
            }

            if (dynamicsApplication.AdoxioPatioservicebar != null)
            {
                applicationVM.PatioServiceBar = dynamicsApplication.AdoxioPatioservicebar;
            }

            // Catering yes / no fields
            if (dynamicsApplication.AdoxioPreviouslicenceapplication != null)
            {
                applicationVM.PreviousApplication = dynamicsApplication.AdoxioPreviouslicenceapplication;
            }

            if (dynamicsApplication.AdoxioRuralagencystoreappointment != null)
            {
                applicationVM.RuralAgencyStoreAppointment = dynamicsApplication.AdoxioRuralagencystoreappointment;
            }

            if (dynamicsApplication.AdoxioLiquorindustryconnections != null)
            {
                applicationVM.LiquorIndustryConnections = dynamicsApplication.AdoxioLiquorindustryconnections;
            }

            if (dynamicsApplication.AdoxioOtherbusinessesatthesamelocation != null)
            {
                applicationVM.OtherBusinesses = dynamicsApplication.AdoxioOtherbusinessesatthesamelocation;
            }


            // id
            if (dynamicsApplication.AdoxioApplicationid != null)
            {
                applicationVM.Id = dynamicsApplication.AdoxioApplicationid.ToString();

                // service areas
                var filter = $"_adoxio_applicationid_value eq {dynamicsApplication.AdoxioApplicationid}";
                try
                {
                    IList <MicrosoftDynamicsCRMadoxioServicearea> areas = dynamicsClient.Serviceareas.Get(filter: filter).Value;
                    foreach (MicrosoftDynamicsCRMadoxioServicearea area in areas)
                    {
                        if (area.AdoxioAreacategory == (int?)AdoxioAreaCategories.Service)
                        {
                            applicationVM.ServiceAreas.Add(area.ToViewModel());
                        }
                        else if (area.AdoxioAreacategory == (int?)AdoxioAreaCategories.OutdoorArea)
                        {
                            applicationVM.OutsideAreas.Add(area.ToViewModel());
                        }
                        else if (area.AdoxioAreacategory == (int?)AdoxioAreaCategories.Capacity)
                        {
                            applicationVM.CapacityArea.Add(area.ToViewModel());
                        }
                    }
                }
                catch (HttpOperationException httpOperationException)
                {
                    logger.LogError(httpOperationException, "Error getting service areas.");
                }

                // service hours
                try
                {
                    var appFilter = $"_adoxio_application_value eq {dynamicsApplication.AdoxioApplicationid}";
                    IList <MicrosoftDynamicsCRMadoxioHoursofservice> hours = dynamicsClient.Hoursofservices.Get(filter: appFilter).Value;
                    if (hours.Count > 0)
                    {
                        MicrosoftDynamicsCRMadoxioHoursofservice hourEntity = hours[0];
                        applicationVM.ServiceHoursSundayOpen     = (ServiceHours?)hourEntity.AdoxioSundayopen;
                        applicationVM.ServiceHoursSundayClose    = (ServiceHours?)hourEntity.AdoxioSundayclose;
                        applicationVM.ServiceHoursMondayOpen     = (ServiceHours?)hourEntity.AdoxioMondayopen;
                        applicationVM.ServiceHoursMondayClose    = (ServiceHours?)hourEntity.AdoxioMondayclose;
                        applicationVM.ServiceHoursTuesdayOpen    = (ServiceHours?)hourEntity.AdoxioTuesdayopen;
                        applicationVM.ServiceHoursTuesdayClose   = (ServiceHours?)hourEntity.AdoxioTuesdayclose;
                        applicationVM.ServiceHoursWednesdayOpen  = (ServiceHours?)hourEntity.AdoxioWednesdayopen;
                        applicationVM.ServiceHoursWednesdayClose = (ServiceHours?)hourEntity.AdoxioWednesdayclose;
                        applicationVM.ServiceHoursThursdayOpen   = (ServiceHours?)hourEntity.AdoxioThursdayopen;
                        applicationVM.ServiceHoursThursdayClose  = (ServiceHours?)hourEntity.AdoxioThursdayclose;
                        applicationVM.ServiceHoursFridayOpen     = (ServiceHours?)hourEntity.AdoxioFridayopen;
                        applicationVM.ServiceHoursFridayClose    = (ServiceHours?)hourEntity.AdoxioFridayclose;
                        applicationVM.ServiceHoursSaturdayOpen   = (ServiceHours?)hourEntity.AdoxioSaturdayopen;
                        applicationVM.ServiceHoursSaturdayClose  = (ServiceHours?)hourEntity.AdoxioSaturdayclose;
                    }
                }
                catch (HttpOperationException httpOperationException)
                {
                    logger.LogError(httpOperationException, "Error getting service hours.");
                }
            }

            if (dynamicsApplication.Statuscode != null)
            {
                applicationVM.ApplicationStatus = (AdoxioApplicationStatusCodes)dynamicsApplication.Statuscode;
            }

            if (dynamicsApplication.AdoxioApplicanttype != null)
            {
                applicationVM.ApplicantType = (AdoxioApplicantTypeCodes)dynamicsApplication.AdoxioApplicanttype;
            }

            //get applying person from Contact entity
            if (dynamicsApplication._adoxioApplyingpersonValue != null)
            {
                Guid applyingPersonId = Guid.Parse(dynamicsApplication._adoxioApplyingpersonValue);
                var  contact          = await dynamicsClient.GetContactById(applyingPersonId);

                applicationVM.ApplyingPerson = contact.Fullname;
            }

            if (dynamicsApplication._adoxioApplicantValue != null)
            {
                var applicant = await dynamicsClient.GetAccountByIdAsync(Guid.Parse(dynamicsApplication._adoxioApplicantValue));

                applicationVM.Applicant = applicant.ToViewModel();
            }

            //get license type from Adoxio_licencetype entity
            if (dynamicsApplication._adoxioLicencetypeValue != null)
            {
                Guid adoxio_licencetypeId = Guid.Parse(dynamicsApplication._adoxioLicencetypeValue);
                var  adoxio_licencetype   = dynamicsClient.GetAdoxioLicencetypeById(adoxio_licencetypeId);
                applicationVM.LicenseType = adoxio_licencetype.AdoxioName;
            }

            // get the license sub type.

            if (dynamicsApplication._adoxioLicencesubcategoryidValue != null)
            {
                try
                {
                    var adoxioLicencesubcategory = dynamicsClient.Licencesubcategories.GetByKey(dynamicsApplication._adoxioLicencesubcategoryidValue);
                    applicationVM.LicenceSubCategory = adoxioLicencesubcategory.AdoxioName;
                }
                catch (Exception e)
                {
                    logger.LogError(e, $"Problem getting licence sub category {dynamicsApplication._adoxioLicencesubcategoryidValue}");
                }
            }

            if (dynamicsApplication.AdoxioAppchecklistfinaldecision != null)
            {
                applicationVM.AppChecklistFinalDecision = (AdoxioFinalDecisionCodes)dynamicsApplication.AdoxioAppchecklistfinaldecision;
            }

            //get payment info
            applicationVM.InvoiceTrigger = (GeneralYesNo?)dynamicsApplication.AdoxioInvoicetrigger;
            applicationVM.IsSubmitted    = (dynamicsApplication.AdoxioInvoicetrigger == 1);


            if (dynamicsApplication.AdoxioLicenceFeeInvoice != null)
            {
                applicationVM.LicenceFeeInvoice = dynamicsApplication.AdoxioLicenceFeeInvoice.ToViewModel();
            }

            if (dynamicsApplication.AdoxioAssignedLicence != null)
            {
                applicationVM.AssignedLicence = dynamicsApplication.AdoxioAssignedLicence.ToViewModel(dynamicsClient);
            }

            if (dynamicsApplication.AdoxioApplicationTypeId != null)
            {
                applicationVM.ApplicationType = dynamicsApplication.AdoxioApplicationTypeId.ToViewModel();

                if (!string.IsNullOrEmpty(applicationVM.ApplicationType.FormReference))
                {
                    applicationVM.ApplicationType.DynamicsForm = dynamicsClient.GetSystemformViewModel(cache, logger, applicationVM.ApplicationType.FormReference);
                }
            }
            if (dynamicsApplication.AdoxioApplicationAdoxioTiedhouseconnectionApplication != null)
            {
                var tiedHouse = dynamicsApplication.AdoxioApplicationAdoxioTiedhouseconnectionApplication.FirstOrDefault();
                if (tiedHouse != null)
                {
                    applicationVM.TiedHouse = tiedHouse.ToViewModel();
                }
            }

            if (dynamicsApplication.AdoxioPoliceJurisdictionId != null)
            {
                applicationVM.PoliceJurisdiction = dynamicsApplication.AdoxioPoliceJurisdictionId.ToViewModel();
            }

            if (dynamicsApplication.AdoxioLocalgovindigenousnationid != null)
            {
                var filter        = $"_adoxio_lginlinkid_value eq {dynamicsApplication.AdoxioLocalgovindigenousnationid.AdoxioLocalgovindigenousnationid} and websiteurl ne null";
                var linkedAccount = (await dynamicsClient.Accounts.GetAsync(filter: filter)).Value.FirstOrDefault();
                applicationVM.IndigenousNation = dynamicsApplication.AdoxioLocalgovindigenousnationid.ToViewModel();

                if (linkedAccount != null)
                {
                    applicationVM.IndigenousNation.WebsiteUrl = linkedAccount.Websiteurl;
                }
            }

            applicationVM.PrevPaymentFailed = (dynamicsApplication._adoxioInvoiceValue != null) && (!applicationVM.IsSubmitted);

            return(applicationVM);
        }
コード例 #24
0
        public async Task <IActionResult> CreateDynamicsAccount([FromBody] ViewModels.Account item)
        {
            ViewModels.Account result       = null;
            Boolean            updateIfNull = true;

            // get UserSettings from the session
            string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);

            // get account Siteminder GUID
            string accountSiteminderGuid = userSettings.SiteMinderBusinessGuid;

            if (accountSiteminderGuid == null || accountSiteminderGuid.Length == 0)
            {
                throw new Exception("Oops no accountSiteminderGuid exernal id");
            }

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

            if (contactSiteminderGuid == null || contactSiteminderGuid.Length == 0)
            {
                throw new Exception("Oops no ContactSiteminderGuid exernal id");
            }

            // get BCeID record for the current user
            //var bceidBusiness = await _bceid.ProcessBusinessQuery("44437132CF6B4E919FE6FBFC5594FC44");
            var bceidBusiness = await _bceid.ProcessBusinessQuery(userSettings.SiteMinderGuid);

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

            // see if the contact exists.
            userContact = await _dynamicsClient.GetContactBySiteminderGuid(contactSiteminderGuid);

            if (userContact == null)
            {
                // create the user contact record.
                userContact = new MicrosoftDynamicsCRMcontact();
                // Adoxio_externalid is where we will store the guid from siteminder.
                userContact.AdoxioExternalid = contactSiteminderGuid;
                userContact.Fullname         = userSettings.UserDisplayName;
                userContact.Nickname         = userSettings.UserDisplayName;
                userContact.Employeeid       = userSettings.UserId;

                if (bceidBusiness != null)
                {
                    // set contact according to item
                    userContact.Firstname     = bceidBusiness.individualFirstname;
                    userContact.Middlename    = bceidBusiness.individualMiddlename;
                    userContact.Lastname      = bceidBusiness.individualSurname;
                    userContact.Emailaddress1 = bceidBusiness.contactEmail;
                    userContact.Telephone1    = bceidBusiness.contactPhone;
                }
                else
                {
                    userContact.Firstname = userSettings.UserDisplayName.GetFirstName();
                    userContact.Lastname  = userSettings.UserDisplayName.GetLastName();
                }
                userContact.Statuscode = 1;
            }
            // this may be an existing account, as this service is used during the account confirmation process.
            MicrosoftDynamicsCRMaccount account = await _dynamicsClient.GetAccountBySiteminderBusinessGuid(accountSiteminderGuid);

            if (account == null) // do a deep create.  create 3 objects at once.
            {
                // create a new account
                account = new MicrosoftDynamicsCRMaccount();
                account.CopyValues(item, updateIfNull);
                // business type must be set only during creation, not in update (removed from copyValues() )
                account.AdoxioBusinesstype = (int)Enum.Parse(typeof(ViewModels.Adoxio_applicanttypecodes), item.businessType, true);
                // ensure that we create an account for the current user.
                account.AdoxioExternalid = accountSiteminderGuid;

                account.Primarycontactid  = userContact;
                account.AdoxioAccounttype = (int)Adoxio_accounttypecodes.Applicant;

                if (bceidBusiness != null)
                {
                    account.Emailaddress1      = bceidBusiness.contactEmail;
                    account.Telephone1         = bceidBusiness.contactPhone;
                    account.Address1City       = bceidBusiness.addressCity;
                    account.Address1Postalcode = bceidBusiness.addressPostal;
                    account.Address1Line1      = bceidBusiness.addressLine1;
                    account.Address1Line2      = bceidBusiness.addressLine2;
                    account.Address1Postalcode = bceidBusiness.addressPostal;
                }

                // sets Business type with numerical value found in Adoxio_applicanttypecodes
                // using account.businessType which is set in bceid-confirmation.component.ts
                account.AdoxioBusinesstype = (int)Enum.Parse(typeof(Adoxio_applicanttypecodes), item.businessType, true);

                var legalEntity = new MicrosoftDynamicsCRMadoxioLegalentity()
                {
                    AdoxioAccount      = account,
                    AdoxioName         = item.name,
                    AdoxioIsindividual = 0,
                    AdoxioIsapplicant  = true
                };

                string legalEntityString = JsonConvert.SerializeObject(legalEntity);
                _logger.LogError("Legal Entity Before --> " + legalEntityString);

                legalEntity = await _dynamicsClient.Adoxiolegalentities.CreateAsync(legalEntity);

                account.Accountid = legalEntity._adoxioAccountValue;

                // fetch the account and get the created contact.
                if (legalEntity.AdoxioAccount == null)
                {
                    legalEntity.AdoxioAccount = await _dynamicsClient.GetAccountById(Guid.Parse(account.Accountid));
                }

                if (legalEntity.AdoxioAccount.Primarycontactid == null)
                {
                    legalEntity.AdoxioAccount.Primarycontactid = await _dynamicsClient.GetContactById(Guid.Parse(legalEntity.AdoxioAccount._primarycontactidValue));
                }

                userContact.Contactid = legalEntity.AdoxioAccount._primarycontactidValue;

                legalEntityString = JsonConvert.SerializeObject(legalEntity);
                _logger.LogError("Legal Entity After --> " + legalEntityString);
            }
            else // it is a new user only.
            {
                userContact = await _dynamicsClient.Contacts.CreateAsync(userContact);
            }

            // always patch the userContact so it relates to the account.

            // parent customer id relationship will be created using the method here:
            //https://msdn.microsoft.com/en-us/library/mt607875.aspx
            MicrosoftDynamicsCRMcontact patchUserContact = new MicrosoftDynamicsCRMcontact();

            patchUserContact.ParentCustomerIdAccountODataBind = _dynamicsClient.GetEntityURI("accounts", account.Accountid);
            try
            {
                await _dynamicsClient.Contacts.UpdateAsync(userContact.Contactid, patchUserContact);
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError("Error binding contact to account");
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
            }


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

                // we can now authenticate.
                if (userSettings.AuthenticatedUser == null)
                {
                    Models.User user = new Models.User();
                    user.Active    = true;
                    user.AccountId = Guid.Parse(userSettings.AccountId);
                    user.ContactId = Guid.Parse(userSettings.ContactId);
                    user.SmUserId  = userSettings.UserId;
                    userSettings.AuthenticatedUser = user;
                }

                userSettings.IsNewUserRegistration = false;

                string userSettingsString = JsonConvert.SerializeObject(userSettings);
                _logger.LogError("AccountController --> " + userSettingsString);

                // add the user to the session.
                _httpContextAccessor.HttpContext.Session.SetString("UserSettings", userSettingsString);
            }
            else
            {
                throw new Exception("Oops not a new user registration");
            }

            //account.accountId = id;
            result = account.ToViewModel();


            return(Json(result));
        }
コード例 #25
0
        /// <summary>
        /// Returns true if the current user can access the entity
        /// </summary>
        /// <param name="entityName"></param>
        /// <param name="entityId"></param>
        /// <param name="isDelete">Some access rules are different for deletes</param>
        /// <returns></returns>
        private async Task <bool> CanAccessEntity(string entityName, string entityId, string relativeUrl, bool isDelete = false)
        {
            var    result     = false;
            var    id         = Guid.Parse(entityId);
            string folderName = null;

            switch (entityName.ToLower())
            {
            case "account":
                var account = await _dynamicsClient.GetAccountByIdAsync(id).ConfigureAwait(true);

                if (account != null)
                {
                    result     = CurrentUserHasAccessToAccount(account.Accountid);
                    folderName = account.GetDocumentFolderName();
                }
                break;

            case "application":
                var application = await _dynamicsClient.GetApplicationById(id).ConfigureAwait(true);

                if (application != null)
                {
                    result = CurrentUserHasAccessToAccount(application._adoxioApplicantValue);
                    var allowLGAccess = await CurrentUserIsLGForApplication(application);

                    result     = result || allowLGAccess && !isDelete;
                    folderName = application.GetDocumentFolderName();
                }

                break;

            case "contact":
                var contact = await _dynamicsClient.GetContactById(id).ConfigureAwait(true);

                if (contact != null)
                {
                    result     = CurrentUserHasAccessToContactOwnedBy(contact.Contactid);
                    folderName = contact.GetDocumentFolderName();
                }

                break;

            case "worker":
                var worker = await _dynamicsClient.GetWorkerById(id).ConfigureAwait(true);

                if (worker != null)
                {
                    result     = CurrentUserHasAccessToContactOwnedBy(worker._adoxioContactidValue);
                    folderName = worker.GetDocumentFolderName();
                }
                break;

            case "event":
                var eventEntity = _dynamicsClient.GetEventById(id);
                if (eventEntity != null)
                {
                    result     = CurrentUserHasAccessToAccount(eventEntity._adoxioAccountValue);
                    folderName = eventEntity.GetDocumentFolderName();
                }

                break;
            }

            if (folderName != null && result && relativeUrl != null)  // do a case insensitive comparison of the first part.
            {
                int slashPos = relativeUrl.IndexOf("/");
                if (slashPos != -1 && slashPos < relativeUrl.Length)
                {
                    slashPos = relativeUrl.IndexOf("/", slashPos + 1);
                }
                result = relativeUrl.ToUpper().Substring(slashPos + 1).StartsWith(folderName.ToUpper());
            }

            return(result);
        }
コード例 #26
0
        public async static Task <Application> ToViewModel(this MicrosoftDynamicsCRMadoxioApplication dynamicsApplication, IDynamicsClient dynamicsClient)
        {
            Application applicationVM = new ViewModels.Application()
            {
                Name      = dynamicsApplication.AdoxioName,
                JobNumber = dynamicsApplication.AdoxioJobnumber,
                //get establishment name and address
                EstablishmentName              = dynamicsApplication.AdoxioEstablishmentpropsedname,
                EstablishmentAddressStreet     = dynamicsApplication.AdoxioEstablishmentaddressstreet,
                EstablishmentAddressCity       = dynamicsApplication.AdoxioEstablishmentaddresscity,
                EstablishmentAddressPostalCode = dynamicsApplication.AdoxioEstablishmentaddresspostalcode,
                EstablishmentAddress           = dynamicsApplication.AdoxioEstablishmentaddressstreet
                                                 + ", " + dynamicsApplication.AdoxioEstablishmentaddresscity
                                                 + " " + dynamicsApplication.AdoxioEstablishmentaddresspostalcode,
                EstablishmentPhone = dynamicsApplication.AdoxioEstablishmentphone,
                EstablishmentEmail = dynamicsApplication.AdoxioEstablishmentemail,

                ServicehHoursStandardHours = dynamicsApplication.AdoxioServicehoursstandardhours,
                ServiceHoursSundayOpen     = (ServiceHours?)dynamicsApplication.AdoxioServicehourssundayopen,
                ServiceHoursSundayClose    = (ServiceHours?)dynamicsApplication.AdoxioServicehourssundayclose,
                ServiceHoursMondayOpen     = (ServiceHours?)dynamicsApplication.AdoxioServicehoursmondayopen,
                ServiceHoursMondayClose    = (ServiceHours?)dynamicsApplication.AdoxioServicehoursmondayclose,
                ServiceHoursTuesdayOpen    = (ServiceHours?)dynamicsApplication.AdoxioServicehourstuesdayopen,
                ServiceHoursTuesdayClose   = (ServiceHours?)dynamicsApplication.AdoxioServicehourstuesdayclose,
                ServiceHoursWednesdayOpen  = (ServiceHours?)dynamicsApplication.AdoxioServicehourswednesdayopen,
                ServiceHoursWednesdayClose = (ServiceHours?)dynamicsApplication.AdoxioServicehourswednesdayclose,
                ServiceHoursThursdayOpen   = (ServiceHours?)dynamicsApplication.AdoxioServicehoursthursdayopen,
                ServiceHoursThursdayClose  = (ServiceHours?)dynamicsApplication.AdoxioServicehoursthursdayclose,
                ServiceHoursFridayOpen     = (ServiceHours?)dynamicsApplication.AdoxioServicehoursfridayopen,
                ServiceHoursFridayClose    = (ServiceHours?)dynamicsApplication.AdoxioServicehoursfridayclose,
                ServiceHoursSaturdayOpen   = (ServiceHours?)dynamicsApplication.AdoxioServicehourssaturdayopen,
                ServiceHoursSaturdayClose  = (ServiceHours?)dynamicsApplication.AdoxioServicehourssaturdayclose,

                AuthorizedToSubmit = dynamicsApplication.AdoxioAuthorizedtosubmit,
                SignatureAgreement = dynamicsApplication.AdoxioSignatureagreement,

                LicenceFeeInvoicePaid = (dynamicsApplication.AdoxioLicencefeeinvoicepaid != null && dynamicsApplication.AdoxioLicencefeeinvoicepaid == true),



                // set a couple of read-only flags to indicate status
                IsPaid = (dynamicsApplication.AdoxioPaymentrecieved != null && (bool)dynamicsApplication.AdoxioPaymentrecieved),

                //get parcel id
                EstablishmentParcelId = dynamicsApplication.AdoxioEstablishmentparcelid,

                //get additional property info
                AdditionalPropertyInformation = dynamicsApplication.AdoxioAdditionalpropertyinformation,
                AdoxioInvoiceId = dynamicsApplication._adoxioInvoiceValue,

                PaymentReceivedDate = dynamicsApplication.AdoxioPaymentreceiveddate,

                //get contact details
                ContactPersonFirstName = dynamicsApplication.AdoxioContactpersonfirstname,
                ContactPersonLastName  = dynamicsApplication.AdoxioContactpersonlastname,
                ContactPersonRole      = dynamicsApplication.AdoxioRole,
                ContactPersonEmail     = dynamicsApplication.AdoxioEmail,
                ContactPersonPhone     = dynamicsApplication.AdoxioContactpersonphone,

                //get record audit info
                CreatedOn  = dynamicsApplication.Createdon,
                ModifiedOn = dynamicsApplication.Modifiedon
            };


            // id
            if (dynamicsApplication.AdoxioApplicationid != null)
            {
                applicationVM.Id = dynamicsApplication.AdoxioApplicationid.ToString();
            }

            if (dynamicsApplication.Statuscode != null)
            {
                applicationVM.ApplicationStatus = (AdoxioApplicationStatusCodes)dynamicsApplication.Statuscode;
            }

            if (dynamicsApplication.AdoxioApplicanttype != null)
            {
                applicationVM.ApplicantType = (AdoxioApplicantTypeCodes)dynamicsApplication.AdoxioApplicanttype;
            }

            //get applying person from Contact entity
            if (dynamicsApplication._adoxioApplyingpersonValue != null)
            {
                Guid applyingPersonId = Guid.Parse(dynamicsApplication._adoxioApplyingpersonValue);
                var  contact          = await dynamicsClient.GetContactById(applyingPersonId);

                applicationVM.ApplyingPerson = contact.Fullname;
            }
            if (dynamicsApplication._adoxioApplicantValue != null)
            {
                var applicant = await dynamicsClient.GetAccountById(Guid.Parse(dynamicsApplication._adoxioApplicantValue));

                applicationVM.Applicant = applicant.ToViewModel();
            }

            //get license type from Adoxio_licencetype entity
            if (dynamicsApplication._adoxioLicencetypeValue != null)
            {
                Guid adoxio_licencetypeId = Guid.Parse(dynamicsApplication._adoxioLicencetypeValue);
                var  adoxio_licencetype   = dynamicsClient.GetAdoxioLicencetypeById(adoxio_licencetypeId);
                applicationVM.LicenseType = adoxio_licencetype.AdoxioName;
            }

            if (dynamicsApplication.AdoxioAppchecklistfinaldecision != null)
            {
                applicationVM.AppChecklistFinalDecision = (AdoxioFinalDecisionCodes)dynamicsApplication.AdoxioAppchecklistfinaldecision;
            }

            //get payment info
            if (dynamicsApplication.AdoxioInvoicetrigger != null && dynamicsApplication.AdoxioInvoicetrigger == 1)
            {
                applicationVM.AdoxioInvoiceTrigger = GeneralYesNo.Yes;
                applicationVM.IsSubmitted          = true;
            }
            else
            {
                applicationVM.AdoxioInvoiceTrigger = GeneralYesNo.No;
                applicationVM.IsSubmitted          = false;
            }

            if (dynamicsApplication.AdoxioLicenceFeeInvoice != null)
            {
                applicationVM.LicenceFeeInvoice = dynamicsApplication.AdoxioLicenceFeeInvoice.ToViewModel();
            }

            if (dynamicsApplication.AdoxioAssignedLicence != null)
            {
                applicationVM.AssignedLicence = dynamicsApplication.AdoxioAssignedLicence.ToViewModel(dynamicsClient);
            }

            applicationVM.PrevPaymentFailed = (dynamicsApplication._adoxioInvoiceValue != null) && (!applicationVM.IsSubmitted);

            return(applicationVM);
        }
コード例 #27
0
        public async static Task <AdoxioApplication> ToViewModel(this MicrosoftDynamicsCRMadoxioApplication dynamicsApplication, IDynamicsClient dynamicsClient)
        {
            AdoxioApplication adoxioApplicationVM = new ViewModels.AdoxioApplication();

            // id
            if (dynamicsApplication.AdoxioApplicationid != null)
            {
                adoxioApplicationVM.id = dynamicsApplication.AdoxioApplicationid.ToString();
            }

            //get name
            adoxioApplicationVM.name = dynamicsApplication.AdoxioName;

            //get applying person from Contact entity
            if (dynamicsApplication._adoxioApplyingpersonValue != null)
            {
                Guid applyingPersonId = Guid.Parse(dynamicsApplication._adoxioApplyingpersonValue);
                var  contact          = await dynamicsClient.GetContactById(applyingPersonId);

                adoxioApplicationVM.applyingPerson = contact.Fullname;
            }
            if (dynamicsApplication._adoxioApplicantValue != null)
            {
                var applicant = await dynamicsClient.GetAccountById(Guid.Parse(dynamicsApplication._adoxioApplicantValue));

                adoxioApplicationVM.applicant = applicant.ToViewModel();
            }

            //get job number
            adoxioApplicationVM.jobNumber = dynamicsApplication.AdoxioJobnumber;

            //get license type from Adoxio_licencetype entity
            if (dynamicsApplication._adoxioLicencetypeValue != null)
            {
                Guid adoxio_licencetypeId = Guid.Parse(dynamicsApplication._adoxioLicencetypeValue);
                var  adoxio_licencetype   = dynamicsClient.GetAdoxioLicencetypeById(adoxio_licencetypeId);
                adoxioApplicationVM.licenseType = adoxio_licencetype.AdoxioName;
            }

            //get establishment name and address
            adoxioApplicationVM.establishmentName              = dynamicsApplication.AdoxioEstablishmentpropsedname;
            adoxioApplicationVM.establishmentaddressstreet     = dynamicsApplication.AdoxioEstablishmentaddressstreet;
            adoxioApplicationVM.establishmentaddresscity       = dynamicsApplication.AdoxioEstablishmentaddresscity;
            adoxioApplicationVM.establishmentaddresspostalcode = dynamicsApplication.AdoxioEstablishmentaddresspostalcode;
            adoxioApplicationVM.establishmentAddress           = dynamicsApplication.AdoxioEstablishmentaddressstreet
                                                                 + ", " + dynamicsApplication.AdoxioEstablishmentaddresscity
                                                                 + " " + dynamicsApplication.AdoxioEstablishmentaddresspostalcode;

            //get application status
            adoxioApplicationVM.applicationStatus = (AdoxioApplicationStatusCodes)dynamicsApplication.Statuscode;

            // set a couple of read-only flags to indicate status
            adoxioApplicationVM.isPaid = (dynamicsApplication.AdoxioPaymentrecieved != null && (bool)dynamicsApplication.AdoxioPaymentrecieved);

            //get parcel id
            adoxioApplicationVM.establishmentparcelid = dynamicsApplication.AdoxioEstablishmentparcelid;

            //get additional property info
            adoxioApplicationVM.additionalpropertyinformation = dynamicsApplication.AdoxioAdditionalpropertyinformation;

            //get payment info
            if (dynamicsApplication.AdoxioInvoicetrigger == 1)
            {
                adoxioApplicationVM.adoxioInvoiceTrigger = GeneralYesNo.Yes;
                adoxioApplicationVM.isSubmitted          = true;
            }
            else
            {
                adoxioApplicationVM.adoxioInvoiceTrigger = GeneralYesNo.No;
                adoxioApplicationVM.isSubmitted          = false;
            }
            adoxioApplicationVM.adoxioInvoiceId = dynamicsApplication._adoxioInvoiceValue;
            //TODO set in autorest
            adoxioApplicationVM.paymentreceiveddate = dynamicsApplication.AdoxioPaymentreceiveddate; //DateTime.Now;
            adoxioApplicationVM.prevPaymentFailed   = (dynamicsApplication._adoxioInvoiceValue != null) && (!adoxioApplicationVM.isSubmitted);

            //get declarations
            adoxioApplicationVM.authorizedtosubmit = dynamicsApplication.AdoxioAuthorizedtosubmit;
            adoxioApplicationVM.signatureagreement = dynamicsApplication.AdoxioSignatureagreement;

            //get contact details
            adoxioApplicationVM.contactpersonfirstname = dynamicsApplication.AdoxioContactpersonfirstname;
            adoxioApplicationVM.contactpersonlastname  = dynamicsApplication.AdoxioContactpersonlastname;
            adoxioApplicationVM.contactpersonrole      = dynamicsApplication.AdoxioRole;
            adoxioApplicationVM.contactpersonemail     = dynamicsApplication.AdoxioEmail;
            adoxioApplicationVM.contactpersonphone     = dynamicsApplication.AdoxioContactpersonphone;

            adoxioApplicationVM.modifiedOn = dynamicsApplication.Modifiedon;

            //get record audit info
            adoxioApplicationVM.createdon  = dynamicsApplication.Createdon;
            adoxioApplicationVM.modifiedon = dynamicsApplication.Modifiedon;

            return(adoxioApplicationVM);
        }
コード例 #28
0
        public async static Task <ViewModels.CovidApplication> ToCovidViewModel(this MicrosoftDynamicsCRMadoxioApplication dynamicsApplication, IDynamicsClient dynamicsClient, IMemoryCache cache, ILogger logger)
        {
            ViewModels.CovidApplication applicationVM = new ViewModels.CovidApplication()
            {
                Name      = dynamicsApplication.AdoxioName,
                JobNumber = dynamicsApplication.AdoxioJobnumber,
                //get establishment name and address
                EstablishmentName              = dynamicsApplication.AdoxioEstablishmentpropsedname,
                EstablishmentAddressStreet     = dynamicsApplication.AdoxioEstablishmentaddressstreet,
                EstablishmentAddressCity       = dynamicsApplication.AdoxioEstablishmentaddresscity,
                EstablishmentAddressPostalCode = dynamicsApplication.AdoxioEstablishmentaddresspostalcode,
                EstablishmentAddress           = dynamicsApplication.AdoxioEstablishmentaddressstreet
                                                 + ", " + dynamicsApplication.AdoxioEstablishmentaddresscity
                                                 + " " + dynamicsApplication.AdoxioEstablishmentaddresspostalcode,
                EstablishmentPhone    = dynamicsApplication.AdoxioEstablishmentphone,
                EstablishmentEmail    = dynamicsApplication.AdoxioEstablishmentemail,
                IsApplicationComplete = (GeneralYesNo?)dynamicsApplication.AdoxioIsapplicationcomplete,

                AddressStreet     = dynamicsApplication.AdoxioAddressstreet,
                AddressCity       = dynamicsApplication.AdoxioAddresscity,
                AddressPostalCode = dynamicsApplication.AdoxioAddresspostalcode,

                NameOfApplicant = dynamicsApplication.AdoxioNameofapplicant,



                AuthorizedToSubmit = dynamicsApplication.AdoxioAuthorizedtosubmit,

                //get parcel id
                EstablishmentParcelId = dynamicsApplication.AdoxioEstablishmentparcelid,

                //get additional property info
                AdditionalPropertyInformation = dynamicsApplication.AdoxioAdditionalpropertyinformation,
                AdoxioInvoiceId = dynamicsApplication._adoxioInvoiceValue,

                Description1 = dynamicsApplication.AdoxioDescription1,

                //get contact details
                ContactPersonFirstName = dynamicsApplication.AdoxioContactpersonfirstname,
                ContactPersonLastName  = dynamicsApplication.AdoxioContactpersonlastname,
                ContactPersonRole      = dynamicsApplication.AdoxioRole,
                ContactPersonEmail     = dynamicsApplication.AdoxioEmail,
                ContactPersonPhone     = dynamicsApplication.AdoxioContactpersonphone,

                //get record audit info
                CreatedOn  = dynamicsApplication.Createdon,
                ModifiedOn = dynamicsApplication.Modifiedon,


                ProposedEstablishmentIsAlr = dynamicsApplication.AdoxioProposedestablishmentisalr
                                             //store opening

                                             // Catering fields.
            };



            // id
            if (dynamicsApplication.AdoxioApplicationid != null)
            {
                applicationVM.Id = dynamicsApplication.AdoxioApplicationid.ToString();
            }


            if (dynamicsApplication.AdoxioApplicanttype != null)
            {
                applicationVM.ApplicantType = (AdoxioApplicantTypeCodes)dynamicsApplication.AdoxioApplicanttype;
            }

            //get applying person from Contact entity
            if (dynamicsApplication._adoxioApplyingpersonValue != null)
            {
                Guid applyingPersonId = Guid.Parse(dynamicsApplication._adoxioApplyingpersonValue);
                var  contact          = await dynamicsClient.GetContactById(applyingPersonId);

                applicationVM.ApplyingPerson = contact.Fullname;
            }


            //get license type from Adoxio_licencetype entity
            if (dynamicsApplication._adoxioLicencetypeValue != null)
            {
                Guid adoxio_licencetypeId = Guid.Parse(dynamicsApplication._adoxioLicencetypeValue);
                var  adoxio_licencetype   = dynamicsClient.GetAdoxioLicencetypeById(adoxio_licencetypeId);
                applicationVM.LicenceType = adoxio_licencetype.AdoxioName;
            }



            if (dynamicsApplication.AdoxioApplicationTypeId != null)
            {
                applicationVM.ApplicationType = dynamicsApplication.AdoxioApplicationTypeId.ToViewModel();

                if (!string.IsNullOrEmpty(applicationVM.ApplicationType.FormReference))
                {
                    applicationVM.ApplicationType.DynamicsForm = dynamicsClient.GetSystemformViewModel(cache, logger, applicationVM.ApplicationType.FormReference);
                }
            }

            return(applicationVM);
        }
コード例 #29
0
        public async Task <IActionResult> GetWorkers(string contactId)
        {
            List <ViewModels.Worker> results = new List <ViewModels.Worker>();

            if (!CurrentUserHasAccessToContactWorkerApplicationOwnedBy(contactId))
            {
                return(NotFound("No access to contact"));
            }

            if (!string.IsNullOrEmpty(contactId))
            {
                Guid id = Guid.Parse(contactId);
                // query the Dynamics system to get the contact record.
                string filter = $"_adoxio_contactid_value eq {contactId}";
                var    fields = new List <string> {
                    "adoxio_ContactId"
                };
                List <MicrosoftDynamicsCRMadoxioWorker> workers = _dynamicsClient.Workers.Get(filter: filter, expand: fields).Value.ToList();
                if (workers != null)
                {
                    workers.ForEach(w =>
                    {
                        results.Add(w.ToViewModel());
                    });

                    // if there is not worker verification record, create one
                    if (results.Count() == 0)
                    {
                        // query the Dynamics system to get the contact record.
                        var contact = await _dynamicsClient.GetContactById(id);

                        if (contact != null)
                        {
                            var worker = new ViewModels.Worker
                            {
                                firstname  = contact.Firstname,
                                middlename = contact.Middlename,
                                lastname   = contact.Lastname,
                                contact    = new ViewModels.Contact()
                                {
                                    id = contactId
                                }
                            };
                            worker = await this.CreateWorkerRecord(worker);

                            worker.contact = contact.ToViewModel();
                            results.Add(worker);
                        }
                    }
                }
                else
                {
                    return(new NotFoundResult());
                }
            }
            else
            {
                return(BadRequest());
            }
            return(new JsonResult(results));
        }