Пример #1
0
        public IActionResult WithdrawCash(Card card)
        {
            Card card1 = (from c in db.Cards
                          where c.CardNumber == CurrentCardNumber
                          select c).Single();

            if (card.Balance > card1.Balance)
            {
                messErr = "На вашем счету недостаточно средств =(";
                return(PartialView("ErrorMessage"));
            }
            else
            {
                //добавить сюда добавление операции в таблицу операций
                WasWithdrawn       = card.Balance;
                card1.Balance     -= card.Balance;
                CurrentCardBalance = card1.Balance;

                Operation op = new Operation
                {
                    CardId          = card1.Id,
                    OperationCodeId = 2,
                    Time            = DateTime.Now
                };
                db.Operations.Add(op);
                db.SaveChanges();
                return(PartialView("WithdrawalResult"));
            }
        }
        public void CheckRecordAmount()
        {
            Database.SetInitializer(
                new DropCreateDatabaseAlways <ATMContext>());

            decimal money      = 2000;
            decimal toWithdraw = 1000;
            int     number     = 1111111111;
            int     cardPin    = 1111;

            using (var db = new ATMContext())
            {
                db.CardAccounts.Add(new CardAccount()
                {
                    CardCash = money, CardNumber = number, CardPIN = cardPin
                });

                db.SaveChanges();

                ATMActions.WithdrawMoney(cardPin, number, toWithdraw, db);
                db.SaveChanges();

                var actual = (from c in db.TransactionsHistory
                              select c).First();

                Assert.AreEqual(1000, actual.Ammount);
                db.Dispose();
            }
        }
Пример #3
0
        public ActionResult Create([Bind(Include = "ID,AccountNumber,FirstName,LastName,Balance")] CheckingAccount checkingAccount)
        {
            if (ModelState.IsValid)
            {
                db.CheckingAccounts.Add(checkingAccount);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(checkingAccount));
        }
Пример #4
0
        public void SetBalance(string cardNum, decimal newBalance)
        {
            var card = GetCardByNum(cardNum);

            card.Balance = newBalance;
            _context.SaveChanges();
        }
Пример #5
0
        public static void RetrieveMoneyFromAccount(ATMContext context, string cardPin, string cardNumber, decimal amount)
        {
            using (TransactionScope transaction = new TransactionScope(
                       TransactionScopeOption.Required,
                       new TransactionOptions {
                IsolationLevel = IsolationLevel.RepeatableRead
            }))
            {
                var card = VerifyCard(context, cardPin, cardNumber);
                if (card == null)
                {
                    throw new ArgumentNullException("The card does not exist.");
                }

                bool cardHasSufficientAmount = amount <= card.CardCash;
                if (!cardHasSufficientAmount)
                {
                    throw new Exception("The card has insufficient funds");
                }

                card.CardCash = card.CardCash - amount;
                context.SaveChanges();
                CreateLog(context, cardNumber, amount);
                //Here is where you can test the isolation level. It locks only the record(row) which is being modified,
                //the rest records from the table are selectable during the transaction.
                //Thread.Sleep(5000);
                transaction.Complete();
            }
        }
Пример #6
0
        private static void InitialDataImport()
        {
            using (var db = new ATMContext())
            {
                var account1 = new CardAccount
                {
                    CardNumber = "1234567893",
                    CardPin    = "1234",
                    CardCash   = 5000.00m
                };
                var account2 = new CardAccount
                {
                    CardNumber = "1234567894",
                    CardPin    = "2234",
                    CardCash   = 5000.00m
                };
                var account3 = new CardAccount
                {
                    CardNumber = "1234567895",
                    CardPin    = "3234",
                    CardCash   = 5000.00m
                };

                db.CardAccounts.Add(account1);
                db.CardAccounts.Add(account2);
                db.CardAccounts.Add(account3);
                db.SaveChanges();
                db.Database.ExecuteSqlCommand("CREATE UNIQUE INDEX IX_CardNumber ON CardAccounts (CardNumber)");
            }
        }
