示例#1
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()));
        }
示例#2
0
        public static void CreateLicenceDocumentLocation(this IDynamicsClient _dynamicsClient, MicrosoftDynamicsCRMadoxioLicences licenceEntity, string folderName, string name)
        {
            // set the parent document library.
            var parentDocumentLibraryReference = _dynamicsClient.GetDocumentLocationReferenceByRelativeURL("adoxio_licences");

            var licenceUri = _dynamicsClient.GetEntityURI("adoxio_licenceses", licenceEntity.AdoxioLicencesid);
            // now create a document location to link them.

            // Create the SharePointDocumentLocation entity
            var mdcsdl = new MicrosoftDynamicsCRMsharepointdocumentlocation
            {
                RegardingobjectIdEventODataBind = licenceUri,
                ParentsiteorlocationSharepointdocumentlocationODataBind =
                    _dynamicsClient.GetEntityURI("sharepointdocumentlocations", parentDocumentLibraryReference),
                Relativeurl = folderName,
                Description = "Licence Files",
                Name        = name
            };

            var sharepointdocumentlocationid = _dynamicsClient.DocumentLocationExistsWithCleanup(mdcsdl);

            if (sharepointdocumentlocationid == null)
            {
                try
                {
                    mdcsdl = _dynamicsClient.Sharepointdocumentlocations.Create(mdcsdl);
                }
                catch (HttpOperationException odee)
                {
                    Log.Error(odee, "Error creating SharepointDocumentLocation");
                    mdcsdl = null;
                }

                if (mdcsdl != null)
                {
                    var sharePointLocationData = _dynamicsClient.GetEntityURI("sharepointdocumentlocations",
                                                                              mdcsdl.Sharepointdocumentlocationid);

                    var oDataId = new Odataid
                    {
                        OdataidProperty = sharePointLocationData
                    };
                    try
                    {
                        _dynamicsClient.Licenceses.AddReference(licenceEntity.AdoxioLicencesid,
                                                                "adoxio_licences_SharePointDocumentLocations", oDataId);
                    }
                    catch (HttpOperationException odee)
                    {
                        Log.Error(odee, "Error adding reference to SharepointDocumentLocation");
                    }
                }
            }
        }
        private static void CreateContactDocumentLocation(this IDynamicsClient _dynamicsClient, MicrosoftDynamicsCRMcontact contact, string folderName, string name)
        {
            var parentDocumentLibraryReference = _dynamicsClient.GetDocumentLocationReferenceByRelativeURL("contact");

            var contactUri = _dynamicsClient.GetEntityURI("contacts", contact.Contactid);
            // now create a document location to link them.

            // Create the SharePointDocumentLocation entity
            var mdcsdl = new MicrosoftDynamicsCRMsharepointdocumentlocation
            {
                RegardingobjectIdContactODataBind = contactUri,
                ParentsiteorlocationSharepointdocumentlocationODataBind =
                    _dynamicsClient.GetEntityURI("sharepointdocumentlocations", parentDocumentLibraryReference),
                Relativeurl = folderName,
                Description = "Contact Files",
                Name        = name
            };

            var sharepointdocumentlocationid = _dynamicsClient.DocumentLocationExistsWithCleanup(mdcsdl);

            if (sharepointdocumentlocationid == null)
            {
                try
                {
                    mdcsdl = _dynamicsClient.Sharepointdocumentlocations.Create(mdcsdl);
                }
                catch (HttpOperationException odee)
                {
                    Log.Error(odee, "Error creating SharepointDocumentLocation");
                    mdcsdl = null;
                }

                if (mdcsdl != null)
                {
                    var sharePointLocationData = _dynamicsClient.GetEntityURI("sharepointdocumentlocations",
                                                                              mdcsdl.Sharepointdocumentlocationid);

                    var oDataId = new Odataid
                    {
                        OdataidProperty = sharePointLocationData
                    };
                    try
                    {
                        _dynamicsClient.Contacts.AddReference(contact.Contactid,
                                                              "adoxio_application_SharePointDocumentLocations", oDataId);
                    }
                    catch (HttpOperationException odee)
                    {
                        Log.Error(odee, "Error adding reference to SharepointDocumentLocation");
                    }
                }
            }
        }
示例#4
0
        public async Task <IActionResult> CreateApplication([FromBody] ViewModels.AdoxioApplication item)
        {
            // for association with current user
            string       userJson     = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(userJson);
            MicrosoftDynamicsCRMadoxioApplication adoxioApplication = new MicrosoftDynamicsCRMadoxioApplication();

            // copy received values to Dynamics Application
            adoxioApplication.CopyValues(item);
            adoxioApplication.AdoxioApplicanttype = (int?)item.applicantType;
            try
            {
                adoxioApplication = _dynamicsClient.Applications.Create(adoxioApplication);
            }
            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);
            }

            MicrosoftDynamicsCRMadoxioApplication patchAdoxioApplication = new MicrosoftDynamicsCRMadoxioApplication();

            // set license type relationship

            var adoxioLicencetype = _dynamicsClient.GetAdoxioLicencetypeByName(item.licenseType).Result;

            patchAdoxioApplication.AdoxioLicenceTypeODataBind = _dynamicsClient.GetEntityURI("adoxio_licencetypes", adoxioLicencetype.AdoxioLicencetypeid);;
            patchAdoxioApplication.AdoxioApplicantODataBind   = _dynamicsClient.GetEntityURI("adoxio_applications", userSettings.AccountId);
            try
            {
                _dynamicsClient.Applications.Update(adoxioApplication.AdoxioApplicationid, patchAdoxioApplication);
            }
            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(await adoxioApplication.ToViewModel(_dynamicsClient)));
        }
        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()));
        }
