Beispiel #1
0
        public static async Task <ViewModels.LegalEntity> CreateOrganizationalShareholder(HttpClient _client, ViewModels.User user, string accountLegalEntityId)
        {
            var request   = new HttpRequestMessage(HttpMethod.Post, "/api/legalentities/child-legal-entity");
            var vmAccount = new ViewModels.Account
            {
                id = user.accountid
            };
            var vmAdoxioLegalEntity = new ViewModels.LegalEntity
            {
                legalentitytype     = ViewModels.AdoxioApplicantTypeCodes.PrivateCorporation,
                firstname           = "Test",
                middlename          = "The",
                lastname            = "Orgshareholder",
                name                = "Test Orgshareholder",
                dateofbirth         = DateTime.Now,
                isShareholder       = true,
                isindividual        = false,
                account             = vmAccount,
                parentLegalEntityId = accountLegalEntityId
            };
            var jsonString = JsonConvert.SerializeObject(vmAdoxioLegalEntity);

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

            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();
            ViewModels.LegalEntity responseDirector = JsonConvert.DeserializeObject <ViewModels.LegalEntity>(jsonString);

            var responseViewModel = await GetLegalEntityRecord(_client, responseDirector.id, true);

            Assert.Equal(responseDirector.name, responseViewModel.name);
            return(responseViewModel);
        }
        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));
        }
        public async System.Threading.Tasks.Task UserCantAccessAnotherUsersShareholders()
        {
            // verify (before we log in) that we are not logged in
            await GetCurrentUserIsUnauthorized();

            // register as a new user (creates an account and contact)
            var loginUser1    = randomNewUserName("NewSecUser1", 6);
            var businessName1 = randomNewUserName(loginUser1, 6);
            var strId1        = await LoginAndRegisterAsNewUser(loginUser1, businessName1);

            // verify the current user represents our new user
            ViewModels.User user1 = await GetCurrentUser();

            Assert.Equal(user1.name, loginUser1 + " TestUser");
            Assert.Equal(user1.businessname, businessName1 + " TestBusiness");

            // fetch our current account
            ViewModels.Account account1 = await GetAccountForCurrentUser();

            ViewModels.LegalEntity legalEntity1 = await SecurityHelper.GetLegalEntityRecordForCurrent(_client);

            Assert.Equal(user1.accountid, account1.id);

            // try to "hack" the query
            string hackId = legalEntity1.id + " or (adoxio_isshareholder eq true)";
            List <ViewModels.LegalEntity> doss = await SecurityHelper.GetLegalEntitiesByPosition(_client, hackId, "director-officer-shareholder", false);

            Assert.Null(doss);

            // logout and cleanup (deletes the account and contact created above ^^^)
            await LogoutAndCleanupTestUser(strId1);
            await GetCurrentUserIsUnauthorized();
        }
        public async System.Threading.Tasks.Task DefaultDevelopmentUserIsValid()
        {
            var loginUser = randomNewUserName("NewLoginUser", 6);
            var strId     = await LoginAndRegisterAsNewUser(loginUser);

            var request  = new HttpRequestMessage(HttpMethod.Get, "/api/user/current");
            var response = await _client.SendAsync(request);

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

            response.EnsureSuccessStatusCode();

            ViewModels.User user = JsonConvert.DeserializeObject <ViewModels.User>(jsonString);

            // The Default development user should not be a new user.
            Assert.False(user.isNewUser);
            Assert.NotNull(user.accountid);
            Assert.NotEmpty(user.accountid);

            ViewModels.Account account = await GetAccountForCurrentUser();

            Assert.NotNull(account);

            await LogoutAndCleanupTestUser(strId);
        }
        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()));
        }
        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));
        }
Beispiel #7
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));
        }
Beispiel #8
0
        public Account()
        {
            NavigationPage.SetHasNavigationBar(this, false);

            BindingContext = new ViewModels.Account();

            InitializeComponent();
        }