Пример #7
0
        static void Main()
        {
            var context = new ATMContext();

            using (var dbContextTransaction = context.Database.BeginTransaction())
            {
                try
                {
                    Console.Write("Card Number: ");
                    string cardNumber = Console.ReadLine();

                    var cardAccount = context.CardAccounts
                                      .FirstOrDefault(c => c.CardNumber == cardNumber);

                    if (cardAccount == null)
                    {
                        throw new InvalidOperationException($"Account with card number: {cardNumber} doesn't exist");
                    }

                    Console.Write("Card Pin: ");
                    string cardPin = Console.ReadLine();

                    if (cardAccount.CardPIN != cardPin)
                    {
                        throw new InvalidOperationException("Wrong Pin.");
                    }

                    Console.Write("Withdraw amount: ");
                    decimal withdrawAmount = decimal.Parse(Console.ReadLine());

                    if (cardAccount.CardCash < withdrawAmount)
                    {
                        throw new InvalidOperationException("Not enough money.");
                    }
                    else
                    {
                        cardAccount.CardCash -= withdrawAmount;
                    }

                    dbContextTransaction.Commit();

                    context.TransactionHistory.Add(new TransactionHistory
                    {
                        CardNumber      = cardNumber,
                        TransactionDate = DateTime.Now,
                        WithdrawAmount  = withdrawAmount
                    });

                    context.SaveChanges();

                    Console.WriteLine($"Succesfully withdrawed {withdrawAmount}, current amount {cardAccount.CardCash:0.00}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    dbContextTransaction.Rollback();
                }
            }
        }
Пример #8
0
        private static void Withdraw(string cardNumber, string cardPIN, decimal moneyAmount)
        {
            using (var atmContext = new ATMContext())
            {
                using (var transaction = atmContext.Database.BeginTransaction())
                {
                    if (atmContext.CardAccounts.Any(cardAccount => cardAccount.CardNumber == cardNumber
                                                                   && cardAccount.CardPIN == cardPIN))
                    {
                        var theAccount =
                            atmContext.CardAccounts.First(cardAccount => cardAccount.CardNumber == cardNumber
                                                                         && cardAccount.CardPIN == cardPIN);

                        if (theAccount.CardCash < moneyAmount)
                        {
                            throw new Exception("nsufficient amount of money.");
                            transaction.Rollback();
                        }
                        else
                        {
                            theAccount.CardCash -= moneyAmount;
                            atmContext.SaveChanges();

                            atmContext.TransactionHistories.Add(new TransactionHistory()
                            {
                                CardNumber = theAccount.CardNumber,
                                Amount = moneyAmount,
                                TransactionDate = DateTime.Now
                            });

                            atmContext.SaveChanges();

                            transaction.Commit();
                        }
                    }
                    else
                    {
                        throw new Exception("Wrong combination of card number and pin code.");
                        transaction.Rollback();
                    }
                }
            }
        }
Пример #9
0
        public async Task AddTransction(Transaction transaction)
        {
            _context.Transactions.Add(transaction);
            Debug.WriteLine(transaction.BankAccountId);
            BankAccount ba = await _context.BankAccounts.SingleOrDefaultAsync(x => x.Id == transaction.BankAccountId);

            ba.changeBalance(transaction.Amount);
            _context.SaveChanges();
            await Task.CompletedTask;
        }
Пример #10
0
 static void Main(string[] args)
 {
     using (var dbContext = new ATMContext())
     {
         var getCards = FillCardNumbers();
         dbContext.Cards.AddRange(getCards);
         dbContext.SaveChanges();
         var cards = dbContext.Cards.ToList();
     }
 }
Пример #11
0
        static void SaveWithdraw(CardAccount cardAccount, decimal amount, ATMContext db)
        {
            cardAccount.CardCash -= amount;

            db.TransactionHistory.Add(new TransactionHistory()
            {
                CardNumber = cardAccount.CardNumber, Amount = amount
            });

            db.SaveChanges();
        }
Пример #12
0
        public static void Main()
        {
            var     atmContext   = new ATMContext();
            string  card         = "8949848946";
            string  pin          = "4892";
            decimal requestedSum = 60m;

            using (var dbContextTransaction = atmContext.Database.BeginTransaction())
            {
                try
                {
                    var cardAccount = atmContext.CardAccount
                                      .Where(a => a.CardNumber == card && a.CardPin == pin)
                                      .FirstOrDefault();

                    if (cardAccount == null)
                    {
                        throw new InvalidOperationException("Invalid card number or pin.");
                    }

                    cardAccount.Money -= requestedSum;
                    if (cardAccount.Money < 0)
                    {
                        throw new InvalidOperationException("There are not enough funds in your card.");
                    }

                    TransactionHistory currentTransaction = new TransactionHistory(
                        cardAccount.CardNumber,
                        DateTime.Now,
                        requestedSum);

                    atmContext.TransactionHistory.Add(currentTransaction);

                    atmContext.SaveChanges();
                    dbContextTransaction.Commit();
                }
                catch (DbUpdateConcurrencyException exc)
                {
                    dbContextTransaction.Rollback();
                    Console.WriteLine("Conflict! Try again.");
                }
                catch (DataException exc)
                {
                    Console.WriteLine("Invalid value!");
                }
                catch (InvalidOperationException exc)
                {
                    Console.WriteLine(exc.Message);
                }
            }
        }
Пример #13
0
 public long GetCardBalance(long cardNumber)
 {
     using (var dbContext = new ATMContext())
     {
         var cardNumberString = GetMD5String(cardNumber.ToString(CultureInfo.InvariantCulture));
         var card             = dbContext.Cards.First(x => x.Active || x.CardNumber == cardNumberString);
         var logInfo          = new LogInfo {
             CardId = cardNumber, OperationCode = 1
         };
         dbContext.Logs.Add(logInfo);
         dbContext.SaveChanges();
         return(card.Balance);
     }
 }
Пример #14
0
        public static void CashWithdraw(string cardNumber,
                                        string cardPin, decimal sum)
        {
            using (var db = new ATMContext())
            {
                bool success = false;
                using (TransactionScope transaction = new TransactionScope())
                {
                    try
                    {
                        // get card number and pin
                        var card = db.CardAccounts.
                                   Where(c => c.CardNumber == cardNumber).
                                   Where(p => p.CardPin == cardPin).First();

                        if (card.CardCash >= sum)
                        {
                            // withdraw sum
                            card.CardCash -= sum;
                        }
                        else
                        {
                            Console.WriteLine("Insufficient funds!");
                        }

                        transaction.Complete();
                        success = true;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Wrong PIN or Invalid card!");
                    }
                }
                if (success)
                {
                    // save in history
                    var log = new TransactionsHistory()
                    {
                        CardNumber      = cardNumber,
                        TransactionDate = DateTime.Now,
                        Ammount         = sum
                    };

                    db.TransactionsHisory.Add(log);

                    db.SaveChanges();
                    Console.WriteLine("Transaction successful!");
                }
            }
        }
Пример #15
0
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new ATMContext(
                       serviceProvider.GetRequiredService <
                           DbContextOptions <ATMContext> >()))
            {
                if (context.CreditCards.Any())
                {
                    return;
                }

                context.CreditCards.AddRange(ATMContext.GetSeedingCards());
                context.SaveChanges();
            }
        }
    static void Main()
    {
        SeedDatabase();

        Console.Write("Enter Card Number: ");
        string cardNumber = Console.ReadLine();

        Console.Write("Enter Card PIN: ");
        string cardPIN = Console.ReadLine();

        var context = new ATMContext();

        var cardAccount = context.CardAccounts
            .Where(c => c.CardPIN == cardPIN && c.CardNumber == cardNumber)
            .FirstOrDefault();

        if (cardAccount != null)
        {
            Console.Write("How much would you like to withdraw? ");
            decimal amount = decimal.Parse(Console.ReadLine());

            TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions
            {
                IsolationLevel = IsolationLevel.RepeatableRead
            });

            using (transactionScope)
            {
                if (cardAccount.CardCash >= amount)
                {
                    cardAccount.CardCash -= amount;
                    Console.WriteLine("Withdrawal successful.");
                }
                else
                {
                    throw new InvalidOperationException("Insufficient amount of money in the card.");
                }

                PreserveTransactionHistory(context, cardNumber, amount);
                context.SaveChanges();
                transactionScope.Complete();
            }
        }
        else
        {
            throw new InvalidOperationException("Invalid Card Number or PIN");
        }
    }
