Tuesday, June 17, 2014

Zau_Save To Text File




namespace Zau_Save_To_Text_File
{
    public class Account
    {
        //Private Fields
        private string _firstName;
        private string _lastName;
        private string _accountNumber;
        private decimal _balance;

        //Constructor
        public Account(string firstName, string lastName, string accountNumber, decimal balance)
        {
            _firstName = firstName;
            _lastName = lastName;
            _accountNumber = accountNumber;
            _balance = balance;
        }

        //Properties
        public string firstName
        { get { return _firstName; } }
        public string lastName
        { get { return _lastName; } }
        public string AccountNumber
        { get { return _accountNumber; } }
        public decimal Balance
        { get { return _balance; } }


        public void Deposit(decimal amt)
        {
            _balance += amt;
        }

        public bool Withdraw(decimal amount)
        {
            if (_balance > amount)
            {
                _balance -= amount;
                return true;
            }
            return false;
        }
    }
}
//====================================================
using System.Windows.Forms;
using System.IO;

namespace Zau_Save_To_Text_File
{
    public partial class Form1 : Form
    {
        List<Account> accountList = new List<Account>();
        //string accountFilePath = "accounts.txt";

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadAccountInformationFile();
            DisplayAccounts();
        }

        private void LoadAccountInformationFile()
        {
            if (File.Exists("accounts.txt"))
            {
                using (StreamReader sr = File.OpenText("accounts.txt"))
                {
                    while (!sr.EndOfStream)
                    {
                        string fName = sr.ReadLine();
                        string lName = sr.ReadLine();
                        string acntNum = sr.ReadLine();
                        decimal balance;
                        if (decimal.TryParse(sr.ReadLine(), out balance))
                        {
                            Account account = new Account(fName, lName, acntNum, balance);
                            accountList.Add(account);
                        }
                        else
                            throw new FormatException("Program Error");
                    }
                }
            }
            else
                throw new FileNotFoundException("The file named 'account.txt' could not be found");
        }

        private void DisplayAccounts()
        {
            listView1.Items.Clear();
            ListViewItem lvi;
            foreach (Account account in accountList)
            {
                lvi = new ListViewItem(account.firstName);
                lvi.SubItems.Add(account.lastName);
                lvi.SubItems.Add(account.AccountNumber);
                lvi.SubItems.Add(account.Balance.ToString("C"));
                listView1.Items.Add(lvi);
            }
        }

        private void btnDisplayAccountList_Click(object sender, EventArgs e)
        {
            DisplayAccounts();
        }

        private void btnCreateNSaveAccount_Click(object sender, EventArgs e)
        {
            if (txtFirstName.Text != String.Empty &&
                txtLastName.Text != String.Empty &&
                txtAccountNumber.Text != String.Empty &&
                txtInitialBalance.Text != String.Empty)
            {
                decimal initBalance;
                decimal.TryParse(txtInitialBalance.Text, out initBalance);
                if (initBalance >= 10)
                {
                    using (StreamWriter sw = File.AppendText("accounts.txt"))
                    {
                        // write to it
                        sw.WriteLine(txtFirstName.Text);
                        sw.WriteLine(txtLastName.Text);
                        sw.WriteLine(txtAccountNumber.Text);
                        sw.WriteLine(initBalance);
                        Account acnt = new Account(txtFirstName.Text, txtLastName.Text, txtAccountNumber.Text, initBalance);
                        accountList.Add(acnt);
                    }
                    // add to listbox
                    //LoadSingleAccount(txtAccountNumber.Text);
                    LoadSingleAccount(txtFirstName.Text);

                    // update account counter
                    //_accountCounter++;
                    //txtAccountNumber.Text = _accountCounter.ToString();

                    // clear fields
                    txtFirstName.Clear();
                    txtLastName.Clear();
                    txtAccountNumber.Clear();
                    txtInitialBalance.Clear();
                }
                else
                    MessageBox.Show("Can not create an account without a balance greater or equal to $25");
            }
            else
                MessageBox.Show("Please fill all the required fields before attempting to create an account");
        }

        private Account GetAccountByNumber(string accountNumber)
        {
            foreach (Account acnt in accountList)
            {
                if (acnt.AccountNumber == accountNumber)
                {
                    return acnt;
                }
            }
            return null;
        }

        private bool LoadSingleAccount(string accountNumber)
        {
            Account singleAccount = GetAccountByNumber(accountNumber);
            if (singleAccount != null)
            {
                listView1.Items.Clear();
                ListViewItem lvi = new ListViewItem(singleAccount.firstName);
                lvi.SubItems.Add(singleAccount.lastName);
                lvi.SubItems.Add(singleAccount.AccountNumber);
                lvi.SubItems.Add(singleAccount.Balance.ToString("C"));
                listView1.Items.Add(lvi);

                return true;
            }
            return false;
        }

