Monday, November 4, 2013

WPF application with Try Parse and Try Catch

The form XAML

<Window x:Name="myWindow" x:Class="MileageApplicationMorning.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Label Content="Enter Beginning Mileage" HorizontalAlignment="Left" Margin="29,25,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="txtBeginMileage" HorizontalAlignment="Left" Height="23" Margin="208,28,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <Label Content="Enter Ending Mileage" HorizontalAlignment="Left" Margin="41,72,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="txtEndingMileage" HorizontalAlignment="Left" Height="23" Margin="208,72,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <Label Content="Enter Gallons" HorizontalAlignment="Left" Margin="38,113,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="txtGallons" HorizontalAlignment="Left" Height="23" Margin="208,116,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <Button x:Name="btnCalculate" Content="Calculate" HorizontalAlignment="Left" Margin="53,171,0,0" VerticalAlignment="Top" Width="75" Click="btnCalculate_Click"/>
        <Label x:Name="lblResult" Content="Label" HorizontalAlignment="Left" Margin="208,168,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.352,-0.24" Width="205" Height="60"/>

    </Grid>
</Window>

The code behind the form


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MileageApplicationMorning
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            //this sets the background to a gradient color pattern
            myWindow.Background = new LinearGradientBrush(Colors.PowderBlue, Colors.White, 45);

        }

        private void btnCalculate_Click(object sender, RoutedEventArgs e)
        {
            //initialize the mileage class
            Mileage m = new Mileage();
            //declare values for the out parameters of the try parses
            int begin;
            int end;
            double gallons;

            //this uses the TryParse in the if statement
            //you can do this because the tryParse returns
            //a boolean--true or false
            if (int.TryParse(txtBeginMileage.Text, out begin))
            {
                //if it is good assign it to the class
                //using the set function of the property
                m.BeginMileage = begin;
            }
            else
            {
                //otherwise show a message box with a prompt
                MessageBox.Show("Enter a valid integer");
                return;
            }

            if (int.TryParse(txtEndingMileage.Text, out end))
            {
                m.EndMileage = end;
            }
                
            else
            {
                MessageBox.Show("Enter a valid integer");
                txtEndingMileage.Clear();
                return;
     
            }
            if (double.TryParse(txtGallons.Text, out gallons))
            {
                //for gallons because we threw the error
                //if it was a 0 we need to catch the error
                //the try tries code. If there is no error 
                //it just executes the code; if it encounters
                //an error it drops to the catch and does
                //whatever it says to do, in this case
                //just display the error message
                try
                {
                    m.Gallons = gallons;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
            else
            {
                 MessageBox.Show("Enter a valid double");
                 txtGallons.Clear();
                 txtGallons.Focus();
                return;
            }
            double mpg;
            try
            {
                mpg = m.CalculateGasMileage();
                //uses the ToString() method of the class
                //to display the results of the calculation
                lblResult.Content = mpg.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

         //changes background colors based on the mpg value
            if (mpg > 40)
            {
                lblResult.Background= new SolidColorBrush(Colors.Green);
            }
            else if (mpg > 30)
            {
                lblResult.Background = new SolidColorBrush(Colors.Purple);
            }
            else if (mpg > 20)
            {
                lblResult.Background = new SolidColorBrush(Colors.Yellow);
            }
            else
            {
                lblResult.Background = new SolidColorBrush(Colors.Red);
            }

           

        }
    }
}

The Mileage class code with the throw exception in the Gallons Property

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MileageApplicationMorning
{
    class Mileage
    {
        //class variables or fields
        //fields should be private
        private int beginMileage;
        private int endMileage;
        private double pricePerGallon;
        private double gallons;

        //constructors are ways of constructing
        //the class, they set the initial values
        //a constructor always has the same name
        //as the the class and no return type
        //A class can have several "overloaded" constructors
        //only one is used per instance of the class
        //the user chooses which constructor he or she
        //wants to use by the signature (what parameters it takes)

        //this is a default constructor. It has no arguments
        //and sets all the properties to their minumum value;
        //If you write no constructor at all this is what you get
        //if you do write a constructor it is up to you to 
        //provide the initial values
        public Mileage()
        {
            PricePerGallon = 1;
            BeginMileage = 0;
            EndMileage = 0;
            Gallons = 1; //had to change to 1 to keep 
            //from throwing the error on calling
            //the class
        }

        //this is an overloaded constructor that takes three
        //values. A user could choose to do this rather than
        //set the values using the properties
        public Mileage(int begin, int end, double gal)
        {
            BeginMileage = begin;
            EndMileage = end;
            Gallons = gal;
            PricePerGallon = 0;

        }

        //this constructor takes four values
        public Mileage(int begin, int end, double gal, double price)
        {
            BeginMileage = begin;
            EndMileage = end;
            Gallons = gal;
            PricePerGallon = price;
        }


        //public properties are ways 
        //to expose the fields in a 
        //controlled way
        //you can do some validation
        //and testing in a property
        public double PricePerGallon
        {
            get { return pricePerGallon; }
            set { pricePerGallon = value; }
        }
        

      
        public double Gallons
        {
            get { return gallons; }
            set
            {
                //here we are going to test to see
                //if the value passed in is equal to 0
                //if it is we will throw an exception
                //that we can handle in the form
                if (value == 0)
                {
                    throw new DivideByZeroException();
                }
                else
                {
                    gallons = value;
                }
            }
                 
        }
      

      
        public int BeginMileage
        {
            get { return beginMileage; }
            set { 
               
                    beginMileage = value; 
                }
            
        }

        public int EndMileage
        {
            get { return endMileage; }
            set {endMileage = value; }
        }

        //a class can contain both private (internal)
        //methods and public methods
        private int TotalMiles()
        {
            return EndMileage - BeginMileage;
        }

        //public method accessible from other
        //classes
        public double CalculateGasMileage()
        {
            int total = TotalMiles();
            double milesPerGallon = total / Gallons;
            return milesPerGallon;
        }

        //this is an overloaded method. It has the same
        //name but a different signature than the previous method
        //again it gives a user of the class another option
        //of how to use the class and call the method
        public double CalculateGasMileage(int bMiles, int eMiles, double gals)
        {
            BeginMileage = bMiles;
            EndMileage = eMiles;
            Gallons = gals;
            int total = TotalMiles();
            double milesPerGallon = total / Gallons;
            return milesPerGallon;


        }

        //this is "overriding" the ToString method
        //which every class inherits from Object
        //the parent of all classes in .NET
        //the combination of overloading and overwriting is 
        //what constitutes the object oriented principle of
        //polymorphism--the ability of a class
        //to behave differently in different environments
        public override string ToString()
        {
            double mpg = CalculateGasMileage();
            return "Your gas mileage is" + mpg.ToString("##.##");
        }


    }
}

No comments:

Post a Comment