Exemplo n.º 1
0
 public CreditsService(BankSystemContext context, IConfiguration _config, ITransactionsService transactionsService, ICreditPayOff creditPay)
 {
     dbContext            = context;
     config               = _config;
     _transactionsService = transactionsService;
     _creditPay           = creditPay;
 }
Exemplo n.º 2
0
        private string ListAccounts()
        {
            if (!AuthenticationManager.IsAuthenticated())
            {
                throw new InvalidOperationException("You should log in first!");
            }

            StringBuilder builder = new StringBuilder();

            using (BankSystemContext context = new BankSystemContext())
            {
                User user = context.Users.Attach(AuthenticationManager.GetCurrentUser());

                builder.AppendLine("Saving Accounts:");
                foreach (SavingAccount userSavingAccount in user.SavingAccounts)
                {
                    builder.AppendLine($"--{userSavingAccount.AccountNumber} {userSavingAccount.Balance}");
                }

                builder.AppendLine("Checking Accounts:");
                foreach (CheckingAccount checkingAccount in user.CheckingAccounts)
                {
                    builder.AppendLine($"--{checkingAccount.AccountNumber} {checkingAccount.Balance}");
                }
            }

            return(builder.ToString().Trim());
        }
Exemplo n.º 3
0
        public void ActionTransferShouldReturnToViewTransferIfAmountNumberLargerThanBalance()
        {
            var user  = CreateUserForTesting();
            var user2 = CreateUserForTesting();

            using (var context = new BankSystemContext(options))
            {
                var uow         = new UnitOfWork(context);
                var userService = new UserService(uow);
                if (userService.Register(user).Status&& userService.Register(user2).Status)
                {
                    var controller = new UserController(context);
                    var result     = controller.Transfer(user.ID) as ViewResult;
                    Assert.NotNull(result);

                    var result1 = controller.Transfer(3000, user2.ID) as ViewResult;
                    Assert.NotNull(result1);
                    Assert.True(result1.ViewData.ModelState["Transfer"].Errors.Count > 0);
                }
                else
                {
                    Assert.True(false);
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Add interest to the balance of the account with given number
        /// </summary>
        /// <param name="context"></param>
        /// <param name="args"></param>
        private void AddInterest(BankSystemContext context, string[] args)
        {
            if (this.bankSystemController.LogedUser == null)
            {
                Console.WriteLine("You should Login first!");
                return;
            }

            //•	AddInterest <Account number>
            string        accountNumber = args[0];
            SavingAccount account       = context
                                          .SavingAccounts
                                          .FirstOrDefault(sa => sa.AccountNumber == accountNumber);

            if (account == null)
            {
                Console.WriteLine("Invalid account number!");
                return;
            }

            account.AddRate();
            context.SaveChanges();

            Console.WriteLine($"Added interest to {account.AccountNumber}. Current balance: {account.Ballance:F2}");
        }
Exemplo n.º 5
0
        public string Execute(string[] input)
        {
            if (input.Length != 2)
            {
                throw new ArgumentException("Input is not valid!");
            }

            if (AuthenticationManager.IsAuthenticated())
            {
                throw new InvalidOperationException("You should logout first!");
            }

            // Login <username> <password>
            string username = input[0];
            string password = input[1];

            using (BankSystemContext context = new BankSystemContext())
            {
                User user = context.Users.FirstOrDefault(u => u.Username == username && u.Password == password);

                if (user == null)
                {
                    throw new ArgumentException("Invalid username/password!");
                }

                AuthenticationManager.Login(user);
            }

            return($"User {username} logged in successfully!");
        }
        public string Execute(string[] input)
        {
            if (input.Length != 1)
            {
                throw new ArgumentException("Input is not valid!");
            }

            if (!AuthenticationManager.IsAuthenticated())
            {
                throw new InvalidOperationException("You should log in first!");
            }

            // AddInterest <Account number>
            string accountNumber = input[0];

            decimal currentBalance;

            using (BankSystemContext context = new BankSystemContext())
            {
                User          user          = context.Users.Attach(AuthenticationManager.GetCurrentUser());
                SavingAccount savingAccount = user.SavingAccounts.FirstOrDefault(a => a.AccountNumber == accountNumber);

                if (savingAccount == null)
                {
                    throw new ArgumentException($"Account {accountNumber} does not exist!");
                }

                savingAccount.Balance += savingAccount.Balance * savingAccount.InterestRate;
                currentBalance         = savingAccount.Balance;

                context.SaveChanges();
            }

            return($"Account interest added {accountNumber} - ${currentBalance}");
        }
        public void BankAccount_Should_GetAccount_By_Id()
        {
            //Arrange
            var effortContext = new BankSystemContext(Effort.DbConnectionFactory.CreateTransient());
            var mapperMock    = new Mock <IMapper>();

            var user = new ApplicationUser()
            {
                PasswordHash = "1234",
                PhoneNumber  = "12455",
                FirstName    = "asdfgh",
                LastName     = "lastName",
                UserName     = "******",
                Email        = "*****@*****.**"
            };

            effortContext.Users.Add(user);

            var bank = new BankAccountAddAspModel()
            {
                BankAccountType = (BankAccountType)1,
                Amount          = 12345,
                Currency        = (Currency)973,
                OwnerId         = user.Id,
                IsDeleted       = false
            };

            var bankMock = new BankAccount()
            {
                BankAccountType = (BankAccountType)1,
                Amount          = 12345,
                Currency        = (Currency)973,
                OwnerId         = user.Id,
                IsDeleted       = false
            };

            var bankReadModel = new BankAccountReadModel()
            {
                BankAccountType = (BankAccountType)1,
                Amount          = 12345,
                Currency        = (Currency)973,
                OwnerId         = user.Id,
                IsDeleted       = false
            };

            mapperMock.Setup(x => x.Map <BankAccount>(It.IsAny <BankAccountAddAspModel>()))
            .Returns(bankMock);

            mapperMock.Setup(x => x.Map <BankAccountReadModel>(It.IsAny <BankAccount>()))
            .Returns(bankReadModel);

            var sut = new BankAccountServices(effortContext, mapperMock.Object);

            sut.AddBankAccount(bank);
            //Act
            var result = sut.GetBankAccountByID(bankMock.Id.ToString());

            Assert.IsInstanceOfType(result, typeof(BankAccountReadModel));
            Assert.IsTrue(result.OwnerId == bankMock.OwnerId);
        }
Exemplo n.º 8
0
        public void ActionTransferShouldReturnToViewTransferWhenSuccess()
        {
            var user  = CreateUserForTesting();
            var user2 = CreateUserForTesting();

            using (var context = new BankSystemContext(options))
            {
                var uow         = new UnitOfWork(context);
                var userService = new UserService(uow);
                if (userService.Register(user).Status&& userService.Register(user2).Status)
                {
                    var controller = new UserController(context);
                    var result     = controller.Transfer(user.ID) as ViewResult;
                    Assert.NotNull(result);

                    var result1 = controller.Transfer(5, user2.ID) as RedirectToActionResult;
                    Assert.NotNull(result1);
                    Assert.Equal("Details", result1.ActionName);
                }
                else
                {
                    Assert.True(false);
                }
            }
        }
        public string Execute(string[] input)
        {
            if (input.Length != 0)
            {
                throw new ArgumentException("Input is not valid!");
            }

            if (!AuthenticationManager.IsAuthenticated())
            {
                throw new InvalidOperationException("You should log in first!");
            }

            StringBuilder builder = new StringBuilder();

            using (BankSystemContext context = new BankSystemContext())
            {
                User user = context.Users.Attach(AuthenticationManager.GetCurrentUser());

                builder.AppendLine("Saving Accounts:");
                foreach (SavingAccount userSavingAccount in user.SavingAccounts)
                {
                    builder.AppendLine($"--{userSavingAccount.AccountNumber} {userSavingAccount.Balance}");
                }

                builder.AppendLine("Checking Accounts:");
                foreach (CheckingAccount checkingAccount in user.CheckingAccounts)
                {
                    builder.AppendLine($"--{checkingAccount.AccountNumber} {checkingAccount.Balance}");
                }
            }

            return(builder.ToString().Trim());
        }
Exemplo n.º 10
0
        public override string Execute()
        {
            using (var context = new BankSystemContext())
            {
                if (this.Data.Length != 3)
                {
                    throw new ArgumentException("Command is invalid!");
                }

                if (!User.IsLoggedIn)
                {
                    throw new InvalidOperationException("No user is logged in.");
                }

                string  accountNumber = this.Data[1];
                decimal money         = Convert.ToDecimal(this.Data[2]);

                var user = context.Users
                           .Include(u => u.Accounts)
                           .FirstOrDefault(u => u.UserId == User.LoggedUserId);
                var account = user.Accounts
                              .FirstOrDefault(a => a.AccountNumber == accountNumber);

                if (account == null)
                {
                    throw new ArgumentException("No such account for this user.");
                }

                string result = account.DepositMoney(money);

                context.SaveChanges();

                return(result);
            }
        }
Exemplo n.º 11
0
        public static string GenerateIBANInVitoshaBank(string BankAccountType, BankSystemContext dbContext)
        {
            string countryCode         = "BG";
            string uniqueNumber        = "18";
            string bankBIC             = "VITB";
            string secondUniqueNumber  = "1234567";
            string bankAccountTypeCode = "";

            if (BankAccountType == "ChargeAccount")
            {
                bankAccountTypeCode = "01";
            }
            else if (BankAccountType == "Credit")
            {
                bankAccountTypeCode = "02";
            }
            else if (BankAccountType == "Deposit")
            {
                bankAccountTypeCode = "03";
            }
            else if (BankAccountType == "Wallet")
            {
                bankAccountTypeCode = "04";
            }
            else
            {
                return(null);
            }
            string currentBankAccountNumber = GetCurrentAvailabeAccountNumber(BankAccountType, dbContext);
            string IBAN = $"{countryCode}{uniqueNumber}{bankBIC}{secondUniqueNumber}{bankAccountTypeCode}{currentBankAccountNumber}";

            return(IBAN);
        }
        public override string Execute()
        {
            using (var context = new BankSystemContext())
            {
                if (this.Data.Length != 3)
                {
                    throw new ArgumentException("Command is invalid!");
                }

                if (!User.IsLoggedIn)
                {
                    throw new InvalidOperationException("No user is logged in.");
                }

                decimal initialBalance = Convert.ToDecimal(this.Data[1]);
                decimal fee            = Convert.ToDecimal(this.Data[2]);

                var user    = context.Users.Find(User.LoggedUserId);
                var account = new CheckingAccount(initialBalance, fee);

                user.Accounts.Add(account);
                context.SaveChanges();

                return($"Succesfully added account with number {account.AccountNumber}");
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Prints a list of overall information for all accounts of currently logged in user .
        /// </summary>
        /// <param name="context"></param>
        /// <param name="args"></param>
        private void ListAccounts(BankSystemContext context, string[] args)
        {
            if (this.bankSystemController.LogedUser == null)
            {
                Console.WriteLine("You should Login first!");
                return;
            }
            int userId = this.bankSystemController.LogedUser.Id;

            List <CheckingAccount> checkingAccounts = context
                                                      .CheckingAccounts
                                                      .Where(ca => ca.OwnerId == userId)
                                                      .ToList();

            List <SavingAccount> savingAccounts = context
                                                  .SavingAccounts
                                                  .Where(sa => sa.OwnerId == userId)
                                                  .ToList();

            //TODO: Sort by count of accounts
            Console.WriteLine($"Accounts for user {this.bankSystemController.LogedUser}");
            Console.WriteLine("Saving Accounts:");
            Console.WriteLine($"{string.Join("\r\n", savingAccounts)}");
            Console.WriteLine("Cheking Accounts:");
            Console.WriteLine($"{string.Join("\r\n", checkingAccounts)}");
        }
Exemplo n.º 14
0
        public void Should_Return_the_expected_exchange()
        {
            var effortContext = new BankSystemContext(Effort.DbConnectionFactory.CreateTransient());



            var exchangeCheck = new ExchangeRateModel()
            {
                FromCurrency = (Currency)840,
                ToCurrency   = (Currency)975,
            };

            var exchangeAdd = new ExchangeRate()
            {
                FromCurrency = (Currency)840,
                ToCurrency   = (Currency)975,
                Rate         = 0.5m,
                IsDeleted    = false
            };


            effortContext.ExchangeRates.Add(exchangeAdd);
            effortContext.SaveChanges();

            var sut = new ExchangeRateService(effortContext);

            //Act & Assert
            Assert.IsTrue(sut.GetExchangeRate(exchangeCheck) == 0.5m);
        }
Exemplo n.º 15
0
        public void Run()
        {
            using (BankSystemContext context = new BankSystemContext())
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();

                string input;
                while ((input = Console.ReadLine()) != "Exit")
                {
                    string[] inputArgs = input
                                         .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    string   command = inputArgs[0];
                    string[] args    = inputArgs.Skip(1).ToArray();

                    Type            type   = typeof(Engine);
                    ConstructorInfo ctor   = type.GetConstructor(new Type[] { typeof(BankSystemController) });
                    Engine          engine = ctor.Invoke(new object[] { this.bankSystemController }) as Engine;
                    MethodInfo      method = type.GetMethod(command, BindingFlags.Instance | BindingFlags.NonPublic);
                    if (method == null)
                    {
                        Console.WriteLine("Invalid command!");
                        continue;
                    }
                    method.Invoke(engine, new object[] { context, args });
                }
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Adds money to the account with given number
        /// </summary>
        /// <param name="context"></param>
        /// <param name="args"></param>
        private void Deposit(BankSystemContext context, string[] args)
        {
            if (this.bankSystemController.LogedUser == null)
            {
                Console.WriteLine("You should Login first!");
                return;
            }
            //•	Deposit <Account number> <money>
            string  accountNumber = args[0];
            decimal money         = decimal.Parse(args[1]);
            Account account       =
                context
                .Accounts
                .FirstOrDefault(a => a.AccountNumber == accountNumber);

            if (account == null)
            {
                Console.WriteLine("Invalid account number!");
                return;
            }

            context.SaveChanges();

            Console.WriteLine($"Account {account.AccountNumber} has balance of {account.Ballance}");
        }
Exemplo n.º 17
0
 public Engine(BankSystemContext db, ICommandInterpreter interpreter, IReader reader, IWriter writer)
 {
     this.db = db;
     this.commandInterpreter = interpreter;
     this.reader             = reader;
     this.writer             = writer;
 }
        public override string Execute()
        {
            using (var context = new BankSystemContext())
            {
                if (this.Data.Length != 3)
                {
                    throw new ArgumentException("Command is invalid!");
                }

                string username = this.Data[1];
                string password = this.Data[2];

                if (User.IsLoggedIn)
                {
                    throw new InvalidOperationException("A user is already logged in");
                }

                if (!context.Users.Any(u => u.Username == username &&
                                       u.Password == password))
                {
                    throw new InvalidOperationException("Incorrect username \\ password");
                }

                int loggedUserId = context.Users
                                   .First(u => u.Username == username && u.Password == password)
                                   .UserId;

                User.IsLoggedIn   = true;
                User.LoggedUserId = loggedUserId;

                return($"Succesfully logged in {username}");
            }
        }
Exemplo n.º 19
0
 private bool Authentication(string mobileNumber, BankSystemContext context)
 {
     if (context.Accounts.SingleOrDefault(x => x.MobileNumber == mobileNumber) is null)
     {
         return(false);
     }
     return(true);
 }
Exemplo n.º 20
0
 public void RahmatSsoDbContext_Should_Fetch_Database_Record()
 {
     using (var ctx = new BankSystemContext())
     {
         var result = ctx.Users.First();
         Assert.NotNull(result);
     }
 }
Exemplo n.º 21
0
 public void ActionCreateShouldReturnToViewCreateIfInputUserNotValid()
 {
     using (var context = new BankSystemContext(options))
     {
         var controller = new UserController(context);
         var result     = (ViewResult)controller.Create(null);
         Assert.True(result.ViewData.ModelState["Create"].Errors.Count > 0);
     }
 }
Exemplo n.º 22
0
 public void ActionLoginShouldReturnToViewLoginIfUserNotValid()
 {
     using (var context = new BankSystemContext(options))
     {
         var controller = new UserController(context);
         var result     = (ViewResult)controller.Login(null);
         Assert.True(result.ViewData.ModelState["Login"].Errors.Count > 0);
     }
 }
Exemplo n.º 23
0
 public void CanGetAllUser()
 {
     using (var context = new BankSystemContext(options))
     {
         var uow   = new UnitOfWork(context);
         var users = uow.UserRepository.GetAll();
         Assert.True(users.Count() > 1);
     }
 }
Exemplo n.º 24
0
        protected TestsBase()
        {
            var connectionString = @"Server=(localdb)\mssqllocaldb;Database=BankSystem_Test;Integrated Security=True;Trusted_Connection=True;MultipleActiveResultSets=true";

            options = new DbContextOptionsBuilder <BankSystemContext>()
                      .UseSqlServer(connectionString)
                      .Options;


            var services = new ServiceCollection()
                           .AddDbContext <BankSystemContext>(
                b => b.UseSqlServer(connectionString));

            // Create the schema in the database
            using (bsc = new BankSystemContext(options))
            {
                bsc.Database.EnsureCreatedAsync();
                Thread.Sleep(1500); //wait for system create
                if (bsc.Users == null || bsc.Users.Any())
                {
                    return;   // DB has been seeded
                }

                Guid   userID;
                Random rnd       = new Random();
                int    rndNumber = rnd.Next(1, 10000000);
                var    userName  = "******" + rndNumber;
                var    user      = new User
                {
                    ID            = userID,
                    AccountNumber = Guid.NewGuid(),
                    AccountName   = userName,
                    Balance       = 1000,
                    Password      = "******",
                    CreatedDate   = DateTime.Now
                };
                bsc.Users.Add(user);

                if (bsc.Transactions.Any())
                {
                    return;   // DB has been seeded
                }
                var transaction = new Transaction()
                {
                    ID          = Guid.NewGuid(),
                    Type        = TransactionTypes.Deposite,
                    CreatedDate = DateTime.Now,
                    Status      = true,
                    Amount      = 1000,
                    UserID      = userID,
                    Target      = null
                };
                bsc.Transactions.Add(transaction);
                bsc.SaveChanges();
            }
        }
Exemplo n.º 25
0
        public void Should_Return_ArgumentNullException_When_ExchangeModel_is_Null()
        {
            var effortContext = new BankSystemContext(Effort.DbConnectionFactory.CreateTransient());


            var sut = new ExchangeRateService(effortContext);


            Assert.ThrowsException <ArgumentNullException>(() => sut.GetExchangeRate(null));
        }
Exemplo n.º 26
0
 public void ActionReportShouldRedirectToHomeIfUserIdNotValid()
 {
     using (var context = new BankSystemContext(options))
     {
         var controller = new UserController(context);
         var result     = (RedirectToActionResult)controller.Report(Guid.NewGuid());
         Assert.Equal("Index", result.ActionName);
         Assert.Equal("Home", result.ControllerName);
     }
 }
Exemplo n.º 27
0
        public void ActionCreateShouldRedirectToActionIndexWhenSuccess()
        {
            var user = CreateUserForTesting();

            using (var context = new BankSystemContext(options))
            {
                var controller = new UserController(context);
                var result     = (RedirectToActionResult)controller.Create(user);
                Assert.Equal("Index", result.ActionName);
            }
        }
Exemplo n.º 28
0
        public string Execute(string[] input)
        {
            if (input.Length != 2)
            {
                throw new ArgumentException("Input is not valid!");
            }

            if (!AuthenticationManager.IsAuthenticated())
            {
                throw new InvalidOperationException("You should log in first!");
            }

            // Deposit <Account number> <money>
            string  accountNumber = input[0];
            decimal amount        = decimal.Parse(input[1]);

            if (amount <= 0)
            {
                throw new ArgumentException("Deposit amount should be positive!");
            }

            decimal currentBalance;

            using (BankSystemContext context = new BankSystemContext())
            {
                // Try to find the account specified.
                User          user          = context.Users.Attach(AuthenticationManager.GetCurrentUser());
                SavingAccount savingAccount = user.SavingAccounts.FirstOrDefault(a => a.AccountNumber == accountNumber);

                CheckingAccount checkingAccount = user.CheckingAccounts.FirstOrDefault(a => a.AccountNumber == accountNumber);

                // If not any accounts were not found throw exception.
                if (savingAccount == null && checkingAccount == null)
                {
                    throw new ArgumentException($"Account {accountNumber} does not exist!");
                }

                if (savingAccount != null)
                {
                    savingAccount.Balance += amount;
                    currentBalance         = savingAccount.Balance;
                }
                else
                {
                    // NOTE: What about if we have both saving and checking account?
                    checkingAccount.Balance += amount;
                    currentBalance           = checkingAccount.Balance;
                }

                context.SaveChanges();
            }

            return($"Account {accountNumber} - ${currentBalance}");
        }
Exemplo n.º 29
0
 public Account SignIn(string mobileNumber, string password)
 {
     using (var context = new BankSystemContext())
     {
         var user = context.Accounts.SingleOrDefault(x => x.MobileNumber == mobileNumber);
         if (user is null || !Verify(password, user.Password))
         {
             return(null);
         }
         return(user);
     }
 }
Exemplo n.º 30
0
        public static void Main()
        {
            var context = new BankSystemContext();

            Database.SetInitializer(
                new MigrateDatabaseToLatestVersion <BankSystemContext, Configuration>());
            context.Database.Initialize(true);

            var engine = new Engine();

            engine.Run();
        }