Пример #17
0
        public ATMRepository(ATMContext context)
        {
            Customer    c  = new Customer(Guid.NewGuid(), "F", "L");
            Card        d  = new Card(Guid.NewGuid(), CardTypes.MasterCard, "1234");
            BankAccount ac = new BankAccount(Guid.NewGuid(), c.Id, d.Id, "A", 3200.87);
            Transaction t  = new Transaction(Guid.NewGuid(), ac.Id, 50);

            _context = context;
            if (_context.BankAccounts.Count() == 0)
            {
                _context.Customers.Add(c);
                _context.Cards.Add(d);
                _context.BankAccounts.Add(ac);
                _context.Transactions.Add(t);
                _context.SaveChanges();
            }
        }
        public static void Main()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<ATMContext, Configuration>());
            var context = new ATMContext();

            using (var dbContextTransaction = context.Database.BeginTransaction())
            {
                try
                {
                    Console.Write("Please, enter card number: ");
                    var cardNumber = Console.ReadLine();

                    Console.Write("Please, enter PIN: ");
                    var pinCode = Console.ReadLine();

                    var account = ATMManager.GetAccount(context, cardNumber, pinCode);

                    Console.Write("Please, enter amount: ");
                    var amount = decimal.Parse(Console.ReadLine());

                    ATMManager.ValidateAccountAmount(account, amount);
                    account.CardCash -= amount;

                    var transaction = new TransactionsHistory()
                    {
                        CardNumber = cardNumber,
                        Amount = amount,
                        TransactionDate = DateTime.Now
                    };

                    context.TransactionHistories.Add(transaction);
                    context.SaveChanges();
                    dbContextTransaction.Commit();

                    Console.WriteLine("Withdraw complete.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    dbContextTransaction.Rollback();
                }
            }
        }