Beispiel #9
0
        /// <summary>
        /// Create a new ViewModel from a Dynamics Account
        /// </summary>
        /// <param name="account"></param>
        public static ViewModels.Account ToViewModel(this MicrosoftDynamicsCRMaccount account)
        {
            ViewModels.Account accountVM = null;
            if (account != null)
            {
                accountVM = new ViewModels.Account();
                if (account.Accountid != null)
                {
                    accountVM.id = account.Accountid;
                }

                accountVM.name                    = account.Name;
                accountVM.description             = account.Description;
                accountVM.externalId              = account.AdoxioExternalid;
                accountVM.bcIncorporationNumber   = account.AdoxioBcincorporationnumber;
                accountVM.dateOfIncorporationInBC = account.AdoxioDateofincorporationinbc;
                accountVM.businessNumber          = account.Accountnumber;
                accountVM.pstNumber               = account.AdoxioPstnumber;
                accountVM.contactEmail            = account.Emailaddress1;
                accountVM.contactPhone            = account.Telephone1;

                accountVM.mailingAddressName     = account.Address1Name;
                accountVM.mailingAddressStreet   = account.Address1Line1;
                accountVM.mailingAddressStreet2  = account.Address1Line2;
                accountVM.mailingAddressCity     = account.Address1City;
                accountVM.mailingAddressCountry  = account.Address1Country;
                accountVM.mailingAddressProvince = account.Address1Stateorprovince;


                accountVM.mailingAddressPostalCode = account.Address1Postalcode;

                accountVM.physicalAddressName       = account.Address2Name;
                accountVM.physicalAddressStreet     = account.Address2Line1;
                accountVM.physicalAddressStreet2    = account.Address2Line2;
                accountVM.physicalAddressCity       = account.Address2City;
                accountVM.physicalAddressCountry    = account.Address2Country;
                accountVM.physicalAddressProvince   = account.Address2Stateorprovince;
                accountVM.physicalAddressPostalCode = account.Address2Postalcode;

                accountVM.TermsOfUseAccepted     = account.AdoxioTermsofuseaccepted;
                accountVM.TermsOfUseAcceptedDate = account.AdoxioTermsofuseaccepteddate;

                accountVM.LocalGovernmentId = account._adoxioLginlinkidValue;

                accountVM.websiteUrl = account.Websiteurl;

                if (account.Primarycontactid != null)
                {
                    accountVM.primarycontact = account.Primarycontactid.ToViewModel();
                }

                if (account.AdoxioBusinesstype != null)
                {
                    accountVM.businessType = Enum.ToObject(typeof(ViewModels.AdoxioApplicantTypeCodes), account.AdoxioBusinesstype).ToString();
                }
            }
            return(accountVM);
        }
        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));
        }
Beispiel #11
0
 public static ViewModels.Application CreateNewApplication(ViewModels.Account currentAccount)
 {
     ViewModels.Application viewmodel_application = new ViewModels.Application()
     {
         applicant         = currentAccount, //account
         mainbusinessfocus = "Testing",
         manufacturingprocessdescription = "Automated Testing"
     };
     return(viewmodel_application);
 }
Beispiel #12
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));
        }
Beispiel #13
0
        public async System.Threading.Tasks.Task LogoutAndCleanupTestUser(string strId)
        {
            string accountService = "accounts";

            // get the account and check if our current user is the primary contact
            var request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + accountService + "/" + strId);
            var response = await _client.SendAsync(request);

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

            response.EnsureSuccessStatusCode();

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

            ViewModels.User user = await GetCurrentUser();

            // TODO once AccountController is cleaned up restore this test
            Console.WriteLine(">>> responseViewModel.primarycontact.id=" + responseViewModel.primarycontact.id);
            Console.WriteLine(">>>                      user.contactid=" + user.contactid);
            Console.WriteLine(">>>                           user.name=" + user.name);
            if (responseViewModel.primarycontact.id.Equals(user.contactid))
            {
                // cleanup - delete the account and contact when we are done
                request  = new HttpRequestMessage(HttpMethod.Post, "/api/" + accountService + "/" + strId + "/delete");
                response = await _client.SendAsync(request);

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

                response.EnsureSuccessStatusCode();

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

                _discard = await response.Content.ReadAsStringAsync();

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

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

                _discard = await response.Content.ReadAsStringAsync();

                Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            }
            else
            {
                // TODO delete the non-primary contact
            }

            await Logout();
        }
 public async Task DisposeAsync()
 {
     try
     {
         ViewModels.Account currentAccount = await GetAccountForCurrentUser();
         await LogoutAndCleanupTestUser(currentAccount.id);
     }
     catch (HttpRequestException requestException)
     {
         // Ignore any failures to clean up the test user.
         Console.WriteLine(requestException.ToString());
     }
 }
