Exemplo n.º 1
0
        // Called when event is raised by the Bank class to apply interest to each account.
        private void CalculateInterestHandler(object sender, InterestRateEventArgs e)
        {
            // Store each secondary thread in a generic list collection.
            List<Thread> threads = new List<Thread>(Accounts.Count);

            // Store the interest rate passed in through the InterestRateEventArgs into a variable.
            decimal interestRateDecimal = e.InterestRate;

            // Loop through each account to call the CalculateInterest method to calculate
            //      and apply the interest to the balance.
            foreach (Account account in Accounts)
            {
                IAccountInfo ia = account as IAccountInfo;

                if (ia != null)
                {
                    ParameterizedThreadStart pts = new ParameterizedThreadStart(
                        ia.CalculateInterest);
                    Thread thread = new Thread(pts);
                    thread.Name = account.ClientName + "(Account ID: " + account.AccountID + ")";
                    threads.Add(thread);
                    thread.Start(interestRateDecimal);
                }
            }

            // Loop through each thread to join to the main thread to make
            //      sure all secondary threads are done before this event
            //      handler is done.
            foreach (Thread thread in threads)
            {
                if (!thread.Join(5000))
                {
                    lock (SyncObject.Sync)
                    {
                        Console.WriteLine("Aborting thread {0}.", thread.Name);
                    }
                    thread.Abort();
                    if (!thread.Join(5000))
                    {
                        lock (SyncObject.Sync)
                        {
                            Console.WriteLine("Still waiting for thread {0} to abort.",
                                thread.Name);
                        }
                    }
                }
            }
        }
