Home

Exception Handling in File Processing

 

Finally

So far, to handle exceptions, we were using the try, catch, and throw keywords. These allowed us to perform normal assignments in a try section and then handle an exception, if any, in a catch block.

In the previous lesson, we mentioned that, when you create a stream, the operating system must allocate resources and dedicate them to the file processing operations. Additional resources may be provided for the object that is in charge of writing to, or reading from, the stream. We also saw that, when the streaming was over, we should free the resources and give them back to the operating system. To do this, we called the Close() method of the variable that was using resources.

 

More than any other assignment, file processing is in prime need of exception handling. As we will see in the next section, during file processing, there are many things that can go wrong. For this reason, the creation and/or management of streams should be performed in a try block to get ready to handle exceptions that would occur. Besides actually handling exceptions, the C# language provides a special keyword used free resources. This keyword is finally.

The finally keyword is used to create a section of an exception. Like catch, a finally block cannot exist by itself. It can be created following a try section. The formula used would be:

try
{
}
finally
{
}

Based on this, the finally section has a body of its own, delimited by its curly brackets. Like catch, the finally section is created after the try section. Unlike catch, finally never has parentheses and never takes arguments. Unlike catch, the finally section is always executed. Because the finally clause always gets executed, you can include any type of code in it but it is usually appropriate to free the resources that were allocated earlier. Here is an example:

using System;
using System.IO;

public class Program
{
    static int Main(string[] args)
    {
        string NameOfFile = "Members.clb";
	
        FileStream fstPersons = new FileStream(NameOfFile, FileMode.Create);
        BinaryWriter wrtPersons = new BinaryWriter(fstPersons);
        
        try 
        {
            wrtPersons.Write("James Bloch");
            wrtPersons.Write("Catherina Wallace");
            wrtPersons.Write("Bruce Lamont");
            wrtPersons.Write("Douglas Truth");
        }
        finally
        {
            wrtPersons.Close();
            fstPersons.Close();
        }

        return 0;
    }
}

In the same way, you can use a finally section to free resources used when reading from a stream:

using System;
using System.IO;

public class Program
{
    static int Main(string[] args)
    {
/*        string NameOfFile = "Members.clb";
	
        FileStream fstPersons = new FileStream(NameOfFile, FileMode.Create);
        BinaryWriter wrtPersons = new BinaryWriter(fstPersons);
        
        try 
        {
            wrtPersons.Write("James Bloch");
            wrtPersons.Write("Catherina Wallace");
            wrtPersons.Write("Bruce Lamont");
            wrtPersons.Write("Douglas Truth");
        }
        finally
        {
            wrtPersons.Close();
            fstPersons.Close();
        }*/
        
        string NameOfFile = "Members.clb";
        string strLine = null;
        
        FileStream fstMembers = new FileStream(NameOfFile, FileMode.Open);
        BinaryReader rdrMembers = new BinaryReader(fstMembers);

        try
        {
            strLine = rdrMembers.ReadString();
            Console.WriteLine(strLine);
            strLine = rdrMembers.ReadString();
            Console.WriteLine(strLine);
            strLine = rdrMembers.ReadString();
            Console.WriteLine(strLine);
            strLine = rdrMembers.ReadString();
            Console.WriteLine(strLine);
        }
        finally
        {
            rdrMembers.Close();
            fstMembers.Close();
        }

        return 0;
    }
}

Of course, since the whole block of code starts with a try section, it is used for exception handling. This means that you can add the necessary and appropriate catch section(s) but you don't have to.