示例#6
0
        public async Task <IActionResult> CreateWorker([FromBody] ViewModels.Worker item)
        {
            // get UserSettings from the session
            string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);
            // create a new worker.
            MicrosoftDynamicsCRMadoxioWorker worker = new MicrosoftDynamicsCRMadoxioWorker()
            {
                AdoxioIsmanual = 0 // 0 for false - is a portal user.
            };

            worker.CopyValues(item);
            if (item?.contact?.id == null)
            {
                return(BadRequest());
            }
            try
            {
                worker = await _dynamicsClient.Workers.CreateAsync(worker);

                var patchWorker = new MicrosoftDynamicsCRMadoxioWorker();
                patchWorker.ContactIdAccountODataBind = _dynamicsClient.GetEntityURI("contacts", item.contact.id);
                await _dynamicsClient.Workers.UpdateAsync(worker.AdoxioWorkerid.ToString(), patchWorker);
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError("Error updating contact");
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
            }
            return(Json(worker));
        }
        private async Task HandleVerifiedIndividualLogin(UserSettings userSettings, HttpContext context)
        {
            IConfiguration    _configuration     = (IConfiguration)context.RequestServices.GetService(typeof(IConfiguration));
            IDynamicsClient   _dynamicsClient    = (IDynamicsClient)context.RequestServices.GetService(typeof(IDynamicsClient));
            FileManagerClient _fileManagerClient = (FileManagerClient)context.RequestServices.GetService(typeof(FileManagerClient));

            Contact contact = new Contact();

            contact.CopyHeaderValues(context.Request.Headers);

            MicrosoftDynamicsCRMcontact savedContact = _dynamicsClient.Contacts.GetByKey(userSettings.ContactId);

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

            _dynamicsClient.Contacts.Update(userSettings.ContactId, contact.ToModel());
        }
        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()));
        }
        private async Task <IActionResult> CreateAlias(ViewModels.Alias item, string contactId)
        {
            if (item == null || String.IsNullOrEmpty(contactId))
            {
                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 (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error creating application");
                // fail if we can't create.
                throw;
            }


            MicrosoftDynamicsCRMadoxioAlias patchAlias = new MicrosoftDynamicsCRMadoxioAlias();

            // set contact association
            try
            {
                patchAlias.ContactIdODataBind = _dynamicsClient.GetEntityURI("contacts", contactId);

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

            return(new JsonResult(alias.ToViewModel()));
        }
示例#10
0
        public async Task <IActionResult> CreateInvoice([FromBody] ViewModels.Invoice item)
        {
            if (TestUtility.InUnitTestMode())
            {
                // create a new invoice.
                MicrosoftDynamicsCRMinvoice invoice = new MicrosoftDynamicsCRMinvoice();

                // get the current user.
                string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
                UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);
                // check that the session is setup correctly.
                userSettings.Validate();
                // copy received values to Dynamics LegalEntity
                invoice.CopyValues(item);
                try
                {
                    invoice = await _dynamicsClient.Invoices.CreateAsync(invoice);
                }
                catch (OdataerrorException odee)
                {
                    _logger.LogError("Error creating invoice");
                    _logger.LogError("Request:");
                    _logger.LogError(odee.Request.Content);
                    _logger.LogError("Response:");
                    _logger.LogError(odee.Response.Content);
                    throw new Exception("Unable to create invoice");
                }

                // setup navigation properties.
                MicrosoftDynamicsCRMinvoice patchEntity = new MicrosoftDynamicsCRMinvoice();
                Guid accountId   = Guid.Parse(userSettings.AccountId);
                var  userAccount = await _dynamicsClient.GetAccountById(accountId);

                patchEntity.CustomerIdAccountODataBind = _dynamicsClient.GetEntityURI("accounts", accountId.ToString());

                // patch the record.
                try
                {
                    await _dynamicsClient.Invoices.UpdateAsync(invoice.Invoiceid, patchEntity);

                    // setup the view model.
                    invoice.CustomeridAccount = userAccount;
                }
                catch (OdataerrorException odee)
                {
                    _logger.LogError("Error patching invoice");
                    _logger.LogError(odee.Request.RequestUri.ToString());
                    _logger.LogError("Request:");
                    _logger.LogError(odee.Request.Content);
                    _logger.LogError("Response:");
                    _logger.LogError(odee.Response.Content);
                }

                return(Json(invoice.ToViewModel()));
            }
            return(new NotFoundResult());
        }
示例#11
0
        public static MicrosoftDynamicsCRMbcgovBusinesscontact ToModel(this ViewModels.BusinessContact from, IDynamicsClient system)
        {
            MicrosoftDynamicsCRMbcgovBusinesscontact result = new MicrosoftDynamicsCRMbcgovBusinesscontact()
            {
                BcgovContacttype = (int?)from.contactType,
                ContactODataBind = system.GetEntityURI("contacts", from.contact.id),
                AccountODataBind = system.GetEntityURI("accounts", from.account.id),
                BcgovJobtitle    = from.jobTitle,
                BcgovRegisteredsellerownermanager = (int?)from.registeredSellerOwnerManager
            };

            if (!string.IsNullOrEmpty(from.id))
            {
                result.BcgovBusinesscontactid = from.id;
            }

            return(result);
        }
示例#12
0
        /// <summary>
        /// Get a document location by reference
        /// </summary>
        /// <param name="relativeUrl"></param>
        /// <returns></returns>
        private string GetDocumentLocationReferenceByRelativeURL(string relativeUrl)
        {
            string result    = null;
            string sanitized = relativeUrl.Replace("'", "''");
            // first see if one exists.
            var locations = _dynamicsClient.Sharepointdocumentlocations.Get(filter: "relativeurl eq '" + sanitized + "'");

            var location = locations.Value.FirstOrDefault();

            if (location == null)
            {
                var parentSite    = _dynamicsClient.Sharepointsites.Get().Value.FirstOrDefault();
                var parentSiteRef = _dynamicsClient.GetEntityURI("sharepointsites", parentSite.Sharepointsiteid);
                MicrosoftDynamicsCRMsharepointdocumentlocation newRecord = new MicrosoftDynamicsCRMsharepointdocumentlocation()
                {
                    Relativeurl         = relativeUrl,
                    Name                = "Application",
                    ParentSiteODataBind = parentSiteRef
                };
                // create a new document location.
                try
                {
                    location = _dynamicsClient.Sharepointdocumentlocations.Create(newRecord);
                }
                catch (OdataerrorException odee)
                {
                    _logger.LogError("Error creating document location");
                    _logger.LogError("Request:");
                    _logger.LogError(odee.Request.Content);
                    _logger.LogError("Response:");
                    _logger.LogError(odee.Response.Content);
                }
            }

            if (location != null)
            {
                result = location.Sharepointdocumentlocationid;
            }

            return(result);
        }
        public static async Task <MicrosoftDynamicsCRMincident> CreateScreeningRequestAsync(IDynamicsClient dynamicsClient, ScreeningRequest screeningRequest, string candidateId, string submitterId, string contactId, int?applicantType, int?cannabisApplicantType)
        {
            string candidate     = dynamicsClient.GetEntityURI("contacts", candidateId);
            string submitter     = dynamicsClient.GetEntityURI("contacts", submitterId);
            string programArea   = dynamicsClient.GetEntityURI("spice_ministries", screeningRequest.ProgramArea);
            string screeningType = dynamicsClient.GetEntityURI("spice_serviceses", screeningRequest.ScreeningType);
            string reason        = dynamicsClient.GetEntityURI("spice_reasonforscreenings", screeningRequest.Reason);
            string contact       = dynamicsClient.GetEntityURI("spice_ministryemployees", contactId);

            var entity = new MicrosoftDynamicsCRMincident
            {
                CustomerIdODataBind                = candidate,
                ApplyingPersonIdODataBind          = submitter,
                SpiceClientIdODataBind             = programArea,
                SpiceServiceIdODataBind            = screeningType,
                SpiceReasonForScreeningIdODataBind = reason,
                SpiceOtherscreeningreason          = screeningRequest.OtherReason,
                SpiceReturnToIdODataBind           = contact,
                SpiceApplicanttype         = applicantType,
                SpiceCannabisapplicanttype = cannabisApplicantType,
            };

            entity = await dynamicsClient.Incidents.CreateAsync(entity);

            return(entity);
        }
示例#14
0
        public async Task <IActionResult> CreateLicenceEvent([FromBody] LicenceEvent item)
        {
            MicrosoftDynamicsCRMadoxioEvent dynamicsEvent = new MicrosoftDynamicsCRMadoxioEvent();

            if (item?.Status == LicenceEventStatus.Submitted)
            {
                bool alwaysAuthorization;
                try
                {
                    var licence = _dynamicsClient.Licenceses.GetByKey(item.LicenceId);
                    alwaysAuthorization = licence.AdoxioIseventapprovalalwaysrequired == null ? false : (bool)licence.AdoxioIseventapprovalalwaysrequired;
                }
                catch (HttpOperationException ex)
                {
                    _logger.LogError(ex, "Error creating event");
                    return(BadRequest());
                }
                item.EventClass = item.DetermineEventClass(alwaysAuthorization);
                if (item.EventClass != EventClass.Authorization || item.EventCategory == EventCategory.Market)
                {
                    item.Status = LicenceEventStatus.Approved;
                }
                else
                {
                    item.Status = LicenceEventStatus.InReview;
                }
            }

            dynamicsEvent.CopyValues(item);

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

            dynamicsEvent.AccountODataBind = _dynamicsClient.GetEntityURI("accounts", userSettings.AccountId);

            if (!string.IsNullOrEmpty(item.LicenceId))
            {
                dynamicsEvent.LicenceODataBind = _dynamicsClient.GetEntityURI("adoxio_licenceses", item.LicenceId);
            }

            try
            {
                dynamicsEvent = _dynamicsClient.Events.Create(dynamicsEvent);
            }
            catch (HttpOperationException ex)
            {
                _logger.LogError(ex, "Error creating event");
                return(BadRequest());
            }

            LicenceEvent viewModelEvent = dynamicsEvent.ToViewModel(_dynamicsClient);

            // create event schedules - if any
            viewModelEvent.Schedules = CreateEventSchedules(item, dynamicsEvent);
            // create TUA event locations - if any
            viewModelEvent.EventLocations = CreateEventLocations(item, dynamicsEvent);

            return(new JsonResult(viewModelEvent));
        }
示例#15
0
        public static void CreateApplicationDocumentLocation(this IDynamicsClient _dynamicsClient, MicrosoftDynamicsCRMadoxioApplication application, string folderName, string name)
        {
            // now create a document location to link them.
            var parentDocumentLibraryReference = _dynamicsClient.GetDocumentLocationReferenceByRelativeURL("adoxio_application");

            var regardingobjectId = _dynamicsClient.GetEntityURI("adoxio_applications", application.AdoxioApplicationid);

            // Create the SharePointDocumentLocation entity
            var mdcsdl = new MicrosoftDynamicsCRMsharepointdocumentlocation
            {
                RegardingobjectidAdoxioApplicationODataBind             = regardingobjectId,
                ParentsiteorlocationSharepointdocumentlocationODataBind = _dynamicsClient.GetEntityURI("sharepointdocumentlocations", parentDocumentLibraryReference),
                Relativeurl = folderName,
                Description = "Application Files",
                Name        = name
            };

            var sharepointdocumentlocationid = _dynamicsClient.DocumentLocationExistsWithCleanup(mdcsdl);

            if (sharepointdocumentlocationid == null)
            {
                sharepointdocumentlocationid = _dynamicsClient.CreateDocumentLocation(mdcsdl);

                var sharePointLocationData = _dynamicsClient.GetEntityURI("sharepointdocumentlocations", sharepointdocumentlocationid);

                var oDataId = new Odataid
                {
                    OdataidProperty = sharePointLocationData
                };
                try
                {
                    _dynamicsClient.Applications.AddReference(application.AdoxioApplicationid, "adoxio_application_SharePointDocumentLocations", oDataId);
                }
                catch (HttpOperationException odee)
                {
                    Log.Error(odee, "Error adding reference to SharepointDocumentLocation");
                }
            }
        }
示例#16
0
        public static async Task <MicrosoftDynamicsCRMcsuSubjectofcomplaint> CreateSubjectOfComplaintAsync(
            IDynamicsClient dynamicsClient, Complaint complaint, string complaintId)
        {
            string dynamicsComplaint = dynamicsClient.GetEntityURI("csu_complaintses", complaintId);

            var address = complaint.Details.Address;
            var entity  = new MicrosoftDynamicsCRMcsuSubjectofcomplaint
            {
                ComplaintODataBind = dynamicsComplaint,

                CsuAddressdescription = complaint.Details.Name,

                CsuAddress1      = address.Line1,
                CsuAddress2      = address.Unit,
                CsuCity          = address.City,
                CsuProvince      = address.ProvinceState,
                CsuCountry       = address.Country,
                CsuZippostalcode = address.ZipPostalCode,
            };

            if (complaint.LegislationType == Constants.LegislationTypeCSA)
            {
                entity.CsuPropertytype      = complaint.Details.PropertyType;
                entity.CsuOtherpropertytype = complaint.Details.OtherPropertyType;
                entity.CsuNameofoccupants   = complaint.Details.OccupantName;
                entity.CsuNameofowners      = complaint.Details.OwnerName;

                if (complaint.Details.PropertyType == Constants.PropertyTypeCommercial)
                {
                    entity.CsuSubjecttype = Constants.SubjectTypeBusiness;
                }
                else if (complaint.Details.PropertyType == Constants.PropertyTypeOther)
                {
                    entity.CsuSubjecttype = Constants.SubjectTypeLocation;
                }
                else
                {
                    entity.CsuSubjecttype = Constants.SubjectTypeResidence;
                }
            }
            else if (complaint.LegislationType == Constants.LegislationTypeCCLA)
            {
                entity.CsuSubjecttype = Constants.SubjectTypeResidence;
            }

            entity = await dynamicsClient.Csusubjectofcomplaints.CreateAsync(entity);

            return(entity);
        }
        public static async Task <MicrosoftDynamicsCRMspiceMinistryemployee> CreateContactAsync(IDynamicsClient dynamicsClient, Contact contact, string programAreaId)
        {
            string programArea = dynamicsClient.GetEntityURI("spice_ministries", programAreaId);

            var entity = new MicrosoftDynamicsCRMspiceMinistryemployee
            {
                SpiceName                = contact.FirstName,
                SpiceLastname            = contact.LastName,
                SpiceEmail               = contact.Email,
                SpiceMinistryIdODataBind = programArea,
            };

            entity = await dynamicsClient.Ministryemployees.CreateAsync(entity);

            return(entity);
        }
        public async Task <IActionResult> CreateInvoice([FromBody] ViewModels.Invoice item)
        {
            if (TestUtility.InUnitTestMode())
            {
                // create a new invoice.
                MicrosoftDynamicsCRMinvoice invoice = new MicrosoftDynamicsCRMinvoice();

                // get the current user.
                UserSettings userSettings = UserSettings.CreateFromHttpContext(_httpContextAccessor);
                // check that the session is setup correctly.
                userSettings.Validate();
                // copy received values to Dynamics LegalEntity
                invoice.CopyValues(item);
                try
                {
                    invoice = await _dynamicsClient.Invoices.CreateAsync(invoice);
                }
                catch (HttpOperationException httpOperationException)
                {
                    _logger.LogError(httpOperationException, "Error creating invoice");
                    throw new Exception("Unable to create invoice");
                }

                // setup navigation properties.
                MicrosoftDynamicsCRMinvoice patchEntity = new MicrosoftDynamicsCRMinvoice();
                Guid accountId   = Guid.Parse(userSettings.AccountId);
                var  userAccount = await _dynamicsClient.GetAccountByIdAsync(accountId);

                patchEntity.CustomerIdAccountODataBind = _dynamicsClient.GetEntityURI("accounts", accountId.ToString());

                // patch the record.
                try
                {
                    await _dynamicsClient.Invoices.UpdateAsync(invoice.Invoiceid, patchEntity);

                    // setup the view model.
                    invoice.CustomeridAccount = userAccount;
                }
                catch (HttpOperationException httpOperationException)
                {
                    _logger.LogError(httpOperationException, "Error patching invoice");
                }

                return(new JsonResult(invoice.ToViewModel()));
            }
            return(new NotFoundResult());
        }
示例#19
0
        public async Task <IActionResult> CreateWorker([FromBody] ViewModels.Worker item)
        {
            // create a new worker.
            MicrosoftDynamicsCRMadoxioWorker worker = new MicrosoftDynamicsCRMadoxioWorker
            {
                AdoxioIsmanual = 0 // 0 for false - is a portal user.
            };

            worker.CopyValues(item);
            if (item?.contact?.id == null)
            {
                return(BadRequest());
            }
            try
            {
                worker = await _dynamicsClient.Workers.CreateAsync(worker);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error creating worker. ");
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Error creating worker.");
            }

            try
            {
                var patchWorker = new MicrosoftDynamicsCRMadoxioWorker();
                patchWorker.ContactIdAccountODataBind = _dynamicsClient.GetEntityURI("contacts", item.contact.id);
                await _dynamicsClient.Workers.UpdateAsync(worker.AdoxioWorkerid, patchWorker);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error updating worker. ");
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Error updating worker.");
            }


            return(new JsonResult(worker.ToViewModel()));
        }
        private async Task <IActionResult> CreateAlias(ViewModels.Alias item, string contactId)
        {
            if (item == null || string.IsNullOrEmpty(contactId))
            {
                return(BadRequest());
            }


            var 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;
            }


            var patchAlias = new MicrosoftDynamicsCRMadoxioAlias();

            // set contact association
            try
            {
                patchAlias.ContactIdODataBind = _dynamicsClient.GetEntityURI("contacts", contactId);

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

            return(new JsonResult(alias.ToViewModel()));
        }
示例#21
0
        public async Task <IActionResult> CreateCustomProduct([FromBody] ViewModels.CustomProduct item)
        {
            if (string.IsNullOrEmpty(item.incidentId))
            {
                return(BadRequest("IncidentId missing"));
            }

            int?maxLength = ControllerUtility.GetAttributeMaxLength((DynamicsClient)_dynamicsClient, _cache, _logger, ENTITY_NAME, "bcgov_productdescriptionandintendeduse");

            if (maxLength != null && item.productdescriptionandintendeduse.Length > maxLength)
            {
                return(BadRequest("productdescriptionandintendeduse exceeds maximum field length"));
            }

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


            // create a new custom product.
            MicrosoftDynamicsCRMbcgovCustomproduct customProduct = new MicrosoftDynamicsCRMbcgovCustomproduct();

            customProduct.CopyValues(item);
            customProduct.RelatedApplicationODataBind = _dynamicsClient.GetEntityURI("incidents", item.incidentId);

            try
            {
                customProduct = await _dynamicsClient.Customproducts.CreateAsync(customProduct);
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError("Error updating custom product");
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
            }


            return(Json(customProduct.ToViewModel()));
        }
示例#22
0
        public void Move(IDynamicsClient _dynamicsClient)
        {
            // first find Cantest1
            string filter = "name eq 'XYZ Cannabis Sales Test'";

            try
            {
                var cantest1 = _dynamicsClient.Accounts.Get(filter: filter).Value.FirstOrDefault();

                if (cantest1 != null)
                {
                    var applications = _dynamicsClient.Applications.Get().Value;

                    foreach (var application in applications)
                    {
                        try
                        {
                            MicrosoftDynamicsCRMadoxioApplication newItem = new MicrosoftDynamicsCRMadoxioApplication()
                            {
                                AdoxioApplicantODataBind = _dynamicsClient.GetEntityURI("accounts", cantest1.Accountid)
                            };
                            _dynamicsClient.Applications.Update(application.AdoxioApplicationid, newItem);
                        }
                        catch (OdataerrorException odee)
                        {
                            Console.Out.WriteLine("Error updating application");
                            Console.Out.WriteLine("Request:");
                            Console.Out.WriteLine(odee.Request.Content);
                            Console.Out.WriteLine("Response:");
                            Console.Out.WriteLine(odee.Response.Content);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("Unable to find Cantest1.");
            }
        }
        // creates a worker record and links it to the contact with id = item.contact.id
        private async Task <ViewModels.Worker> CreateWorkerRecord(ViewModels.Worker item)
        {
            if (item?.contact?.id == null)
            {
                throw new ArgumentNullException(nameof(item.contact.id));
            }

            MicrosoftDynamicsCRMadoxioWorker worker = new MicrosoftDynamicsCRMadoxioWorker();

            try
            {
                // create the worker
                worker.AdoxioIsmanual = 0; // 0 for false - is a portal user.
                worker.CopyValues(item);
                worker = await _dynamicsClient.Workers.CreateAsync(worker).ConfigureAwait(true);

                // add contact reference to the worker record
                var patchWorker = new MicrosoftDynamicsCRMadoxioWorker();
                patchWorker.ContactIdAccountODataBind = _dynamicsClient.GetEntityURI("contacts", item.contact.id);
                await _dynamicsClient.Workers.UpdateAsync(worker.AdoxioWorkerid, patchWorker).ConfigureAwait(true);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error updating worker. ");
                throw;
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Error updating worker.");
                throw;
            }

            var result = worker.ToViewModel();

            return(worker.ToViewModel());
        }
示例#24
0
        public ActionResult InitiateTransfer(LicenceTransfer item)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            // check access to licence
            MicrosoftDynamicsCRMadoxioLicences adoxioLicense = _dynamicsClient.GetLicenceByIdWithChildren(item.LicenceId);

            if (adoxioLicense == null)
            {
                return(NotFound());
            }

            if (!CurrentUserHasAccessToLicenseOwnedBy(adoxioLicense.AdoxioLicencee.Accountid))
            {
                return(Forbid());
            }

            try
            {
                var yes          = 845280001;
                var patchLicence = new MicrosoftDynamicsCRMadoxioLicences()
                {
                    ProposedOwnerODataBind  = _dynamicsClient.GetEntityURI("accounts", item.AccountId),
                    AdoxioTransferrequested = yes
                };

                // create application
                _dynamicsClient.Licenceses.Update(item.LicenceId, patchLicence);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error initiating licence transfer");
                // fail if we can't create.
                throw (httpOperationException);
            }
            return(Ok());
        }
        private async Task CreateSharepointDynamicsLink(MicrosoftDynamicsCRMadoxioWorker worker)
        {
            // create a SharePointDocumentLocation link
            string folderName = await FileController.GetFolderName("worker", worker.AdoxioWorkerid, _dynamicsClient);

            string name = worker.AdoxioWorkerid + " Files";

            SharePointFileManager _sharePointFileManager = new SharePointFileManager(_configuration);

            // Create the folder
            bool folderExists = await _sharePointFileManager.FolderExists(SharePointFileManager.WorkertDocumentUrlTitle, folderName);

            if (!folderExists)
            {
                try
                {
                    await _sharePointFileManager.CreateFolder(SharePointFileManager.WorkertDocumentUrlTitle, folderName);
                }
                catch (Exception e)
                {
                    _logger.LogError("Error creating Sharepoint Folder");
                    _logger.LogError($"List is: {SharePointFileManager.WorkertDocumentUrlTitle}");
                    _logger.LogError($"FolderName is: {folderName}");
                    throw e;
                }
            }

            // Create the SharePointDocumentLocation entity
            MicrosoftDynamicsCRMsharepointdocumentlocation mdcsdl = new MicrosoftDynamicsCRMsharepointdocumentlocation()
            {
                Relativeurl = folderName,
                Description = "Worker Qualification",
                Name        = name
            };


            try
            {
                mdcsdl = _dynamicsClient.Sharepointdocumentlocations.Create(mdcsdl);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError("Error creating SharepointDocumentLocation");
                _logger.LogError("Request:");
                _logger.LogError(httpOperationException.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(httpOperationException.Response.Content);
                mdcsdl = null;
            }
            if (mdcsdl != null)
            {
                // add a regardingobjectid.
                string workerReference = _dynamicsClient.GetEntityURI("adoxio_workers", worker.AdoxioWorkerid);
                var    patchSharePointDocumentLocation = new MicrosoftDynamicsCRMsharepointdocumentlocation();
                patchSharePointDocumentLocation.RegardingobjectidWorkerApplicationODataBind = workerReference;
                // set the parent document library.
                string parentDocumentLibraryReference = GetDocumentLocationReferenceByRelativeURL(SharePointFileManager.WorkertDocumentUrlTitle);
                patchSharePointDocumentLocation.ParentsiteorlocationSharepointdocumentlocationODataBind = _dynamicsClient.GetEntityURI("sharepointdocumentlocations", parentDocumentLibraryReference);

                try
                {
                    _dynamicsClient.Sharepointdocumentlocations.Update(mdcsdl.Sharepointdocumentlocationid, patchSharePointDocumentLocation);
                }
                catch (HttpOperationException httpOperationException)
                {
                    _logger.LogError("Error adding reference SharepointDocumentLocation to application");
                    _logger.LogError("Request:");
                    _logger.LogError(httpOperationException.Request.Content);
                    _logger.LogError("Response:");
                    _logger.LogError(httpOperationException.Response.Content);
                    throw httpOperationException;
                }

                string sharePointLocationData = _dynamicsClient.GetEntityURI("sharepointdocumentlocations", mdcsdl.Sharepointdocumentlocationid);
                // update the sharePointLocationData.
                Odataid oDataId = new Odataid()
                {
                    OdataidProperty = sharePointLocationData
                };
                try
                {
                    _dynamicsClient.Workers.AddReference(worker.AdoxioWorkerid, "adoxio_worker_SharePointDocumentLocations", oDataId);
                }
                catch (HttpOperationException httpOperationException)
                {
                    _logger.LogError("Error adding reference to SharepointDocumentLocation");
                    _logger.LogError("Request:");
                    _logger.LogError(httpOperationException.Request.Content);
                    _logger.LogError("Response:");
                    _logger.LogError(httpOperationException.Response.Content);
                    throw httpOperationException;
                }
            }
        }
        public async Task <IActionResult> UpdateAnnualVolumeForApplication(string applicationId, [FromBody] AnnualVolume volume)
        {
            var dynamicsApplication = await _dynamicsClient.GetApplicationByIdWithChildren(Guid.Parse(applicationId));

            if (!CurrentUserHasAccessToApplicationOwnedBy(dynamicsApplication._adoxioApplicantValue))
            {
                return(NotFound());
            }

            // Remove other annual volumes that are attached to application
            string filter = $"_adoxio_application_value eq {applicationId}";

            try
            {
                IList <MicrosoftDynamicsCRMadoxioAnnualvolume> vols = _dynamicsClient.Annualvolumes.Get(filter: filter).Value;
                foreach (MicrosoftDynamicsCRMadoxioAnnualvolume vol in vols)
                {
                    try
                    {
                        _dynamicsClient.Annualvolumes.Delete(vol.AdoxioAnnualvolumeid);
                    }
                    catch (HttpOperationException httpOperationException)
                    {
                        _logger.Error(httpOperationException, "Unexpected error deleting an annual volume.");
                    }
                    catch (Exception e)
                    {
                        _logger.Error(e, "Unexpected error deleting an annual volume.");
                    }
                }
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.Error(httpOperationException, "Unexpected error getting annual volumes");
            }
            catch (Exception e)
            {
                _logger.Error(e, "Unexpected error getting annual volumes.");
            }

            MicrosoftDynamicsCRMadoxioAnnualvolume dynamicsVol = new MicrosoftDynamicsCRMadoxioAnnualvolume()
            {
                AdoxioVolumedestroyed      = volume.VolumeDestroyed,
                AdoxioVolumeproduced       = volume.VolumeProduced,
                AdoxioCalendaryear         = volume.CalendarYear,
                AdoxioApplicationODataBind = _dynamicsClient.GetEntityURI("adoxio_applications", applicationId)
            };

            // create it!
            try
            {
                _dynamicsClient.Annualvolumes.Create(dynamicsVol);
                return(Ok());
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.Error(httpOperationException, "Unexpected error creating annual volume");
                return(BadRequest());
            }
            catch (Exception e)
            {
                _logger.Error(e, "Unexpected error creating annual volume");
                return(BadRequest());
            }
        }
示例#27
0
        /// <summary>
        /// Import requests to Dynamics.
        /// </summary>
        /// <returns></returns>
        public async Task ImportApplicationRequests(PerformContext hangfireContext, List <IncompleteApplicationScreening> requests)
        {
            foreach (IncompleteApplicationScreening applicationRequest in requests)
            {
                if (applicationRequest.ApplicantAccount == null)
                {
                    _logger.LogError("Application sent without a valid account");
                    return;
                }
                // Company
                string uniqueFilter = "spice_carla_company eq '" + applicationRequest.ApplicantAccount.AccountId + "'";
                CompaniesGetResponseModel companiesResponse;
                try
                {
                    companiesResponse = _dynamicsClient.Companies.Get(1, filter: uniqueFilter);
                }
                catch (OdataerrorException e)
                {
                    _logger.LogError(e, "Failed to query companies");
                    _logger.LogError(e.Request.Content);
                    _logger.LogError(e.Response.Content);
                    return;
                }
                MicrosoftDynamicsCRMspiceCompany company;
                if (companiesResponse.Value.Count > 0)
                {
                    company = companiesResponse.Value[0];
                }
                else
                {
                    try
                    {
                        company = _dynamicsClient.Companies.Create(new MicrosoftDynamicsCRMspiceCompany()
                        {
                            SpiceCarlaCompany  = applicationRequest.ApplicantAccount.AccountId,
                            SpiceName          = applicationRequest.ApplicantAccount.Name,
                            SpiceBusinesstypes = (int)Enum.Parse(typeof(BusinessTypes), applicationRequest.ApplicantAccount.BusinessType),
                            SpiceStreet        = applicationRequest.BusinessAddress.AddressStreet1,
                            SpiceCity          = applicationRequest.BusinessAddress.City,
                            SpiceProvince      = applicationRequest.BusinessAddress.StateProvince,
                            SpiceCountry       = applicationRequest.BusinessAddress.Country,
                            SpicePostalcode    = applicationRequest.BusinessAddress.Postal
                        });
                    }
                    catch (OdataerrorException e)
                    {
                        _logger.LogError(e, "Failed to create new company");
                        _logger.LogError(e.Request.Content);
                        _logger.LogError(e.Response.Content);
                        return;
                    }
                }

                // Contact person
                uniqueFilter = "externaluseridentifier eq '" + applicationRequest.ContactPerson.ContactId + "'";
                ContactsGetResponseModel contactResponse;
                try
                {
                    contactResponse = _dynamicsClient.Contacts.Get(1, filter: uniqueFilter);
                }
                catch (OdataerrorException e)
                {
                    _logger.LogError(e, "Failed to query contacts");
                    _logger.LogError(e.Request.Content);
                    _logger.LogError(e.Response.Content);
                    return;
                }
                MicrosoftDynamicsCRMcontact contactPerson;
                if (contactResponse.Value.Count > 0)
                {
                    contactPerson = contactResponse.Value[0];
                }
                else
                {
                    try
                    {
                        contactPerson = _dynamicsClient.Contacts.Create(new MicrosoftDynamicsCRMcontact()
                        {
                            Externaluseridentifier = applicationRequest.ContactPerson.ContactId,
                            Firstname     = applicationRequest.ContactPerson.FirstName,
                            Middlename    = applicationRequest.ContactPerson.MiddleName,
                            Lastname      = applicationRequest.ContactPerson.LastName,
                            Emailaddress1 = applicationRequest.ContactPerson.Email,
                            Telephone1    = applicationRequest.ContactPerson.PhoneNumber
                        });
                    }
                    catch (OdataerrorException e)
                    {
                        _logger.LogError(e, "Failed to create new contact");
                        _logger.LogError(e.Request.Content);
                        _logger.LogError(e.Response.Content);
                        return;
                    }
                }


                uniqueFilter = "spice_carla_account eq '" + applicationRequest.ApplicantAccount.AccountId + "'";
                AccountsGetResponseModel accountResponse;
                try
                {
                    accountResponse = _dynamicsClient.Accounts.Get(1, filter: uniqueFilter);
                }
                catch (OdataerrorException e)
                {
                    _logger.LogError(e, "Failed to query accounts");
                    _logger.LogError(e.Request.Content);
                    _logger.LogError(e.Response.Content);
                    return;
                }
                MicrosoftDynamicsCRMaccount account;
                if (accountResponse.Value.Count > 10)
                {
                    account = accountResponse.Value[0];
                }
                else
                {
                    try
                    {
                        account = _dynamicsClient.Accounts.Create(new MicrosoftDynamicsCRMaccount()
                        {
                            SpiceCarlaAccount = applicationRequest.ApplicantAccount.AccountId,
                            Name                      = applicationRequest.Establishment.Name,
                            Address1Line1             = applicationRequest.Establishment.Address.AddressStreet1,
                            Address1City              = applicationRequest.Establishment.Address.City,
                            Address1Country           = applicationRequest.Establishment.Address.Country,
                            Address1Postalcode        = applicationRequest.Establishment.Address.Postal,
                            SpiceLcrbjobid            = applicationRequest.RecordIdentifier,
                            SpiceParcelidnumber       = applicationRequest.Establishment.ParcelId,
                            SpiceBccorpregnumber      = applicationRequest.ApplicantAccount.BCIncorporationNumber,
                            SpiceCompanyIdOdataBind   = _dynamicsClient.GetEntityURI("spice_companies", company.SpiceCompanyid),
                            PrimaryContactIdOdataBind = _dynamicsClient.GetEntityURI("contacts", contactPerson.Contactid)
                        });
                    }
                    catch (OdataerrorException e)
                    {
                        _logger.LogError(e, "Failed to create new account");
                        _logger.LogError(e.Request.Content);
                        _logger.LogError(e.Response.Content);
                        return;
                    }
                }

                string accountEntityUri = _dynamicsClient.GetEntityURI("accounts", account.Accountid);
                bool   isMarketing      = applicationRequest.ApplicationType == "Marketing";
                string servicesFilter   = isMarketing ? "spice_name eq 'Marketing Business - Initial Check'" : "spice_name eq 'Cannabis Applicant (Business)'";
                MicrosoftDynamicsCRMspiceServices service;
                try
                {
                    service = _dynamicsClient.Serviceses.Get(filter: servicesFilter).Value[0];
                }
                catch (OdataerrorException e)
                {
                    _logger.LogError(e, "Failed to query services");
                    _logger.LogError(e.Request.Content);
                    _logger.LogError(e.Response.Content);
                    return;
                }

                string clientFilter = "spice_name eq 'LCRB'";
                MicrosoftDynamicsCRMspiceMinistry client;
                try
                {
                    client = _dynamicsClient.Ministries.Get(filter: clientFilter).Value[0];
                }
                catch (OdataerrorException e)
                {
                    _logger.LogError(e, "Failed to query ministries");
                    _logger.LogError(e.Request.Content);
                    _logger.LogError(e.Response.Content);
                    return;
                }
                string clientEntityUri = _dynamicsClient.GetEntityURI("spice_ministries", client.SpiceMinistryid);

                MicrosoftDynamicsCRMincident incident = new MicrosoftDynamicsCRMincident()
                {
                    SpiceCannabisapplicanttype = isMarketing ? (int)CannabisApplicantType.MarketingBusiness : (int)CannabisApplicantType.Business,
                    SpiceApplicanttype         = (int)SpiceApplicantType.Cannabis,
                    Prioritycode = (int)PriorityCode.Normal,
                    CustomerIdAccountOdataBind = accountEntityUri,
                    SpiceServiceIdODataBind    = _dynamicsClient.GetEntityURI("spice_serviceses", service.SpiceServicesid),
                    SpiceClientIdODataBind     = clientEntityUri
                };

                LcrblicencetypesGetResponseModel response = _dynamicsClient.Lcrblicencetypes.Get(filter: "spice_name eq '" + applicationRequest.ApplicationType + "'");
                if (response.Value.Count > 0)
                {
                    incident.LCRBLicenceTypeIdOdataBind = _dynamicsClient.GetEntityURI("spice_lcrblicencetypes", response.Value[0].SpiceLcrblicencetypeid);
                }
                else
                {
                    _logger.LogError($"Licence type {applicationRequest.ApplicationType} not found");
                }

                try
                {
                    // Create the business incident
                    incident = _dynamicsClient.Incidents.Create(incident);
                }
                catch (OdataerrorException e)
                {
                    _logger.LogError(e, "Failed to create new incident");
                    _logger.LogError(e.Request.Content);
                    _logger.LogError(e.Response.Content);
                    return;
                }

                foreach (var associate in applicationRequest.Associates)
                {
                    CreateAssociate(clientEntityUri, accountEntityUri, incident.Incidentid, associate, isMarketing);
                }
            }
        }
        public ActionResult CreateOrUpdate([FromBody] Sol sol)
        {
            if (sol == null || string.IsNullOrEmpty(sol.SolLicenceNumber) || !sol.SolLicenceNumber.Contains("-"))
            {
                return(BadRequest());
            }

            // format of the "SolLicenceNumber" field is {EventLicenceNumber}-{LocationReference}

            string solIdEscaped = sol.SolLicenceNumber.Replace("'", "''");

            if (solIdEscaped.Contains("-"))
            {
                solIdEscaped = solIdEscaped.Substring(0, solIdEscaped.IndexOf("-"));
            }


            // string locationReference = sol.SolLicenceNumber.Substring(sepLicenceNumber.Length);

            // determine if the record is new.
            MicrosoftDynamicsCRMadoxioSpecialevent existingRecord =
                _dynamicsClient.GetSpecialEventByLicenceNumber(solIdEscaped);

            if (existingRecord == null) // new record
            {
                MicrosoftDynamicsCRMadoxioSpecialevent newRecord = new MicrosoftDynamicsCRMadoxioSpecialevent()
                {
                    AdoxioCapacity = sol.Capacity,
                    AdoxioSpecialeventdescripton = sol.EventDescription,
                    AdoxioEventname = AdjustString255(sol.EventName),
                    AdoxioSpecialeventpermitnumber = solIdEscaped,
                    // applicant
                    AdoxioSpecialeventapplicant      = AdjustString255(sol.Applicant?.ApplicantName),
                    AdoxioSpecialeventapplicantemail = AdjustString255(sol.Applicant?.EmailAddress),
                    AdoxioSpecialeventapplicantphone = sol.Applicant?.PhoneNumber,
                    // location
                    AdoxioSpecialeventstreet1    = AdjustString255(sol.Applicant?.Address?.Address1),
                    AdoxioSpecialeventstreet2    = AdjustString255(sol.Applicant?.Address?.Address2),
                    AdoxioSpecialeventcity       = AdjustString255(sol.Applicant?.Address?.City),
                    AdoxioSpecialeventpostalcode = sol.Applicant?.Address?.PostalCode,
                    AdoxioSpecialeventprovince   = AdjustString255(sol.Applicant?.Address?.Province),
                    // responsible individual
                    AdoxioResponsibleindividualfirstname     = AdjustString255(sol.ResponsibleIndividual?.FirstName),
                    AdoxioResponsibleindividuallastname      = AdjustString255(sol.ResponsibleIndividual?.LastName),
                    AdoxioResponsibleindividualmiddleinitial = AdjustString255(sol.ResponsibleIndividual?.MiddleInitial),
                    AdoxioResponsibleindividualposition      = AdjustString255(sol.ResponsibleIndividual?.Position),
                    AdoxioResponsibleindividualsir           = sol.ResponsibleIndividual?.SirNumber,
                    // tasting event
                    AdoxioTastingevent = sol.TastingEvent
                };

                newRecord.AdoxioSpecialeventSpecialeventlocations = new List <MicrosoftDynamicsCRMadoxioSpecialeventlocation>();

                newRecord.AdoxioSpecialeventSpecialeventlocations.Add(ExtractLocation(sol));


                // notes
                if (sol.SolNote != null)
                {
                    newRecord.AdoxioSpecialeventSpecialeventnotes =
                        new List <MicrosoftDynamicsCRMadoxioSpecialeventnote>();

                    foreach (var item in sol.SolNote)
                    {
                        newRecord.AdoxioSpecialeventSpecialeventnotes.Add(
                            new MicrosoftDynamicsCRMadoxioSpecialeventnote()
                        {
                            AdoxioNote   = item.Text,
                            AdoxioAuthor = AdjustString255(item.Author),
                            Createdon    = AdjustDateTime(item.CreatedDate),
                            Modifiedon   = AdjustDateTime(item.LastUpdatedDate)
                        });
                    }
                }

                // terms and conditions
                if (sol.TsAndCs != null)
                {
                    newRecord.AdoxioSpecialeventSpecialeventtsacs =
                        new List <MicrosoftDynamicsCRMadoxioSpecialeventtandc>();
                    foreach (var item in sol.TsAndCs)
                    {
                        var newTandC = new MicrosoftDynamicsCRMadoxioSpecialeventtandc()
                        {
                            AdoxioTermsandcondition = item.Text,
                            AdoxioOriginator        = AdjustString255(item.Originator)
                        };

                        if (item.TandcType == TandcType.GlobalCondition)
                        {
                            newTandC.AdoxioTermsandconditiontype = true;
                        }

                        newRecord.AdoxioSpecialeventSpecialeventtsacs.Add(newTandC);
                    }
                }

                try
                {
                    newRecord = _dynamicsClient.Specialevents.Create(newRecord);
                    _logger.Information($"Created special event {newRecord.AdoxioSpecialeventid}");
                }
                catch (HttpOperationException httpOperationException)
                {
                    _logger.Error(httpOperationException, "Error creating special event record");
                    // fail
                    return(StatusCode(500, "Server Error creating record."));
                }
            }
            else // existing record.
            {
                if (sol.Location != null)
                {
                    MicrosoftDynamicsCRMadoxioSpecialeventlocation location = ExtractLocation(sol);

                    try
                    {
                        location = _dynamicsClient.Specialeventlocations.Create(location);
                        _logger.Information(
                            $"Created new special event location {location.AdoxioSpecialeventlocationid}");
                    }
                    catch (HttpOperationException httpOperationException)
                    {
                        _logger.Error(httpOperationException, "Error creating special event schedule");
                        // fail
                        return(StatusCode(500, "Server Error creating record."));
                    }

                    // now bind the record to the parent.

                    var specialEventLocationData = _dynamicsClient.GetEntityURI("adoxio_specialeventlocations",
                                                                                location.AdoxioSpecialeventlocationid);

                    var oDataIdEventLocation = new Odataid
                    {
                        OdataidProperty = specialEventLocationData
                    };
                    try
                    {
                        _dynamicsClient.Specialevents.AddReference(existingRecord.AdoxioSpecialeventid,
                                                                   "adoxio_specialevent_specialeventlocations", oDataIdEventLocation);
                    }
                    catch (HttpOperationException odee)
                    {
                        Log.Error(odee, "Error adding reference to adoxio_specialevent_specialeventlocations");
                    }
                }
            }


            return(Ok());
        }
        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));
        }
示例#30
0
        /// <summary>
        /// Get a Account by their Guid
        /// </summary>
        /// <param name="system"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static void CreateBusinessContactLink(this IDynamicsClient system, ILogger _logger, string contactId, string accountId, string jobtitle, int?contactType, string jobTitle)
        {
            bool   valid        = true;
            string errorMessage = "";

            if (string.IsNullOrEmpty(contactId))
            {
                errorMessage += "ContactId is null. ";
                valid         = false;
            }
            if (string.IsNullOrEmpty(accountId))
            {
                errorMessage += "AccountId is null. ";
                valid         = false;
            }

            if (contactType == null)
            {
                errorMessage += "ContactType is null. ";
                valid         = false;
            }

            if (valid)
            {
                MicrosoftDynamicsCRMbcgovBusinesscontact result = system.GetBusinessContactLink(_logger, contactId, accountId);

                if (result == null)
                {
                    // create it.
                    try
                    {
                        result = new MicrosoftDynamicsCRMbcgovBusinesscontact()
                        {
                            BcgovContacttype = contactType,
                            ContactODataBind = system.GetEntityURI("contacts", contactId),
                            AccountODataBind = system.GetEntityURI("accounts", accountId),
                            BcgovJobtitle    = jobTitle,
                            BcgovFromdate    = DateTimeOffset.Now
                        };

                        if (!string.IsNullOrEmpty(jobtitle))
                        {
                            result.BcgovJobtitle = jobtitle;
                        }
                        result = system.Businesscontacts.Create(result);
                    }
                    catch (OdataerrorException odee)
                    {
                        if (_logger != null)
                        {
                            _logger.LogError(LoggingEvents.Error, "Error while creating a business contact.");
                            _logger.LogError("Request:");
                            _logger.LogError(odee.Request.Content);
                            _logger.LogError("Response:");
                            _logger.LogError(odee.Response.Content);
                        }
                    }

                    // now link the BusinessContact to the Account.

                    try
                    {
                        OdataId oDataId = new OdataId()
                        {
                            OdataIdProperty = system.GetEntityURI("bcgov_businesscontacts", result.BcgovBusinesscontactid)
                        };
                        system.Accounts.AddReference(accountId, "bcgov_account_bcgov_businesscontact_BusinessProfile", oDataId);
                    }
                    catch (OdataerrorException odee)
                    {
                        if (_logger != null)
                        {
                            _logger.LogError(LoggingEvents.Error, "Error while adding reference from account to business contact");
                            _logger.LogError("Request:");
                            _logger.LogError(odee.Request.Content);
                            _logger.LogError("Response:");
                            _logger.LogError(odee.Response.Content);
                        }
                    }

                    // now link the contact

                    try
                    {
                        OdataId oDataId = new OdataId()
                        {
                            OdataIdProperty = system.GetEntityURI("bcgov_businesscontacts", result.BcgovBusinesscontactid)
                        };
                        system.Contacts.AddReference(contactId, "bcgov_contact_bcgov_businesscontact_Contact", oDataId);
                    }
                    catch (OdataerrorException odee)
                    {
                        if (_logger != null)
                        {
                            _logger.LogError(LoggingEvents.Error, "Error while adding reference from contact to business contact.");
                            _logger.LogError("Request:");
                            _logger.LogError(odee.Request.Content);
                            _logger.LogError("Response:");
                            _logger.LogError(odee.Response.Content);
                        }
                    }
                }
            }
            else
            {
                if (_logger != null)
                {
                    _logger.LogError(LoggingEvents.Error, "Invalid parameters passed.");
                    _logger.LogError(errorMessage);
                }
            }
        }