Beispiel #15
0
        /// <summary>
        /// Create a new ViewModel from a Dynamics Account
        /// </summary>
        /// <param name="account"></param>
        public static ViewModels.Account ToViewModel(this MicrosoftDynamicsCRMaccount account)
        {
            ViewModels.Account accountVM = null;
            if (account != null)
            {
                accountVM = new ViewModels.Account();
                if (account.Accountid != null)
                {
                    accountVM.id = account.Accountid.ToString();
                }

                accountVM.name                    = account.Name;
                accountVM.description             = account.Description;
                accountVM.externalId              = account.AdoxioExternalid;
                accountVM.bcIncorporationNumber   = account.AdoxioBcincorporationnumber;
                accountVM.dateOfIncorporationInBC = account.AdoxioDateofincorporationinbc;
                accountVM.businessNumber          = account.Accountnumber;
                accountVM.pstNumber               = account.AdoxioPstnumber;
                accountVM.contactEmail            = account.Emailaddress1;
                accountVM.contactPhone            = account.Telephone1;
                accountVM.mailingAddressName      = account.Address1Name;
                accountVM.mailingAddressStreet    = account.Address1Line1;
                accountVM.mailingAddressCity      = account.Address1City;
                accountVM.mailingAddressCountry   = account.Address1County;
                if (account.AdoxioStateprovince != null)
                {
                    accountVM.mailingAddressProvince = (ViewModels.Adoxio_stateprovince)account.AdoxioStateprovince;
                }
                else
                {
                    accountVM.mailingAddressProvince = ViewModels.Adoxio_stateprovince.BC;
                }
                accountVM.mailingAddresPostalCode = account.Address1Postalcode;

                if (account.Primarycontactid != null)
                {
                    // add the primary contact.
                    accountVM.primarycontact    = new ViewModels.Contact();
                    accountVM.primarycontact.id = account.Primarycontactid.Contactid.ToString();
                    // TODO - load other fields (if necessary)
                }

                if (account.AdoxioBusinesstype != null)
                {
                    accountVM.businessType = Enum.ToObject(typeof(Gov.Lclb.Cllb.Public.ViewModels.Adoxio_applicanttypecodes), account.AdoxioBusinesstype).ToString();
                }
            }
            return(accountVM);
        }
Beispiel #16
0
        public async Task <JsonResult> CreateAccount([FromBody] ViewModels.Account item)
        {
            // create a new account
            Contexts.Microsoft.Dynamics.CRM.Account account = new Contexts.Microsoft.Dynamics.CRM.Account();

            DataServiceCollection <Contexts.Microsoft.Dynamics.CRM.Account> AccountCollection = new DataServiceCollection <Contexts.Microsoft.Dynamics.CRM.Account>(_system);
            DataServiceCollection <Contexts.Microsoft.Dynamics.CRM.Contact> ContactCollection = new DataServiceCollection <Contexts.Microsoft.Dynamics.CRM.Contact>(_system);

            AccountCollection.Add(account);
            account.Name        = item.name;
            account.Description = item.description;

            if (item.primarycontact != null)
            {
                // get the contact.
                Contexts.Microsoft.Dynamics.CRM.Contact contact = new Contexts.Microsoft.Dynamics.CRM.Contact();
                contact.Fullname         = item.primarycontact.name;
                contact.Contactid        = new Guid(item.primarycontact.id);
                account.Primarycontactid = contact;
            }


            await _system.SaveChangesAsync(SaveChangesOptions.PostOnlySetProperties | SaveChangesOptions.BatchWithSingleChangeset);

            // if we have not yet authenticated, then this is the new record for the user.
            string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);

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

                userSettings.IsNewUserRegistration = false;

                string userSettingsString = JsonConvert.SerializeObject(userSettings);
                // add the user to the session.
                _httpContextAccessor.HttpContext.Session.SetString("UserSettings", userSettingsString);
            }

            return(Json(account));
        }
Beispiel #17
0
        public ViewModels.Account Create(ViewModels.Account accountModel)
        {
            data.Entities.Account acc = null;
            try
            {
                acc = _repository.Create(_mapper.Map <data.Entities.Account>(accountModel));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(null);
            }

            return(_mapper.Map <ViewModels.Account>(acc));
        }