Practical LearningPractical Learning: Finally Releasing Resources

  1. Start Microsoft Visual C# and create a Console Application named IceCream4
  2. To save the project, on the Standard toolbar, click the Save All button Save All
  3. Change the Solution Name to VendingMachine4
  4. Accept the Name of the project as IceCream3 and click Save
  5. To create a new class, on the main menu, click Project -> Add Class...
  6. Set the Name to IceCream and click Add
  7. Change the file as follows:
     
    using System;
    using System.IO;
    
    namespace IceCream4
    {
        delegate void Request();
    
        // This class is used to create and manage an Ice Cream
        // and to process an order
        public sealed class IceCream
        {
            // This is the base price of an Ice Cream
            // Optional values may be added to it
            public const decimal BasePrice = 1.55M;
    
            // These arrays are used to build the components 
            // of various Ice Creams
            // In C#, we can allocate an array's memory in 
            // the body of the class
            private string[] Flavor;
            private string[] Container;
            private string[] Ingredient;
    
            // Additional factor used to process an Ice Cream order
            private int Scoops;
            private decimal TotalPrice;
    
            // Variables that will hold the user's choice
            // These are declared "globally" so they can be 
            // shared among methods
            int ChoiceFlavor;
            int ChoiceContainer;
            int ChoiceIngredient;
    
            // This default constructor is the best place for 
            // us to initialize the array
            public IceCream()
            {
                Flavor = new string[10];
                Flavor[0] = "Vanilla";
                Flavor[1] = "Cream of Cocoa";
                Flavor[2] = "Chocolate Chip";
                Flavor[3] = "Organic Strawberry";
                Flavor[4] = "Butter Pecan";
                Flavor[5] = "Cherry Coke";
                Flavor[6] = "Chocolate Brownies";
                Flavor[7] = "Caramel Au Lait";
                Flavor[8] = "Chunky Butter";
                Flavor[9] = "Chocolate Cookie";
    
                Ingredient = new string[4];
                Ingredient[0] = "No Ingredient";
                Ingredient[1] = "Peanuts";
                Ingredient[2] = "M & M";
                Ingredient[3] = "Cookies";
    
                Container = new string[3];
                Container[0] = "Cone";
                Container[1] = "Cup";
                Container[2] = "Bowl";
            }
    
            // This method requests a flavor from the user and
            // returns the choice
            public void ChooseFlavor()
            {
                // Make sure the user selects a valid number 
                //that represents a flavor...
                do
                {
                    // In case the user types a symbol that 
                    // is not a number
                    try
                    {
                        Console.WriteLine("What type of flavor do you want?");
                        for (int i = 0; i < Flavor.Length; i++)
                            Console.WriteLine("{0} - {1}", i + 1, Flavor[i]);
                        Console.Write("Your Choice? ");
                        ChoiceFlavor = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)	// display an appropriate message
                    {
                        Console.WriteLine("You must enter a valid number " +
                                          "and no other character!");
                    }
    
                    // If the user typed an invalid number out of the 
                    // allowed range
                    // let him or her know and provide another chance
                    if (ChoiceFlavor < 1 || ChoiceFlavor > Flavor.Length)
                        Console.WriteLine("Invalid Choice - Try Again!\n");
                } while (ChoiceFlavor < 1 || ChoiceFlavor > Flavor.Length);
            }
    
            // This method allows the user to select a container
            public void ChooseContainer()
            {
                // Make sure the user selects a valid number that 
                // represents a container
                do
                {
                    // If the user types a symbol that is not a number
                    try
                    {
                        Console.WriteLine("What type of container do you want?");
                        for (int i = 0; i < Container.Length; i++)
                            Console.WriteLine("{0} - {1}", i + 1, Container[i]);
                        Console.Write("Your Choice? ");
                        ChoiceContainer = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)	// display an appropriate message
                    {
                        Console.WriteLine("You must enter a valid " +
                                          "number and no other character!");
                    }
    
                    // If the user typed an invalid number out of the 
                    // allowed range
                    // let him or her know and provide another chance
                    if ((ChoiceContainer < 1) ||
                        (ChoiceContainer > Container.Length))
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while ((ChoiceContainer < 1) ||
                         (ChoiceContainer > Container.Length));
            }
    
            public void ChooseIngredient()
            {
                do
                {
                    try
                    {
                        Console.WriteLine("Do you want an ingredient or not");
                        for (int i = 0; i < Ingredient.Length; i++)
                            Console.WriteLine("{0} - {1}",
                                              i + 1,
                                              Ingredient[i]);
                        Console.Write("Your Choice? ");
                        ChoiceIngredient = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("You must enter a valid " +
                                          "number and no other character!");
                    }
    
                    if ((ChoiceIngredient < 1) ||
                        (ChoiceIngredient > Ingredient.Length))
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while ((ChoiceIngredient < 1) ||
                         (ChoiceIngredient > Ingredient.Length));
            }
    
            public void SpecifyNumberOfScoops()
            {
                do
                {
                    try
                    {
                        Console.Write("How many scoops(1, 2, or 3)? ");
                        Scoops = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("You must enter a valid number " +
                                          "and no other character!");
                    }
    
                    if (Scoops < 1 || Scoops > 3)
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while (Scoops < 1 || Scoops > 3);
            }
    
            // This method is used to process a customer order
            // It uses the values of the above methods
            public void ProcessAnOrder()
            {
                //			int ChoiceFlavor;
                //			int ChoiceContainer;
                //			int ChoiceIngredient;
                decimal PriceIngredient, PriceScoop;
    
                // Let the user know that this is a vending machine
                Console.WriteLine("=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=");
                Console.WriteLine("Ice Cream Vending Machine");
                Console.WriteLine("-----------------------------------");
    
                // Let the user select the components of the Ice Cream
                Request Get = new Request(ChooseFlavor);
                Get();
                Console.WriteLine("-----------------------------------");
                Get = new Request(ChooseContainer);
                Get();
                Console.WriteLine("-----------------------------------");
                Get = new Request(ChooseIngredient);
                Get();
                Console.WriteLine("-----------------------------------");
                Get = new Request(SpecifyNumberOfScoops);
                Get();
                Console.WriteLine("-----------------------------------");
    
                // If the user selects an ingredient instead of "No Ingredient",
                // add $0.50 to the order
                if ((ChoiceIngredient == 2) ||
                    (ChoiceIngredient == 3) ||
                    (ChoiceIngredient == 4))
                    PriceIngredient = 0.50M;
                else
                    PriceIngredient = 0.00M;
    
                // Instead of multiplying a number scoops to a value,
                // We will use an incremental value depending on 
                // the number of scoops
                if (Scoops == 1)
                    PriceScoop = 0.65M;
                else if (Scoops == 2)
                    PriceScoop = 1.05M;
                else
                    PriceScoop = 1.55M;
    
                // Calculate the total price of the Ice Cream
                TotalPrice = BasePrice + PriceScoop + PriceIngredient;
    
                // Create the Ice Cream...
    
                // And display a receipt to the user
                DisplayReceipt();
            }
    
            // This method is used to display a receipt to the user
            public void DisplayReceipt()
            {
                Console.WriteLine("\n=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=");
                Console.WriteLine("Ice Cream Order");
                Console.WriteLine("-----------------------------------");
                Console.WriteLine("Flavor:      {0}",
                                  Flavor[ChoiceFlavor - 1]);
                Console.WriteLine("Container:   {0}",
                                  Container[ChoiceContainer - 1]);
                Console.WriteLine("Ingredient:  {0}",
                                  Ingredient[ChoiceIngredient - 1]);
                Console.WriteLine("Scoops:      {0}", Scoops);
                Console.WriteLine("Total Price: {0:C}", TotalPrice);
                Console.WriteLine("=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=\n");
            }
    
            public void SaveOrder()
            {
                string strNameOfFile;
    
                Console.Write("Please enter your initials or the name " +
                                  "we will use to remember your order: ");
                strNameOfFile = Console.ReadLine();
                strNameOfFile = strNameOfFile + ".icr";
    
                // Find out if the user entered a name of a file 
                // that is already in the machine
                if (File.Exists(strNameOfFile))
                {
                    char answer;
    
                    FileStream stmIceCream =
                        new FileStream(strNameOfFile, FileMode.Create);
                    BinaryWriter bnwIceCream =
                        new BinaryWriter(stmIceCream);
    
                    try
                    {
    
                        // If so, find out if the user wants to 
                        // replace the old file
                        Console.WriteLine("The file you entered exists already.");
                        Console.Write("Do you want to replace it(y/n)?");
                        answer = char.Parse(Console.ReadLine());
    
                        // If the customer wants to replace it...
                        if (answer == 'y' || answer == 'Y')
                        {
                            // ... do so
                            Console.WriteLine("The former order with the same " +
                                              "name will be replaced");
    
                        Console.WriteLine("\n=-= Ice Cream Vending Machine =-=");
                        Console.WriteLine(" Saving Order: {0}", strNameOfFile);
                            bnwIceCream.Write(Flavor[ChoiceFlavor - 1]);
                            bnwIceCream.Write(Container[ChoiceContainer - 1]);
                            bnwIceCream.Write(Ingredient[ChoiceIngredient - 1]);
                            bnwIceCream.Write(Scoops);
                            bnwIceCream.Write(TotalPrice);
                        }
                        // If the customer wants to save the new order with 
                        // a different name
                        else if (answer == 'n' || answer == 'N')
                        {
                            // Ask the user to enter a name to remember the order
                            Console.Write("Please enter a name we will use " +
                                          "to remember this order: ");
                            strNameOfFile = Console.ReadLine();
                            strNameOfFile = strNameOfFile + ".icr";
    
                    stmIceCream = new FileStream(strNameOfFile, FileMode.Create);
                            bnwIceCream = new BinaryWriter(stmIceCream);
    
                    Console.WriteLine("\n=-= Ice Cream Vending Machine =-=");
                    Console.WriteLine(" Saving Order: {0}", strNameOfFile);
                            bnwIceCream.Write(Flavor[ChoiceFlavor - 1]);
                            bnwIceCream.Write(Container[ChoiceContainer - 1]);
                            bnwIceCream.Write(Ingredient[ChoiceIngredient - 1]);
                            bnwIceCream.Write(Scoops);
                            bnwIceCream.Write(TotalPrice);
                        }
                        else
                            Console.WriteLine("Invalid Answer - We will close");
                    }
                    finally
                    {
                        bnwIceCream.Close();
                        stmIceCream.Close();
                    }
                }
                else
                {
                    FileStream stmIceCream =
                        new FileStream(strNameOfFile, FileMode.Create);
                    BinaryWriter bnwIceCream =
                        new BinaryWriter(stmIceCream);
    
                    try
                    {
                        Console.WriteLine("\n=-= Ice Cream Vending Machine =-=");
                        Console.WriteLine(" Saving Order: {0}", strNameOfFile);
                        bnwIceCream.Write(Flavor[ChoiceFlavor - 1]);
                        bnwIceCream.Write(Container[ChoiceContainer - 1]);
                        bnwIceCream.Write(Ingredient[ChoiceIngredient - 1]);
                        bnwIceCream.Write(Scoops);
                        bnwIceCream.Write(TotalPrice);
                    }
                    finally
                    {
                        bnwIceCream.Close();
                        stmIceCream.Close();
                    }
                }
            }
    
            public void OpenOrder()
            {
                string strNameOfFile;
    
                string SelectedFlavor;
                string SelectedContainer;
                string SelectedIngredient;
    
                // Ask the user to enter a name of a previously saved order
                Console.Write("Please enter the name you previously " +
                              "gave to remember your order: ");
                strNameOfFile = Console.ReadLine();
                strNameOfFile = strNameOfFile + ".icr";
    
                FileStream stmIceCream =
                    new FileStream(strNameOfFile, FileMode.Open);
                BinaryReader bnrIceCream =
                    new BinaryReader(stmIceCream);
    
                try
                {
                    // Find out if this order was previously saved in the machine
                    if (File.Exists(strNameOfFile))
                    {
                        // If so, open it
                        SelectedFlavor = bnrIceCream.ReadString();
                        SelectedContainer = bnrIceCream.ReadString();
                        SelectedIngredient = bnrIceCream.ReadString();
                        Scoops = bnrIceCream.ReadInt32();
                        TotalPrice = bnrIceCream.ReadDecimal();
    
                        // And display it to the user
                        Console.WriteLine("\n=-= Ice Cream Vending Machine =-=");
                        Console.WriteLine(" Previous Order: {0}", strNameOfFile);
                        Console.WriteLine("Flavor:      {0}", SelectedFlavor);
                        Console.WriteLine("Container:   {0}", SelectedContainer);
                        Console.WriteLine("Ingredient:  {0}", SelectedIngredient);
                        Console.WriteLine("Scoops:      {0}", Scoops);
                        Console.WriteLine("Total Price: {0:C}\n", TotalPrice);
                    }
                    else
                        Console.WriteLine("The name you entered is not " +
                                          "registered in our previous orders");
                }
                finally
                {
                    bnrIceCream.Close();
                    stmIceCream.Close();
                }
            }
        }
    }
     
    Access the Program.cs file and change it as follows:
     
    using System;
    
    namespace IceCream4
    {
        class Program
        {
            static int Main(string[] args)
            {
                char answer = 'n';
                IceCream ic = new IceCream();
                Request process = new Request(ic.ProcessAnOrder);
    
                Console.Write("Do you want to re-order a previously " +
                              "saved order(y/n)? ");
                answer = char.Parse(Console.ReadLine());
    
                if (answer == 'y' || answer == 'Y')
                    ic.OpenOrder();
                else
                {
                    process();
                    Console.Write("Do you want us to remember this " +
                                  "order the next time you come to " +
                                  "get your Ice Cream (y/n)? ");
                    answer = char.Parse(Console.ReadLine());
                    if (answer == 'y' || answer == 'Y')
                        ic.SaveOrder();
                    else
                        Console.WriteLine("\nIt was nice serving you." +
                                          "\nCome Again!!!\n");
                }
    
                return 0;
            }
        }
    }
  8. Execute the application and test it. Here is an example:
     
    Do you want to re-order a previously saved order(y/n)? n
    =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
    Ice Cream Vending Machine
    -----------------------------------
    What type of flavor do you want?
    1 - Vanilla
    2 - Cream of Cocoa
    3 - Chocolate Chip
    4 - Organic Strawberry
    5 - Butter Pecan
    6 - Cherry Coke
    7 - Chocolate Brownies
    8 - Caramel Au Lait
    9 - Chunky Butter
    10 - Chocolate Cookie
    Your Choice? 6
    -----------------------------------
    What type of container do you want?
    1 - Cone
    2 - Cup
    3 - Bowl
    Your Choice? 2
    -----------------------------------
    Do you want an ingredient or not
    1 - No Ingredient
    2 - Peanuts
    3 - M & M
    4 - Cookies
    Your Choice? 1
    -----------------------------------
    How many scoops(1, 2, or 3)? 2
    -----------------------------------
    
    =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
    Ice Cream Order
    -----------------------------------
    Flavor:      Cherry Coke
    Container:   Cup
    Ingredient:  No Ingredient
    Scoops:      2
    Total Price: $2.60
    =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
    
    Do you want us to remember this order the next time you 
    come to get your Ice Cream (y/n)? n
    
    It was nice serving you.
    Come Again!!!
    
    Press any key to continue . . .
  9. Close the DOS window
  10. Execute the application and test it. Enter a wrong file name. Here is an example:
     
    Do you want to re-order a previously saved order(y/n)? y
    Please enter the name you previously gave to remember your order: dtr
    
    Unhandled Exception: System.IO.FileNotFoundException: Could not find file 'C:\Do
    cuments and Settings\Administrator\My Documents\Visual Studio 2005\Projects\Vend
    ingMachine4\IceCream4\bin\Release\dtr.icr'.
    File name: 'C:\Documents and Settings\Administrator\My Documents\Visual Studio 2
    005\Projects\VendingMachine4\IceCream4\bin\Release\dtr.icr'
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, I
    nt32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions o
    ptions, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
       at System.IO.FileStream..ctor(String path, FileMode mode)
       at IceCream4.IceCream.OpenOrder() in C:\Documents and Settings\Administrator
    \My Documents\Visual Studio 2005\Projects\VendingMachine4\IceCream4\IceCream.cs
    :line 360
       at IceCream4.Program.Main(String[] args) in C:\Documents and Settings\Adminis
    trator\My Documents\Visual Studio 2005\Projects\VendingMachine4\IceCream4\Progra
    m.cs:line 18
    Press any key to continue . . .
  11. Close the DOS window

.NET Framework Exception Handling for File Processing

In the previous lesson as our introduction to file processing, we behaved as if everything was alright. Unfortunately, file processing can be very strict in its assignments. Based on this, the .NET Framework provides various Exception-oriented classes to deal with almost any type of exception you can think of.

One of the most important aspects of file processing is the name of the file that will be dealt with. In some cases you can provide this name to the application or document. In some other cases, you would let the user specify the name of the path. Regardless of how the name of the file would be provided to the operating system, when this name is acted upon, the compiler be asked to work on the file. If the file doesn't exist, the operation cannot be carried. Furthermore, the compiler would throw an error. There are many other exceptions that can thrown as a result of something going bad during file processing:

FileNotFoundException: The exception thrown when a file has not been found is of type FileNotFoundException. Here is an example of handling it:

using System;
using System.IO;

public class Program
{
    static int Main(string[] args)
    {
/*        string NameOfFile = "Members.clb";
	
        FileStream fstPersons = 
            new FileStream(NameOfFile, FileMode.Create);
        BinaryWriter wrtPersons = new BinaryWriter(fstPersons);
        
        try 
        {
            wrtPersons.Write("James Bloch");
            wrtPersons.Write("Catherina Wallace");
            wrtPersons.Write("Bruce Lamont");
            wrtPersons.Write("Douglas Truth");
        }
        finally
        {
            wrtPersons.Close();
            fstPersons.Close();
        }*/


        string NameOfFile = "Members.clc";
        string strLine = null;

        try
        {
            FileStream fstMembers =
                new FileStream(NameOfFile, FileMode.Open);
            BinaryReader rdrMembers = new BinaryReader(fstMembers);

            try
            {
                strLine = rdrMembers.ReadString();
                Console.WriteLine(strLine);
                strLine = rdrMembers.ReadString();
                Console.WriteLine(strLine);
                strLine = rdrMembers.ReadString();
                Console.WriteLine(strLine);
                strLine = rdrMembers.ReadString();
                Console.WriteLine(strLine);
            }
            finally
            {
                rdrMembers.Close();
                fstMembers.Close();
            }
        }
        catch (FileNotFoundException ex)
        {
            Console.Write("Error: " + ex.Message);
            Console.WriteLine(" May be the file doesn't exist " +
                              "or you typed it wrong!");
        }

        return 0;
    }
}

Here is an example of what this would produce:

Error: Could not find file 'C:\Documents and Settings\Administrator\Local 
Settings\Application Data\Temporary 
Projects\ConsoleApplication1\bin\Release\Members.clc'. 
May be the file doesn't exist or you typed it wrong!
Press any key to continue . . .

IOException: As mentioned already, during file processing, anything could go wrong. If you don't know what caused an error, you can throw the IOException exception.

Practical LearningPractical Learning: Handling File Processing Exceptions

  1. To throw exceptions, change the file processing methods from the IceCream.cs file as follows:
     
    using System;
    using System.IO;
    
    namespace IceCream4
    {
        delegate void Request();
    
        // This class is used to create and manage an Ice Cream
        // and to process an order
        public sealed class IceCream
        {
            // This is the base price of an Ice Cream
            // Optional values may be added to it
            public const decimal BasePrice = 1.55M;
    
            // These arrays are used to build the components 
            // of various Ice Creams
            // In C#, we can allocate an array's memory in 
            // the body of the class
            private string[] Flavor;
            private string[] Container;
            private string[] Ingredient;
    
            // Additional factor used to process an Ice Cream order
            private int Scoops;
            private decimal TotalPrice;
    
            // Variables that will hold the user's choice
            // These are declared "globally" so they can be 
            // shared among methods
            int ChoiceFlavor;
            int ChoiceContainer;
            int ChoiceIngredient;
    
            // This default constructor is the best place for 
            // us to initialize the array
            public IceCream()
            {
                Flavor = new string[10];
                Flavor[0] = "Vanilla";
                Flavor[1] = "Cream of Cocoa";
                Flavor[2] = "Chocolate Chip";
                Flavor[3] = "Organic Strawberry";
                Flavor[4] = "Butter Pecan";
                Flavor[5] = "Cherry Coke";
                Flavor[6] = "Chocolate Brownies";
                Flavor[7] = "Caramel Au Lait";
                Flavor[8] = "Chunky Butter";
                Flavor[9] = "Chocolate Cookie";
    
                Ingredient = new string[4];
                Ingredient[0] = "No Ingredient";
                Ingredient[1] = "Peanuts";
                Ingredient[2] = "M & M";
                Ingredient[3] = "Cookies";
    
                Container = new string[3];
                Container[0] = "Cone";
                Container[1] = "Cup";
                Container[2] = "Bowl";
            }
    
            // This method requests a flavor from the user and
            // returns the choice
            public void ChooseFlavor()
            {
                // Make sure the user selects a valid number 
                //that represents a flavor...
                do
                {
                    // In case the user types a symbol that 
                    // is not a number
                    try
                    {
                        Console.WriteLine("What type of flavor do you want?");
                        for (int i = 0; i < Flavor.Length; i++)
                            Console.WriteLine("{0} - {1}", i + 1, Flavor[i]);
                        Console.Write("Your Choice? ");
                        ChoiceFlavor = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)	// display an appropriate message
                    {
                        Console.WriteLine("You must enter a valid number " +
                                          "and no other character!");
                    }
    
                    // If the user typed an invalid number out of the 
                    // allowed range
                    // let him or her know and provide another chance
                    if (ChoiceFlavor < 1 || ChoiceFlavor > Flavor.Length)
                        Console.WriteLine("Invalid Choice - Try Again!\n");
                } while (ChoiceFlavor < 1 || ChoiceFlavor > Flavor.Length);
            }
    
            // This method allows the user to select a container
            public void ChooseContainer()
            {
                // Make sure the user selects a valid number that 
                // represents a container
                do
                {
                    // If the user types a symbol that is not a number
                    try
                    {
                        Console.WriteLine("What type of container do you want?");
                        for (int i = 0; i < Container.Length; i++)
                            Console.WriteLine("{0} - {1}", i + 1, Container[i]);
                        Console.Write("Your Choice? ");
                        ChoiceContainer = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)	// display an appropriate message
                    {
                        Console.WriteLine("You must enter a valid " +
                                          "number and no other character!");
                    }
    
                    // If the user typed an invalid number out of the 
                    // allowed range
                    // let him or her know and provide another chance
                    if ((ChoiceContainer < 1) ||
                        (ChoiceContainer > Container.Length))
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while ((ChoiceContainer < 1) ||
                         (ChoiceContainer > Container.Length));
            }
    
            public void ChooseIngredient()
            {
                do
                {
                    try
                    {
                        Console.WriteLine("Do you want an ingredient or not");
                        for (int i = 0; i < Ingredient.Length; i++)
                            Console.WriteLine("{0} - {1}",
                                              i + 1,
                                              Ingredient[i]);
                        Console.Write("Your Choice? ");
                        ChoiceIngredient = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("You must enter a valid " +
                                          "number and no other character!");
                    }
    
                    if ((ChoiceIngredient < 1) ||
                        (ChoiceIngredient > Ingredient.Length))
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while ((ChoiceIngredient < 1) ||
                         (ChoiceIngredient > Ingredient.Length));
            }
    
            public void SpecifyNumberOfScoops()
            {
                do
                {
                    try
                    {
                        Console.Write("How many scoops(1, 2, or 3)? ");
                        Scoops = int.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("You must enter a valid number " +
                                          "and no other character!");
                    }
    
                    if (Scoops < 1 || Scoops > 3)
                        Console.WriteLine("Invalid Choice - Try Again!");
                } while (Scoops < 1 || Scoops > 3);
            }
    
            // This method is used to process a customer order
            // It uses the values of the above methods
            public void ProcessAnOrder()
            {
                //			int ChoiceFlavor;
                //			int ChoiceContainer;
                //			int ChoiceIngredient;
                decimal PriceIngredient, PriceScoop;
    
                // Let the user know that this is a vending machine
                Console.WriteLine("=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=");
                Console.WriteLine("Ice Cream Vending Machine");
                Console.WriteLine("-----------------------------------");
    
                // Let the user select the components of the Ice Cream
                Request Get = new Request(ChooseFlavor);
                Get();
                Console.WriteLine("-----------------------------------");
                Get = new Request(ChooseContainer);
                Get();
                Console.WriteLine("-----------------------------------");
                Get = new Request(ChooseIngredient);
                Get();
                Console.WriteLine("-----------------------------------");
                Get = new Request(SpecifyNumberOfScoops);
                Get();
                Console.WriteLine("-----------------------------------");
    
                // If the user selects an ingredient instead of "No Ingredient",
                // add $0.50 to the order
                if ((ChoiceIngredient == 2) ||
                    (ChoiceIngredient == 3) ||
                    (ChoiceIngredient == 4))
                    PriceIngredient = 0.50M;
                else
                    PriceIngredient = 0.00M;
    
                // Instead of multiplying a number scoops to a value,
                // We will use an incremental value depending on 
                // the number of scoops
                if (Scoops == 1)
                    PriceScoop = 0.65M;
                else if (Scoops == 2)
                    PriceScoop = 1.05M;
                else
                    PriceScoop = 1.55M;
    
                // Calculate the total price of the Ice Cream
                TotalPrice = BasePrice + PriceScoop + PriceIngredient;
    
                // Create the Ice Cream...
    
                // And display a receipt to the user
                DisplayReceipt();
            }
    
            // This method is used to display a receipt to the user
            public void DisplayReceipt()
            {
                Console.WriteLine("\n=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=");
                Console.WriteLine("Ice Cream Order");
                Console.WriteLine("-----------------------------------");
                Console.WriteLine("Flavor:      {0}",
                                  Flavor[ChoiceFlavor - 1]);
                Console.WriteLine("Container:   {0}",
                                  Container[ChoiceContainer - 1]);
                Console.WriteLine("Ingredient:  {0}",
                                  Ingredient[ChoiceIngredient - 1]);
                Console.WriteLine("Scoops:      {0}", Scoops);
                Console.WriteLine("Total Price: {0:C}", TotalPrice);
                Console.WriteLine("=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=\n");
            }
    
            public void SaveOrder()
            {
                string strNameOfFile;
    
                Console.Write("Please enter your initials or the name " +
                                  "we will use to remember your order: ");
                strNameOfFile = Console.ReadLine();
                strNameOfFile = strNameOfFile + ".icr";
    
                try
                {
                    // Find out if the user entered a name of a file 
                    // that is already in the machine
                    if (File.Exists(strNameOfFile))
                    {
                        char answer;
    
                        FileStream stmIceCream =
                            new FileStream(strNameOfFile, FileMode.Create);
                        BinaryWriter bnwIceCream =
                            new BinaryWriter(stmIceCream);
    
                        try
                        {
    
                            // If so, find out if the user wants to 
                            // replace the old file
                            Console.WriteLine("The file you entered exists already.");
                            Console.Write("Do you want to replace it(y/n)?");
                            answer = char.Parse(Console.ReadLine());
    
                            // If the customer wants to replace it...
                            if (answer == 'y' || answer == 'Y')
                            {
                                // ... do so
                                Console.WriteLine("The former order with the same " +
                                                  "name will be replaced");
    
                                Console.WriteLine("\n=-= Ice Cream " +
    						"Vending Machine =-=");
                                Console.WriteLine(" Saving Order: {0}", strNameOfFile);
                                bnwIceCream.Write(Flavor[ChoiceFlavor - 1]);
                                bnwIceCream.Write(Container[ChoiceContainer - 1]);
                                bnwIceCream.Write(Ingredient[ChoiceIngredient - 1]);
                                bnwIceCream.Write(Scoops);
                                bnwIceCream.Write(TotalPrice);
                            }
                            // If the customer wants to save the new order with 
                            // a different name
                            else if (answer == 'n' || answer == 'N')
                            {
                                // Ask the user to enter a name to remember the order
                                Console.Write("Please enter a name we will use " +
                                              "to remember this order: ");
                                strNameOfFile = Console.ReadLine();
                                strNameOfFile = strNameOfFile + ".icr";
    
                                try
                                {
                                    stmIceCream = new FileStream(strNameOfFile,
    							 FileMode.Create);
                                    bnwIceCream = new BinaryWriter(stmIceCream);
    
                                    Console.WriteLine("\n=-= Ice Cream " +
    						  "Vending Machine =-=");
                                    Console.WriteLine(" Saving Order: {0}",
    						 strNameOfFile);
                                    bnwIceCream.Write(Flavor[ChoiceFlavor - 1]);
                                bnwIceCream.Write(Container[ChoiceContainer - 1]);
                                bnwIceCream.Write(Ingredient[ChoiceIngredient - 1]);
                                    bnwIceCream.Write(Scoops);
                                    bnwIceCream.Write(TotalPrice);
                                }
                                catch (IOException)
                                {
                                    Console.Write("\nThe file you wanted us to " +
    						"create exists already. ");
                                    Console.WriteLine("In case it was registered " +
    						  "by a different customer, " +
    						  "we will not delete it.");
                                }
                            }
                            else
                                Console.WriteLine("Invalid Answer - We will close");
                        }
                        catch (IOException)
                        {
                            Console.Write("\nThat file exists already. ");
                            Console.WriteLine("We need to preserve it just in " +
    					"case another customer will require it.");
                        }
                        finally
                        {
                            bnwIceCream.Close();
                            stmIceCream.Close();
                        }
                    }
                    else
                    {
                        FileStream stmIceCream =
                            new FileStream(strNameOfFile, FileMode.Create);
                        BinaryWriter bnwIceCream =
                            new BinaryWriter(stmIceCream);
    
                        try
                        {
                            Console.WriteLine("\n=-= Ice Cream Vending Machine =-=");
                            Console.WriteLine(" Saving Order: {0}", strNameOfFile);
                            bnwIceCream.Write(Flavor[ChoiceFlavor - 1]);
                            bnwIceCream.Write(Container[ChoiceContainer - 1]);
                            bnwIceCream.Write(Ingredient[ChoiceIngredient - 1]);
                            bnwIceCream.Write(Scoops);
                            bnwIceCream.Write(TotalPrice);
                        }
                        finally
                        {
                            bnwIceCream.Close();
                            stmIceCream.Close();
                        }
                    }
                }
                catch (IOException ex)
                {
                    Console.WriteLine("\nError: " + ex.Message);
                    Console.WriteLine("Operation Canceled: The file you want " +
    					"to create exists already.");
                }
            }
    
            public void OpenOrder()
            {
                string strNameOfFile;
    
                string SelectedFlavor;
                string SelectedContainer;
                string SelectedIngredient;
    
                // Ask the user to enter a name of a previously saved order
                Console.Write("Please enter the name you previously " +
                              "gave to remember your order: ");
                strNameOfFile = Console.ReadLine();
                strNameOfFile = strNameOfFile + ".icr";
    
                try
                {
                    FileStream stmIceCream =
                        new FileStream(strNameOfFile, FileMode.Open);
                    BinaryReader bnrIceCream =
                        new BinaryReader(stmIceCream);
    
                    try
                    {
                        // Find out if this order was previously saved in the machine
                        if (File.Exists(strNameOfFile))
                        {
                            // If so, open it
                            SelectedFlavor = bnrIceCream.ReadString();
                            SelectedContainer = bnrIceCream.ReadString();
                            SelectedIngredient = bnrIceCream.ReadString();
                            Scoops = bnrIceCream.ReadInt32();
                            TotalPrice = bnrIceCream.ReadDecimal();
    
                            // And display it to the user
                            Console.WriteLine("\n=-= Ice Cream Vending Machine =-=");
                            Console.WriteLine(" Previous Order: {0}", strNameOfFile);
                            Console.WriteLine("Flavor:      {0}", SelectedFlavor);
                            Console.WriteLine("Container:   {0}", SelectedContainer);
                            Console.WriteLine("Ingredient:  {0}", SelectedIngredient);
                            Console.WriteLine("Scoops:      {0}", Scoops);
                            Console.WriteLine("Total Price: {0:C}\n", TotalPrice);
                        }
                        else
                            Console.WriteLine("The name you entered is not " +
                                              "registered in our previous orders");
                    }
                    finally
                    {
                        bnrIceCream.Close();
                        stmIceCream.Close();
                    }
                }
                catch (FileNotFoundException ex)
                {
                    Console.Write("\nError: " + ex.Message);
                    Console.WriteLine("It is unlikely that the file exists in " +
    				  "our machine's register.");
                }
            }
        }
    }
  2. Exercise the application and test it
  3. Close the DOS window
 

Previous Copyright © 2006 FunctionX, Inc. Next