コード例 #1
0
        public async Task <IActionResult> GetCurrentAccount()
        {
            ViewModels.Account result = null;

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

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

                if (account == null)
                {
                    return(new NotFoundResult());
                }

                result = account.ToViewModel();
            }
            else
            {
                return(new NotFoundResult());
            }

            return(Json(result));
        }
コード例 #2
0
        public async Task <IActionResult> GetAccount(string id)
        {
            ViewModels.Account result = null;

            // query the Dynamics system to get the account record.
            if (id != null)
            {
                // verify the currently logged in user has access to this account
                Guid accountId = new Guid(id);
                //TODO: This permission check needs to be revised
                // if (!CurrentUserHasAccessToAccount(accountId))
                // {
                //     return new NotFoundResult();
                // }

                MicrosoftDynamicsCRMaccount account = await _dynamicsClient.GetAccountById(accountId);

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

            return(Json(result));
        }
コード例 #3
0
        public async Task <IActionResult> UpdateDynamicsAccount([FromBody] ViewModels.Account item, string id)
        {
            if (id != item.id)
            {
                return(BadRequest());
            }

            // get the legal entity.
            Guid accountId = new Guid(id);

            MicrosoftDynamicsCRMaccount adoxioAccount = await _dynamicsClient.GetAccountById(accountId);

            if (adoxioAccount == null)
            {
                return(new NotFoundResult());
            }

            // we are doing a patch, so wipe out the record.
            adoxioAccount = new MicrosoftDynamicsCRMaccount();

            // copy values over from the data provided
            adoxioAccount.CopyValues(item);

            await _dynamicsClient.Accounts.UpdateAsync(accountId.ToString(), adoxioAccount);

            return(Json(adoxioAccount.ToViewModel()));
        }
コード例 #4
0
        public async Task <IActionResult> GetApplicantDynamicsLegalEntity()
        {
            ViewModels.AdoxioLegalEntity result = null;

            // 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();

            // query the Dynamics system to get the legal entity record.
            MicrosoftDynamicsCRMadoxioLegalentity legalEntity = null;

            _logger.LogError("Find legal entity for applicant = " + userSettings.AccountId.ToString());

            legalEntity = _dynamicsClient.GetAdoxioLegalentityByAccountId(Guid.Parse(userSettings.AccountId));

            if (legalEntity == null)
            {
                return(new NotFoundResult());
            }
            // fix the account.

            result = legalEntity.ToViewModel();

            if (result.account == null)
            {
                MicrosoftDynamicsCRMaccount account = await _dynamicsClient.GetAccountById(Guid.Parse(userSettings.AccountId));

                result.account = account.ToViewModel();
            }

            return(Json(result));
        }
コード例 #5
0
        public async Task <IActionResult> UpdateDynamicsAccount([FromBody] ViewModels.Account item, string id)
        {
            _logger.LogDebug(LoggingEvents.HttpPut, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);
            _logger.LogDebug(LoggingEvents.HttpPut, "Account parameter: " + JsonConvert.SerializeObject(item));
            _logger.LogDebug(LoggingEvents.HttpPut, "id parameter: " + id);

            if (id != item.id)
            {
                _logger.LogWarning(LoggingEvents.BadRequest, "Bad Request. Id doesn't match the account id.");
                return(BadRequest());
            }

            // get the legal entity.
            Guid accountId = new Guid(id);

            if (!DynamicsExtensions.CurrentUserHasAccessToAccount(accountId, _httpContextAccessor, _dynamicsClient))
            {
                _logger.LogWarning(LoggingEvents.NotFound, "Current user has NO access to the account.");
                return(NotFound());
            }

            MicrosoftDynamicsCRMaccount adoxioAccount = await _dynamicsClient.GetAccountById(accountId);

            if (adoxioAccount == null)
            {
                _logger.LogWarning(LoggingEvents.NotFound, "Account NOT found.");
                return(new NotFoundResult());
            }

            // we are doing a patch, so wipe out the record.
            adoxioAccount = new MicrosoftDynamicsCRMaccount();

            // copy values over from the data provided
            adoxioAccount.CopyValues(item);

            try
            {
                await _dynamicsClient.Accounts.UpdateAsync(accountId.ToString(), adoxioAccount);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error updating the account. ");
                throw new Exception("Error updating the account.");
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Error updating the account.");
                throw new Exception("Error updating the account.");
            }

            var updatedAccount = adoxioAccount.ToViewModel();

            _logger.LogDebug(LoggingEvents.HttpPut, "updatedAccount: " +
                             JsonConvert.SerializeObject(updatedAccount, Formatting.Indented, new JsonSerializerSettings {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            }));

            return(new JsonResult(updatedAccount));
        }
コード例 #6
0
        public IActionResult GetAccount(string id)
        {
            _logger.LogInformation(LoggingEvents.HttpGet, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);
            _logger.LogDebug(LoggingEvents.HttpGet, "id: " + id);

            Boolean userAccessToAccount = false;

            ViewModels.Account result = null;

            // query the Dynamics system to get the account record.
            if (!string.IsNullOrEmpty(id) && Guid.TryParse(id, out Guid accountId))
            {
                // verify the currently logged in user has access to this account
                try
                {
                    userAccessToAccount = UserDynamicsExtensions.CurrentUserHasAccessToAccount(accountId, _httpContextAccessor, _dynamicsClient);
                }
                catch (OdataerrorException odee)
                {
                    _logger.LogError(LoggingEvents.Error, "Error while checking if current user has access to account.");
                    _logger.LogError("Request:");
                    _logger.LogError(odee.Request.Content);
                    _logger.LogError("Response:");
                    _logger.LogError(odee.Response.Content);
                }

                if (!userAccessToAccount)
                {
                    _logger.LogWarning(LoggingEvents.NotFound, "Current user has NO access to account.");
                    return(new NotFoundResult());
                }
                List <string> expand = new List <string> {
                    "bcgov_CurrentBusinessPhysicalAddress",
                    "bcgov_CurrentBusinessMailingAddress", "bcgov_AdditionalContact", "primarycontactid"
                };
                try
                {
                    MicrosoftDynamicsCRMaccount account = _dynamicsClient.Accounts.GetByKey(accountId.ToString(), expand: expand);
                    result = account.ToViewModel();
                }
                catch (OdataerrorException)
                {
                    return(new NotFoundResult());
                }
            }
            else
            {
                _logger.LogWarning(LoggingEvents.BadRequest, "Bad Request.");
                return(BadRequest());
            }

            _logger.LogDebug(LoggingEvents.HttpGet, "Account result: " +
                             JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            }));
            return(Json(result));
        }