        private void btnDeposit_Click(object sender, EventArgs e)
        {
            Account existingAccount = GetAccountByNumber(txtAccountNumToPull.Text);
            if (existingAccount != null)
            {
                decimal depositAmount;
                if (decimal.TryParse(txtDeposit.Text, out depositAmount))
                {
                    existingAccount.Deposit(depositAmount);
                    // re-write file
                    //WriteAllAccountsToFile();
                    WriteDepositToFile(existingAccount.AccountNumber, depositAmount);

                    // Load the account to the list view after depositing.
                    LoadSingleAccount(txtAccountNumToPull.Text);

                    // Clear textboxes
                    txtAccountNumToPull.Clear();
                    txtDeposit.Clear();
                }
                else
                    MessageBox.Show("Invalid Input.");
            }
            else
                MessageBox.Show("Account does not exist");
        }

        private void WriteDepositToFile(string accountNumber, decimal amount)
        {
            try
            {
                string[] accountInformation = File.ReadAllLines("accounts.txt");
                for (int i = 0; i < accountInformation.Length; i++)
                {
                    if (accountInformation[i] == accountNumber)
                    {
                        decimal balance = decimal.Parse(accountInformation[i + 1]) + amount;
                        accountInformation[i + 1] = balance.ToString();
                    }
                }
                using (StreamWriter sw = new StreamWriter("accounts.txt", false))
                {
                    foreach (string line in accountInformation)
                    {
                        sw.WriteLine(line);
                    }
                }
            }
            catch (FileNotFoundException fnf)
            {
                MessageBox.Show(fnf.Message);
            }
        }

        private void btnWithdrawal_Click(object sender, EventArgs e)
        {
            Account existingAccount = GetAccountByNumber(txtAccountNumToPull.Text);
            if (existingAccount != null)
            {
                decimal withdrawAmount;
                if (decimal.TryParse(txtWithdraw.Text, out withdrawAmount))
                {
                    if (!existingAccount.Withdraw(withdrawAmount))
                        MessageBox.Show("You do not have enough money to withdraw that amount!");
                    // re-write file
                    WriteAllAccountsToFile();

                    // Load Account for viewing
                    LoadSingleAccount(txtAccountNumToPull.Text);

                    // Clear textboxes
                    txtAccountNumToPull.Clear();
                    txtWithdraw.Clear();
                }
                else
                    MessageBox.Show("The amount you are trying to deposit is invalid.");
            }
            else
                MessageBox.Show("That account could not be found, please check the number and try again");
        }

        private void WriteWithdrawlToFile(string accountNumber, decimal amount)
        {
            try
            {
                string[] accountInformation = File.ReadAllLines("accounts.txt");
                for (int i = 0; i < accountInformation.Length; i++)
                {
                    if (accountInformation[i] == accountNumber)
                    {
                        decimal balance = decimal.Parse(accountInformation[i + 1]) - amount;
                        accountInformation[i + 1] = balance.ToString(); // adjust the value in the string array, then
                    }
                }
                using (StreamWriter sw = new StreamWriter("accounts.txt", false)) // write the string array to the file.
                {
                    foreach (string line in accountInformation)
                    {
                        sw.WriteLine(line);
                    }
                }
            }
            catch (FileNotFoundException fnf)
            {
                MessageBox.Show(fnf.Message);
            }
        }

        private void WriteAllAccountsToFile()
        {
            using (StreamWriter sw = new StreamWriter("accounts.txt", false))
            {
                foreach (Account account in accountList)
                {
                    sw.WriteLine(account.firstName);
                    sw.WriteLine(account.lastName);
                    sw.WriteLine(account.AccountNumber);
                    sw.WriteLine(account.Balance);
                }
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Close();
        }
        //Restrict textbox to numbers only
        //Add a keypress event to the textbox and add the code below.
        //If the key is a digit
        //e.Handled is set to false, which allows the system to handle
        //the input and display it on the textbox.

        //if the key is not a digit, e.Handled = true, which tells the system 
        //the input has been handled and the system
        //won't display it on the textbox

        //Click on textbox | in event double click on "KeyPress"
        private void txtAccountNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !char.IsDigit(e.KeyChar);
        }

        private void txtInitialBalance_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !char.IsDigit(e.KeyChar);
        }

        private void txtDeposit_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !char.IsDigit(e.KeyChar);
        }

        private void txtWithdraw_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !char.IsDigit(e.KeyChar);
        }
    }
}

No comments:

Post a Comment