Beispiel #1
0
        public void GuiTien()
        {
            if (Program.currentLoggedInAccount != null)
            {
                Console.Clear();
                Console.WriteLine("Tien hanh gui tien tai he thong SHB");
                Console.WriteLine("Vui Long nhap so tien can gui");
                var amount = Double.Parse(Console.ReadLine());
                if (amount <= 0)
                {
                    Console.WriteLine("So luong khong hop le, vui long nhap lai");
                    return;
                }

                var transaction = new SHBTransaction()
                {
                    TransactionId         = Guid.NewGuid().ToString(),
                    SenderAccountNumber   = Program.currentLoggedInAccount.AccountNumber,
                    ReceiverAccountNumber = Program.currentLoggedInAccount.AccountNumber,
                    Type         = 2,
                    Message      = "Tien hanh gui tien tai ATM voi so tien" + amount,
                    Amount       = amount,
                    CreatedAtMLS = DateTime.Now.Ticks,
                    UpdatedAtMLS = DateTime.Now.Ticks,
                    Status       = 1
                };
                bool result = shbAccountModel.UpdateBalance(Program.currentLoggedInAccount, transaction);
            }
            else
            {
                Console.WriteLine("Vui long dang nhap de su dung chuc nang nay");
            }
        }
Beispiel #2
0
        public void GuiTien()
        {
            if (Program.currentLoggedInAccount != null)
            {
                Console.Clear();
                Console.WriteLine("Vui lòng nhập số tiền cần gui :");
                var Amount = Double.Parse(Console.ReadLine());

                var transaction = new SHBTransaction
                {
                    TransactionId         = Guid.NewGuid().ToString(),
                    SenderAccountNumber   = Program.currentLoggedInAccount.AccountNumber,
                    ReceiverAccountNumber = Program.currentLoggedInAccount.AccountNumber,
                    Type         = SHBTransaction.TransactionType.DEPOSIT,
                    Amount       = Amount,
                    Message      = "Tiến hành gui tiền tại ATM với số tiền: " + Amount,
                    CreatedAtMLS = DateTime.Now.Ticks,
                    UpdatedAtMLS = DateTime.Now.Ticks,
                    Status       = 1
                };
                if (shbAccountModel.UpdateBalance(Program.currentLoggedInAccount, transaction))
                {
                    Console.WriteLine("Giao dịch thành công.");
                }
                else
                {
                    Console.WriteLine("Giao dịch eos thành công.");
                }
            }

            else
            {
                Console.WriteLine("Vui lòng đăng nhập để sử dụng chức năng này.");
            }
        }
Beispiel #3
0
        public void Transfer()
        {
            if (Program.CurrentLoggedInAccount != null)
            {
                Console.Clear();
                Console.WriteLine("===== Transfer on Blockchain =====");
                Console.WriteLine("Enter your amount");
                var amount = double.Parse(Console.ReadLine());
                if (amount <= 0)
                {
                    Console.WriteLine("Your amount is unavaiable. Please try again.");
                    return;
                }

                var transaction = new SHBTransaction
                {
                    TransactionId     = Guid.NewGuid().ToString(),
                    SenderAccountId   = Program.CurrentLoggedInAccount.AccountNumber,
                    ReceiverAccountId = Program.CurrentLoggedInAccount.AccountNumber,
                    Type         = 3,
                    Message      = "Transfer completed: " + amount,
                    Amount       = amount,
                    CreatedAtMLS = DateTime.Now.Ticks,
                    UpdatedAtMLS = DateTime.Now.Ticks,
                    Status       = 3
                };
                BlockchainTransaction blockchainTransaction;
                bool result = BlockchainAddressModel.UpdateBalance(Program.CurrentLoggedInAccount,
                                                                   typeof(BlockchainTransaction));
            }
            else
            {
                Console.WriteLine("Please login your account to use this function.");
            }
        }
Beispiel #4
0
        public void Withdrawal()
        {
            if (Program.CurrentLoggedInAccount != null)
            {
                Console.Clear();
                Console.WriteLine("===== Withdrawal on SHB =====");
                Console.WriteLine("Enter your amount: ");
                var amount = double.Parse(Console.ReadLine());
                if (amount <= 0)
                {
                    Console.WriteLine("Your amount is unavaiable. Please try again");
                    return;
                }

                var transaction = new SHBTransaction
                {
                    TransactionId     = Guid.NewGuid().ToString(),
                    SenderAccountId   = Program.CurrentLoggedInAccount.AccountNumber,
                    ReceiverAccountId = Program.CurrentLoggedInAccount.AccountNumber,
                    Type         = 1,
                    Message      = "Withdrawal completed: " + amount,
                    Amount       = amount,
                    CreatedAtMLS = DateTime.Now.Ticks,
                    UpdatedAtMLS = DateTime.Now.Ticks,
                    Status       = 1
                };
                bool result = shbAccountModel.UpdateBalance(Program.CurrentLoggedInAccount, transaction);
            }
            else
            {
                Console.WriteLine("Please login your account to use this function.");
            }
        }
        public void RutTien()
        {
            if (Program.currentLoggedInAccount != null)
            {
                Console.Clear();
                Console.WriteLine("Tiến hành rút tiền tại Hệ thống Ngân hàng Blockchain.");
                Console.WriteLine("Vui lòng nhập số tiền cần rút: ");
                var amount = double.Parse(Console.ReadLine());
                if (amount <= 0)
                {
                    Console.WriteLine("Số lượng tiền không hợp lệ, vui lòng thử lại.");
                    return;
                }

                var transaction = new SHBTransaction
                {
                    TransactionId         = Guid.NewGuid().ToString(),
                    SenderAccountNumber   = Program.currentLoggedInAccount.AccountNumber,
                    ReceiverAccountNumber = Program.currentLoggedInAccount.AccountNumber,
                    Type         = 1,
                    Message      = "Tiến hành rút tiền ở ATM với số tiền: " + amount,
                    Amount       = amount,
                    CreatedAtMLS = DateTime.Now.Ticks,
                    UpdatedAtMLS = DateTime.Now.Ticks,
                    Status       = 1
                };
                BlockchainTransaction blockchainTransaction;
                bool result =
                    BlockchainAddressModel.UpdateBalance(Program.currentLoggedInAccount, typeof(BlockchainTransaction));
            }
            else
            {
                Console.WriteLine("Vui lòng đăng nhập lại để sử dụng chức năng này.");
            }
        }
Beispiel #6
0
        public void GuiTien()
        {
            if (Program.currentLoggedInAccount != null)
            {
                Console.Clear();
                Console.WriteLine("Tiến hành gửi tiền tại hệ thống SHB.");
                Console.WriteLine("Vui lòng nhập số tiền cần gửi.");
                var amount = double.Parse(Console.ReadLine());
                if (amount <= 50000)
                {
                    Console.WriteLine("Số tiền phải trên 50000vnđ, vui lòng thử lại.");
                    return;
                }

                var transaction = new SHBTransaction
                {
                    TransactionId         = Guid.NewGuid().ToString(),
                    SenderAccountNumber   = Program.currentLoggedInAccount.AccountNumber,
                    ReceiverAccountNumber = Program.currentLoggedInAccount.AccountNumber,
                    Type         = 1,
                    Message      = "Tiến hành rút tiền tại ATM với số tiền: " + amount,
                    Amount       = amount,
                    CreatedAtMLS = DateTime.Now.Ticks,
                    UpdatedAtMLS = DateTime.Now.Ticks,
                    Status       = 1
                };
                bool result = shbAccountModel.UpdateBalance(Program.currentLoggedInAccount, transaction);
            }
            else
            {
                Console.WriteLine("Vui lòng đăng nhập để sử dụng chức năng này.");
            }
        }
Beispiel #7
0
        // 7. Truy vấn lịch sử giao dịch
        public List <SHBTransaction> TransactionHistory()
        {
            List <SHBTransaction> list = null;
            SHBTransaction        shbTransaction;
            Account account = _guestModel.GetActiveAccountByUserName(Program.currentLogin.Username);

            if (account == null)
            {
                Console.WriteLine("Không tìm thấy tài khoản hoặc tài khoản đã bị khóa!");
                return(null);
            }

            var cnn = ConnectionHelpers.GetConnection();

            cnn.Open();
            try
            {
                list = new List <SHBTransaction>();
                var stringCmdGetTransaction =
                    $"SELECT * FROM `transactions` WHERE senderAccountNumber = '{account.AccountNumber}' OR receiverAccountNumber = '{account.AccountNumber}'";
                var cmdGetTransaction    = new MySqlCommand(stringCmdGetTransaction, cnn);
                var readerGetTransaction = cmdGetTransaction.ExecuteReader();
                while (readerGetTransaction.Read())
                {
                    shbTransaction = new SHBTransaction()
                    {
                        TransactionCode       = readerGetTransaction.GetString("transactionCode"),
                        SenderAccountNumber   = readerGetTransaction.GetString("senderAccountNumber"),
                        ReceiverAccountNumber = readerGetTransaction.GetString("receiverAccountNumber"),
                        Type      = (TransactionType)readerGetTransaction.GetInt32("type"),
                        Amount    = readerGetTransaction.GetDouble("amount"),
                        Fee       = readerGetTransaction.GetDouble("fee"),
                        Message   = readerGetTransaction.GetString("message"),
                        CreateAt  = readerGetTransaction.GetDateTime("createAt"),
                        UpdatedAt = readerGetTransaction.GetDateTime("updatedAt"),
                        Status    = (TransactionStatus)readerGetTransaction.GetInt32("status")
                    };
                    list.Add(shbTransaction);
                }
                cnn.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                cnn.Close();
            }

            return(list);
        }