Пример #19
0
        public static bool WithdrawMoney(int PIN, int cardNumber, decimal moneyToWithdraw, ATMContext db)
        {
            bool success            = true;
            int  cardNumberToRecord = 0;


            using (var scope = new TransactionScope(
                       TransactionScopeOption.RequiresNew,
                       new TransactionOptions()
            {
                IsolationLevel = IsolationLevel.RepeatableRead
            }
                       ))
            {
                var card = (from c in db.CardAccounts
                            where c.CardNumber == cardNumber
                            select c).First();


                if (card == null || card.CardPIN != PIN || card.CardCash < moneyToWithdraw)
                {
                    success = false;
                }
                else
                {
                    card.CardCash     -= moneyToWithdraw;
                    cardNumberToRecord = card.CardNumber;
                    scope.Complete();
                }
            }

            if (success)
            {
                RecordWithdrawal(cardNumberToRecord, moneyToWithdraw, db);
                db.SaveChanges();
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #20
0
        public CheckPinDTO CheckPinNumber(long cardNumber, int pin, int numberOfTries)
        {
            var retVal = new CheckPinDTO();

            using (var dbContext = new ATMContext())
            {
                var cardNumberString = GetMD5String(cardNumber.ToString(CultureInfo.InvariantCulture));
                var card             = dbContext.Cards.First(x => x.Active || x.CardNumber == cardNumberString);
                retVal.Successful = card.PinCode == GetMD5String(pin.ToString(CultureInfo.InvariantCulture));
                if (!retVal.Successful)
                {
                    if (numberOfTries == 3) //TODO: move this magic number to the settings
                    {
                        card.Active    = false;
                        retVal.Blocked = true;
                        dbContext.SaveChanges();
                    }
                }
            }
            return(retVal);
        }
Пример #21
0
        static void Main(string[] args)
        {
            Database.SetInitializer
                (new MigrateDatabaseToLatestVersion <ATMContext, Configuration>());
            var atmContext = new ATMContext();

            using (atmContext)
            {
                atmContext.CardAccounts.Add(new CardAccount()
                {
                    CardCash = 10000, CardNumber = "12356asdf", CardPin = "1234"
                });
                atmContext.CardAccounts.Add(new CardAccount()
                {
                    CardCash = 5000, CardNumber = "78901asdf", CardPin = "4321"
                });
                atmContext.SaveChanges();

                AccountManager.RetrieveMoneyFromAccount(atmContext, "1234", "12356asdf", 666);
            }
        }
Пример #22
0
        public WithdrawMoneyDTO WithdrawMoney(long cardNumber, long ammount)
        {
            var retVal = new WithdrawMoneyDTO();

            using (var dbContext = new ATMContext())
            {
                var cardNumberString = GetMD5String(cardNumber.ToString(CultureInfo.InvariantCulture));
                var card             = dbContext.Cards.First(x => x.Active || x.CardNumber == cardNumberString);
                if (card.Balance >= ammount)
                {
                    card.Balance      -= ammount;
                    retVal.Successfull = true;
                    retVal.Balance     = card.Balance;
                    var logInfo = new LogInfo {
                        CardId = cardNumber, OperationCode = 0, OperationValue = ammount
                    };
                    dbContext.Logs.Add(logInfo);
                    dbContext.SaveChanges();
                }
            }
            return(retVal);
        }
Пример #23
0
        public static void RecordWithdrawal(string cardNumber, decimal ammount)
        {
            using (var scope = new TransactionScope(
                       TransactionScopeOption.RequiresNew,
                       new TransactionOptions()
            {
                IsolationLevel = IsolationLevel.RepeatableRead
            }))
            {
                using (ATMContext db = new ATMContext())
                {
                    db.TransactionsHistories.Add(new TransactionsHistory()
                    {
                        TransactionDate = DateTime.Now,
                        Ammount         = ammount,
                        CardNumber      = cardNumber
                    });

                    db.SaveChanges();
                    scope.Complete();
                }
            }
        }
Пример #24
0
 private static void CreateLog(ATMContext context, string cardNumber, decimal amount)
 {
     using (TransactionScope transaction = new TransactionScope(
                TransactionScopeOption.RequiresNew,
                new TransactionOptions {
         IsolationLevel = IsolationLevel.ReadUncommitted
     }))
     {
         try
         {
             context.TransactionHistories.Add(new TransactionHistory()
             {
                 Amount = amount, CardNumber = cardNumber, TransactionDate = DateTime.Now,
             });
             context.SaveChanges();
             transaction.Complete();
         }
         catch (Exception e)
         {
             Console.WriteLine(e.Message);
         }
     }
 }
Пример #25
0
        public static bool RetrieveMoney(string CardPIN, string cardNumber, decimal moneyToWithdraw)
        {
            using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions()
            {
                IsolationLevel = IsolationLevel.RepeatableRead
            }))
            {
                using (ATMContext db = new ATMContext())
                {
                    var card = db.CardAccounts
                               .Where(c => c.CardNumber == cardNumber).First();

                    bool success = true;
                    if (card == null || card.CardPIN != CardPIN || card.CardCash < moneyToWithdraw)
                    {
                        success = false;
                    }
                    else
                    {
                        card.CardCash -= moneyToWithdraw;
                    }

                    if (success)
                    {
                        RecordWithdrawal(cardNumber, moneyToWithdraw);
                        db.SaveChanges();
                        scope.Complete();
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
        }
Пример #26
0
        protected override void Seed(ATM.Data.ATMContext context)
        {
            var db = new ATMContext();

            var cardAccounts = new List <CardAccount>
            {
                new CardAccount("1234567890", "1234", 999.9m),
                new CardAccount("9876543210", "9874", 15000.3m),
                new CardAccount("8949848946", "4892", 66.6m),
                new CardAccount("6489123898", "4945", 0.0m),
                new CardAccount("4984548887", "8135", 99m),
                new CardAccount("7981528365", "7753", 617.21m)
            };

            cardAccounts.ForEach(delegate(CardAccount c)
            {
                if (!db.CardAccount.Any(x => c.CardNumber == x.CardNumber))
                {
                    db.CardAccount.AddOrUpdate(c);
                }
            });

            db.SaveChanges();
        }
Пример #27
0
        static void Main()
        {
            var context = new ATMContext();

            var acc = context.CardAccounts.Find(1);

            using (TransactionScope tran = new TransactionScope(TransactionScopeOption.Required))
            {
                if (context.CardAccounts.Any(c => c.CardNumber == acc.CardNumber && c.CardPIN == acc.CardPIN))
                {
                    if (context.CardAccounts.First(c => c.CardNumber == acc.CardNumber).CardCash >= acc.CardCash &&
                        context.CardAccounts.First(c => c.CardNumber == acc.CardNumber).CardCash > 0)
                    {
                        context.TransactionHistories.Add(new TransactionHistory
                        {
                            CardNumber      = context.CardAccounts.First(c => c.CardNumber == acc.CardNumber).CardNumber,
                            Amount          = acc.CardCash,
                            TransactionDate = DateTime.Now
                        });

                        context.CardAccounts.First(c => c.CardNumber == acc.CardNumber).CardCash -= acc.CardCash;
                        Console.WriteLine("Transaction complete!");
                        context.SaveChanges();
                        tran.Complete();
                    }
                    else
                    {
                        throw new ArgumentException("You cannot request more money than you have in your account.");
                    }
                }
                else
                {
                    throw new ArgumentException("Invalid credit card number and / or card PIN.");
                }
            }
        }
Пример #28
0
 public void Save()
 {
     context.SaveChanges();
 }
    static void SeedDatabase()
    {
        ATMContext context = new ATMContext();

        context.CardAccounts.Add(new CardAccount()
        {
            CardCash = 500,
            CardNumber = "2001",
            CardPIN = "1112"
        });

        context.CardAccounts.Add(new CardAccount()
        {
            CardCash = 800,
            CardNumber = "2002",
            CardPIN = "1113"
        });

        context.CardAccounts.Add(new CardAccount()
        {
            CardCash = 1000,
            CardNumber = "2003",
            CardPIN = "1114"
        });

        context.SaveChanges();
    }
Пример #30
0
 public void NoteOperation(Operation operation)
 {
     _context.Operations.Add(operation);
     _context.SaveChanges();
 }
Пример #31
0
 public void Save()
 {
     db.SaveChanges();
 }
Пример #32
0
        public static void Initialize(ATMContext context)
        {
            context.Database.EnsureCreated();

            // Tạo data mẫu
            var checkData = context.Accounts.LastOrDefault();

            if (checkData == null)
            {
                Account account = new Account
                {
                    AccountName = "Nguyen Trong Thang",
                    PinCode     = EncryptProvider.Sha256("123456")
                };
                context.Accounts.Add(account);
                context.SaveChanges();

                var WalletType1 = new WalletType()
                {
                    WalletTypeName = "CHECKING"
                };
                var WalletType2 = new WalletType()
                {
                    WalletTypeName = "SAVING"
                };
                context.WalletType.Add(WalletType1);
                context.WalletType.Add(WalletType2);
                context.SaveChanges();

                Guid   g2      = Guid.NewGuid();
                Wallet wallet2 = new Wallet()
                {
                    AccountId    = account.AccountId,
                    Balance      = 0,
                    WalletId     = g2,
                    WalletTypeId = WalletType2.WalletTypeId,
                };
                context.Wallets.Add(wallet2);
                context.SaveChanges();

                Guid   g1      = Guid.NewGuid();
                Wallet wallet1 = new Wallet()
                {
                    AccountId    = account.AccountId,
                    Balance      = 5000000,
                    WalletId     = g1,
                    WalletTypeId = WalletType1.WalletTypeId,
                };
                context.Wallets.Add(wallet1);
                context.SaveChanges();

                var transactiontype1 = new TransactionType()
                {
                    TransactionTypeName = "DEPOSIT",
                    Fee = 0
                };
                var transactiontype2 = new TransactionType()
                {
                    TransactionTypeName = "WITHDRAW",
                    Fee = 3000
                };
                var transactiontype3 = new TransactionType()
                {
                    TransactionTypeName = "TRANSFER",
                    Fee = 0
                };
                context.TransactionType.Add(transactiontype1);
                context.TransactionType.Add(transactiontype2);
                context.TransactionType.Add(transactiontype3);
                context.SaveChanges();
            }
        }