public async Task CreateBankAccountForCurrentUser_AccountNameExists_ThrowsException()
        {
            // Arrange
            var bankAccountModel = new BankAccountModel
            {
                AccountType  = BankAccountType.Checking,
                Disabled     = true,
                Name         = "BankAccountName",
                StartBalance = 1000
            };

            InsertEntity(new BankAccountEntity
            {
                Name   = bankAccountModel.Name,
                UserId = _defaultUserId
            });

            var bankAccountService = _mocker.CreateInstance <BankAccountService>();

            // Act
            var result = FluentActions.Awaiting(async() => await bankAccountService.CreateBankAccountForCurrentUser(bankAccountModel));

            // Assert
            await result.Should().ThrowAsync <AlreadyExistsException>();
        }
Example #2
0
 public HttpResponseMessage GetAllBankAccount(BankAccountModel aBankAccountModel)
 {
     try
     {
         if (this.ModelState.IsValid)
         {
             var result = service.GetAllBankAccountList(aBankAccountModel);
             if (result != null)
             {
                 return(Request.CreateResponse(HttpStatusCode.OK, result));
             }
             else
             {
                 string message = "Error in getting Data";
                 return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, message));
             }
         }
         else
         {
             return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
         }
     }
     catch (Exception ex)
     {
         return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.InnerException.Message));
     }
 }
        public async Task <HttpResponseMessage> Get(int accountNumber, decimal amount, string currency)
        {
            BankAccountModel result = await Task.FromResult(modelFactory.Create(sqlComm.GetAccount(accountNumber)));

            if (result == null)
            {
                return(await Task.FromResult(Request.CreateResponse(HttpStatusCode.NotFound)));
            }

            if (amount < 0)
            {
                return(await Task.FromResult(Request.CreateResponse(HttpStatusCode.Forbidden, modelFactory.CreateResponse(result, false, message: "Invalid Amount!"))));
            }

            if (!result.Currency.Equals(currency, StringComparison.OrdinalIgnoreCase))
            {
                return(await Task.FromResult(Request.CreateResponse(HttpStatusCode.Conflict, modelFactory.CreateResponse(result, false, message: "Currency Mismatch"))));
            }

            var bankAccount = await Task.FromResult(sqlComm.Withdraw(result, amount, currency));

            if (bankAccount == null)
            {
                return(await Task.FromResult(Request.CreateResponse(HttpStatusCode.Forbidden, modelFactory.CreateResponse(result, false, message: "Your account balance is insufficient to fulfill this request."))));
            }

            result = await Task.FromResult(modelFactory.Create(bankAccount));

            return(await Task.FromResult(Request.CreateResponse(HttpStatusCode.OK, modelFactory.CreateResponse(result, message: "Withdrawal Complete!"))));
        }
        public async Task UpdateBankAccountForCurrentUser_StartBalanceChanged_UpdatesCurrentBalance()
        {
            // Arrange
            var bankAccountModel = new BankAccountModel
            {
                Id           = 1,
                AccountType  = BankAccountType.Checking,
                Disabled     = true,
                Name         = "BankAccountName",
                StartBalance = 100
            };

            var bankAccountEntity = new BankAccountEntity
            {
                Name         = bankAccountModel.Name,
                UserId       = _defaultUserId,
                StartBalance = 200
            };

            InsertEntity(bankAccountEntity);

            _mocker.GetMock <IBankAccountCalculationService>().Setup(x =>
                                                                     x.CalculateCurrentBalanceForBankAccount(
                                                                         It.IsAny <IUnitOfWork>(),
                                                                         It.Is <BankAccountEntity>(x => x.Id == bankAccountEntity.Id))).ReturnsAsync(bankAccountModel.StartBalance).Verifiable();

            var bankAccountService = _mocker.CreateInstance <BankAccountService>();

            // Act
            await bankAccountService.UpdateBankAccountForCurrentUser(bankAccountModel);

            // Assert
            _mocker.GetMock <IBankAccountCalculationService>().VerifyAll();
            _mocker.GetMock <IBankAccountCalculationService>().VerifyNoOtherCalls();
        }
        public async Task UpdateBankAccountForCurrentUser_UserDoesNotOwnAccount_ThrowsException()
        {
            // Arrange
            var existingEntity = new BankAccountEntity
            {
                AccountType    = BankAccountType.Checking,
                Disabled       = false,
                CurrentBalance = 100,
                StartBalance   = 100,
                Name           = "BankAccountName",
                UserId         = _defaultUserId + 1
            };

            InsertEntity(existingEntity);

            var bankAccountModel = new BankAccountModel
            {
                Id          = existingEntity.Id,
                AccountType = BankAccountType.Checking,
                Name        = "OtherName"
            };

            var bankAccountService = _mocker.CreateInstance <BankAccountService>();

            // Act
            var result = FluentActions.Awaiting(async() => await bankAccountService.UpdateBankAccountForCurrentUser(bankAccountModel));

            // Arrange
            await result.Should().ThrowAsync <NotFoundException>();
        }
        public async Task CreateBankAccountForCurrentUser_NewAccount_CreatesBankAccount()
        {
            // Arrange
            var bankAccountModel = new BankAccountModel
            {
                AccountType  = BankAccountType.Checking,
                Disabled     = true,
                Name         = "BankAccountName",
                StartBalance = 1000
            };

            var bankAccountService = _mocker.CreateInstance <BankAccountService>();

            // Act
            var result = await bankAccountService.CreateBankAccountForCurrentUser(bankAccountModel);

            // Assert
            result.Should().NotBeNull();
            result.Should().Match <BankAccountModel>(x =>
                                                     x.AccountType == bankAccountModel.AccountType &&
                                                     x.CurrentBalance == bankAccountModel.StartBalance &&
                                                     x.Disabled == bankAccountModel.Disabled &&
                                                     x.Name == bankAccountModel.Name &&
                                                     x.StartBalance == bankAccountModel.StartBalance);
        }