コード例 #7
0
        public async Task <IActionResult> GetAccount(string id)
        {
            _logger.LogInformation(LoggingEvents.HttpGet, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);
            _logger.LogDebug(LoggingEvents.HttpGet, "id: " + id);

            Boolean userAccessToAccount = false;

            ViewModels.Account result = null;

            // query the Dynamics system to get the account record.
            if (id != null)
            {
                // verify the currently logged in user has access to this account
                Guid accountId = new Guid(id);

                try
                {
                    userAccessToAccount = DynamicsExtensions.CurrentUserHasAccessToAccount(accountId, _httpContextAccessor, _dynamicsClient);
                }
                catch (OdataerrorException odee)
                {
                    _logger.LogError(LoggingEvents.Error, "Error while checking if current user has access to account.");
                    _logger.LogError("Request:");
                    _logger.LogError(odee.Request.Content);
                    _logger.LogError("Response:");
                    _logger.LogError(odee.Response.Content);
                }

                if (!userAccessToAccount)
                {
                    _logger.LogWarning(LoggingEvents.NotFound, "Current user has NO access to account.");
                    return(new NotFoundResult());
                }

                MicrosoftDynamicsCRMaccount account = await _dynamicsClient.GetAccountById(accountId);

                if (account == null)
                {
                    _logger.LogWarning(LoggingEvents.NotFound, "Account NOT found.");
                    return(new NotFoundResult());
                }
                result = account.ToViewModel();
            }
            else
            {
                _logger.LogWarning(LoggingEvents.BadRequest, "Bad Request.");
                return(BadRequest());
            }

            _logger.LogDebug(LoggingEvents.HttpGet, "Account result: " +
                             JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            }));
            return(Json(result));
        }