Beispiel #18
0
        /// <summary>
        /// Convert a given voteQuestion to a ViewModel
        /// </summary>
        public static ViewModels.Account ToViewModel(this Account account)
        {
            ViewModels.Account result = null;
            if (account != null)
            {
                result = new ViewModels.Account();
                if (account.Accountid != null)
                {
                    result.id = account.Accountid.ToString();
                }

                result.name = account.Name;
            }
            return(result);
        }
        private async Task <ViewModels.Account> AccountFactory()
        {
            var request  = new HttpRequestMessage(HttpMethod.Get, "/api/user/current");
            var response = await _client.SendAsync(request);

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

            response.EnsureSuccessStatusCode();
            ViewModels.User    user      = JsonConvert.DeserializeObject <ViewModels.User>(jsonString);
            ViewModels.Account vmAccount = new ViewModels.Account
            {
                id = user.accountid
            };
            return(vmAccount);
        }
Beispiel #20
0
        public ViewModels.Account Update(ViewModels.Account accountModel)
        {
            data.Entities.Account changedAccount = null;
            try
            {
                changedAccount = _repository.Update(_mapper.Map <data.Entities.Account>(accountModel));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(null);
            }

            accountModel = _mapper.Map <ViewModels.Account>(changedAccount);

            return(accountModel);
        }
        public async System.Threading.Tasks.Task NewUserRegistrationProcessTwoUsersUnderSameBusinessWorks()
        {
            // verify (before we log in) that we are not logged in
            await GetCurrentUserIsUnauthorized();

            // register as a new user (creates an account and contact)
            var temp         = randomNewUserName("NewLoginUser", 6);
            var loginUser1   = temp + "-1";
            var businessName = randomNewUserName(temp, 6);
            var strId1       = await LoginAndRegisterAsNewUser(loginUser1, businessName);

            // verify the current user represents our new user
            ViewModels.User user = await GetCurrentUser();

            Assert.Equal(user.name, loginUser1 + " TestUser");
            Assert.Equal(user.businessname, businessName + " TestBusiness");

            // fetch our current account
            ViewModels.Account account1 = await GetAccountForCurrentUser();

            // logout and verify we are logged out
            await Logout();
            await GetCurrentUserIsUnauthorized();

            // login again as a new user under the same business as above ^^^
            var loginUser2 = temp + "-2";
            var strId2     = await LoginAndRegisterAsNewUser(loginUser2, businessName);

            user = await GetCurrentUser();

            Assert.Equal(user.name, loginUser2 + " TestUser");
            Assert.Equal(user.businessname, businessName + " TestBusiness");
            var account2 = await GetAccountForCurrentUser();

            Assert.Equal(account1.id, account2.id);

            // logout and cleanup (deletes the account and contact created above ^^^)
            await LogoutAndCleanupTestUser(strId2);
            await Login(loginUser1, businessName);
            await LogoutAndCleanupTestUser(strId1);

            // verify we are now logged out and un-authorized
            await GetCurrentUserIsUnauthorized();
        }
Beispiel #22
0
        /// <summary>
        /// Create a new ViewModel from a Dynamics Account
        /// </summary>
        /// <param name="account"></param>
        public static ViewModels.Account ToViewModel(this Account account)
        {
            ViewModels.Account accountVM = null;
            if (account != null)
            {
                accountVM = new ViewModels.Account();
                if (account.Accountid != null)
                {
                    accountVM.id = account.Accountid.ToString();
                }

                accountVM.name                    = account.Name;
                accountVM.description             = account.Description;
                accountVM.externalId              = account.Adoxio_externalid;
                accountVM.bcIncorporationNumber   = account.Adoxio_bcincorporationnumber;
                accountVM.dateOfIncorporationInBC = account.Adoxio_dateofincorporationinbc;
                accountVM.businessNumber          = account.Accountnumber;
                accountVM.pstNumber               = account.Adoxio_pstnumber;
                accountVM.contactEmail            = account.Emailaddress1;
                accountVM.contactPhone            = account.Telephone1;
                accountVM.mailingAddressName      = account.Address1_name;
                accountVM.mailingAddressStreet    = account.Address1_line1;
                accountVM.mailingAddressCity      = account.Address1_city;
                accountVM.mailingAddressCountry   = account.Address1_county;
                if (account.Adoxio_stateprovince != null)
                {
                    accountVM.mailingAddressProvince = (ViewModels.Adoxio_stateprovince)account.Adoxio_stateprovince;
                }
                else
                {
                    accountVM.mailingAddressProvince = ViewModels.Adoxio_stateprovince.BC;
                }
                accountVM.mailingAddresPostalCode = account.Address1_postalcode;

                if (account._primarycontactid_value != null)
                {
                    // add the primary contact.
                    accountVM.primarycontact    = new ViewModels.Contact();
                    accountVM.primarycontact.id = account._primarycontactid_value.ToString();
                    // TODO - load other fields (if necessary)
                }
            }
            return(accountVM);
        }