Example #7
0
 public HttpResponseMessage DeleteBankAccount(BankAccountModel aBankAccountModel)
 {
     try
     {
         if (this.ModelState.IsValid)
         {
             var result = service.DeleteBankAccount(aBankAccountModel);
             if (result != null)
             {
                 return(Request.CreateResponse(HttpStatusCode.OK, result));
             }
             else
             {
                 string message = "Not deleted successfully";
                 return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, message));
             }
         }
         else
         {
             return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
         }
     }
     catch (Exception ex)
     {
         return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
     }
 }
Example #8
0
        public async Task <BankAccountModel> UpdateBankAccountForCurrentUser(BankAccountModel model)
        {
            using var unitOfWork = _unitOfWork();

            var bankAccountEntity = await unitOfWork.BankAccountRepository.FindSingleTracked(x => x.Id == model.Id);

            if (bankAccountEntity == null)
            {
                throw new NotFoundException(nameof(BankAccountEntity));
            }

            var recalculateCurrentBalance = bankAccountEntity.StartBalance != model.StartBalance;

            bankAccountEntity.UpdateFromModel(model);

            if (recalculateCurrentBalance)
            {
                bankAccountEntity.CurrentBalance = await _bankAccountCalculationService.CalculateCurrentBalanceForBankAccount(unitOfWork, bankAccountEntity);
            }

            unitOfWork.BankAccountRepository.Update(bankAccountEntity);
            await unitOfWork.SaveAsync();

            return(bankAccountEntity.ToDto());
        }
        public async Task <ActionResult <BankAccountModel> > Post(int customerId, BankAccountModel model)
        {
            try
            {
                //Make sure BankAccountId is not already taken
                var existing = await _repository.GetBankAccountAsync(customerId, model.Id);

                if (existing != null)
                {
                    return(BadRequest("BankAccount Id in Use"));
                }

                //map
                var BankAccount = _mapper.Map <BankAccount>(model);

                //save and return
                if (!await _repository.StoreNewBankAccountAsync(customerId, BankAccount))
                {
                    return(BadRequest("Bad request, could not create record!"));
                }
                else
                {
                    var location = _linkGenerator.GetPathByAction("Get",
                                                                  "BankAccount",
                                                                  new { BankAccount.CustomerId, BankAccount.Id });

                    return(Created(location, _mapper.Map <BankAccountModel>(BankAccount)));
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                return(this.StatusCode(StatusCodes.Status500InternalServerError, "Request Failure"));
            }
        }
Example #10
0
        public async Task <BankAccountModel> UpdateBankAccountForCurrentUser(BankAccountModel model)
        {
            var userId = await _authenticationService.GetCurrentUserId();

            using var unitOfWork = _unitOfWork();

            var bankAccount = await unitOfWork.BankAccountRepository.FindSingleTracked(x => x.UserId == userId && x.Id == model.Id);

            if (bankAccount != null)
            {
                var recalculateCurrentBalance = bankAccount.StartBalance != model.StartBalance;

                bankAccount.UpdateFromModel(model);
                unitOfWork.BankAccountRepository.Update(bankAccount);

                if (recalculateCurrentBalance)
                {
                    bankAccount.CurrentBalance = await TransactionHandler.CalculateCurrentBalanceForBankAccount(unitOfWork, bankAccount);
                }
                await unitOfWork.SaveAsync();

                return(bankAccount.ToDto());
            }
            else
            {
                throw new NotFoundException(nameof(BankAccountEntity));
            }
        }
Example #11
0
        public ActionResult Edit(int id)
        {
            ViewBag.ActiveMenu = "transaction";
            var model = new BankAccountModel().GetBankDetails(id);

            return(View("..\\BankAccount\\Edit", model));
        }
Example #12
0
 /// <summary>
 /// Updates bank account info in database.
 /// </summary>
 /// <param name="account"></param>
 /// <returns></returns>
 public bool UpdateBankAccount(BankAccountModel account)
 {
     using (SqlConnection connection = new SqlConnection(CONNECTION_STRING))
     {
         try
         {
             connection.Open();
         }
         catch (SqlException e)
         {
             Debug.WriteLine(e.Message);
             return(false);
         }
         string     sqlQuery = @"UPDATE BankAccounts 
                             SET AccountName = @accountName, AuthOverdraftLimit = @limit
                             WHERE AccountID = @id;";
         SqlCommand command  = new SqlCommand(sqlQuery, connection);
         command.Parameters.Add("@accountName", SqlDbType.NVarChar).Value = account.AccountName;
         command.Parameters.Add("@limit", SqlDbType.Decimal).Value        = account.AuthOverdraftLimit;
         command.Parameters.Add("@id", SqlDbType.Int).Value = account.AccountID;
         try
         {
             command.ExecuteNonQuery();
             return(true);
         }
         catch (SqlException e)
         {
             Debug.WriteLine(e.Message);
             return(false);
         }
     }
 }
        public IActionResult AddBankAccount([FromBody] BankAccountModel bankAccountViewModel)
        {
            bankAccountViewModel.UserIdentityId = this.GetUserId();
            int paymentId = this.bankAccountService.Add(bankAccountViewModel);

            return(Ok(paymentId));
        }
Example #14
0
        // ----------------------------------------------- [ UPDATE ]
        public void Update(int ID, BankAccountModel account)
        {
            // FIND BASED UPON ID
            var a = accountList.Where(x => x.ID == ID).FirstOrDefault();

            a = account;
        }
Example #15
0
        public static List <BankAccountViewModel> GetAccounts()
        {
            //na WCF
            List <BankAccountViewModel> accounts = new List <BankAccountViewModel>();

            List <string> statusList = new List <string>();

            statusList.Add("Aktivan");
            statusList.Add("Neaktivan");
            statusList.Add("Nepoznat");

            for (int i = 0; i < 15; i++)
            {
                BankAccountModel account = new BankAccountModel {
                    Id = i, Code = "000" + i.ToString(), IBAN = "RBZSGSGS" + i.ToString(), Name = "AccountName" + i.ToString(), Status = "Neaktivan"
                };

                BankAccountViewModel model = new BankAccountViewModel {
                    Account = account, StatusList = statusList
                };

                accounts.Add(model);
            }
            return(accounts);
        }
Example #16
0
        /// <summary>
        /// Constructor
        /// </summary>
        public DepotView()
        {
            InitializeComponent();
            depotModel = new DepotModel();
            bankModel  = new BankAccountModel();

            refreshDepotDataAsync();
            updateStockPricesInListViewAsync();

            cbxDataProvider.Items.Add(FinanceAPI.FinanceStrategies.Google);
            cbxDataProvider.Items.Add(FinanceAPI.FinanceStrategies.Yahoo);
            cbxDataProvider.SelectedItem = webFinanceStrategy;

            lvwColumnSorter            = new ListViewColumnSorter();
            lvDepot.ListViewItemSorter = lvwColumnSorter;

            lvDepot.Columns.Add("Buchwert");
            lvDepot.Columns.Add("Marktkapitalisierung");
            lvDepot.Columns.Add("50 Tage");
            lvDepot.Columns.Add("250 Tage");

            setDefaultCurrencyInLabel();
            mainForm.setHeadline("Depot");
            toggleToolbar(true);

            dpEnddate.Value     = endDate;
            dpStartdate.MaxDate = DateTime.Now;
            dpStartdate.Value   = startDate;

            dpEnddate.ValueChanged   += new EventHandler(datetime_Changed);
            dpStartdate.ValueChanged += new EventHandler(datetime_Changed);
        }
Example #17
0
        public ActionResult <BankAccountModel> Post(BankAccountModel accountIn)
        {
            var newAccount = _bankAccountService.CreateAccount(accountIn.ToDomain());

            return(BankAccountModel.FromDomain(newAccount));
            //return CreatedAtRoute("BankAccounts", new { id = accountIn.Id.ToString() }, accountIn);
        }
        public void Should_Return_Success_When_Valid_Bank_Model()
        {
            var client = new ClientModel();

            client.Name     = "Marlon";
            client.LastName = "Graciano Machado de Amorim";
            client.Type     = (KindPerson)1;

            var address = new AddressModel();

            address.City         = "Rio de Janeiro";
            address.Country      = "Brasil";
            address.Neighborhood = "Campo Grande";
            address.Number       = 55;
            address.Street       = "Rua Argoin";

            var bankAccount = new BankAccountModel();

            bankAccount.AccountNumber = 12345;
            bankAccount.AgencyNumber  = 1234;
            bankAccount.Type          = (BankAccountType)1;
            bankAccount.Owner         = client;
            bankAccount.Address       = address;

            var context = new ValidationContext(bankAccount, null, null);
            var results = new List <ValidationResult>();

            TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(BankAccountModel), typeof(BankAccountModel)), typeof(BankAccountModel));

            var isModelStateValid = Validator.TryValidateObject(bankAccount, context, results, true);

            Assert.IsTrue(isModelStateValid);
        }