コード例 #8
0
        public async Task <IActionResult> GetCurrentAccount()
        {
            _logger.LogInformation(LoggingEvents.HttpGet, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);
            ViewModels.Account result = null;

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

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

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

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

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

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

            _logger.LogDebug(LoggingEvents.HttpGet, "Current Account Result: " +
                             JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            }));
            return(Json(result));
        }
コード例 #9
0
        public async System.Threading.Tasks.Task TestCRUD()
        {
            string initialName = "InitialName";
            string changedName = "ChangedName";
            string service     = "account";

            // register and login as our first user
            var loginUser1 = randomNewUserName("TestAccountUser", 6);

            await Login(loginUser1);

            // C - Create
            var request = new HttpRequestMessage(HttpMethod.Post, "/api/" + service);

            MicrosoftDynamicsCRMaccount account = new MicrosoftDynamicsCRMaccount()
            {
                Name             = initialName,
                AdoxioExternalid = Guid.NewGuid().ToString()
            };

            ViewModels.Account viewmodel_account = account.ToViewModel();
            viewmodel_account.businessType = "PublicCorporation";

            string jsonString = JsonConvert.SerializeObject(viewmodel_account);

            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            var response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            // parse as JSON.
            ViewModels.Account responseViewModel = JsonConvert.DeserializeObject <ViewModels.Account>(jsonString);

            // name should match.
            Assert.Equal(initialName, responseViewModel.name);
            Guid id = new Guid(responseViewModel.id);

            //String strid = responseViewModel.externalId;
            //Assert.Equal(strid, viewmodel_account.externalId);

            // R - Read

            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id);
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            jsonString = await response.Content.ReadAsStringAsync();

            responseViewModel = JsonConvert.DeserializeObject <ViewModels.Account>(jsonString);
            Assert.Equal(initialName, responseViewModel.name);

            account.Accountid = id.ToString();

            // get legal entity record for account
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/adoxiolegalentity/applicant");
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            jsonString = await response.Content.ReadAsStringAsync();

            ViewModels.AdoxioLegalEntity legalentityViewModel = JsonConvert.DeserializeObject <ViewModels.AdoxioLegalEntity>(jsonString);
            Assert.Equal(id.ToString(), legalentityViewModel.account.id);

            // U - Update
            account.Name = changedName;


            request = new HttpRequestMessage(HttpMethod.Put, "/api/" + service + "/" + id)
            {
                Content = new StringContent(JsonConvert.SerializeObject(account.ToViewModel()), Encoding.UTF8, "application/json")
            };
            response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            // verify that the update persisted.

            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id);
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            jsonString = await response.Content.ReadAsStringAsync();

            responseViewModel = JsonConvert.DeserializeObject <ViewModels.Account>(jsonString);
            Assert.Equal(changedName, responseViewModel.name);

            // D - Delete

            request  = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + id + "/delete");
            response = await _client.SendAsync(request);

            string responseText = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            // second delete should return a 404.
            request  = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + id + "/delete");
            response = await _client.SendAsync(request);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            // should get a 404 if we try a get now.
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id);
            response = await _client.SendAsync(request);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            await Logout();
        }