Exemplo n.º 2
0
        static void Main()
        {
            string inputRecordString = null;
            char[] delimiters = { '\t' };
            string[] fieldsStringArray;
            decimal balanceDecimal = 0.0m;
            decimal minBalanceDecimal = 0.0m;
            decimal amountDecimal = 0.0m;
            DateTime endDate = DateTime.Parse("1/1/0001");
            int accountID = 0;
            int indexInteger = -1;
            Account clientAccount = null;

            try
            {
                // The using block ensures that the Dispose method of the
                //      Bank class will be called when the block is done
                //      executing.
                using (Bank b = new Bank())
                {

                    BankAccounts ba = new BankAccounts(b, _MAX_NUMBER_OF_ACCOUNTS_Integer);

                    //------------------------------------------------------------------------------------------------------------------------------------------------------------------------
                    //  Read data file to create instances of the two account types and store in the accounts array.
                    //------------------------------------------------------------------------------------------------------------------------------------------------------------------------

                    try
                    //Open file
                    {
                        _dataFileStreamReader = new StreamReader(_DATA_FILE_NAME_String);
                    }
                    catch
                    {
                        Console.WriteLine(
                            "File {0} can not be found. Please locate and store it into the bin/debug folder of this project.",
                            _DATA_FILE_NAME_String);
                        return;
                    }

                    // Loop through file
                    while (_dataFileStreamReader.Peek() != -1)
                    {
                        // Read data, create instance with data
                        inputRecordString = _dataFileStreamReader.ReadLine();
                        fieldsStringArray = inputRecordString.Split(delimiters);

                        if (fieldsStringArray.Length == 1)
                        {
                            // Display a message that the input record is empty and will be bypassed.
                            Console.WriteLine("Record is empty.  It is being bypassed.\n");
                            continue;
                        }
                        else if (fieldsStringArray.Length == 5)
                        {
                            // Make sure first value in input record is a whole numeric value.
                            if (!int.TryParse(fieldsStringArray[0], out accountID))
                            {
                                Console.WriteLine(
                                    "Error: The value of the account ID in the following record is not numeric: {0}\n",
                                    inputRecordString);
                                continue;
                            }

                            // Make sure fourth value in input record is a numeric value.
                            if (!decimal.TryParse(fieldsStringArray[3], out balanceDecimal))
                            {
                                Console.WriteLine("Error: The value of the balance in the following record is not numeric: {0}\n",
                                    inputRecordString);
                                continue;
                            }

                            // Supply a default value if the third value in input record is empty.
                            if (fieldsStringArray[2].Length == 0)
                            {
                                fieldsStringArray[2] = "Unknown";
                            }

                            indexInteger++;

                            // Create an instance of the Account class passing in the client information.
                            switch (fieldsStringArray[1].ToUpper())
                            {
                                case "CHECKING":
                                    // Make sure fifth value in input record is a numeric value.
                                    if (!decimal.TryParse(fieldsStringArray[4], out minBalanceDecimal))
                                    {
                                        Console.WriteLine(
                                            "Error: The value of the minimum balance in the following record is not numeric: {0}\n",
                                            inputRecordString);
                                        break;
                                    }

                                    clientAccount = new Checking(accountID, fieldsStringArray[2], balanceDecimal, minBalanceDecimal);

                                    break;

                                case "CD":
                                    // Make sure fifth value in input record is a date value.
                                    if (!DateTime.TryParse(fieldsStringArray[4], out endDate))
                                    {
                                        Console.WriteLine(
                                            "Error: The value of the end date in the following record is not a date: {0}\n",
                                            inputRecordString);
                                        break;
                                    }

                                    clientAccount = new CD(accountID, fieldsStringArray[2], balanceDecimal, endDate, _MIN_CD_TRANSACTION_AMOUNT_Decimal);
                                    break;

                                default:
                                    Console.WriteLine(
                                        "Error: The second value in the following record is not a recognized account type: {0}\n",
                                         inputRecordString);
                                    break;
                            }

                            if (clientAccount == null)
                            {
                                continue;
                            }
                            else
                            {
                                ba[clientAccount.AccountID] = clientAccount;
                            }
                        }
                        else
                        {
                            Console.WriteLine("Error: The following record does not have five values: {0}\n",
                                inputRecordString);
                            continue;
                        }

                        // Remove reference to Account.
                        clientAccount = null;
                    }

                    // Close file
                    _dataFileStreamReader.Close();
                    _dataFileStreamReader = null;

                    //------------------------------------------------------------------------------------------------------------------------------------------------------------------------
                    // Read and process data file containing transaction amounts to update the
                    //      balance in each of the 2 account types.
                    //------------------------------------------------------------------------------------------------------------------------------------------------------------------------

                    try
                    //Open file
                    {
                        _dataFileStreamReader = new StreamReader(_UPDATE_DATA_FILE_NAME_String);
                    }
                    catch
                    {
                        Console.WriteLine(
                            "File {0} can not be found. Please locate and store it into the bin/debug folder of this project.",
                            _UPDATE_DATA_FILE_NAME_String);
                        return;
                    }

                    // Loop through file
                    while (_dataFileStreamReader.Peek() != -1)
                    {
                        // Read data, create instance with data
                        inputRecordString = _dataFileStreamReader.ReadLine();
                        fieldsStringArray = inputRecordString.Split(delimiters);

                        if (fieldsStringArray.Length == 2)
                        {
                            // Make sure first value in input record is a whole numeric value.
                            if (!int.TryParse(fieldsStringArray[0], out accountID))
                            {
                                Console.WriteLine(
                                    "Error: The value of the account ID in the following record is not numeric: {0}\n",
                                    inputRecordString);
                                continue;
                            }

                            // Make sure second value in input record is a numeric value.
                            if (!decimal.TryParse(fieldsStringArray[1], out amountDecimal))
                            {
                                Console.WriteLine(
                                    "Error: The value of the transaction amount in the following record is not numeric: {0}\n",
                                    inputRecordString);
                                continue;
                            }

                            // Locate the account ID in the accounts array.
                            clientAccount = ba[accountID];

                            // Display error message if account is not found in the array.
                            if (clientAccount == null)
                            {
                                Console.WriteLine(
                                    "Error: There is no account for the account id in this record: {0}\n",
                                    inputRecordString);
                                continue;
                            }

                            try
                            {
                                // Using polymorphism, update the balance in the account from the
                                //      transaction amount.
                                clientAccount.UpdateBalance(amountDecimal);
                            }
                            catch (TransactionOutOfRangeException ex)
                            {
                                // Because PrintClientInformation is explicitly implemented,
                                //      a cast must occur to execute that method.
                                IAccountInfo ia = ex.CustomerAccount as IAccountInfo;

                                if (ia != null)
                                {
                                    Console.WriteLine("ERROR: {0}\nTransaction amount is: {1}.\nAccount: {2}\n",
                                        ex.Message, ex.TransactionAmount, ia.PrintClientInformation());
                                }
                                else
                                {
                                    Console.WriteLine("ERROR: {0}\nTransaction amount is: {1}.\nAccount: {2}\n",
                                        ex.Message, ex.TransactionAmount, "Customer information not available.");
                                }

                                continue;
                            }

                            ba[clientAccount.AccountID] = clientAccount;
                        }
                        else
                        {
                            Console.WriteLine("Error: The following record does not have two values: {0}\n",
                                inputRecordString);
                            continue;
                        }
                    }  // Loop back up to read and process the next record.

                    // Close file
                    CloseFile();

                    // Update accounts by adding in interest.  Each element in the array
                    //      represents the interest rate to be applied in each interest period.
                    foreach (decimal interestRateDecimal in b._interestRatesDecimal)
                    {
                        // This is a dummy way to pretend that the bank raises the event at the end of
                        //      every month to apply interest to the accounts.
                        System.Threading.Thread.Sleep(2000);

                        // Raises the event to apply interest to each account.  The custom InterestRateEventArgs
                        //      contains the interest rate amount.
                        InterestRateEventArgs ea = new InterestRateEventArgs(interestRateDecimal);
                        b.OnInterestRateCalculate(b, ea);
                    }

                    //Print the customer account information.
                    ba.PrintAccounts();

                    //Make sure all messages on the console are read before program ends.
                    Console.Write("\nPress any key to end the program.");
                    Console.ReadLine();

                }   // End of using block for Bank class instance.
            }   // End of outer try block in the Main method.
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: The following exception has occurred:\n{0}\nApplication is now ending.",
                    ex.Message);
                CloseFile();
            }
        }