Example #19
0
        public static BankAccountModel GetBankAccount(long bankAccountId)
        {
            BankAccountModel bankAccount = new BankAccountModel(bankAccountService
                                                                .GetSingle(bankAccountId.ToString(), AuthenticationHelper.CompanyId.Value));

            return(bankAccount);
        }
Example #20
0
        public BankAccountModel GetAccountModel(int pageNumber, int?accountId, int webToPayPageNumber, int pageSize)
        {
            using (var session = usersSessionFactory.CreateContext())
            {
                var accounts = (from a in session.BankAccounts
                                select new BankAccountModel.AccountModel()
                {
                    Id = a.Id,
                    AccountNo = a.AccountNo,
                    Balance = (double)a.Balance
                }).ToList();

                accounts.ForEach(
                    x =>
                {
                    x.Items = session.BankAccountItems.Where(q => q.BankAccountId == x.Id)
                              .OrderByDescending(q => q.Date)
                              .Select(i =>
                                      new BankAccountItemModel()
                    {
                        Id             = i.Id,
                        Date           = i.Date,
                        ExpenseDecimal = i.Expense,
                        IncomeDecimal  = i.Income,
                        Operation      = i.Operation,
                        UserFullName   = i.User.FirstName + " " + i.User.LastName,
                        UserObjectId   = i.User.ObjectId,
                        OrganizationId = i.OrganizationId
                    }).ToPagedList(x.Id == accountId ? pageNumber : 1, pageSize);

                    x.Currency = x.AccountNo.Substring(x.AccountNo.IndexOf('(') + 1, x.AccountNo.IndexOf(')') - x.AccountNo.IndexOf('(') - 1);
                    x.Items.ForEach(
                        m =>
                        m.OrganizationName = organizationService.GetOrganizationName(m.OrganizationId)
                        );
                });

                var model = new BankAccountModel()
                {
                    Accounts = accounts
                };

                model.WebToPayItems = (from i in session.WebToPayLogs
                                       where i.Status == 1
                                       orderby i.Date descending
                                       select new BankAccountItemModel()
                {
                    Id = i.Id,
                    Date = i.Date,
                    ExpenseDecimal = null,
                    IncomeDecimal = i.Amount / 100,
                    Operation = i.Firstname + " " + i.LastName + " " + i.PayText,
                    UserFullName = i.User.FirstName + " " + i.User.LastName,
                    UserObjectId = i.User.ObjectId
                }).ToPagedList(webToPayPageNumber, pageSize);

                return(model);
            }
        }
 private void saveBankAccount(BankAccountModel account)
 {
     MySQL.execute("UPDATE bank_accounts SET Balance = @bal WHERE AccountID = @id", new Dictionary <string, dynamic>
     {
         ["@bal"] = account.Balance,
         ["@id"]  = account.AccountID
     });
 }