コード例 #10
0
        public async Task <IActionResult> UpdateAccount([FromBody] ViewModels.Account item, string id)
        {
            if (!string.IsNullOrEmpty(id) && Guid.TryParse(id, out Guid accountId))
            {
                _logger.LogInformation(LoggingEvents.HttpPut, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name);
                _logger.LogDebug(LoggingEvents.HttpPut, "Account parameter: " + JsonConvert.SerializeObject(item));
                _logger.LogDebug(LoggingEvents.HttpPut, "id parameter: " + id);


                if (!UserDynamicsExtensions.CurrentUserHasAccessToAccount(accountId, _httpContextAccessor, _dynamicsClient))
                {
                    _logger.LogWarning(LoggingEvents.NotFound, "Current user has NO access to the account.");
                    return(NotFound());
                }

                MicrosoftDynamicsCRMaccount account = _dynamicsClient.GetAccountByIdWithChildren(accountId);
                if (account == null)
                {
                    _logger.LogWarning(LoggingEvents.NotFound, "Account NOT found.");
                    return(new NotFoundResult());
                }

                // handle the contacts.

                UpdateContacts(item);

                // we are doing a patch, so wipe out the record.
                MicrosoftDynamicsCRMaccount patchAccount = new MicrosoftDynamicsCRMaccount();

                // copy values over from the data provided
                patchAccount.CopyValues(item);
                if (item.primaryContact != null && item.primaryContact.id != null &&
                    (account._primarycontactidValue == null || account._primarycontactidValue != item.primaryContact.id))
                {
                    patchAccount.PrimaryContactidODataBind = _dynamicsClient.GetEntityURI("contacts", item.primaryContact.id);
                }
                else
                {
                    if (account._primarycontactidValue != null && !item.primaryContact.HasValue())
                    {
                        // remove the reference.
                        try
                        {
                            // pass null as recordId to remove the single value navigation property
                            _dynamicsClient.Accounts.RemoveReference(accountId.ToString(), "primarycontactid", null);
                        }
                        catch (OdataerrorException odee)
                        {
                            _logger.LogError(LoggingEvents.Error, "Error updating the account.");
                            _logger.LogError("Request:");
                            _logger.LogError(odee.Request.Content);
                            _logger.LogError("Response:");
                            _logger.LogError(odee.Response.Content);
                            throw new OdataerrorException("Error updating the account.");
                        }

                        // delete the contact.
                        try
                        {
                            _dynamicsClient.Contacts.Delete(account._primarycontactidValue);
                        }
                        catch (OdataerrorException odee)
                        {
                            _logger.LogError(LoggingEvents.Error, "Error removing primary contact");
                            _logger.LogError("Request:");
                            _logger.LogError(odee.Request.Content);
                            _logger.LogError("Response:");
                            _logger.LogError(odee.Response.Content);
                            throw new OdataerrorException("Error updating the account.");
                        }
                    }
                }


                if (item.additionalContact != null && item.additionalContact.id != null &&
                    (account._bcgovAdditionalcontactValue == null || account._bcgovAdditionalcontactValue != item.additionalContact.id))
                {
                    patchAccount.AdditionalContactODataBind = _dynamicsClient.GetEntityURI("contacts", item.additionalContact.id);
                }
                else
                {
                    if (account._bcgovAdditionalcontactValue != null && !item.additionalContact.HasValue())
                    {
                        // remove the reference.
                        try
                        {
                            // pass null as recordId to remove the single value navigation property
                            _dynamicsClient.Accounts.RemoveReference(accountId.ToString(), "bcgov_AdditionalContact", null);
                        }
                        catch (OdataerrorException odee)
                        {
                            _logger.LogError(LoggingEvents.Error, "Error updating the account.");
                            _logger.LogError("Request:");
                            _logger.LogError(odee.Request.Content);
                            _logger.LogError("Response:");
                            _logger.LogError(odee.Response.Content);
                            throw new OdataerrorException("Error updating the account.");
                        }

                        // delete the contact.
                        try
                        {
                            _dynamicsClient.Contacts.Delete(account._bcgovAdditionalcontactValue);
                        }
                        catch (OdataerrorException odee)
                        {
                            _logger.LogError(LoggingEvents.Error, "Error removing additional contact");
                            _logger.LogError("Request:");
                            _logger.LogError(odee.Request.Content);
                            _logger.LogError("Response:");
                            _logger.LogError(odee.Response.Content);
                            throw new OdataerrorException("Error updating the account.");
                        }
                    }
                }


                try
                {
                    await _dynamicsClient.Accounts.UpdateAsync(accountId.ToString(), patchAccount);
                }
                catch (OdataerrorException odee)
                {
                    _logger.LogError(LoggingEvents.Error, "Error updating the account.");
                    _logger.LogError("Request:");
                    _logger.LogError(odee.Request.Content);
                    _logger.LogError("Response:");
                    _logger.LogError(odee.Response.Content);
                    throw new OdataerrorException("Error updating the account.");
                }

                // purge any existing non bceid accounts.
                _dynamicsClient.DeleteNonBceidBusinessContactLinkForAccount(_logger, accountId.ToString());

                // create the business contact links.
                if (item.primaryContact != null)
                {
                    _dynamicsClient.CreateBusinessContactLink(_logger, item.primaryContact.id, accountId.ToString(), null, (int?)ContactTypeCodes.Primary, item.primaryContact.title);
                }
                if (item.additionalContact != null)
                {
                    _dynamicsClient.CreateBusinessContactLink(_logger, item.additionalContact.id, accountId.ToString(), null, (int?)ContactTypeCodes.Additional, item.additionalContact.title);
                }


                // populate child items in the account.
                patchAccount = _dynamicsClient.GetAccountByIdWithChildren(accountId);

                var updatedAccount = patchAccount.ToViewModel();
                _logger.LogDebug(LoggingEvents.HttpPut, "updatedAccount: " +
                                 JsonConvert.SerializeObject(updatedAccount, Formatting.Indented, new JsonSerializerSettings {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                }));

                return(Json(updatedAccount));
            }
            else
            {
                return(new BadRequestResult());
            }
        }