Beispiel #8
0
 public void Transfer()
 {
     if (Program.currentLoggedInAccount != null)
     {
         Console.WriteLine("Transfer money at the banking system SHB.");
         Console.WriteLine("Please enter the account number you want to transfer: ");
         var accountNumber   = Console.ReadLine();
         var receiverAccount = shbAccountModel.GetAccountByAccountNumber(accountNumber);
         if (receiverAccount == null)
         {
             Console.WriteLine("Money receiving account does not exist or has been locked, please check again.");
             return;
         }
         Console.WriteLine("Money receiving account: " + accountNumber);
         Console.WriteLine("account holder: " + receiverAccount.Username);
         Console.WriteLine("Enter the amount you want to transfer: ");
         var amount = double.Parse(Console.ReadLine());
         Program.currentLoggedInAccount = shbAccountModel.GetAccountByUsername(Program.currentLoggedInAccount.Username);
         if (amount > Program.currentLoggedInAccount.Balance)
         {
             Console.WriteLine("Account balance is not enough to make transactions.");
             return;
         }
         Console.WriteLine("Enter transaction content: ");
         var message        = Console.ReadLine();
         var shbTransaction = new SHBTransaction()
         {
             TransactionId         = Guid.NewGuid().ToString(),
             Type                  = SHBTransaction.TransactionType.TRANSFER,
             Amount                = amount,
             Message               = message,
             CreateAtMLS           = DateTime.Now.Ticks,
             UpdateAtMLS           = DateTime.Now.Ticks,
             Status                = SHBTransaction.TransactionStatus.DONE,
             SenderAccountNumber   = Program.currentLoggedInAccount.AccountNumber,
             ReceiverAccountNumber = accountNumber
         };
         if (shbAccountModel.Transfer(Program.currentLoggedInAccount, shbTransaction))
         {
             Console.WriteLine("Successful transaction.");
         }
         else
         {
             Console.WriteLine("The transaction failed, please check again.");
         }
     }
 }
Beispiel #9
0
 public void ChuyenTien()
 {
     if (Program.currentLoggedInAccount != null)
     {
         Console.WriteLine("Tiến hành chuyển tiền tại hệ thống SHB.");
         Console.WriteLine("Vui lòng nhập số tài khoản chuyển tiền: ");
         var accountNumber   = Console.ReadLine();
         var receiverAccount = shbAccountModel.GetAccountByAccountNumber(accountNumber);
         if (receiverAccount == null)
         {
             Console.WriteLine("Tài khoản nhận tiền không tồn tại hoặc đã bị khoá.");
             return;
         }
         Console.WriteLine("Tài khoản nhận tiền: " + accountNumber);
         Console.WriteLine("Chủ tài khoản: " + receiverAccount.Username);
         Console.WriteLine("Nhập số tiền chuyển khoản: ");
         var amount = double.Parse(Console.ReadLine());
         Program.currentLoggedInAccount = shbAccountModel.GetAccountByUsername(Program.currentLoggedInAccount.Username);
         if (amount > Program.currentLoggedInAccount.Balance)
         {
             Console.WriteLine("Số dư tài khoản không đủ thực hiện giao dịch.");
             return;
         }
         Console.WriteLine("Nhập nội dung giao dịch: ");
         var message        = Console.ReadLine();
         var shbTransaction = new SHBTransaction()
         {
             TransactionId         = Guid.NewGuid().ToString(),
             Type                  = SHBTransaction.TransactionType.TRANSFER,
             Amount                = amount,
             Message               = message,
             CreateAtMLS           = DateTime.Now.Ticks,
             UpdateAtMLS           = DateTime.Now.Ticks,
             Status                = SHBTransaction.TransactionStatus.DONE,
             SenderAccountNumber   = Program.currentLoggedInAccount.AccountNumber,
             ReceiverAccountNumber = accountNumber
         };
         if (shbAccountModel.Transfer(Program.currentLoggedInAccount, shbTransaction))
         {
             Console.WriteLine("Giao dịch thành công.");
         }
         else
         {
             Console.WriteLine("Giao dịch thất bại, vui lòng thử lại.");
         }
     }
 }
Beispiel #10
0
        public void ChuyenKhoan()
        {
            if (Program.currentLoggedInAccount != null)
            {
                Console.Clear();
                Console.WriteLine("Vui lòng nhập số tài khoản chuyển tiền: ");
                var accountNumber   = Console.ReadLine();
                var receiverAccount = shbAccountModel.GetAccountByAccountNumber(accountNumber);
                if (receiverAccount == null)
                {
                    Console.WriteLine("Tài khoản nhận tiền không tồn tại hoặc đã bị khoá.");
                    return;
                }
                Console.WriteLine("Tài khoản nhận tiền: " + accountNumber);
                Console.WriteLine("Chủ tài khoản: " + receiverAccount.Username);
                Console.WriteLine("Nhập số tiền chuyển khoản: ");
                var Amount = Double.Parse(Console.ReadLine());
                Console.WriteLine("Nhập nội dung giao dịch: ");
                var message        = Console.ReadLine();
                var transactionShb = new SHBTransaction()
                {
                    TransactionId         = Guid.NewGuid().ToString(),
                    Type                  = SHBTransaction.TransactionType.TRANFER,
                    SenderAccountNumber   = Program.currentLoggedInAccount.AccountNumber,
                    ReceiverAccountNumber = accountNumber,
                    Amount                = Amount,
                    Message               = "Tiến hành chuyen khoan với số tiền: " + Amount + ", Noi dung: " + message,
                    CreatedAtMLS          = DateTime.Now.Ticks,
                    UpdatedAtMLS          = DateTime.Now.Ticks,
                    Status                = 1
                };

                if (shbAccountModel.Tranfer(Program.currentLoggedInAccount, transactionShb))
                {
                    Console.WriteLine("Giao dịch thành công.");
                }
                else
                {
                    Console.WriteLine("Giao dịch thất bại, vui lòng thử lại.");
                }
            }
        }