Exemplo n.º 3
0
        // Called when event is raised by the Bank class to apply interest to each account.
        private void CalculateInterestHandler(object sender, InterestRateEventArgs e)
        {
            // Store each secondary thread in a generic list collection.
            // TODO: 2.  Note the name of the collection below.  This is
            //  to be the collection of secondary foreground threads as they
            //  are started.
            List<Thread> threads = new List<Thread>(Accounts.Count);

            // Store the interest rate passed in through the InterestRateEventArgs into a variable.
            decimal interestRateDecimal = e.InterestRate;

            // Loop through each account to call the CalculateInterest method to calculate
            //      and apply the interest to the balance.
            foreach (Account account in Accounts)
            {
                IAccountInfo ia = account as IAccountInfo;

                if (ia != null)
                {
                    // TODO: 3. Replace the code line below with:
                    //      a.  A call to the same method below on a secondary foreground thread.
                    //      b.  Give the following name to the thread before it is started:
                    //          "ClientName(Account ID: AccountID)"
                    //          The ClientName and AccountID are stored in the account.
                    //      c.  Store the thread created into the threads collection above
                    //          before starting the thread.
                    //      d.  Be sure to pass in the interest rate, which is in the
                    //          "interestRateDecimal" variable.
                    ia.CalculateInterest(interestRateDecimal);
                }
            }

            // Loop through each thread to join to the main thread to make
            //      sure all secondary threads are done before this event
            //      handler is done.
            // TODO: 4. Loop through each thread in the threads collection and join each one
            //  to the main thread that is executing this code:
            //      - Allow for 5 seconds for the join.
            //      - If the thread is not completed by then, then abort it and join
            //          for another 5 seconds to allow for the abort to take place.
            //      - A message should be displayed when the thread is being aborted.
            //      - This message should be synchronized using the "lock" block and
            //          indicate the name of the thread being aborted.
        }