public async Task <JsonResult> CreateApplicationForAction(string licenceId, string applicationTypeName) { // for association with current user string userJson = _httpContextAccessor.HttpContext.Session.GetString("UserSettings"); UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(userJson); var expand = new List <string> { "adoxio_Licencee", "adoxio_LicenceType", "adoxio_adoxio_licences_adoxio_applicationtermsconditionslimitation_Licence", "adoxio_adoxio_licences_adoxio_application_AssignedLicence", "adoxio_establishment" }; MicrosoftDynamicsCRMadoxioLicences adoxioLicense = _dynamicsClient.Licenceses.GetByKey(licenceId, expand: expand); if (adoxioLicense == null) { throw new Exception("Error getting license."); } else { var adoxioLicencetype = _dynamicsClient.GetAdoxioLicencetypeByName(applicationTypeName); MicrosoftDynamicsCRMadoxioApplication application = new MicrosoftDynamicsCRMadoxioApplication() { // START WITH BLANK FIELDS. }; application.CopyValuesForChangeOfLocation(adoxioLicense, applicationTypeName != "CRS Location Change"); // get the previous application for the licence. application.AdoxioApplicanttype = adoxioLicense.AdoxioLicencee.AdoxioBusinesstype; // set applicaiton type relationship var applicationType = _dynamicsClient.GetApplicationTypeByName(applicationTypeName); application.AdoxioApplicationTypeIdODataBind = _dynamicsClient.GetEntityURI("adoxio_applicationtypes", applicationType.AdoxioApplicationtypeid); // set license type relationship application.AdoxioLicenceTypeODataBind = _dynamicsClient.GetEntityURI("adoxio_licencetypes", adoxioLicense.AdoxioLicenceType.AdoxioLicencetypeid); application.AdoxioApplicantODataBind = _dynamicsClient.GetEntityURI("accounts", userSettings.AccountId); application.AdoxioLicenceEstablishmentODataBind = _dynamicsClient.GetEntityURI("adoxio_establishments", adoxioLicense.AdoxioEstablishment.AdoxioEstablishmentid); try { application = _dynamicsClient.Applications.Create(application); } catch (HttpOperationException httpOperationException) { string applicationId = _dynamicsClient.GetCreatedRecord(httpOperationException, null); if (!string.IsNullOrEmpty(applicationId) && Guid.TryParse(applicationId, out Guid applicationGuid)) { application = await _dynamicsClient.GetApplicationById(applicationGuid); } else { _logger.LogError(httpOperationException, "Error creating application"); // fail if we can't create. throw (httpOperationException); } } // now bind the new application to the given licence. var patchApplication = new MicrosoftDynamicsCRMadoxioApplication() { AdoxioAssignedLicenceODataBind = _dynamicsClient.GetEntityURI("adoxio_licenceses", licenceId) }; try { _dynamicsClient.Applications.Update(application.AdoxioApplicationid, patchApplication); } catch (HttpOperationException httpOperationException) { _logger.LogError(httpOperationException, "Error updating application"); } return(new JsonResult(await application.ToViewModel(_dynamicsClient))); } }
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)); }
public async Task <IActionResult> CreateApplication([FromBody] ViewModels.Application item) { // for association with current user string userJson = _httpContextAccessor.HttpContext.Session.GetString("UserSettings"); UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(userJson); int count = GetSubmittedCountByApplicant(userSettings.AccountId); if (count >= 8) { return(BadRequest("8 applications have already been submitted. Can not create more")); } MicrosoftDynamicsCRMadoxioApplication adoxioApplication = new MicrosoftDynamicsCRMadoxioApplication(); // copy received values to Dynamics Application adoxioApplication.CopyValues(item); adoxioApplication.AdoxioApplicanttype = (int?)item.ApplicantType; try { var adoxioLicencetype = _dynamicsClient.GetAdoxioLicencetypeByName(item.LicenseType); // set license type relationship adoxioApplication.AdoxioLicenceTypeODataBind = _dynamicsClient.GetEntityURI("adoxio_licencetypes", adoxioLicencetype.AdoxioLicencetypeid); adoxioApplication.AdoxioApplicantODataBind = _dynamicsClient.GetEntityURI("accounts", userSettings.AccountId); adoxioApplication = _dynamicsClient.Applications.Create(adoxioApplication); } catch (OdataerrorException odee) { string applicationId = _dynamicsClient.GetCreatedRecord(odee, null); if (!string.IsNullOrEmpty(applicationId) && Guid.TryParse(applicationId, out Guid applicationGuid)) { adoxioApplication = await _dynamicsClient.GetApplicationById(applicationGuid); } else { _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); } } // in case the job number is not there, try getting the record from the server. if (adoxioApplication.AdoxioJobnumber == null) { _logger.LogError("AdoxioJobnumber is null, fetching record again."); Guid id = Guid.Parse(adoxioApplication.AdoxioApplicationid); adoxioApplication = await _dynamicsClient.GetApplicationById(id); } if (adoxioApplication.AdoxioJobnumber == null) { _logger.LogError("Unable to get the Job Number for the Application."); throw new Exception("Error creating Licence Application."); } await initializeSharepoint(adoxioApplication); return(Json(await adoxioApplication.ToViewModel(_dynamicsClient))); }
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); int count = GetSubmittedCountByApplicant(userSettings.AccountId); if (count >= 8) { return(BadRequest("8 applications have already been submitted. Can not create more")); } MicrosoftDynamicsCRMadoxioApplication adoxioApplication = new MicrosoftDynamicsCRMadoxioApplication(); // copy received values to Dynamics Application adoxioApplication.CopyValues(item); adoxioApplication.AdoxioApplicanttype = (int?)item.applicantType; try { var adoxioLicencetype = _dynamicsClient.GetAdoxioLicencetypeByName(item.licenseType); // set license type relationship adoxioApplication.AdoxioLicenceTypeODataBind = _dynamicsClient.GetEntityURI("adoxio_licencetypes", adoxioLicencetype.AdoxioLicencetypeid); adoxioApplication.AdoxioApplicantODataBind = _dynamicsClient.GetEntityURI("accounts", userSettings.AccountId); adoxioApplication = _dynamicsClient.Applications.Create(adoxioApplication); } catch (OdataerrorException odee) { string applicationId = _dynamicsClient.GetCreatedRecord(odee, null); if (!string.IsNullOrEmpty(applicationId) && Guid.TryParse(applicationId, out Guid applicationGuid)) { adoxioApplication = await _dynamicsClient.GetApplicationById(applicationGuid); } else { _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); } } // in case the job number is not there, try getting the record from the server. if (adoxioApplication.AdoxioJobnumber == null) { _logger.LogError("AdoxioJobnumber is null, fetching record again."); Guid id = Guid.Parse(adoxioApplication.AdoxioApplicationid); adoxioApplication = await _dynamicsClient.GetApplicationById(id); } if (adoxioApplication.AdoxioJobnumber == null) { _logger.LogError("Unable to get the Job Number for the Application."); throw new Exception("Error creating Licence Application."); } // create a SharePointDocumentLocation link string folderName = GetApplicationFolderName(adoxioApplication); string name = adoxioApplication.AdoxioJobnumber + " Files"; // Create the folder bool folderExists = await _sharePointFileManager.FolderExists(ApplicationDocumentUrlTitle, folderName); if (!folderExists) { try { var folder = await _sharePointFileManager.CreateFolder(ApplicationDocumentUrlTitle, folderName); } catch (Exception e) { _logger.LogError("Error creating Sharepoint Folder"); _logger.LogError($"List is: {ApplicationDocumentUrlTitle}"); _logger.LogError($"FolderName is: {folderName}"); throw e; } } // Create the SharePointDocumentLocation entity MicrosoftDynamicsCRMsharepointdocumentlocation mdcsdl = new MicrosoftDynamicsCRMsharepointdocumentlocation() { Relativeurl = folderName, Description = "Application Files", Name = name }; try { mdcsdl = _dynamicsClient.SharepointDocumentLocations.Create(mdcsdl); } catch (OdataerrorException odee) { string mdcsdlId = _dynamicsClient.GetCreatedRecord(odee, null); if (!string.IsNullOrEmpty(mdcsdlId)) { mdcsdl.Sharepointdocumentlocationid = mdcsdlId; } else { _logger.LogError("Error creating SharepointDocumentLocation"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); mdcsdl = null; } } if (mdcsdl != null) { // add a regardingobjectid. string applicationReference = _dynamicsClient.GetEntityURI("adoxio_applications", adoxioApplication.AdoxioApplicationid); var patchSharePointDocumentLocation = new MicrosoftDynamicsCRMsharepointdocumentlocation(); patchSharePointDocumentLocation.RegardingobjectidAdoxioApplicationODataBind = applicationReference; // set the parent document library. string parentDocumentLibraryReference = GetDocumentLocationReferenceByRelativeURL("adoxio_application"); patchSharePointDocumentLocation.ParentsiteorlocationSharepointdocumentlocationODataBind = _dynamicsClient.GetEntityURI("sharepointdocumentlocations", parentDocumentLibraryReference); try { _dynamicsClient.SharepointDocumentLocations.Update(mdcsdl.Sharepointdocumentlocationid, patchSharePointDocumentLocation); } catch (OdataerrorException odee) { _logger.LogError("Error adding reference SharepointDocumentLocation to application"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); } string sharePointLocationData = _dynamicsClient.GetEntityURI("sharepointdocumentlocations", mdcsdl.Sharepointdocumentlocationid); // update the sharePointLocationData. Odataid oDataId = new Odataid() { OdataidProperty = sharePointLocationData }; try { _dynamicsClient.Applications.AddReference(adoxioApplication.AdoxioApplicationid, "adoxio_application_SharePointDocumentLocations", oDataId); } catch (OdataerrorException odee) { _logger.LogError("Error adding reference to SharepointDocumentLocation"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); } } return(Json(await adoxioApplication.ToViewModel(_dynamicsClient))); }