Beispiel #11
0
        // 2. Danh sách lịch sử giao dịch.
        public List <SHBTransaction> ListTransaction()
        {
            List <SHBTransaction> listTran = null;
            SHBTransaction        transaction;
            var cnn = ConnectionHelpers.GetConnection();

            cnn.Open();
            try
            {
                listTran = new List <SHBTransaction>();
                var stringCmdGetAccount = $"select * from `transactions`";
                var cmd            = new MySqlCommand(stringCmdGetAccount, cnn);
                var getListHistory = cmd.ExecuteReader();
                while (getListHistory.Read())
                {
                    transaction = new SHBTransaction()
                    {
                        TransactionCode       = getListHistory.GetString("transactionCode"),
                        SenderAccountNumber   = getListHistory.GetString("senderAccountNumber"),
                        ReceiverAccountNumber = getListHistory.GetString("receiverAccountNumber"),
                        Type      = (TransactionType)getListHistory.GetInt32("type"),
                        Amount    = getListHistory.GetDouble("amount"),
                        Fee       = getListHistory.GetDouble("fee"),
                        Message   = getListHistory.GetString("message"),
                        CreateAt  = getListHistory.GetDateTime("createAt"),
                        UpdatedAt = getListHistory.GetDateTime("updatedAt"),
                        Status    = (TransactionStatus)getListHistory.GetInt32("status")
                    };
                    listTran.Add(transaction);
                }

                cnn.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            return(listTran);
        }
        public List <SHBTransaction> GetTransactionsByAccountNumber(string accountNumber)
        {
            List <SHBTransaction> listTransactions = new List <SHBTransaction>();
            var connection = ConnectionHelper.GetConnection();

            try
            {
                connection.Open();
                string getTransactionStringCmd =
                    $"SELECT * FROM `shb-transactions` WHERE senderAccountNumber = '{accountNumber}'";
                MySqlCommand getTransactionSqlCommand = new MySqlCommand(getTransactionStringCmd, connection);
                var          transactionReader        = getTransactionSqlCommand.ExecuteReader();
                while (transactionReader.Read())
                {
                    var shbTransaction = new SHBTransaction()
                    {
                        Code = transactionReader.GetString("code"),
                        SenderAccountNumber   = transactionReader.GetString("senderAccountNumber"),
                        ReceiverAccountNumber = transactionReader.GetString("receiverAccountNumber"),
                        Message  = transactionReader.GetString("message"),
                        Amount   = transactionReader.GetDouble("amount"),
                        Fee      = transactionReader.GetDouble("fee"),
                        CreateAt = transactionReader.GetDateTime("createAt"),
                        UpdateAt = transactionReader.GetDateTime("updateAt"),
                        Status   = (TransactionStatus)transactionReader.GetInt32("status"),
                        Type     = (TransactionType)transactionReader.GetInt32("type")
                    };
                    listTransactions.Add(shbTransaction);
                }

                connection.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("lỗi khi lấy danh sách giao dịch " + e.Message);
                connection.Close();
                return(null);
            }

            return(listTransactions);
        }
        public void ChuyenKhoan()
        {
            if (Program.currentLoggedInAccount != null)
            {
                Console.Clear();
                Console.WriteLine("Tiến hành gửi tiền tại hệ thống SHB.");
                Console.WriteLine("Vui lòng nhập số tiền cần gửi.");
                var amount = decimal.Parse(Console.ReadLine());
                if (amount <= 0)
                {
                    Console.WriteLine("Số lượng không hợp lệ, vui lòng thử lại.");
                    return;
                }

                Console.WriteLine("Nhap username nguoi nhan");
                var receiver    = Console.ReadLine();
                var transaction = new SHBTransaction
                {
                    TransactionId         = Guid.NewGuid().ToString(),
                    SenderAccountNumber   = Program.currentLoggedInAccount.UserName,
                    ReceiverAccountNumber = receiver,
                    Type         = SHBTransaction.TransactionType.TRANSFER,
                    Message      = "Tien hanh gui tien voi so tien la: " + amount,
                    Amount       = amount,
                    CreatedAtMLS = DateTime.Now.Ticks,
                    UpdatedAtMLS = DateTime.Now.Ticks,
                    Status       = SHBTransaction.TransactionStatus.DONE
                };
                bool result = shbAccountModel.Transfer(Program.currentLoggedInAccount, transaction);
                if (result)
                {
                    Console.WriteLine("Thanh cong");
                }
            }
            else
            {
                Console.WriteLine("Vui lòng đăng nhập để sử dụng chức năng này.");
            }
        }
Beispiel #14
0
        public void RutTien()
        {
            if (Program.currentLoggedInAccount != null)
            {
                Console.Clear();
                Console.WriteLine("Tiến hành rút tiền tại hệ thống SHB.");
                Console.WriteLine("Vui lòng nhập số tiền cần rút.");
                var amount = double.Parse(Console.ReadLine());

                if (amount > Program.currentLoggedInAccount.Balance)
                {
                    Console.WriteLine("Số lượng không hợp lệ, vui lòng thử lại.");
                    return;
                }

                var transaction = new SHBTransaction
                {
                    TransactionId         = Guid.NewGuid().ToString(),
                    SenderAccountNumber   = Program.currentLoggedInAccount.AccountNumber,
                    ReceiverAccountNumber = Program.currentLoggedInAccount.AccountNumber,
                    Type        = SHBTransaction.TransactionType.WITHDRAW,
                    Amount      = amount,
                    Message     = "Tiến hành rút tiền tại ATM với số tiền: " + amount,
                    CreateAtMLS = DateTime.Now.Ticks,
                    UpdateAtMLS = DateTime.Now.Ticks,
                    Status      = SHBTransaction.TransactionStatus.DONE
                };
                if (shbAccountModel.UpdateBalance(Program.currentLoggedInAccount, transaction))
                {
                    Console.WriteLine("Giao dịch thành công.");
                }
//                bool result = shbAccountModel.UpdateBalance(Program.currentLoggedInAccount, transaction);
            }
            else
            {
                Console.WriteLine("Vui lòng đăng nhập để sử dụng chức năng này.");
            }
        }
Beispiel #15
0
        // 8. Tim  lich su giao dich theo stk
        public List <SHBTransaction> TransactionHistory(string accountNumber)
        {
            List <SHBTransaction> list = new List <SHBTransaction>();
            var cnn = ConnectionHelpers.GetConnection();

            cnn.Open();
            try
            {
                var cmdStringTransactionHistory =
                    $"SELECT * FROM transactions WHERE senderAccountNumber = '{accountNumber}' OR receiverAccountNumber = '{accountNumber}'";
                var cmd    = new MySqlCommand(cmdStringTransactionHistory, cnn);
                var reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    var transactionHistory = new SHBTransaction()
                    {
                        TransactionCode       = reader.GetString("transactionCode"),
                        SenderAccountNumber   = reader.GetString("senderAccountNumber"),
                        ReceiverAccountNumber = reader.GetString("receiverAccountNumber"),
                        Type      = (TransactionType)reader.GetInt32("type"),
                        Amount    = reader.GetDouble("amount"),
                        Fee       = reader.GetDouble("fee"),
                        Message   = reader.GetString("message"),
                        CreateAt  = (DateTime)reader.GetMySqlDateTime("createAt"),
                        UpdatedAt = (DateTime)reader.GetMySqlDateTime("updatedAt"),
                        Status    = (TransactionStatus)reader.GetInt32("status"),
                    };
                    list.Add(transactionHistory);
                }
                cnn.Close();
                return(list);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Beispiel #16
0
        public void Withdraw()
        {
            if (Program.currentLoggedInAccount != null)
            {
                Console.Clear();
                Console.WriteLine("Withdraw money at the banking system SHB.");
                Console.WriteLine("Please enter the amount to withdraw: ");
                var amount = double.Parse(Console.ReadLine());

                if (amount > Program.currentLoggedInAccount.Balance)
                {
                    Console.WriteLine("Invalid amount, please check again.");
                    return;
                }

                var transaction = new SHBTransaction
                {
                    TransactionId         = Guid.NewGuid().ToString(),
                    SenderAccountNumber   = Program.currentLoggedInAccount.AccountNumber,
                    ReceiverAccountNumber = Program.currentLoggedInAccount.AccountNumber,
                    Type        = SHBTransaction.TransactionType.WITHDRAW,
                    Amount      = amount,
                    Message     = "withdraw money at ATM SHB with money: " + amount,
                    CreateAtMLS = DateTime.Now.Ticks,
                    UpdateAtMLS = DateTime.Now.Ticks,
                    Status      = SHBTransaction.TransactionStatus.DONE
                };
                if (shbAccountModel.UpdateBalance(Program.currentLoggedInAccount, transaction))
                {
                    Console.WriteLine("Successful transaction.");
                }
//                bool result = shbAccountModel.UpdateBalance(Program.currentLoggedInAccount, transaction);
            }
            else
            {
                Console.WriteLine("Please login to use this function.");
            }
        }
Beispiel #17
0
        public bool UpdateBalance(SHBAccount currentLoggedInAccount, SHBTransaction transaction)
        {
            ConnectionHelper.OpenConnection();
            MySqlConnection mySqlConnection;
            var             tran = ConnectionHelper.OpenConnection().BeginTransaction();

            try
            {
                var cmd = new MySqlCommand("select * from account where username = @username",
                                           ConnectionHelper.OpenConnection());
                cmd.Parameters.AddWithValue("@Username", currentLoggedInAccount.AccountNumber);
                SHBAccount shbAccount            = null;
                var        reader                = cmd.ExecuteReader();
                double     currentAccountBalance = 0;

                if (reader.Read())
                {
                    currentAccountBalance = reader.GetDouble("balance");
                }

                reader.Close();
                if (currentAccountBalance < 0)
                {
                    Console.WriteLine("You have not enough money");
                    return(false);
                }

                if (transaction.Type == 1)
                {
                    if (currentAccountBalance < transaction.Amount)
                    {
                        Console.WriteLine("Not enough money");
                        return(false);
                    }
                    currentAccountBalance -= transaction.Amount;
                }
                else if (transaction.Type == 2)
                {
                    currentAccountBalance += transaction.Amount;
                }

                var updateQuery =
                    "update `account` set `balance` = @balance where accountId = @accountId";
                var sqlCmd = new MySqlCommand(updateQuery, ConnectionHelper.OpenConnection());
                sqlCmd.Parameters.AddWithValue("@balance", currentAccountBalance);
                sqlCmd.Parameters.AddWithValue("@accountId", currentLoggedInAccount.AccountNumber);
                var updateResult            = sqlCmd.ExecuteNonQuery();
                var historyTransactionQuery =
                    "insert into `SHB` (transactionId, type, senderId, receiverId, amount, message) " +
                    "values (@transactionId, @type, @senderId, @receiverId, @amount, @message)";
                var historyTransactionCmd =
                    new MySqlCommand(historyTransactionQuery, ConnectionHelper.OpenConnection());
                historyTransactionCmd.Parameters.AddWithValue("@transactionId", transaction.TransactionId);
                historyTransactionCmd.Parameters.AddWithValue("@amount", transaction.Amount);
                historyTransactionCmd.Parameters.AddWithValue("@type", transaction.Type);
                historyTransactionCmd.Parameters.AddWithValue("@message", transaction.Message);
                historyTransactionCmd.Parameters.AddWithValue("@senderId",
                                                              transaction.SenderAccountId);
                historyTransactionCmd.Parameters.AddWithValue("@receiverId",
                                                              transaction.ReceiverAccountId);
                var historyResult = historyTransactionCmd.ExecuteNonQuery();

                if (updateResult != 1 || historyResult != 1)
                {
                    throw new Exception("Can not transaction or update your account");
                }

                tran.Commit();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                tran.Rollback();
                return(false);
            }

            ConnectionHelper.CloseConnection();
            return(true);
        }
Beispiel #18
0
        // 2. Rút tiền
        public bool Withdraw(string accountNumber, double amount)
        {
            var cnn = ConnectionHelpers.GetConnection();

            cnn.Open();
            var transaction = cnn.BeginTransaction();

            try
            {
                if (amount <= 0)
                {
                    throw new Exception("Giá trị không hợp !");
                }
                var stringCmdGetAccount =
                    $"SELECT balance FROM `accounts` WHERE accountNumber = '{accountNumber}' AND status = {(int) AccountStatus.ACTIVE}";
                var cmdGetAccount = new MySqlCommand(stringCmdGetAccount, cnn);
                var accountReader = cmdGetAccount.ExecuteReader();
                if (!accountReader.Read())
                {
                    throw new Exception("Không tìm thấy tài khoản hoặc tài khoản đã bị khóa!");
                }
                var currentBalance = accountReader.GetDouble("balance");
                accountReader.Close();

                // check balance
                if (currentBalance < amount + 50000)
                {
                    Console.WriteLine("Số dư tài khoản không đủ!");
                    cnn.Close();
                    return(false);
                }

                currentBalance -= amount;
                var stringCmdUpdateAccount =
                    $"UPDATE `accounts` SET balance = '{currentBalance}' WHERE accountNumber = '{accountNumber}' AND status = 1";
                var cmdUpdateAccount = new MySqlCommand(stringCmdUpdateAccount, cnn);
                cmdUpdateAccount.ExecuteNonQuery();
                var shbtransaction = new SHBTransaction()
                {
                    TransactionCode       = Guid.NewGuid().ToString(),
                    SenderAccountNumber   = accountNumber,
                    ReceiverAccountNumber = accountNumber,
                    Type      = TransactionType.DEPOSIT,
                    Amount    = amount,
                    Fee       = 0,
                    Message   = "Withdraw: " + amount,
                    CreateAt  = DateTime.Now,
                    UpdatedAt = DateTime.Now,
                    Status    = TransactionStatus.DONE
                };
                var stringCmdInsertTransaction = $"INSERT INTO `transactions`(`transactionCode`, `senderAccountNumber`, `receiverAccountNumber`, " +
                                                 $"`type`, `amount`, `fee`, `message`, `createAt`, `updatedAt`, `status`) " +
                                                 $"VALUES ('{shbtransaction.TransactionCode}', '{shbtransaction.SenderAccountNumber}', " +
                                                 $"'{shbtransaction.ReceiverAccountNumber}', {(int)shbtransaction.Type}," +
                                                 $"{shbtransaction.Amount}, {shbtransaction.Fee}, '{shbtransaction.Message}', " +
                                                 $"'{shbtransaction.CreateAt:yyyy-MM-dd hh:mm:ss}', '{shbtransaction.UpdatedAt: yyyy-MM-dd hh:mm:ss}'," +
                                                 $"{(int)shbtransaction.Status})";
                var cmdInsertTransaction = new MySqlCommand(stringCmdInsertTransaction, cnn);
                cmdInsertTransaction.ExecuteNonQuery();
                transaction.Commit();
                cnn.Close();
                Console.WriteLine($"Rút {amount} thành công!");
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                transaction.Rollback();
                cnn.Close();
            }
            return(false);
        }
Beispiel #19
0
        public bool Transfer(string senderAccountNumber, string receiverAccountNumber, double amount)
        {
            double minBalance = 50000.0;
            //1. Open connection
            var connection = ConnectionHelper.GetConnection();

            //check connection (hot fix)
            if (ConnectionHelper.IsConnectionSuccess() == false)
            {
                return(false);
            }
            var transaction = connection.BeginTransaction();

            try
            {
                //. get balacne of the sender
                string getSenderBalanceStringCmd =
                    $"SELECT balance from `accounts` WHERE accountNumber = {senderAccountNumber} and status = {(int) AccountStatus.ACTIVE};";
                var getSenderBalanceSqlCmd = new MySqlCommand(getSenderBalanceStringCmd, connection);
                var senderBalanceReader    = getSenderBalanceSqlCmd.ExecuteReader();
                if (!senderBalanceReader.Read())
                {
                    senderBalanceReader.Close();
                    throw new Exception("Tài khoản người gửi không tồn tại hoặc đã bị khóa");
                }

                var senderBalance = senderBalanceReader.GetDouble("balance");
                //close reader
                senderBalanceReader.Close();
                //. get balacne of the receiver
                string getReceiverBalanceStringCmd =
                    $"SELECT balance from `accounts` WHERE accountNumber = {receiverAccountNumber} and status = {(int) AccountStatus.ACTIVE};";
                var getReceiverBalanceSqlCmd = new MySqlCommand(getReceiverBalanceStringCmd, connection);
                var receiverBalanceReader    = getReceiverBalanceSqlCmd.ExecuteReader();
                if (!receiverBalanceReader.Read())
                {
                    receiverBalanceReader.Close();
                    throw new Exception("Tài khoản người nhận không tồn tại hoặc đã bị khóa");
                }

                var receiverBalance = receiverBalanceReader.GetDouble("balance");
                //close reader
                receiverBalanceReader.Close();
                //khởi tạo transaction với trạng thái penđing
                var shbTransactionCode = Guid.NewGuid().ToString();
                var shbTransaction     = new SHBTransaction()
                {
                    Code = shbTransactionCode,
                    SenderAccountNumber   = senderAccountNumber,
                    ReceiverAccountNumber = receiverAccountNumber,
                    Type     = TransactionType.TRANSFER,
                    Amount   = amount,
                    Fee      = 1100,
                    Message  = "Transer " + amount,
                    CreateAt = DateTime.Now,
                    UpdateAt = DateTime.Now,
                    Status   = TransactionStatus.PENDING
                };
                //lưu transaction pending vào database
                string insertShbTransactionStringCmd =
                    $"INSERT INTO `shb-transactions` VAlUES ('{shbTransaction.Code}','{shbTransaction.SenderAccountNumber}','{shbTransaction.ReceiverAccountNumber}','{shbTransaction.Message}',{shbTransaction.Amount},{shbTransaction.Fee},'{shbTransaction.CreateAt:yyyy-MM-dd hh:mm:ss}','{shbTransaction.UpdateAt:yyyy-MM-dd hh:mm:ss}',{(int) shbTransaction.Status},{(int) shbTransaction.Type});";
                var insertShbTransactionCmd = new MySqlCommand(insertShbTransactionStringCmd, connection);
                insertShbTransactionCmd.ExecuteNonQuery();
                //update số dư của ng nhận và ng gửi
                senderBalance   = senderBalance - amount - shbTransaction.Fee;
                receiverBalance = receiverBalance + amount;
                if (senderBalance < minBalance)
                {
                    //update transaction status to failed -> commit dabatabase -> return false
                    var updateTime = DateTime.Now;
                    var updateTransactionFailStringCmd =
                        $"UPDATE `shb-transactions` SET status =' {(int) TransactionStatus.FAILED}', updateAt = '{updateTime:yyyy-MM-dd hh:mm:ss}' WHERE code = '{shbTransactionCode}'";
                    var updateTransactionFailCmd = new MySqlCommand(updateTransactionFailStringCmd, connection);
                    var updatedRow = updateTransactionFailCmd.ExecuteNonQuery();
                    if (updatedRow == 0)
                    {
                        throw new Exception("Cập nhật transaction thất bại");
                    }

                    //commit and close connection
                    transaction.Commit();
                    connection.Close();
                    Console.WriteLine("Số dư tài khoản không đủ để thực hiện giao địch");
                    return(false);
                }

                //update số dư của ng gửi và nhận trong database
                //ng gửi
                var updateSenderBalanceStringCmd =
                    $"UPDATE accounts SET balance = {senderBalance} WHERE accountNumber = '{senderAccountNumber}';";
                var updateSenderBalanceSqlCmd = new MySqlCommand(updateSenderBalanceStringCmd, connection);
                int updatedSenderRecord       = updateSenderBalanceSqlCmd.ExecuteNonQuery();
                if (updatedSenderRecord == 0)
                {
                    throw new Exception("cập nhật số dư mới cho người gửi thất bại");
                }

                //ng nhận
                var updateReceiverBalanceStringCmd =
                    $"UPDATE accounts SET balance = {receiverBalance} WHERE accountNumber = '{receiverAccountNumber}';";
                var updateReceiverBalanceSqlCmd = new MySqlCommand(updateReceiverBalanceStringCmd, connection);
                int updatedReceiverRecord       = updateReceiverBalanceSqlCmd.ExecuteNonQuery();
                if (updatedReceiverRecord == 0)
                {
                    throw new Exception("cập nhật số dư mới cho người nhận thất bại");
                }

                //update trạng thái transaction pending -> done
                var    updateDoneTime = DateTime.Now;
                string updateShbTransactionStatusCmdString =
                    $"UPDATE `shb-transactions` SET status = {(int) TransactionStatus.DONE}, updateAt = '{updateDoneTime:yyyy-MM-dd hh:mm:ss}' WHERE code = '{shbTransactionCode}'";
                var updateShbTransactionStatusCmd =
                    new MySqlCommand(updateShbTransactionStatusCmdString, connection);
                var transactionUpdated = updateShbTransactionStatusCmd.ExecuteNonQuery();
                if (transactionUpdated == 0)
                {
                    throw new Exception("Cập nhật lịch sử giao dịch thất bại");
                }

                //commit -> close -> return
                transaction.Commit();
                connection.Close();
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine("Chuyển khoản thất bại " + e.Message);
                //roll back if an error occured in try block
                transaction.Rollback();
                connection.Close();
                return(false);
            }
        }
Beispiel #20
0
        // 1. Gui tien
        public bool Deposit(string accountNumber, double amount)
        {
            var cnn = ConnectionHelpers.GetConnection();

            cnn.Open();
            var transaction = cnn.BeginTransaction();

            try
            {
                if (amount <= 0)
                {
                    throw new Exception("Giá trị không hợp lệ");
                }

                var stringCmdGetAccount = $"select balance from `accounts` where accountNumber = '{accountNumber}'" +
                                          $"and status = 1";
                var cmdGetAccount = new MySqlCommand(stringCmdGetAccount, cnn);
                var accountReader = cmdGetAccount.ExecuteReader();
                if (!accountReader.Read())
                {
                    throw new Exception("Không tìm thấy tài khoản hoặc tài khoản đã bị khóa!");
                }

                var currentBalance = accountReader.GetDouble("balance");
                accountReader.Close();
                currentBalance += amount;
                var stringCmdUpdateAccount = $"update `accounts` set balance = {currentBalance} where " +
                                             $"accountNumber = '{accountNumber}' and status = 1";
                var cmdUpdateAccount = new MySqlCommand(stringCmdUpdateAccount, cnn);
                cmdUpdateAccount.ExecuteNonQuery();

                var shbTransaction = new SHBTransaction()
                {
                    TransactionCode       = Guid.NewGuid().ToString(),
                    SenderAccountNumber   = accountNumber,
                    ReceiverAccountNumber = accountNumber,
                    Type      = TransactionType.DEPOSIT,
                    Amount    = amount,
                    Fee       = 0,
                    Message   = "Deposit " + amount,
                    CreateAt  = DateTime.Now,
                    UpdatedAt = DateTime.Now,
                    Status    = TransactionStatus.DONE
                };

                var stringCmdInsertTransaction =
                    $"INSERT INTO `transactions`(`transactionCode`, `senderAccountNumber`, `receiverAccountNumber`, " +
                    $"`type`, `amount`, `fee`, `message`, `createAt`, `updatedAt`, `status`) " +
                    $"VALUES ('{shbTransaction.TransactionCode}', '{shbTransaction.SenderAccountNumber}', " +
                    $"'{shbTransaction.ReceiverAccountNumber}', {(int)shbTransaction.Type}," +
                    $"{shbTransaction.Amount}, {shbTransaction.Fee}, '{shbTransaction.Message}', " +
                    $"'{shbTransaction.CreateAt:yyyy-MM-dd hh:mm:ss}', '{shbTransaction.UpdatedAt: yyyy-MM-dd hh:mm:ss}'," +
                    $"{(int)shbTransaction.Status})";
                var cmdInsertTransaction = new MySqlCommand(stringCmdInsertTransaction, cnn);
                cmdInsertTransaction.ExecuteNonQuery();
                transaction.Commit();
                cnn.Close();
                Console.WriteLine("Gửi tiền vào tài khoản thành công!");
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                transaction.Rollback();
                cnn.Close();
            }
            return(false);
        }
        public bool Transfer(SHBAccount currentLoggedInAccount, SHBTransaction transactionHistory)
        {
            ConnectionHelper.CloseConnect();
            var mySqlTransaction = ConnectionHelper.GetConnect().BeginTransaction();

            try
            {
                var selectBalance =
                    "select balance from `accounts` where username = @username";
                var cmdSelect = new MySqlCommand(selectBalance, ConnectionHelper.GetConnect());
                cmdSelect.Parameters.AddWithValue("@username", currentLoggedInAccount.UserName);
                var     reader = cmdSelect.ExecuteReader();
                decimal currentAccountBalance = 0;
                if (reader.Read())
                {
                    currentAccountBalance = reader.GetDecimal("balance");
                }

                reader.Close();
                if (currentAccountBalance < transactionHistory.Amount)
                {
                    throw new Exception("Không đủ tiền trong tài khoản.");
                }

                currentAccountBalance -= transactionHistory.Amount;
                var updateQuery =
                    "update `accounts` set `balance` = @balance where username = @username";
                var sqlCmd = new MySqlCommand(updateQuery, ConnectionHelper.GetConnect());
                sqlCmd.Parameters.AddWithValue("@balance", currentAccountBalance);
                sqlCmd.Parameters.AddWithValue("@username", currentLoggedInAccount.UserName);
                var updateResult          = sqlCmd.ExecuteNonQuery();
                var selectBalanceReceiver =
                    "select balance from `accounts` where username = @username";
                var cmdSelectReceiver = new MySqlCommand(selectBalanceReceiver, ConnectionHelper.GetConnect());
                cmdSelectReceiver.Parameters.AddWithValue("@username", transactionHistory.ReceiverAccountNumber);
                var     readerReceiver  = cmdSelectReceiver.ExecuteReader();
                decimal receiverBalance = 0;
                if (readerReceiver.Read())
                {
                    receiverBalance = readerReceiver.GetDecimal("balance");
                }

                readerReceiver.Close();
                receiverBalance += transactionHistory.Amount;
                var updateQueryReceiver =
                    "update `accounts` set `balance` = @balance where username = @username";
                var sqlCmdReceiver = new MySqlCommand(updateQueryReceiver, ConnectionHelper.GetConnect());
                sqlCmdReceiver.Parameters.AddWithValue("@balance", receiverBalance);
                sqlCmdReceiver.Parameters.AddWithValue("@username", transactionHistory.ReceiverAccountNumber);
                var updateResultReceiver    = sqlCmdReceiver.ExecuteNonQuery();
                var historyTransactionQuery =
                    "insert into `transactions` (id, type, senderId, receiverId, amount, message) " +
                    "values (@id, @type, @senderAccountNumber, @receiverAccountNumber, @amount, @message)";
                var historyTransactionCmd =
                    new MySqlCommand(historyTransactionQuery, ConnectionHelper.GetConnect());
                historyTransactionCmd.Parameters.AddWithValue("@id", transactionHistory.TransactionId);
                historyTransactionCmd.Parameters.AddWithValue("@amount", transactionHistory.Amount);
                historyTransactionCmd.Parameters.AddWithValue("@type", transactionHistory.Type);
                historyTransactionCmd.Parameters.AddWithValue("@message", transactionHistory.Message);
                historyTransactionCmd.Parameters.AddWithValue("@senderAccountNumber",
                                                              transactionHistory.SenderAccountNumber);
                historyTransactionCmd.Parameters.AddWithValue("@receiverAccountNumber",
                                                              transactionHistory.ReceiverAccountNumber);
                var historyResult = historyTransactionCmd.ExecuteNonQuery();

                if (updateResult != 1 || historyResult != 1 || updateResultReceiver != 1)
                {
                    throw new Exception("Không thể thêm giao dịch hoặc update tài khoản.");
                }

                mySqlTransaction.Commit();
                return(true);
            }
            catch (Exception e)
            {
                mySqlTransaction.Rollback();
                return(false);
            }
            finally
            {
                ConnectionHelper.CloseConnect();
            }
        }
        public bool UpdateBalance(SHBAccount currentLoggedInAccount, SHBTransaction transaction)
        {
            ConnectionHelper.CloseConnect();
            var tran = ConnectionHelper.GetConnect().BeginTransaction();

            try
            {
                var cmd = new MySqlCommand("select * from accounts where username = @Username",
                                           ConnectionHelper.GetConnect());
                cmd.Parameters.AddWithValue("@Username", currentLoggedInAccount.UserName);
                SHBAccount shbAccount            = null;
                var        reader                = cmd.ExecuteReader();
                decimal    currentAccountBalance = 0;

                if (reader.Read())
                {
                    currentAccountBalance = reader.GetDecimal("balance");
                }

                reader.Close();
                if (currentAccountBalance < 0)
                {
                    Console.WriteLine("Không đủ tiền trong tài khoản.");
                    return(false);
                }

                if (transaction.Type == SHBTransaction.TransactionType.WITHDRAW)
                {
                    if (currentAccountBalance < transaction.Amount)
                    {
                        Console.WriteLine("Khong du tien thuc hien giao dich");
                        return(false);
                    }

                    currentAccountBalance -= transaction.Amount;
                }
                else if (transaction.Type == SHBTransaction.TransactionType.DEPOSIT)
                {
                    currentAccountBalance += transaction.Amount;
                }

                var updateQuery =
                    "update `accounts` set `balance` = @balance where username = @username";
                var sqlCmd = new MySqlCommand(updateQuery, ConnectionHelper.GetConnect());
                sqlCmd.Parameters.AddWithValue("@balance", currentAccountBalance);
                sqlCmd.Parameters.AddWithValue("@username", currentLoggedInAccount.UserName);
                var updateResult            = sqlCmd.ExecuteNonQuery();
                var historyTransactionQuery =
                    "insert into `transactions` (id, type, senderId, receiverId, amount, message) " +
                    "values (@id, @type, @senderAccountNumber, @receiverAccountNumber, @amount, @message)";
                var historyTransactionCmd =
                    new MySqlCommand(historyTransactionQuery, ConnectionHelper.GetConnect());
                historyTransactionCmd.Parameters.AddWithValue("@id", transaction.TransactionId);
                historyTransactionCmd.Parameters.AddWithValue("@amount", transaction.Amount);
                historyTransactionCmd.Parameters.AddWithValue("@type", transaction.Type);
                historyTransactionCmd.Parameters.AddWithValue("@message", transaction.Message);
                historyTransactionCmd.Parameters.AddWithValue("@senderAccountNumber",
                                                              transaction.SenderAccountNumber);
                historyTransactionCmd.Parameters.AddWithValue("@receiverAccountNumber",
                                                              transaction.ReceiverAccountNumber);
                var historyResult = historyTransactionCmd.ExecuteNonQuery();

                if (updateResult != 1 || historyResult != 1)
                {
                    throw new Exception("Không thể thêm giao dịch hoặc update tài khoản.");
                }

                tran.Commit();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                tran.Rollback();
                return(false);
            }

            ConnectionHelper.CloseConnect();
            return(true);
        }
Beispiel #23
0
        public bool Tranfer(SHBAccount currentLoggedInAccount, SHBTransaction shbTransaction)
        {
            var conn = ConnectionHelper.GetConnection();

            var myTransaction = conn.BeginTransaction();

            try
            {
                var balanceSender = new MySqlCommand("select * from accounts where AccountNumber = @AccountNumber ",
                                                     conn);
                balanceSender.Parameters.AddWithValue("@AccountNumber", currentLoggedInAccount.AccountNumber);
                double currentAccountBalance = 0;
                var    reader = balanceSender.ExecuteReader();
                if (reader.Read())
                {
                    currentAccountBalance = reader.GetDouble("Balance");
                }

                reader.Close();
                if (shbTransaction.Type == SHBTransaction.TransactionType.TRANFER &&
                    currentAccountBalance < shbTransaction.Amount)
                {
                    throw new Exception("Không đủ tiền trong tài khoản.");
                }

                currentAccountBalance -= shbTransaction.Amount;


                var updateQuery = ("update accounts set Balance = @balance where AccountNumber = @AccountNumber");
                var sqlCmd      = new MySqlCommand(updateQuery, conn);
                sqlCmd.Parameters.AddWithValue("@balance", currentAccountBalance);
                sqlCmd.Parameters.AddWithValue("@AccountNumber", currentLoggedInAccount.AccountNumber);
                var updateRs = sqlCmd.ExecuteNonQuery();

                var balanceReceiver = new MySqlCommand("select * from accounts where AccountNumber = @AccountNumber ",
                                                       conn);
                balanceReceiver.Parameters.AddWithValue("@AccountNumber", shbTransaction.ReceiverAccountNumber);
                double receiverBalance = 0;
                var    readerReceiver  = balanceReceiver.ExecuteReader();
                if (readerReceiver.Read())
                {
                    receiverBalance = readerReceiver.GetDouble("balance");
                }

                readerReceiver.Close();

                receiverBalance += shbTransaction.Amount;


                var updateQueryReceiver =
                    ("update accounts set Balance = @balance where AccountNumber = @AccountNumber");
                var sqlCmdReceiver = new MySqlCommand(updateQueryReceiver, conn);
                sqlCmdReceiver.Parameters.AddWithValue("@balance", receiverBalance);
                sqlCmdReceiver.Parameters.AddWithValue("@AccountNumber", shbTransaction.ReceiverAccountNumber);
                var updateResultReceiver = sqlCmdReceiver.ExecuteNonQuery();

                var historyTransactionQuery =
                    "insert into shbtransaction (transaction_id, type, sender_account_number, receiver_account_number, amount, message, createdAt, updatedAt, status) " +
                    "values (@id, @type, @senderAccountNumber, @receiverAccountNumber, @amount, @message, @createdAtMLS, @updatedAtMLS, @status)";
                var historyTransactionCmd =
                    new MySqlCommand(historyTransactionQuery, conn);
                historyTransactionCmd.Parameters.AddWithValue("@id", shbTransaction.TransactionId);
                historyTransactionCmd.Parameters.AddWithValue("@type", shbTransaction.Type);
                historyTransactionCmd.Parameters.AddWithValue("@senderAccountNumber",
                                                              shbTransaction.SenderAccountNumber);
                historyTransactionCmd.Parameters.AddWithValue("@receiverAccountNumber",
                                                              shbTransaction.ReceiverAccountNumber);
                historyTransactionCmd.Parameters.AddWithValue("@amount", shbTransaction.Amount);
                historyTransactionCmd.Parameters.AddWithValue("@message", shbTransaction.Message);
                historyTransactionCmd.Parameters.AddWithValue("@createdAtMLS", shbTransaction.CreatedAtMLS);
                historyTransactionCmd.Parameters.AddWithValue("@updatedAtMLS", shbTransaction.UpdatedAtMLS);
                historyTransactionCmd.Parameters.AddWithValue("@status", shbTransaction.Status);
                var historyResult = historyTransactionCmd.ExecuteNonQuery();

                if (updateRs != 1 || historyResult != 1 || updateResultReceiver != 1)
                {
                    throw new Exception("Không thể thêm giao dịch hoặc update tài khoản.");
                }

                myTransaction.Commit();
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                myTransaction.Rollback();
                return(false);
            }
            finally
            {
                conn.Close();
            }
        }
Beispiel #24
0
        public bool UpdateBalance(SHBAccount currentLoggedInAccount, SHBTransaction transaction)
        {
            var trans = ConnectionHelper.GetConnection().BeginTransaction();

            try
            {
                var cmd = new MySqlCommand("select * from accounts where Username = @username ",
                                           ConnectionHelper.GetConnection());
                cmd.Parameters.AddWithValue("@username", currentLoggedInAccount.Username);
                double currentAccountBalance = 0;
                var    reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    currentAccountBalance = reader.GetDouble("Balance");
                }

                reader.Close();

                if (transaction.Type == SHBTransaction.TransactionType.WITHDRAW &&
                    currentAccountBalance < transaction.Amount)
                {
                    throw new Exception("Không đủ tiền trong tài khoản.");
                }

                if (transaction.Type == SHBTransaction.TransactionType.WITHDRAW)
                {
                    currentAccountBalance -= transaction.Amount;
                }
                else if (transaction.Type == SHBTransaction.TransactionType.DEPOSIT)
                {
                    currentAccountBalance += transaction.Amount;
                }

                var updateQuery = ("update accounts set Balance = @balance where Username = @username");
                var sqlCmd      = new MySqlCommand(updateQuery, ConnectionHelper.GetConnection());
                sqlCmd.Parameters.AddWithValue("@balance", currentAccountBalance);
                sqlCmd.Parameters.AddWithValue("@username", currentLoggedInAccount.Username);
                var updateRs = sqlCmd.ExecuteNonQuery();

                var transactionQuery =
                    "insert into shbtransaction (transaction_id, type, sender_account_number, receiver_account_number, amount, message, createdAt, updatedAt, status) " +
                    "values (@id, @type, @senderAccountNumber, @receiverAccountNumber, @amount, @message, @createdAtMLS, @updatedAtMLS, @status)";
                var historyTransactionCmd =
                    new MySqlCommand(transactionQuery, ConnectionHelper.GetConnection());
                historyTransactionCmd.Parameters.AddWithValue("@id", transaction.TransactionId);
                historyTransactionCmd.Parameters.AddWithValue("@type", transaction.Type);
                historyTransactionCmd.Parameters.AddWithValue("@senderAccountNumber",
                                                              transaction.SenderAccountNumber);
                historyTransactionCmd.Parameters.AddWithValue("@receiverAccountNumber",
                                                              transaction.ReceiverAccountNumber);
                historyTransactionCmd.Parameters.AddWithValue("@amount", transaction.Amount);
                historyTransactionCmd.Parameters.AddWithValue("@message", transaction.Message);
                historyTransactionCmd.Parameters.AddWithValue("@createdAtMLS", transaction.CreatedAtMLS);
                historyTransactionCmd.Parameters.AddWithValue("@updatedAtMLS", transaction.UpdatedAtMLS);
                historyTransactionCmd.Parameters.AddWithValue("@status", transaction.Status);
                var historyResult = historyTransactionCmd.ExecuteNonQuery();
                Console.WriteLine("query status: " + historyResult);

                if (updateRs != 1 || historyResult != 1)
                {
                    throw new Exception("Không thể thêm giao dịch hoặc update tài khoản.");
                }

                trans.Commit();
            }
            catch (Exception e)
            {
                Console.WriteLine("Err: " + e.Message);
                try
                {
                    trans.Rollback();
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                    throw;
                }

                return(false);
            }

            ConnectionHelper.CloseConnection();
            return(true);
        }
Beispiel #25
0
        public bool Deposit(string accountNumber, double amount)
        {
            //amount da dc validate > 0 o controller
            var cnn = ConnectionHelper.GetConnection();

            //check connection (hot fix)
            if (ConnectionHelper.IsConnectionSuccess() == false)
            {
                return(false);
            }
            var transaction = cnn.BeginTransaction();

            try
            {
                var stringCmdGetAccount =
                    $"SELECT balance from `accounts` WHERE accountNumber = {accountNumber} and status = {(int) AccountStatus.ACTIVE};";
                var cmdGetAccount = new MySqlCommand(stringCmdGetAccount, cnn);
                var accountReader = cmdGetAccount.ExecuteReader();
                if (!accountReader.Read())
                {
                    accountReader.Close();
                    throw new Exception("Tài khoản không tồn tại hoặc đã bị xóa");
                }

                var currentBalence = accountReader.GetDouble("balance");
                accountReader.Close();
                //khởi tạo transaction với trạng thái penđing
                var shbTransactionCode = Guid.NewGuid().ToString();
                var shbTransaction     = new SHBTransaction()
                {
                    Code = shbTransactionCode,
                    SenderAccountNumber   = accountNumber,
                    ReceiverAccountNumber = accountNumber,
                    Type     = TransactionType.DEPOSIT,
                    Amount   = amount,
                    Fee      = 1100,
                    Message  = "Deposit" + amount,
                    CreateAt = DateTime.Now,
                    UpdateAt = DateTime.Now,
                    Status   = TransactionStatus.PENDING
                };
                //lưu transaction pending vào database
                string insertShbTransactionStringCmd =
                    $"INSERT INTO `shb-transactions` VAlUES ('{shbTransaction.Code}','{shbTransaction.SenderAccountNumber}','{shbTransaction.ReceiverAccountNumber}','{shbTransaction.Message}',{shbTransaction.Amount},{shbTransaction.Fee},'{shbTransaction.CreateAt:yyyy-MM-dd hh:mm:ss}','{shbTransaction.UpdateAt:yyyy-MM-dd hh:mm:ss}',{(int) shbTransaction.Status},{(int) shbTransaction.Type}) ";
                var insertShbTransactionCmd = new MySqlCommand(insertShbTransactionStringCmd, cnn);
                insertShbTransactionCmd.ExecuteNonQuery();
                //update so du moi
                currentBalence = currentBalence + amount - shbTransaction.Fee;

                var updateBalanceStringCmd =
                    $"UPDATE accounts SET balance = {currentBalence} WHERE accountNumber = '{accountNumber}'";
                var updateBalanceCmd = new MySqlCommand(updateBalanceStringCmd, cnn);
                int affectedRecord   = updateBalanceCmd.ExecuteNonQuery();
                if (affectedRecord == 0)
                {
                    throw new Exception("cập nhật số dư mới thất bại");
                }

                //update trạng thái transaction pending -> done
                var    updateTime = DateTime.Now;
                string updateShbTransactionStatusCmdString =
                    $"UPDATE `shb-transactions` SET status = {(int) TransactionStatus.DONE}, updateAt = '{updateTime:yyyy-MM-dd hh:mm:ss}' WHERE code = '{shbTransactionCode}'";
                var updateShbTransactionStatusCmd = new MySqlCommand(updateShbTransactionStatusCmdString, cnn);
                var updated = updateShbTransactionStatusCmd.ExecuteNonQuery();
                if (updated == 0)
                {
                    throw new Exception("Cập nhật lịch sử giao dịch thất bại");
                }

                //commmit transaction -> close connection -> return fuction
                transaction.Commit();
                cnn.Close();
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine("gửi tiền thất bại " + e.Message);
                Console.WriteLine(e);
                transaction.Rollback();
                cnn.Close();
                return(false);
            }
        }
        public bool Transfer(SHBAccount currentLoggedInAccount, SHBTransaction transaction)
        {
            ConnectionHelper.GetConnection();
            var transaction1 = ConnectionHelper.GetConnection().BeginTransaction(); // mở giao dịch.

            try
            {
                // Kiểm tra số dư tài khoản.
                var selectBalance =
                    "select balance from SHBAccount where accountNumber = @accountNumber";
                var cmdSelect = new MySqlCommand(selectBalance, ConnectionHelper.GetConnection());
                cmdSelect.Parameters.AddWithValue("@accountNumber", currentLoggedInAccount.AccountNumber);
                var    dataReader            = cmdSelect.ExecuteReader();
                double currentAccountBalance = 0;
                if (dataReader.Read())
                {
                    currentAccountBalance = dataReader.GetDouble("balance");
                }

                dataReader.Close();

                if (currentAccountBalance < transaction.Amount)
                {
                    throw new Exception("Không đủ tiền trong tài khoản.");
                }

                currentAccountBalance -= transaction.Amount;
                //Tiến hành trừ tiền tài khoản gửi.



                // Update tài khoản.

                var updateQuery =
                    "update `SHBAccount` set `balance` = @balance where accountNumber = @accountNumber";
                var sqlCmd = new MySqlCommand(updateQuery, ConnectionHelper.GetConnection());
                sqlCmd.Parameters.AddWithValue("@balance", currentAccountBalance);
                sqlCmd.Parameters.AddWithValue("@accountNumber", currentLoggedInAccount.AccountNumber);
                var updateResult = sqlCmd.ExecuteNonQuery();

                // Kiểm tra số dư tài khoản.
                var selectBalanceReceiver =
                    "select balance from `SHBAccount` where accountNumber = @accountNumber";
                var cmdSelectReceiver = new MySqlCommand(selectBalanceReceiver, ConnectionHelper.GetConnection());
                cmdSelectReceiver.Parameters.AddWithValue("@accountNumber", transaction.ReceiverAccountNumber);
                var    readerReceiver  = cmdSelectReceiver.ExecuteReader();
                double receiverBalance = 0;
                if (readerReceiver.Read())
                {
                    receiverBalance = readerReceiver.GetDouble("balance");
                }

                readerReceiver.Close(); // important.
                //Tiến hành cộng tiền tài khoản nhận.
                receiverBalance += transaction.Amount;

                // Update tài khoản.
                var updateQueryReceiver =
                    "update `SHBAccount` set `balance` = @balance where accountNumber = @accountNumber";
                var sqlCmdReceiver = new MySqlCommand(updateQueryReceiver, ConnectionHelper.GetConnection());
                sqlCmdReceiver.Parameters.AddWithValue("@balance", receiverBalance);
                sqlCmdReceiver.Parameters.AddWithValue("@accountNumber", transaction.ReceiverAccountNumber);
                var updateResultReceiver = sqlCmdReceiver.ExecuteNonQuery();

                // Lưu lịch sử giao dịch.
                var historyTransactionQuery =
                    "insert into `SHBTransaction` (transactionId, amount, type, message, senderAccountNumber, receiverAccountNumber) " +
                    "values (@transactionId, @amount, @type, @message, @senderAccountNumber, @receiverAccountNumber)";
                var historyTransactionCmd =
                    new MySqlCommand(historyTransactionQuery, ConnectionHelper.GetConnection());
                historyTransactionCmd.Parameters.AddWithValue("@transactionId", transaction.TransactionId);
                historyTransactionCmd.Parameters.AddWithValue("@amount", transaction.Amount);
                historyTransactionCmd.Parameters.AddWithValue("@type", transaction.Type);
                historyTransactionCmd.Parameters.AddWithValue("@message", transaction.Message);
                historyTransactionCmd.Parameters.AddWithValue("@senderAccountNumber",
                                                              transaction.SenderAccountNumber);
                historyTransactionCmd.Parameters.AddWithValue("@receiverAccountNumber",
                                                              transaction.ReceiverAccountNumber);
                var historyResult = historyTransactionCmd.ExecuteNonQuery();

                if (updateResult != 1 || historyResult != 1 || updateResultReceiver != 1)
                {
                    throw new Exception("Không thể thêm giao dịch hoặc update tài khoản.");
                }

                transaction1.Commit();
                return(true);
            }
            catch (Exception e)
            {
                transaction1.Rollback();
                Console.WriteLine(e.StackTrace);
                Console.WriteLine(e.Message);
                Console.WriteLine(e.Source);
                Console.WriteLine(e.ToString());
                return(false);
            }
            finally
            {
                ConnectionHelper.CloseConnection();
            }
        }
        public void GuiTien()
        {
            if (Program.currentLoggedInAccount != null)
            {
                Console.Clear();
                Console.WriteLine("Tiến hành gửi tiền ở Hệ thống Ngân hàng Blockchain.");
                Console.WriteLine("Vui lòng nhập số tiền cần gửi: ");
                var amount = double.Parse(Console.ReadLine());
                if (amount <= 0)
                {
                    Console.WriteLine("Số lượng tiền không hợp lệ, vui lòng thử lại.");
                    return;
                }

                var transaction = new SHBTransaction
                {
                    TransactionId         = Guid.NewGuid().ToString(),
                    SenderAccountNumber   = Program.currentLoggedInAccount.AccountNumber,
                    ReceiverAccountNumber = Program.currentLoggedInAccount.AccountNumber,
                    Type         = 2,
                    Message      = "Tiến hành gửi tiền ở ATM với số tiền: " + amount,
                    Amount       = amount,
                    CreatedAtMLS = DateTime.Now.Ticks,
                    UpdatedAtMLS = DateTime.Now.Ticks,
                    Status       = 2
                };
                bool result = shbAccountModel.UpdateBalance(Program.currentLoggedInAccount, transaction);
            }
            else
            {
                Console.WriteLine("Vui lòng đăng nhập lại để sử dụng chức năng này.");
            }

            void ChuyenKhoan()
            {
                if (Program.currentLoggedInAccount != null)
                {
                    Console.Clear();
                    Console.WriteLine("Tiến hành chuyển tiền ở Hệ thống Ngân hàng SHB.");
                    Console.WriteLine("Vui lòng nhâp số tiền cần chuyển: ");
                    var amount = double.Parse(Console.ReadLine());
                    if (amount <= 0)
                    {
                        Console.WriteLine("Số lượng tiền chuyển không phù hợp, vui lòng nhập lại.");
                        return;
                    }

                    var transaction = new SHBTransaction
                    {
                        TransactionId         = Guid.NewGuid().ToString(),
                        SenderAccountNumber   = Program.currentLoggedInAccount.AccountNumber,
                        ReceiverAccountNumber = Program.currentLoggedInAccount.AccountNumber,
                        Type         = 3,
                        Message      = "Tiến hàng chuyển khoản tại ATM với số tiền: " + amount,
                        Amount       = amount,
                        CreatedAtMLS = DateTime.Now.Ticks,
                        UpdatedAtMLS = DateTime.Now.Ticks,
                        Status       = 3
                    };
                    bool result = shbAccountModel.UpdateBalance(Program.currentLoggedInAccount, transaction);
                }
                else
                {
                    Console.WriteLine("Vui lòng đăng nhập lại để sử dụng chức năng này.");
                }
            }
        }
        public bool UpdateBalance(SHBAccount currentLoggedInAccount, SHBTransaction transaction)
        {
            // 1. Kiểm tra số dư tài khoản hiện tại.
            // 2. Update số dư tài khoản hiện tại.
            // 3. Lưu thông tin giao dịch.
            // 4. Commit transaction.
            ConnectionHelper.GetConnection();
            var transaction1 = ConnectionHelper.GetConnection().BeginTransaction(); // mở giao dịch.

            try
            {
                // Kiểm tra số dư tài khoản.
                var cmd = new MySqlCommand("select balance from SHBAccount where accountNumber = @accountNumber",
                                           ConnectionHelper.GetConnection());
                cmd.Parameters.AddWithValue("@accountNumber", currentLoggedInAccount.AccountNumber);
//                SHBAccount shbAccount = null;
                var    dataReader            = cmd.ExecuteReader();
                double currentAccountBalance = 0;
                if (dataReader.Read())
                {
                    currentAccountBalance = dataReader.GetDouble("balance");
                }

                dataReader.Close();
                if (currentAccountBalance < transaction.Amount)
                {
                    throw new Exception("Không đủ tiền trong tài khoản.");
                }

                if (transaction.Type == SHBTransaction.TransactionType.WITHDRAW &&
                    currentAccountBalance < transaction.Amount)
                {
                    throw new Exception("Không đủ tiền trong tài khoản.");
                }

                if (transaction.Type == SHBTransaction.TransactionType.WITHDRAW)
                {
                    currentAccountBalance -= transaction.Amount;
                }

                else if (transaction.Type == SHBTransaction.TransactionType.DEPOSIT)
                {
                    currentAccountBalance += transaction.Amount;
                }



                var updateQuery =
                    "update `SHBAccount` set `balance` = @balance where accountNumber = @accountNumber";
                var sqlCmd = new MySqlCommand(updateQuery, ConnectionHelper.GetConnection());
                sqlCmd.Parameters.AddWithValue("@balance", currentAccountBalance);
                sqlCmd.Parameters.AddWithValue("@accountNumber", currentLoggedInAccount.AccountNumber);
                var updateResult = sqlCmd.ExecuteNonQuery();

                var historyTransactionQuery =
                    "insert into `SHBTransaction` (transactionId, type, senderAccountNumber, receiverAccountNumber, amount, message) " +
                    "values (@transactionId, @type, @senderAccountNumber, @receiverAccountNumber, @amount, @message)";
                var historyTransactionCmd =
                    new MySqlCommand(historyTransactionQuery, ConnectionHelper.GetConnection());
                historyTransactionCmd.Parameters.AddWithValue("@transactionId", transaction.TransactionId);
                historyTransactionCmd.Parameters.AddWithValue("@amount", transaction.Amount);
                historyTransactionCmd.Parameters.AddWithValue("@type", transaction.Type);
                historyTransactionCmd.Parameters.AddWithValue("@message", transaction.Message);
                historyTransactionCmd.Parameters.AddWithValue("@senderAccountNumber",
                                                              transaction.SenderAccountNumber);
                historyTransactionCmd.Parameters.AddWithValue("@receiverAccountNumber",
                                                              transaction.ReceiverAccountNumber);
                var historyResult = historyTransactionCmd.ExecuteNonQuery();

                if (updateResult != 1 || historyResult != 1)
                {
                    throw new Exception("Không thể thêm giao dịch hoặc update tài khoản.");
                }

                transaction1.Commit();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                transaction1.Rollback();                // lưu giao dịch vào.
                return(false);
            }
            ConnectionHelper.CloseConnection();
            return(true);
        }
Beispiel #29
0
        public bool Withdraw(string accountNumber, double amount)
        {
            var minBalance = 50000;
            var cnn        = ConnectionHelper.GetConnection();

            //check connection (hot fix)
            if (ConnectionHelper.IsConnectionSuccess() == false)
            {
                return(false);
            }
            var transaction = cnn.BeginTransaction();

            try
            {
                var stringCmdGetAccount =
                    $"SELECT balance from `accounts` WHERE accountNumber = '{accountNumber}' and status = {(int) AccountStatus.ACTIVE}";
                var cmdGetAccount = new MySqlCommand(stringCmdGetAccount, cnn);
                var accountReader = cmdGetAccount.ExecuteReader();
                if (!accountReader.Read())
                {
                    accountReader.Close();
                    throw new Exception("Không tìm thấy tài khoản hoặc tài khoản đã bị khóa");
                }

                var currentBalence = accountReader.GetDouble("balance");
                accountReader.Close();
                //khởi tạo transaction với trạng thái penđing
                var shbTransactionCode = Guid.NewGuid().ToString();
                var shbTransaction     = new SHBTransaction()
                {
                    Code = shbTransactionCode,
                    SenderAccountNumber   = accountNumber,
                    ReceiverAccountNumber = accountNumber,
                    Type     = TransactionType.WITHDRAW,
                    Amount   = amount,
                    Fee      = 1100,
                    Message  = "Withdraw " + amount,
                    CreateAt = DateTime.Now,
                    UpdateAt = DateTime.Now,
                    Status   = TransactionStatus.PENDING
                };
                //lưu transaction pending vào database

                string insertShbTransactionStringCmd =
                    $"INSERT INTO `shb-transactions` VALUES ('{shbTransaction.Code}','{shbTransaction.SenderAccountNumber}','{shbTransaction.ReceiverAccountNumber}','{shbTransaction.Message}',{shbTransaction.Amount},{shbTransaction.Fee},'{shbTransaction.CreateAt:yyyy-MM-dd hh:mm:ss}','{shbTransaction.UpdateAt:yyyy-MM-dd hh:mm:ss}',{(int) shbTransaction.Status},{(int) shbTransaction.Type}) ";
                var insertShbTransactionCmd = new MySqlCommand(insertShbTransactionStringCmd, cnn);
                insertShbTransactionCmd.ExecuteNonQuery();
                //update so du

                currentBalence = currentBalence - amount - shbTransaction.Fee;
                //new so du khong hop le thi commit 1 failed transaction vao database
                if (currentBalence < minBalance)
                {
                    var updateTime = DateTime.Now;
                    var updateTransactionFailStringCmd =
                        $"UPDATE `shb-transactions` SET status =' {(int) TransactionStatus.FAILED}', updateAt = '{updateTime:yyyy-MM-dd hh:mm:ss}' WHERE code = '{shbTransactionCode}'";
                    var updateTransactionFailCmd = new MySqlCommand(updateTransactionFailStringCmd, cnn);
                    updateTransactionFailCmd.ExecuteNonQuery();

                    transaction.Commit();
                    cnn.Close();
                    Console.WriteLine("Số dư tài khoản không đủ để thực hiện giao địch");
                    return(false);
                }

                var updateBalanceStringCmd =
                    $"UPDATE accounts SET balance = {currentBalence} WHERE accountNumber = '{accountNumber}'";
                var updateBalanceCmd = new MySqlCommand(updateBalanceStringCmd, cnn);
                int affectedRecord   = updateBalanceCmd.ExecuteNonQuery();
                if (affectedRecord == 0)
                {
                    throw new Exception("cập nhật số dư mới thất bại");
                }

                //update transaction thành done
                string updateShbTransactionStatusCmdString =
                    $"UPDATE `shb-transactions` SET status =' {(int) TransactionStatus.DONE}' WHERE code = '{shbTransactionCode}'";
                var updateShbTransactionStatusCmd = new MySqlCommand(updateShbTransactionStatusCmdString, cnn);
                var updated = updateShbTransactionStatusCmd.ExecuteNonQuery();
                if (updated == 0)
                {
                    throw new Exception("cập nhật lịch sử giao dịc thất bại");
                }

                transaction.Commit();
                cnn.Close();
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine("rút tiền thất bại " + e.Message);
                Console.WriteLine(e);
                transaction.Rollback();
                cnn.Close();
                return(false);
            }
        }