public ActionResult OpenAccount(OpenAccountViewModel viewModel) { if (ModelState.IsValid) { using (CryptoWalletDbContext ctx = new CryptoWalletDbContext()) { User currentUser = ctx.Users.AsNoTracking().FirstOrDefault(u => u.Email == User.Identity.Name); List <UserBankAccount> currentUserAccounts = ctx.UserBankAccounts.Where(b => b.UserId == currentUser.UserId).ToList(); UserBankAccount bankAccount = currentUserAccounts.FirstOrDefault(x => x.Currency == viewModel.NewCurrency); if (bankAccount != null) { ModelState.AddModelError("", "You have already an account in this currency."); SetupOpenAccount(viewModel); return(View(viewModel)); } bankAccount = new UserBankAccount { Currency = viewModel.NewCurrency, UserId = currentUser.UserId }; // bankAccount.User = currentUser; ----- imi aduce userid gresit bankAccount.UserId = currentUser.UserId; ctx.UserBankAccounts.Add(bankAccount); ctx.SaveChanges(); return(RedirectToAction("Index")); } } else { SetupOpenAccount(viewModel); return(View(viewModel)); } }
public UserBankAccount UseNewUserBankAccount( Guid dataBaseName, Guid userId, Guid bankAccountId, bool isOwner = false, bool isReadOnly = false) { var userBankAccount = new UserBankAccount() { CreationDate = DateTime.Now, Id = Guid.NewGuid(), ModificationDate = DateTime.Now, BankAccountId = bankAccountId, IsOwner = isOwner, IsReadOnly = isReadOnly, UserId = userId }; var dbContextOptions = new DbContextOptionsBuilder <DaGetContext>() .UseInMemoryDatabase(databaseName: dataBaseName.ToString()) .Options; using (var context = new DaGetContext(dbContextOptions)) { context.UserBankAccounts.Add(userBankAccount); context.Commit(); } return(userBankAccount); }
public decimal CalculateProfit() { decimal totalProfit = 0; ExchangeService exchangeService = new ExchangeService(); CurrencyRate changeRate = new CurrencyRate(); using (CryptowalletDbContext ctx = new CryptowalletDbContext()) { List <CurrencyRate> rates = exchangeService.GetConversionRate(Currency.EUR, new Currency[] { Currency.EUR, Currency.ETH, Currency.LTC, Currency.BTC, Currency.EOS }); User currentUser = ctx.Users.AsNoTracking().FirstOrDefault(u => u.Email == User.Identity.Name); IQueryable <UserBankAccount> userBankAccounts = from u in ctx.UserBankAccounts where u.UserId == currentUser.UserId && u.Currency == Currency.EUR.ToString() select u; UserBankAccount eurAccount = userBankAccounts.FirstOrDefault(); try { List <UserTransaction> userTransactions = eurAccount.FromTransaction.Where(a => a.FromAccountId != a.ToAccountId && a.ToAccount.UserId == currentUser.UserId).ToList(); foreach (var tr in userTransactions) { changeRate = rates.FirstOrDefault(a => a.Currency.ToString() == tr.ToAccount.Currency); totalProfit += tr.Amount * tr.CurrencyRate - tr.Amount * changeRate.Rate; } } catch { totalProfit = 0; } } return(totalProfit); }
public void CreateBankAccount(UserIdentifier userId, long minimumCash) { UserBankAccount account = new UserBankAccount(userId, minimumCash); _users.Add(userId.GetID(), account); _usersRegistered.Add(account); }
public ActionResult BindBankCard(string bank, string accountNum) { var bankAccount = CurrentUser.BankAccount; //ur.GetBankAccount(CurrentUser.Id); if (string.IsNullOrEmpty(bank) || string.IsNullOrEmpty(accountNum)) { ModelState.AddModelError("bank", "请输入银行和卡号"); return(View(bankAccount)); } if (bankAccount == null) { bankAccount = new UserBankAccount(); bankAccount.UserId = CurrentUser.Id; bankAccount.CreateTime = DateTime.Now; } bankAccount.Bank = bank; bankAccount.AccountNum = accountNum; bankAccount.AccountName = CurrentUser.DisplayName; ur.SaveBankAccount(bankAccount); RefreshCurrentUser(); return(RedirectToAction("BindBankCard")); }
public ActionResult DeleteConfirmed(int id) { UserBankAccount userBankAccount = db.UserBankAccounts.Find(id); db.UserBankAccounts.Remove(userBankAccount); db.SaveChanges(); return(RedirectToAction("Index")); }
public void Delete(Guid?userId, int id) { try { if (userId == null) { throw new DaGetServiceException("Impossible de supprimer le compte, utilisateur non défini"); } using (var context = Factory.CreateContext(ConnexionString)) { // on vérifie les droits var baRepo = Factory.GetBankAccountRepository(context); var bankAccount = ExtractBankAccount(userId, id, context); var ubaRepo = Factory.GetUserBankAccountRepository(context); UserBankAccount userbankAccount = ubaRepo.GetByUserPublicIdAndBankAccountId(userId.Value, id); if (userbankAccount == null) { throw new DaGetServiceException("Impossible de supprimer le compte, compte non existant ou n'appartenant pas à l'utilisateur"); } var baoRepo = Factory.GetBankAccountOperationTypeRepository(context); foreach (var bao in baoRepo.GetAllByBankAccountId(id)) { baoRepo.Delete(bao); } var oRepo = Factory.GetOperationRepository(context); foreach (var o in oRepo.GetAllByBankAccountId(id)) { oRepo.Delete(o); } var roRepo = Factory.GetReccurentOperationRepository(context); foreach (var ro in roRepo.GetAllByBankAccountId(id)) { roRepo.Delete(ro); } ubaRepo.Delete(userbankAccount); baRepo.Delete(bankAccount); context.Commit(); } } catch (DaGetServiceException) { throw; } catch (Exception ex) { throw new DaGetServiceException( String.Format("Erreur lors de suppression du compte pour l'utilisateur {0}", userId), ex); } }
public bool Use(UserIdentifier user, long cashToUser) { UserBankAccount account = GetAccountOf(user); if (account == null) { return(false); } return(account.Use(cashToUser)); }
internal void Add(UserIdentifier user, long cashToUser) { UserBankAccount account = GetAccountOf(user); if (account == null) { return; } account.Add(cashToUser); }
public ActionResult UpdateBankAccount([Bind(Prefix = "ManageBankAccountVM")] ManageBankAccountViewModels model) { try { //Check if bank combination already existed /* This project will not use this method because multiple account could possibly have same bank account (same owner) */ //var isValidBankRecord = _userService.IsNotInUsedBankAccount(model.BankId, model.BankAccountNo); //if (!isValidBankRecord) //{ // return Json(new { result = "This bank account has already registered on another account.", alertClass = "warning" }, JsonRequestBehavior.AllowGet); //} var curUser = _userService.GetUserBy(User.Identity.GetUserId <int>()); //No Bank Account if (curUser.UserBankAccount.Count < 1) { UserBankAccount uba = new UserBankAccount { UBAId = Guid.NewGuid(), IsPrimary = true, CreatedTimestamp = DateTime.UtcNow, BankId = model.BankId, BankAccountHolder = model.BankAccountHolder, BankAccountNo = model.BankAccountNo, BankBranch = model.BankBranch, }; curUser.UserBankAccount.Add(uba); _userService.UpdateUser(curUser); } else { curUser.UserBankAccount.FirstOrDefault().BankId = model.BankId; curUser.UserBankAccount.FirstOrDefault().BankAccountHolder = model.BankAccountHolder; curUser.UserBankAccount.FirstOrDefault().BankAccountNo = model.BankAccountNo; curUser.UserBankAccount.FirstOrDefault().BankBranch = model.BankBranch; _userService.UpdateUser(curUser); } var saveSuccess = _userService.SaveChanges(User.Identity.GetUserId <int>()); if (saveSuccess) { return(Json(new { result = "Your bank account has been updated.", alertClass = "success" }, JsonRequestBehavior.AllowGet)); } }catch (Exception ex) { Log.Error(ex.Message, ex); } return(Json(new { result = "Failed to update your bank account. Please contact our customer support if problem still persist.", alertClass = "danger" }, JsonRequestBehavior.AllowGet)); }
public ActionResult Edit([Bind(Include = "AccountId,UserId,Currency,Amount")] UserBankAccount userBankAccount) { if (ModelState.IsValid) { db.Entry(userBankAccount).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.UserId = new SelectList(db.Users, "UserId", "Name", userBankAccount.UserId); return(View(userBankAccount)); }
public void SaveBankAccount(UserBankAccount bankAccount) { if (bankAccount.Id == 0) { Conn.Insert <UserBankAccount>(bankAccount); } else { Conn.Update <UserBankAccount>(bankAccount); } }
public void CheckCardNoPassword() { bool isLoginPassed = false; while (isLoginPassed == false) { var inputAccount = screen.LoginForm(); AtmScreen.LoginProgress(); foreach (UserBankAccount account in _accountList) { selectedAccount = account; if (inputAccount.CardNumber.Equals(account.CardNumber)) { selectedAccount.TotalLogin++; if (inputAccount.CardPin.Equals(account.CardPin)) { selectedAccount = account; if (selectedAccount.IsLocked) { // This is when database is used and when the app is restarted. // Even user login with the correct card number and pin, // If IsLocked status is locked, user still will be still blocked. AtmScreen.PrintLockAccount(); } else { selectedAccount.TotalLogin = 0; isLoginPassed = true; break; } } } } if (isLoginPassed == false) { Utility.PrintMessage("Invalid card number or PIN.", false); // Lock the account if user fail to login more than 3 times. selectedAccount.IsLocked = selectedAccount.TotalLogin == 3; if (selectedAccount.IsLocked) { AtmScreen.PrintLockAccount(); } } Console.Clear(); } }
public ActionResult MyTransactions() { using (CryptowalletDbContext ctx = new CryptowalletDbContext()) { User currentUser = ctx.Users.AsNoTracking().FirstOrDefault(u => u.Email == User.Identity.Name); UserBankAccount myAccount = ctx.UserBankAccounts.FirstOrDefault(a => a.UserId == currentUser.UserId); IQueryable <UserTransaction> userTransactions = from u in ctx.UserTransactions where u.FromAccountId == myAccount.AccountId || u.ToAccountId == myAccount.AccountId select u; return(View(userTransactions.ToList())); } }
internal UserBankAccount LoginForm() { var vmUserBankAccount = new UserBankAccount(); // Actual ATM system will accept and validate physical ATM card. // Card validation includes read card number and check bank account status // and other security checking. vmUserBankAccount.CardNumber = Validator.Convert <long>("card number"); vmUserBankAccount.CardPin = Convert.ToInt32(Utility.GetHiddenConsoleInput("Enter card pin: ")); return(vmUserBankAccount); }
// GET: UserBankAccounts/Details/5 public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } UserBankAccount userBankAccount = db.UserBankAccounts.Find(id); if (userBankAccount == null) { return(HttpNotFound()); } return(View(userBankAccount)); }
private decimal TotalAmount() { using (CryptoWalletDBContext ctx = new CryptoWalletDBContext()) { User currentUser = ctx.Users.AsNoTracking().FirstOrDefault(u => u.Email == User.Identity.Name); List <CurrencyRate> rates = new ExchangeService().GetConversionRate(Currency.EUR, new Currency[] { Currency.USD, Currency.GBP, Currency.BTC, Currency.XRP }); decimal totalAmount = ctx.UsersBankAccounts.FirstOrDefault(u => u.Currency == "EUR" && u.UserId == currentUser.UserId).Amount; UserBankAccount userBankAccount = ctx.UsersBankAccounts.FirstOrDefault(u => u.Currency == "USD" && u.UserId == currentUser.UserId); if (userBankAccount != null) { rates = new ExchangeService().GetConversionRate(Currency.USD, new Currency[] { Currency.EUR }); totalAmount += (userBankAccount.Amount * rates.First().Rate); } userBankAccount = ctx.UsersBankAccounts.FirstOrDefault(u => u.Currency == "GBP" && u.UserId == currentUser.UserId); if (userBankAccount != null) { rates = new ExchangeService().GetConversionRate(Currency.GBP, new Currency[] { Currency.EUR }); totalAmount += (userBankAccount.Amount * rates.First().Rate); } userBankAccount = ctx.UsersBankAccounts.FirstOrDefault(u => u.Currency == "BTC" && u.UserId == currentUser.UserId); if (userBankAccount != null) { rates = new ExchangeService().GetConversionRate(Currency.BTC, new Currency[] { Currency.EUR }); totalAmount += (userBankAccount.Amount * rates.First().Rate); } userBankAccount = ctx.UsersBankAccounts.FirstOrDefault(u => u.Currency == "XRP" && u.UserId == currentUser.UserId); if (userBankAccount != null) { rates = new ExchangeService().GetConversionRate(Currency.XRP, new Currency[] { Currency.EUR }); totalAmount += (userBankAccount.Amount * rates.First().Rate); } return(totalAmount); } }
public ActionResult Send(SendViewModel viewModel) { if (ModelState.IsValid) { using (CryptowalletDbContext ctx = new CryptowalletDbContext()) { User currentUser = ctx.Users.AsNoTracking().FirstOrDefault(u => u.Email == User.Identity.Name); SetupSendViewModel(viewModel); UserBankAccount fromAccount = ctx.UserBankAccounts.FirstOrDefault(a => a.AccountId == viewModel.SenderAccountId && a.UserId == currentUser.UserId); UserBankAccount toAccount = ctx.UserBankAccounts.AsNoTracking().FirstOrDefault(u => u.User.Email == viewModel.ReciverName && u.Currency == fromAccount.Currency); if (viewModel.Amount > fromAccount.Amount) { ModelState.AddModelError("", "Insuficient funds"); } else if (toAccount == null) { ModelState.AddModelError("", "Reciver don`t have an account in this currency or doesn`t exist"); } else { fromAccount.Amount -= viewModel.Amount; toAccount.Amount += viewModel.Amount; ctx.SaveChanges(); UserTransaction userTransaction = new UserTransaction { Amount = viewModel.Amount, FromAccountId = fromAccount.AccountId, ToAccountId = toAccount.AccountId, CurrencyRate = 0, TransactionDate = DateTime.Now }; ctx.UserTransactions.Add(userTransaction); ctx.SaveChanges(); ViewBag.successMessage = "Transaction successful"; return(View(viewModel)); } } } return(View(viewModel)); }
// GET: UserBankAccounts/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } UserBankAccount userBankAccount = db.UserBankAccounts.Find(id); if (userBankAccount == null) { return(HttpNotFound()); } ViewBag.UserId = new SelectList(db.Users, "UserId", "Name", userBankAccount.UserId); return(View(userBankAccount)); }
private void SetupIndexDeposits(BankAccountViewModelTest viewModel, User user) { using (CryptoWalletDbContext ctx = new CryptoWalletDbContext()) { UserBankAccount bankAccount = ctx.UserBankAccounts.FirstOrDefault(x => x.UserId == user.UserId && x.Currency == "EUR"); if (bankAccount != null) { List <UserTransaction> transactions = ctx.UserTransactions.Where(x => x.FromAccountId == bankAccount.AccountId && x.ToAccountId == bankAccount.AccountId).ToList(); if (transactions != null) { foreach (var transaction in transactions) { viewModel.sumDeposits += transaction.Amount; } } } } }
public ActionResult Deposit(DepositViewModel viewModel) { if (ModelState.IsValid) { using (CryptoWalletDBContext ctx = new CryptoWalletDBContext()) { User currentUser = ctx.Users.AsNoTracking().FirstOrDefault(u => u.Email == User.Identity.Name); UserBankAccount eurAccount = ctx.UsersBankAccounts.FirstOrDefault(u => u.Currency == "EUR" && u.UserId == currentUser.UserId); if (eurAccount == null) { eurAccount = new UserBankAccount { Currency = "EUR", UserId = currentUser.UserId, Amount = 0 }; ctx.UsersBankAccounts.Add(eurAccount); } eurAccount.Amount += viewModel.Amount; ctx.SaveChanges(); UserTransaction transaction = new UserTransaction { Amount = viewModel.Amount, FromAccountId = eurAccount.AccountId, ToAccountId = eurAccount.AccountId, TransactionDate = DateTime.Now }; ctx.UsersTransactions.Add(transaction); ctx.SaveChanges(); } return(RedirectToAction("Index")); } return(View(viewModel)); }
public ActionResult Deposit(DepositViewModel viewModel) { if (ModelState.IsValid) { using (CryptoWalletDbContext ctx = new CryptoWalletDbContext()) { User user = ctx.Users.AsNoTracking().FirstOrDefault(u => u.Email == User.Identity.Name); UserBankAccount eurAccount = ctx.UserBankAccounts.FirstOrDefault(a => a.Currency == "EUR" && a.UserId == user.UserId); if (eurAccount == null) { eurAccount = new UserBankAccount { Currency = "EUR", UserId = user.UserId, Amount = 0 }; ctx.UserBankAccounts.Add(eurAccount); } ctx.SaveChanges(); eurAccount.Amount += viewModel.Amount; UserTransaction userTransaction = new UserTransaction { Amount = viewModel.Amount, CurrencyRate = 1, FromAccountId = eurAccount.AccountId, ToAccountId = eurAccount.AccountId, TransactionDate = DateTime.Now, FromAccount = eurAccount, ToAccount = eurAccount }; ctx.UserTransactions.Add(userTransaction); ctx.SaveChanges(); return(RedirectToAction("Index", "BankAccounts")); } } else { return(View(viewModel)); } }
static void Main(string[] args) { var userAccount = new UserBankAccount(Guid.NewGuid(), 1234, Currency.EUR); Log(userAccount); userAccount.Deposit(1000); Log(userAccount); userAccount.Withdraw(100); Log(userAccount); userAccount.Withdraw(100, Currency.USD); Log(userAccount); Console.Read(); }
public BankAccount UseNewBankAccount(Guid databaseName, Guid userId, Guid bankAccountTypeId) { var bankAccountAmount = GenerateNewAmount(); var bankAccount = new BankAccount() { Balance = bankAccountAmount, BankAccountTypeId = bankAccountTypeId, CreationDate = DateTime.Now, Id = Guid.NewGuid(), ModificationDate = DateTime.Now, OpeningBalance = bankAccountAmount, ActualBalance = bankAccountAmount, Wording = "Test bank account" }; var userBankAccount = new UserBankAccount() { BankAccountId = bankAccount.Id, CreationDate = DateTime.Now, Id = Guid.NewGuid(), IsOwner = true, IsReadOnly = false, ModificationDate = DateTime.Now, UserId = userId }; var dbContextOptions = new DbContextOptionsBuilder <DaGetContext>() .UseInMemoryDatabase(databaseName: databaseName.ToString()) .Options; using (var context = new DaGetContext(dbContextOptions)) { context.BankAccounts.Add(bankAccount); context.UserBankAccounts.Add(userBankAccount); context.Commit(); } return(bankAccount); }
public ActionResult Exchange(ExchangeViewModel viewModel) { if (ModelState.IsValid) { using (CryptoWalletDbContext ctx = new CryptoWalletDbContext()) { User currentUser = ctx.Users.AsNoTracking().FirstOrDefault(u => u.Email == User.Identity.Name); UserBankAccount fromAccount = ctx.UserBankAccounts.FirstOrDefault(x => x.AccountId.ToString() == viewModel.CurrencyFrom); UserBankAccount toAccount = ctx.UserBankAccounts.FirstOrDefault(x => x.AccountId.ToString() == viewModel.CurrencyTo); if (toAccount == null) { ModelState.AddModelError("", "Invalid to currency."); SetupExchange(viewModel); return(View(viewModel)); } if (fromAccount == null) { ModelState.AddModelError("", "Invalid from currency."); SetupExchange(viewModel); return(View(viewModel)); } if (fromAccount.AccountId == toAccount.AccountId) { ModelState.AddModelError("", "Selected currencies are the same."); SetupExchange(viewModel); return(View(viewModel)); } if (fromAccount.Amount < viewModel.Amount) { ModelState.AddModelError("", "Insufficient funds."); SetupExchange(viewModel); return(View(viewModel)); } Currency currencyFrom = (Currency)Enum.Parse(typeof(Currency), fromAccount.Currency, true); Currency currencyTo = (Currency)Enum.Parse(typeof(Currency), toAccount.Currency, true); ExchangeService echangeService = new ExchangeService(); List <CurrencyRate> rates = echangeService.GetConversionRate(currencyFrom, new Currency[] { currencyTo }); viewModel.Rate = rates[0].Rate; fromAccount.Amount -= viewModel.Amount; toAccount.Amount += (viewModel.Amount * viewModel.Rate); UserTransaction userTransaction = new UserTransaction { FromAccountId = fromAccount.AccountId, ToAccountId = toAccount.AccountId, FromAccount = fromAccount, ToAccount = toAccount, Amount = viewModel.Amount, CurrencyRate = viewModel.Rate * (decimal)1.0000000, TransactionDate = DateTime.Now }; ctx.UserTransactions.Add(userTransaction); ctx.SaveChanges(); return(RedirectToAction("Transactions")); } } else { SetupExchange(viewModel); return(View(viewModel)); } }
public ActionResult Send(SendViewModel viewModel) { if (ModelState.IsValid) { using (CryptoWalletDbContext ctx = new CryptoWalletDbContext()) { User currentUser = ctx.Users.AsNoTracking().FirstOrDefault(u => u.Email == User.Identity.Name); User receiverEmail = ctx.Users.AsNoTracking().FirstOrDefault(x => x.Email == viewModel.ReceiverName); if (receiverEmail == null) { ModelState.AddModelError("", "The email is invalid."); SetupSendViewModel(viewModel); return(View(viewModel)); } UserBankAccount fromAccount = ctx.UserBankAccounts.FirstOrDefault(a => a.AccountId.ToString() == viewModel.SenderAccountId); UserBankAccount toAccount = ctx.UserBankAccounts.FirstOrDefault(a => a.Currency == fromAccount.Currency && a.UserId == receiverEmail.UserId); if (fromAccount == null) { ModelState.AddModelError("", "The currency of the sender does not match."); SetupSendViewModel(viewModel); return(View(viewModel)); } if (toAccount == null) { ModelState.AddModelError("", "The currency of the receiver does not match."); SetupSendViewModel(viewModel); return(View(viewModel)); } if (fromAccount.Amount < viewModel.Amount) { ModelState.AddModelError("", "Insufficient funds."); SetupSendViewModel(viewModel); return(View(viewModel)); } fromAccount.Amount -= viewModel.Amount; toAccount.Amount += viewModel.Amount; UserTransaction transaction = new UserTransaction { Amount = viewModel.Amount, FromAccountId = fromAccount.AccountId, ToAccountId = toAccount.AccountId, TransactionDate = DateTime.Now, CurrencyRate = 1, FromAccount = fromAccount, ToAccount = toAccount }; ctx.UserTransactions.Add(transaction); ctx.SaveChanges(); return(RedirectToAction("Index")); } } return(View(viewModel)); }
public BankAccountDto Create(Guid?userId, string userName, BankAccountDto toCreate) { BankAccountDto result = null; try { if (userId == null) { throw new DaGetServiceException("Impossible de créer le compte, utilisateur non défini"); } using (var context = Factory.CreateContext(ConnexionString)) { var baRepo = Factory.GetBankAccountRepository(context); // on vérifie que le nom du compte n'est pas déjà utilisé par l'utilisateur if (baRepo.GetAllByIdUser(userId.Value).Any(ba => ba.Wording.Equals(toCreate.Wording))) { throw new DaGetServiceException("Vous possédez déjà un compte avec ce nom"); } // création du compte BankAccount bankAccountToAdd = new BankAccount() { BankAccountTypeId = toCreate.BankAccountTypeId.Value, CreationDate = DateTime.Now, DateSolde = DateTime.Now, ModificationDate = DateTime.Now, Number = toCreate.Number, Solde = 0M, SoldeInitial = toCreate.SoldeInitial, Wording = toCreate.Wording }; baRepo.Add(bankAccountToAdd); // création de l'user var ubaRepo = Factory.GetUserBankAccountRepository(context); UserBankAccount userBankAccountToAdd = new UserBankAccount() { BankAccountId = bankAccountToAdd.Id, BankAccountAccessId = 1, UserId = userId.Value, UserName = userName }; ubaRepo.Add(userBankAccountToAdd); context.Commit(); result = bankAccountToAdd.ToDto(); } } catch (DaGetServiceException) { throw; } catch (Exception ex) { throw new DaGetServiceException( String.Format("Erreur lors de création du compte pour l'utilisateur {0}", userId), ex); } return(result); }
public Bank GetBank(UserBankAccount userBankAccount) { return(_bankService.GetByKey(userBankAccount.BankId)); }
public ActionResult Exchange(ExchangeViewModel viewModel) { SetupExchangeViewModel(viewModel); CurrencyRate changeRate = new CurrencyRate(); if (ModelState.IsValid) { using (CryptowalletDbContext ctx = new CryptowalletDbContext()) { User currentUser = ctx.Users.AsNoTracking().FirstOrDefault(u => u.Email == User.Identity.Name); ExchangeService exchangeService = new ExchangeService(); Enum.TryParse(viewModel.fromCurrency, out Currency fromCurrency); List <CurrencyRate> rates = exchangeService.GetConversionRate(fromCurrency, new Currency[] { Currency.EUR, Currency.ETH, Currency.LTC, Currency.BTC, Currency.EOS }); // List<CurrencyRate> rate =e.GetConversionRate(Currency.BTC, new Currency[] { Currency.EUR, Currency.USD, Currency.GBP }); changeRate = rates.FirstOrDefault(a => a.Currency.ToString() == viewModel.toCurrency); UserBankAccount bankAccount = ctx.UserBankAccounts.FirstOrDefault(a => a.Currency == viewModel.toCurrency && a.UserId == currentUser.UserId); UserBankAccount fromBankAccount = ctx.UserBankAccounts.FirstOrDefault(a => a.Currency == viewModel.fromCurrency && a.UserId == currentUser.UserId); if (fromBankAccount.Amount < viewModel.Amount) { ModelState.AddModelError("", "Insuficient funds"); return(View(viewModel)); } if (bankAccount == null) { bankAccount = new UserBankAccount { Currency = viewModel.toCurrency, UserId = currentUser.UserId, Amount = 0, }; ctx.UserBankAccounts.Add(bankAccount); } bankAccount.Amount += viewModel.Amount * changeRate.Rate; fromBankAccount.Amount -= viewModel.Amount; ctx.SaveChanges(); UserTransaction userTransaction = new UserTransaction { Amount = viewModel.Amount, FromAccountId = fromBankAccount.AccountId, ToAccountId = bankAccount.AccountId, CurrencyRate = changeRate.Rate, TransactionDate = DateTime.Now }; ctx.UserTransactions.Add(userTransaction); ctx.SaveChanges(); ViewBag.successMessage = "Transaction successful"; } return(View(viewModel)); } return(View(viewModel)); }
private ActionResult Sell(ExchangeViewModel exchangeViewModel) { CurrencyRate changeRate = new CurrencyRate(); int transactionType; if (Enum.TryParse(exchangeViewModel.toCurrency, out Currency currentCurrency)) { if (ModelState.IsValid) { using (CryptowalletDbContext ctx = new CryptowalletDbContext()) { User currentUser = ctx.Users.AsNoTracking().FirstOrDefault(u => u.Email == User.Identity.Name); ExchangeService exchangeService = new ExchangeService(); var sellingAccount = ctx.UserBankAccounts.FirstOrDefault(a => a.Currency == currentCurrency.ToString() && a.UserId == currentUser.UserId); if (sellingAccount == null) { ModelState.AddModelError("", "Inexistent account"); switch (TempData["TransactionType"]) { case "Buy": transactionType = 1; break; case "Sell": transactionType = 0; break; default: transactionType = 0; break; } return(MakeTransactions(transactionType, currentCurrency)); } List <CurrencyRate> rates = exchangeService.GetConversionRate(currentCurrency, new Currency[] { Currency.EUR }); changeRate = rates.FirstOrDefault(a => a.Currency == Currency.EUR); if (exchangeViewModel.Amount > sellingAccount.Amount) { ModelState.AddModelError("", "Insuficient funds"); //return RedirectToAction("MakeTransactions", new { transactionType = 1 }); switch (TempData["TransactionType"]) { case "Buy": transactionType = 1; break; case "Sell": transactionType = 0; break; default: transactionType = 0; break; } return(MakeTransactions(transactionType, currentCurrency)); } UserBankAccount euroBankAccount = ctx.UserBankAccounts.FirstOrDefault(a => a.Currency == Currency.EUR.ToString() && a.UserId == currentUser.UserId); euroBankAccount.Amount += exchangeViewModel.Amount * changeRate.Rate; sellingAccount.Amount -= exchangeViewModel.Amount; ctx.SaveChanges(); UserTransaction userTransaction = new UserTransaction { Amount = exchangeViewModel.Amount, FromAccountId = sellingAccount.AccountId, ToAccountId = euroBankAccount.AccountId, CurrencyRate = changeRate.Rate, TransactionDate = DateTime.Now }; ctx.UserTransactions.Add(userTransaction); ctx.SaveChanges(); } return(View(exchangeViewModel)); } } else { ModelState.AddModelError("", "Invalid Currency"); switch (TempData["TransactionType"]) { case "Buy": transactionType = 1; break; case "Sell": transactionType = 0; break; default: transactionType = 0; break; } return(MakeTransactions(transactionType, currentCurrency)); } return(RedirectToAction("Wallet")); }