Beispiel #23
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));
        }
Beispiel #24
0
        public static Account ToModel(this ViewModels.Account account)
        {
            Account result = null;

            if (account != null)
            {
                result = new Account();
                if (string.IsNullOrEmpty(account.id))
                {
                    result.Accountid = new Guid();
                }
                else
                {
                    result.Accountid = new Guid(account.id);
                }
                result.Name = account.name;
            }
            return(result);
        }
Beispiel #25
0
        public static async Task <ViewModels.Account> GetAccountRecord(HttpClient _client, string id, bool expectSuccess)
        {
            var request  = new HttpRequestMessage(HttpMethod.Get, "/api/accounts/" + id);
            var response = await _client.SendAsync(request);

            if (expectSuccess)
            {
                response.EnsureSuccessStatusCode();
                var jsonString = await response.Content.ReadAsStringAsync();

                ViewModels.Account responseViewModel = JsonConvert.DeserializeObject <ViewModels.Account>(jsonString);
                return(responseViewModel);
            }
            else
            {
                Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
                var _discard = await response.Content.ReadAsStringAsync();

                return(null);
            }
        }
        /// <summary>
        /// Create a new Application for testing, using the passed account.
        /// </summary>
        /// <param name="currentAccount">Non-null account to use when creating the Application</param>
        /// <returns>The GUID of the created Application</returns>
        protected async Task <Guid> CreateNewApplicationGuid(ViewModels.Account currentAccount)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, "/api/Application/Waiver");

            ViewModels.Application viewmodel_application = SecurityHelper.CreateNewApplication(currentAccount);

            var jsonString = JsonConvert.SerializeObject(viewmodel_application);

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

            var response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            // parse as JSON.
            jsonString = await response.Content.ReadAsStringAsync();

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

            return(new Guid(responseViewModel.id));
        }
Beispiel #27
0
        /// <summary>
        /// Create a new Dynamics Account from a ViewModel
        /// </summary>
        /// <param name="accountVM"></param>
        public static Account ToModel(this ViewModels.Account accountVM)
        {
            Account result = null;

            if (accountVM != null)
            {
                result = new Account();
                if (string.IsNullOrEmpty(accountVM.id))
                {
                    result.Accountid = new Guid();
                }
                else
                {
                    result.Accountid = new Guid(accountVM.id);
                }
                result.Name = accountVM.name;
                result.Adoxio_externalid              = accountVM.externalId;
                result.Adoxio_bcincorporationnumber   = accountVM.bcIncorporationNumber;
                result.Adoxio_dateofincorporationinbc = accountVM.dateOfIncorporationInBC;
                result.Accountnumber    = accountVM.businessNumber;
                result.Adoxio_pstnumber = accountVM.pstNumber;
                result.Emailaddress1    = accountVM.contactEmail;
                result.Telephone1       = accountVM.contactPhone;
                result.Address1_name    = accountVM.mailingAddressName;
                result.Address1_line1   = accountVM.mailingAddressStreet;
                result.Address1_city    = accountVM.mailingAddressCity;
                result.Address1_county  = accountVM.mailingAddressCountry;
                if (accountVM.mailingAddressProvince >= ViewModels.Adoxio_stateprovince.AB &&
                    accountVM.mailingAddressProvince <= ViewModels.Adoxio_stateprovince.YT)
                {
                    result.Adoxio_stateprovince = (int?)accountVM.mailingAddressProvince;
                }
                else
                {
                    result.Adoxio_stateprovince = (int?)ViewModels.Adoxio_stateprovince.BC;
                }
                result.Address1_postalcode = accountVM.mailingAddresPostalCode;
            }
            return(result);
        }
        public async System.Threading.Tasks.Task NewUserRegistrationProcessWorksForDifferentBusinessName()
        {
            // verify (before we log in) that we are not logged in
            await GetCurrentUserIsUnauthorized();

            // register as a new user (creates an account and contact)
            var loginUser    = randomNewUserName("NewLoginUser", 6);
            var businessName = randomNewUserName(loginUser, 6);
            var strId        = await LoginAndRegisterAsNewUser(loginUser, businessName);

            // verify the current user represents our new user
            ViewModels.User user = await GetCurrentUser();

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

            // fetch our current account
            ViewModels.Account account = await GetAccountForCurrentUser();

            // logout and verify we are logged out
            await Logout();
            await GetCurrentUserIsUnauthorized();

            // login again as the same user as above ^^^
            await Login(loginUser, businessName);

            user = await GetCurrentUser();

            Assert.Equal(user.name, loginUser + " TestUser");
            Assert.Equal(user.businessname, businessName + " TestBusiness");
            account = await GetAccountForCurrentUser();

            // logout and cleanup (deletes the account and contact created above ^^^)
            await LogoutAndCleanupTestUser(strId);

            // verify we are now logged out and un-authorized
            await GetCurrentUserIsUnauthorized();
        }
