public static void Main() { var context = new ATMEntities(); var requiredAmount = 200M; WithdrawMoneyExtended(context, requiredAmount); }
public static void WithdrawMoney(string cardNumber, string pinNumber, decimal money) { using (var context = new ATMEntities()) { using (var dbContextTransaction = context.Database.BeginTransaction(IsolationLevel.RepeatableRead)) { try { if (CheckIsValid(context, cardNumber, pinNumber)) { if (CheckIsHasMoney(context, cardNumber, money)) { var currentEntity = context.CardAccounts.First(c => c.CardNumber == cardNumber && c.CardPIN == pinNumber); currentEntity.CardCach = currentEntity.CardCach - money; context.SaveChanges(); Console.WriteLine("You have got your money!Amount after withdraw {0}!", currentEntity.CardCach); } } dbContextTransaction.Commit(); } catch (Exception e) { dbContextTransaction.Rollback(); Console.WriteLine("Transaction cancled!\nError occured: {0}", e.Message); } } } }
private static bool CheckIsHasMoney(ATMEntities context, string cardNumber, decimal money) { var currentEntity = context.CardAccounts.First(c => c.CardNumber == cardNumber); if (currentEntity.CardCach >= money) { return(true); } throw new Exception("You do not have enough money!"); }
private static bool CheckIsValid(ATMEntities context, string cardNumber, string pinNumber) { try { var currentEntity = context.CardAccounts.First(c => c.CardNumber == cardNumber && c.CardPIN == pinNumber); } catch (Exception) { throw new Exception("You're entering a wrong card number or PIN!"); } return(true); }
private static void WithdrawMoneyExtended(ATMEntities context, decimal amount) { using (var dbContextTransaction = context.Database.BeginTransaction()) { try { var account = context.CardAccounts.First(); if (account.CardNumber.Length != 10) { throw new InvalidOperationException("Card Number is invalid"); } if (account.CardPIN.Length != 4) { throw new InvalidOperationException("Card PIN is invalid"); } if (account.CardCash < amount) { throw new InvalidOperationException("Not enough money in the account."); } account.CardCash = account.CardCash - amount; var transactionHistory = new TransactionHistory { CardNumber = account.CardNumber, TransactionDate = DateTime.Now, Amount = amount }; context.TransactionHistories.Add(transactionHistory); context.SaveChanges(); dbContextTransaction.Commit(); Console.WriteLine("Withdraw was successful."); } catch (InvalidOperationException ioe) { Console.WriteLine(ioe.Message); } catch (Exception e) { Console.WriteLine(e.Message); } } }