コード例 #11
0
        // this fellow returns the external id of the new account
        public async System.Threading.Tasks.Task <string> LoginAndRegisterAsNewUser(string loginUser, string businessName, string businessType = "PublicCorporation")
        {
            string accountService = "accounts";

            await Login(loginUser + "::" + businessName);

            ViewModels.User user = await GetCurrentUser();

            Assert.Equal(user.name, loginUser + " TestUser");
            Assert.Equal(user.businessname, businessName + " TestBusiness");
            Assert.True(user.isNewUser);

            // create a new account and contact in Dynamics
            var request = new HttpRequestMessage(HttpMethod.Post, "/api/" + accountService);

            MicrosoftDynamicsCRMaccount account = new MicrosoftDynamicsCRMaccount()
            {
                Name             = user.businessname,
                AdoxioExternalid = user.accountid
            };

            ViewModels.Account viewmodel_account = account.ToViewModel();

            viewmodel_account.businessType = businessType;

            Assert.Equal(account.AdoxioExternalid, viewmodel_account.externalId);

            string jsonString2 = JsonConvert.SerializeObject(viewmodel_account);

            request.Content = new StringContent(jsonString2, Encoding.UTF8, "application/json");
            var response = await _client.SendAsync(request);

            var jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            ViewModels.Account responseViewModel = JsonConvert.DeserializeObject <ViewModels.Account>(jsonString);

            // name should match.
            Assert.Equal(user.businessname, responseViewModel.name);
            string strId = responseViewModel.externalId;
            string id    = responseViewModel.id;

            Assert.Equal(strId, responseViewModel.externalId);

            // verify we can fetch the account via web service
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + accountService + "/" + id);
            response = await _client.SendAsync(request);

            string _discard = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            // test that the current user is updated
            user = await GetCurrentUser();

            Assert.NotNull(user.accountid);
            Assert.NotEmpty(user.accountid);
            Assert.Equal(id, user.accountid);

            return(id);
        }