Beispiel #29
0
        public static async Task <ViewModels.Account> UpdateAccountRecord(HttpClient _client, string id, ViewModels.Account account, bool expectSuccess)
        {
            var request = new HttpRequestMessage(HttpMethod.Put, "/api/account/" + id)
            {
                Content = new StringContent(JsonConvert.SerializeObject(account), Encoding.UTF8, "application/json")
            };
            var response = await _client.SendAsync(request);

            if (expectSuccess)
            {
                response.EnsureSuccessStatusCode();
                var jsonString = await response.Content.ReadAsStringAsync();

                ViewModels.Account responseViewModel = JsonConvert.DeserializeObject <ViewModels.Account>(jsonString);
                return(responseViewModel);
            }
            else
            {
                Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
                var _discard = await response.Content.ReadAsStringAsync();

                return(null);
            }
        }
Beispiel #30
0
        public async System.Threading.Tasks.Task GetAllLicensesTest()
        {
            string initialName = randomNewUserName("License Test ", 6);
            string service     = "adoxioapplication";

            // login as default and get account for current user
            string loginUser1   = randomNewUserName("TestAppUser", 6);
            string loginAccount = randomNewUserName(loginUser1, 6);

            loginUser1 = loginUser1 + "-1";
            var strId1 = await LoginAndRegisterAsNewUser(loginUser1, loginAccount);

            ViewModels.User user1 = await GetCurrentUser();

            ViewModels.Account currentAccount1 = await GetAccountForCurrentUser();

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

            ViewModels.AdoxioApplication viewmodel_application = new ViewModels.AdoxioApplication()
            {
                name                           = initialName,
                applyingPerson                 = "Applying Person",
                applicant                      = currentAccount1,
                applicantType                  = ViewModels.AdoxioApplicantTypeCodes.PrivateCorporation,
                jobNumber                      = "123",
                licenseType                    = "Cannabis Retail Store",
                establishmentName              = "Shared Retail Store",
                establishmentAddress           = "666 Any Street, Victoria, BC, V1X 1X1",
                establishmentaddressstreet     = "666 Any Street",
                establishmentaddresscity       = "Victoria, BC",
                establishmentaddresspostalcode = "V1X 1X1",
                applicationStatus              = AdoxioApplicationStatusCodes.Approved
            };

            var jsonString = JsonConvert.SerializeObject(viewmodel_application);

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

            var response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            jsonString = await response.Content.ReadAsStringAsync();

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

            Assert.Equal("Shared Retail Store", responseViewModel.establishmentName);
            Assert.Equal("Victoria, BC", responseViewModel.establishmentaddresscity);
            Assert.Equal("V1X 1X1", responseViewModel.establishmentaddresspostalcode);

            Guid id = new Guid(responseViewModel.id);

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

            response.EnsureSuccessStatusCode();

            jsonString = await response.Content.ReadAsStringAsync();

            responseViewModel = JsonConvert.DeserializeObject <ViewModels.AdoxioApplication>(jsonString);
            Assert.Equal(currentAccount1.id, responseViewModel.applicant.id);

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

            jsonString = await response.Content.ReadAsStringAsync();

            var responseViewModelList = JsonConvert.DeserializeObject <List <AdoxioLicense> >(jsonString);

            response.EnsureSuccessStatusCode();

            // TODO: License controller is not set up yet. Response passes, however, nothing is returned.

            await LogoutAndCleanupTestUser(strId1);
        }