Example #22
0
        /// <summary>
        /// 删
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JsonRsp Remove(BankAccountModel model)
        {
            int returnvalue = EntityQuery <BankAccountModel> .Instance.Delete(model);

            return(new JsonRsp {
                success = returnvalue > 0, code = returnvalue
            });
        }
Example #23
0
        /// <summary>
        /// 改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JsonRsp Update(BankAccountModel model)
        {
            int returnvalue = Update <BankAccountModel>(model);

            return(new JsonRsp {
                success = returnvalue > 0, code = returnvalue
            });
        }
Example #24
0
        /// <summary>
        /// 增
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JsonRsp Add(BankAccountModel model)
        {
            int returnvalue = Add <BankAccountModel>(model);

            return(new JsonRsp {
                success = returnvalue > 0, code = returnvalue
            });
        }
Example #25
0
 /// <summary>
 /// 查 根据Id获取详情,如果没有则返回空对象
 /// </summary>
 /// <param name="customerID"></param>
 /// <returns></returns>
 public BankAccountModel GetModelById(int accountId)
 {
     BankAccountModel model = new BankAccountModel() { ID = accountId };
     if (EntityQuery<BankAccountModel>.Fill(model))
         return model;
     else
         return null;
 }
Example #26
0
        public ActionResult DeleteConfirmed(int id)
        {
            BankAccountModel bankaccountmodel = db.Accounts.Find(id);

            db.Accounts.Remove(bankaccountmodel);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Example #27
0
        public AddBankAccounts(int _bankAccountTypeId)
        {
            InitializeComponent();

            this._repo            = new Repo();
            this.bankAccountModel = this.DataContext as BankAccountModel;
            this.bankAccountModel.BankAccountTypeId = _bankAccountTypeId;
        }
Example #28
0
        public Guid Create(Guid companyId, [FromBody] BankAccountModel model)
        {
            model.Id = Guid.NewGuid();
            var bankAccount = _factory.Create(model.Id, companyId);

            bankAccount.CopyModelFields(model);
            _bankAccountRepository.Save(bankAccount);
            return(bankAccount.Id);
        }
 private async Task SetBankAccount(UserModel user)
 {
     BankAccountModel details = new BankAccountModel()
     {
         Balance     = 0.0M,
         CustomerRef = user.Id
     };
     await API.SetBankAccount(details);
 }
        public async Task UpdateAccount(BankAccountModel acc)
        {
            using HttpResponseMessage response = await ApiClient.PutAsJsonAsync($"api/BankAccounts/{acc.Id}", acc);

            if (!response.IsSuccessStatusCode)
            {
                MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
            }
        }
        protected Boolean SubmitForm()
        {
            StringBuilder formattedHtml = new StringBuilder();
            StringBuilder formattedInternalHtml = new StringBuilder();
            string seasonalMonths = "";

            try
            {
                foreach (ListItem item in cblSeasonal.Items)
                {
                    if (item.Selected)
                    {
                        seasonalMonths += item.Value + " - ";
                    }
                }

                if (seasonalMonths.Length > 3)
                {
                    seasonalMonths = seasonalMonths.Substring(0, seasonalMonths.Length - 3);
                }
            }
            catch (System.Exception ex)
            {
                _newLogic.WriteExceptionToDB(ex, "AdminSubmitForm - Get Seasonal Months");
            }

            try
            {
                //Instanciate new model objects for each piece of data to be created
                MerchantModel newMerchant = new MerchantModel();
                MerchantPrincipalModel newMerchantPrincipal = new MerchantPrincipalModel();
                ContactModel newMerchantPrincipalContact = new ContactModel();
                AddressModel newMerchantPrincipalContactAddress = new AddressModel();
                ContactModel newContact = new ContactModel();
                ContactModel newBusiness = new ContactModel();
                AddressModel newBusinessAddress = new AddressModel();
                ProcessorModel newProcessor = new ProcessorModel();
                DebitCardModel newDebitCard = new DebitCardModel();
                BankModel newBankModel = new BankModel();
                BankAccountModel newBankAccountModel = new BankAccountModel();

                //Set base merchant information in newMerchant object
                if (txtMerchantId.Text != "") { newMerchant.MerchantId = txtMerchantId.Text; }
                if (txtCorpName.Text != "") { newMerchant.CorpName = txtCorpName.Text; }
                if (txtDBAName.Text != "") { newMerchant.DbaName = txtDBAName.Text; }
                if (txtBusLicNumber.Text != "") { newMerchant.BusLicNumber = txtBusLicNumber.Text; }
                if (txtBusLicType.Text != "") { newMerchant.BusLicType = txtBusLicType.Text; }
                if (txtBusLicIssuer.Text != "") { newMerchant.BusLicIssuer = txtBusLicIssuer.Text; }
                if (radBusLicDate.SelectedDate.HasValue) { newMerchant.BusLicDate = Convert.ToDateTime(radBusLicDate.SelectedDate); }
                if (txtFedTaxId.Text != "") { newMerchant.FedTaxId = txtFedTaxId.Text; }
                if (txtMerchandiseSold.Text != "") { newMerchant.MerchandiseSold = txtMerchandiseSold.Text; }
                if (txtYearsInBus.Text != "") { newMerchant.YearsInBusiness = Convert.ToInt32(txtYearsInBus.Text); }
                if (txtMonthsInBus.Text != "") { newMerchant.MonthsInBusiness = Convert.ToInt32(txtMonthsInBus.Text); }
                if (rblSeasonal.SelectedValue != "") { newMerchant.SeasonalSales = Convert.ToBoolean(rblSeasonal.SelectedValue); }
                if (seasonalMonths != "") { newMerchant.SeasonalMonths = seasonalMonths; }
                if (txtSwipedPct.Text != "") { newMerchant.SwipedPct = Convert.ToInt32(txtSwipedPct.Text); }
                if (txtAvgMonthlySales.Text != "") { newMerchant.AvgMonthlySales = Convert.ToDecimal(txtAvgMonthlySales.Text); }
                if (txtHighestMonthlySales.Text != "") { newMerchant.HighestMonthlySales = Convert.ToDecimal(txtHighestMonthlySales.Text); }
                if (txtAvgWeeklySales.Text != "") { newMerchant.AvgWeeklySales = Convert.ToDecimal(txtAvgWeeklySales.Text); }
                if (rblHighRisk.SelectedValue != "") { newMerchant.HighRisk = Convert.ToBoolean(rblHighRisk.SelectedValue); }
                if (txtHighRiskWho.Text != "") { newMerchant.HighRiskWho = txtHighRiskWho.Text; }
                if (radHighRiskDate.SelectedDate.HasValue) { newMerchant.HighRiskDate = Convert.ToDateTime(radHighRiskDate.SelectedDate); }
                if (rblBankruptcy.SelectedValue != "") { newMerchant.Bankruptcy = Convert.ToBoolean(rblBankruptcy.SelectedValue); }
                if (radBankruptcyDate.SelectedDate.HasValue) { newMerchant.BankruptcyDate = Convert.ToDateTime(radBankruptcyDate.SelectedDate); }

                //Add Legal Org State to merchant
                if (ddlLegalOrgState.SelectedValue != "")
                {
                    Int32 legalOrgStateId = Convert.ToInt32(ddlLegalOrgState.SelectedValue);
                    newMerchant.LegalOrgState = _globalCtx.GeoStates.Where(gs => gs.RecordId == legalOrgStateId).FirstOrDefault();
                }

                //Add Legal Org Type to merchant
                if (ddlLegalOrgType.SelectedValue != "")
                {
                    Int32 legalOrgTypeId = Convert.ToInt32(ddlLegalOrgType.SelectedValue);
                    newMerchant.LegalOrgType = _globalCtx.LegalOrgTypes.Where(lot => lot.RecordId == legalOrgTypeId).FirstOrDefault();
                }

                //Add Merchant Type to Merchant
                if (rblMerchantType.SelectedValue != "") { newMerchant.MerchantType = _globalCtx.MerchantTypes.Where(mt => mt.MerchantTypeName == rblMerchantType.SelectedValue).FirstOrDefault(); }

                //Add MCC to merchant
                if (ddlMCC.SelectedValue != "")
                {
                    Int32 mccId = Convert.ToInt32(ddlMCC.SelectedValue);
                    newMerchant.Mcc = _globalCtx.MerchantCategoryCodes.Where(mcc => mcc.RecordId == mccId).FirstOrDefault();
                }

                //Add Business Contact info - Email, Phone, Fax
                if (txtBusEmail.Text != "") { newBusiness.Email = txtBusEmail.Text; }
                if (txtBusFax.Text != "") { newBusiness.Fax = txtBusFax.Text; }
                if (txtBusPhone.Text != "") { newBusiness.HomePhone = txtBusPhone.Text; }

                _globalCtx.Contacts.Add(newBusiness);

                //Add Business Contact Addess
                if (txtCorpAddress.Text != "") { newBusinessAddress.Address = txtCorpAddress.Text; }
                if (txtCorpCity.Text != "") { newBusinessAddress.City = txtCorpCity.Text; }
                if (ddlCorpState.SelectedValue != "")
                {
                    Int32 businessAddressStateId = Convert.ToInt32(ddlCorpState.SelectedValue);
                    newBusinessAddress.State = _globalCtx.GeoStates.Where(gs => gs.RecordId == businessAddressStateId).FirstOrDefault();
                }
                if (txtCorpZip.Text != "") { newBusinessAddress.Zip = txtCorpZip.Text; }

                _globalCtx.Addresses.Add(newBusinessAddress);

                //Add new Business Contact Address to new Business
                newBusiness.Address = newBusinessAddress;

                //Add new Contact to new Merchant
                newMerchant.Business = newBusiness;

                //Add new Contact
                if (txtContactFirstName.Text != "") { newContact.FirstName = txtContactFirstName.Text; }
                if (txtContactLastName.Text != "") { newContact.LastName = txtContactLastName.Text; }
                if (txtContactEmail.Text != "") { newContact.Email = txtContactEmail.Text; }
                if (txtContactPhone.Text != "") { newContact.HomePhone = txtContactPhone.Text; }
                if (txtContactFax.Text != "") { newContact.Fax = txtContactFax.Text; }

                _globalCtx.Contacts.Add(newContact);

                //Add new contact to new Merchant
                newMerchant.Contact = newContact;

                //Add new Merchant Principal
                if (txtPrincipalDLNumber.Text != "") { newMerchantPrincipal.PrincipalDLNumber = PWDTK.StringToUtf8Bytes(txtPrincipalDLNumber.Text); }
                if (ddlPrincipalDLState.SelectedValue != "")
                {
                    Int32 dlStateId = Convert.ToInt32(ddlPrincipalDLState.SelectedValue);
                    newMerchantPrincipal.PrincipalDLState = _globalCtx.GeoStates.Where(gs => gs.RecordId == dlStateId).FirstOrDefault();
                }
                if (radPrincipalDoB.SelectedDate.HasValue) { newMerchantPrincipal.PrincipalDoB = Convert.ToDateTime(radPrincipalDoB.SelectedDate); }
                if (txtPrincipalPctOwn.Text != "") { newMerchantPrincipal.PrincipalPctOwn = Convert.ToInt32(txtPrincipalPctOwn.Text); }

                _globalCtx.MerchantPrincipal.Add(newMerchantPrincipal);

                //Create new contact for Merchant Principal
                if (txtPrincipalFirstName.Text != "") { newMerchantPrincipalContact.FirstName = txtPrincipalFirstName.Text; }
                if (txtPrincipalLastName.Text != "") { newMerchantPrincipalContact.LastName = txtPrincipalLastName.Text; }
                if (txtPrincipalMI.Text != "") { newMerchantPrincipalContact.MiddleInitial = txtPrincipalMI.Text; }
                if (txtPrincipalTitle.Text != "") { newMerchantPrincipalContact.Title = txtPrincipalTitle.Text; }
                if (txtPrincipalCellPhone.Text != "") { newMerchantPrincipalContact.CellPhone = txtPrincipalCellPhone.Text; }
                if (txtPrincipalHomePhone.Text != "") { newMerchantPrincipalContact.HomePhone = txtPrincipalHomePhone.Text; }

                _globalCtx.Contacts.Add(newMerchantPrincipalContact);

                //Create new address for Merchant principal Contact
                if (txtPrincipalAddress.Text != "") { newMerchantPrincipalContactAddress.Address = txtPrincipalAddress.Text; }
                if (txtPrincipalCity.Text != "") { newMerchantPrincipalContactAddress.City = txtPrincipalCity.Text; }
                if (ddlPrincipalState.SelectedValue != "")
                {
                    Int32 mpcStateId = Convert.ToInt32(ddlPrincipalState.SelectedValue);
                    newMerchantPrincipalContactAddress.State = _globalCtx.GeoStates.Where(gs => gs.RecordId == mpcStateId).FirstOrDefault();
                }
                if (txtPrincipalZip.Text != "") { newMerchantPrincipalContactAddress.Zip = txtPrincipalZip.Text; }

                _globalCtx.Addresses.Add(newMerchantPrincipalContactAddress);

                //Add new address to Merchant Principal Contact
                newMerchantPrincipalContact.Address = newMerchantPrincipalContactAddress;

                //Add new Contact to Merchant Principal
                newMerchantPrincipal.Contact = newMerchantPrincipalContact;

                //Add new Principal to the new merchant
                newMerchant.MerchantPrincipal = newMerchantPrincipal;

                //Check if merchant processor already exists, if so link to merchant.  If not, create it and add to merchant.
                if (txtCardProcessor.Text != "")
                {
                    if (_globalCtx.Processor.Where(p => p.ProcessorName == txtCardProcessor.Text.Trim()).ToList().Count > 0)
                    {
                        newMerchant.Processor = _globalCtx.Processor.First(p => p.ProcessorName == txtCardProcessor.Text.Trim());
                    }
                    else
                    {
                        newProcessor.ProcessorName = txtCardProcessor.Text.Trim();
                        _globalCtx.Processor.Add(newProcessor);
                        newMerchant.Processor = newProcessor;
                    }
                }

                _globalCtx.Banks.Add(newBankModel);

                newBankAccountModel.Bank = newBankModel;
                newDebitCard.Bank = newBankModel;

                _globalCtx.BankAccounts.Add(newBankAccountModel);
                _globalCtx.DebitCards.Add(newDebitCard);

                newMerchant.BankAccount = newBankAccountModel;
                newMerchant.DebitCard = newDebitCard;

                //Set Merchant Status to "Admin Registered"
                newMerchant.MerchantStatus = _globalCtx.MerchantStatuses.FirstOrDefault(ms => ms.StatusDescription == "Pre-Enrolled");

                //Set Underwriting Status to "Pending"
                newMerchant.UnderwritingStatus = _globalCtx.UnderwritingStatuses.FirstOrDefault(ms => ms.StatusDescription == "Pending");

                newMerchant.AdvancePlan = _globalCtx.AdvancePlans.First(ap => ap.DefaultPlan == true);

                //Add new Merchant to context
                _globalCtx.Merchants.Add(newMerchant);

                //Add new merchant to selected User
                if (txtSelectedUserName.Text != "")
                {
                    var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_globalCtx));
                    ApplicationUser selectedUser = manager.FindByName(txtSelectedUserName.Text);
                    if (selectedUser != null)
                    {
                        selectedUser.Merchant = newMerchant;

                        //Save Context and Update DB
                        _globalCtx.SaveChanges();
                    }
                }
                else
                {
                    lblSubmissionMessage.Text = "Please select a User to join with this merchant.";
                    return false;
                }
            }
            catch (System.Exception ex)
            {
                _newLogic.WriteExceptionToDB(ex, "AdminSubmitForm - Add Data to DB");
                return false;
            }

            return true;
        }