Sunday, December 1, 2013

File IO C#

The code for this is on GitHub at https://github.com/spconger/HandlingFiles/tree/master/HandlingFiles

Here are screen shots of the program running

Here is a screen shot of the file in the folder

Sunday, November 24, 2013

Assignment 7: Division

Division is by far the hardest part of the assignment. Now that you have struggled with it for awhile, lets talk through the process of how you would handle it.

The code for this example can be found at https://github.com/spconger/ThirdGradeMath

First you should identify what the unique elements of division are. Remember we are doing third grade level, integer division.

* For one the first number should be bigger than the second
* we want to avoid 0 in the divisor or the dividend
* because we are using integer division we must handle remainders

First we add a division method and a remainder method to the BasicMath class



You should add some error checking to these methods

Next we add a division button and a textbox called "txtRemainder" to the WebForm. Double click the button to get the click event. Then we call the GetNumbers() method just like the other operators:



We are going to have to make some alterations to the GetNumbers() method, but first lets create a new method that makes sure the first number is bigger than the second number.



We need to make other changes.

Number1 and Number2 need to be declared at the class level



Then we need to change GetNumbers() so that it looks like the code below. Basically, we need to check to see if the operator is subtraction or division, then we need to check if the first number is less than the second one. If it is we call our swap method. The other main difference is that we now assign the random numbers to the variables number1 and number2 rather than directly to the labels. We test them first and then assign them to the labels.



We also have to make some changes to the check answer method. Division needs to be handled differently because of the remainder issue.

So at the top of the CheckAnswer method we add the following if statement:



Next we will create a new check for division. We need to make sure both the answer and remainder session variables exist. Then I use a try parse to check that the users answers are valid. Here is the complete check Division method:



Here is the button click method for division:


Wednesday, November 20, 2013

SQL Part Two: Joins, Insert, Update, Delete

use TutorManagement

Select * From TutorCourse

--here is a simple inner join
--joins are used to "join" two or more tables
--Here the tutor and tutorCourse tables
--to find the names of all the tutors who
--teach Web110
Select Tutor.TutorKey, TutorFirstName, TutorLastName, CourseKey
From Tutor
inner join TutorCourse
on Tutor.TutorKey=TutorCourse.TutorKey
Where CourseKey = 'Web110'

--same query but with the tables aliased.
--it just saves time
Select t.TutorKey, TutorFirstName, TutorLastName, CourseKey
From Tutor t
inner join TutorCourse tc
on t.TutorKey=tc.TutorKey
Where CourseKey = 'Web110'

--an old way to do a join. Shorter but more dangerous
--especially as you start joining more tables
Select t.TutorKey, TutorFirstName, TutorLastName, CourseKey
From Tutor t, TutorCourse tc
Where t.TutorKey=tc.TutorKey
And CourseKey='Web110'

--creates a cross join
--a cross join is where each record in the first table
--is matched to every record in the second table
--this can happen on purpose or by accident
--if you forget to add a realtionshio
Select t.TutorKey, TutorFirstName, TutorLastName, CourseKey
From Tutor t, TutorCourse tc
Where CourseKey='Web110'

Select * From Session

--A join with three tables
Select TutorLastName, SessionDateKey, SessionTimeKey,
Coursekey, StudentLastName
From Tutor
Inner Join [Session] 
on Tutor.TutorKey=[Session].TutorKey
Inner Join Student
on Student.StudentKey=[Session].StudentKey

Select * From tutor
order by TutorLastName

--Insert new records into the tutor table
--if you have an auto increment (identity) column, do not include it in the 
--fields for the insert
Insert into Tutor(TutorKey, TutorLastName, 
TutorFirstName, TutorPhone, 
TutorEmail, TutorHireDate, TutorStatus)
Values('980000000', 'Smith', 'John', '2065552356','js@gmail.com',GetDate(),'Active'),
('980000001', 'Jones', 'Jason', '2065552956','jj@gmail.com',GetDate(),'Active')


--this begins a manual transaction
--this allows for the possiblity of an undo
Begin tran

--updates the tutor table
--essential that this has a where clause
--unless you wish to update all the rows
--in the table
Update Tutor
Set TutorFirstName = 'Jonathan'
Where TutorKey='980000000' 

Select * from Tutor

rollback tran --cancels the transaction, your undo
Commit tran--commits the transaction to the database
--once commited there is no undo

--Deletes a row from the table Tutor
--this is best done in a transaction also
--you cannot delete a parent that has children
--unless you delete the children first
Delete from Tutor
Where TutorKey='980000000' 


Monday, November 18, 2013

Addition ASP Net Page

Here is the RandomGenerator.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// 
/// this class returns a random number
/// between the minimum and maximum values
/// 
public class RandomGenerator
{

    //private variables
  
    private int maximum = 0;
    private int minimum = 0;
    private Random rand;

    //only one constructor that requires a 
    //minimum and maximum value
 public RandomGenerator(int max, int min)
 {
        //initialize the random number 
        rand = new Random();
        maximum = max;
        minimum = min;
     }

    public int GetNumber()
    {
        //return a new random number
        return rand.Next(minimum, maximum);
    }
}

Here is the BasicMath.cs class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// 
/// This class is for doing the most basic
/// of math. I have included only addition
/// 
public class BasicMath
{
    //the private fields
    private int number1;
    private int number2;

    //the empty default constructor
 public BasicMath()
 {
        number1 = 0;
        number2 = 0;
 }

    //an alternate overloaded constructor
    public BasicMath(int num1, int num2)
    {
        NumberOne = num1;
        NumberTwo = num2;
    }

    //public properties
    public int NumberOne
    {
        get { return number1; }
        set { number1 = value; }
    }

    public int NumberTwo
    {
        get { return number2; }
        set { number2 = value; }
    }

    //addition method
    public int Addition()
    {
        return number1 + number2;
    }
}

here is Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>math time</title>
    <link href="BasicMathStyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1>Math Play Time</h1>
        <p>
        <asp:Button ID="getNumbers" runat="server" Text="+" OnClick="addition_Click" />

        </p>
        <p>
            <asp:Label ID="lblNumber1" runat="server" Text=""></asp:Label>
            <asp:Label ID="lblOperator" runat="server" Text=""></asp:Label>
            <asp:Label ID="lblNumber2" runat="server" Text=""></asp:Label>
            <asp:TextBox ID="txtUserAnswer" runat="server"></asp:TextBox>
            </p>
        <p>
            <asp:Button ID="btnCheckAnswer" runat="server" Text="Check Answer" OnClick="btnCheckAnswer_Click" />
            <asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
        </p>

    </div>
    </form>
</body>
</html>


Here is the Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    //initialize the basic math class
    BasicMath m = new BasicMath();
    int answer = 0; //declare answer variable

    protected void Page_Load(object sender, EventArgs e)
    {
        //this is to provide a problem when the page first loads
        //the !IsPostback guarantees it runs only
        //on the first page load not on button clicks
        if (!IsPostBack)
        GetAddition();
    }
    protected void addition_Click(object sender, EventArgs e)
    {
        //call the get addition method
        GetAddition();
    }

    protected void GetAddition()
    {
        // call the getNumbers method and pass
        //it the min, max, and operator
        GetNumbers(0, 1000, "+");
        //get the answer from the class
        answer = m.Addition();
        //store it in a session variable
        Session["answer"] = answer;
    }

    protected void GetNumbers(int min, int max, string oper)
    {
        //get the random numbers and display them in the labels
        //including the operation
        RandomGenerator rg = new RandomGenerator(max, min);
        lblNumber1.Text = rg.GetNumber().ToString();
        lblNumber2.Text = rg.GetNumber().ToString();
        m.NumberOne = int.Parse(lblNumber1.Text);
        m.NumberTwo = int.Parse(lblNumber2.Text);
        lblOperator.Text = oper;

    }
    protected void btnCheckAnswer_Click(object sender, EventArgs e)
    {
       
        //if the session exists
        if (Session["answer"] != null)
        {
            //get their answer --should be try parse
            int userAnswer = int.Parse(txtUserAnswer.Text);
            //get the actual answer from the session variable
            answer = (int)Session["answer"];
            //if the anser is correct congrats
            if (userAnswer == answer)
            {
                lblResult.Text = "Great job";
                //assign a cssClass on the fly
                lblResult.CssClass = "correct";

            }
            else //otherwise try again
            {
                lblResult.Text = "Try again";
                txtUserAnswer.Text = "";
                txtUserAnswer.Focus();
                lblResult.CssClass = "mistake";
            }
        }
    }
}

Here is BasicMath.css

body {
}

.correct {
    color:green;
}

.mistake {
    color:red;
}

h1 {
    color:navy;
}

SQL (part one)

Use Tutormanagement

--basic sql statement

/*
this is a multiline
comment
*/

Select StudentLastname, Studentfirstname from Student;

Select * From Student

Select StudentLastName as [Last Name], StudentFirstName as [First Name]
From Student
order by StudentLastName desc, StudentFirstname

Select StudentLastName [Last Name], StudentFirstName [First Name]
From Student

Select StudentLastName LastName, StudentFirstName FirstName
From Student

Select distinct TutorKey from [Session]

Select 5 + 14 * (3 /2 )


Use CommunityAssist

Select * from Donation

Select donationamount, donationAmount * .8 as charity, donationamount * .2 as organization
from donation

Use TutorManagement

Select * from Student

Select StudentLastName, StudentEmail from Student
Where StudentLastName= 'Bradbury'

Select StudentLastName, StudentAge
from Student
Where StudentAge > 24

-->,< >=, <=, !=, =,<>

Select StudentLastName, StudentAge
from Student
Where StudentAge > 24
And StudentLastName like 'C%'

Select StudentLastName, StudentAge
from Student
Where StudentAge > 24
or StudentLastName like 'C%'

-- % for any number of characters
-- _ for a single character

-- MIC 1_2  MIC 122, MIC 102,

Select * From Student

Select StudentLastName, StudentEmail
From Student
Where studentEmail is not null


Select StudentLastName, StudentEmail
From Student
Where studentEmail is null

--scalar only operates on one row at a time

Select * from Session
Select distinct Year(SessionDateKey) as [Year] from Session
order by year(SessionDateKey) Desc

Select distinct Month(SessionDateKey) as [Month] from Session
order by Month(SessionDateKey) Desc

Select  Year(SessionDateKey) as [Year], Month(SessionDateKey) as [Month]
From Session
order by year(SessionDateKey) Desc,Month(SessionDateKey) Desc

Select DATEDIFF(dd, '11/18/2013', '12/11/13')
Select DateAdd(yy,  20,'11/18/13')

Select GetDate()

--aggregate operate across multilple rows

Select * From [Session]
Select count(StudentKey) as NumberOfStudents from Student
Select count (Distinct SessionDateKey) as [Sessions] from [Session]
Select count (SessionStatus) as [Sessions] from [Session]

Select Sum(StudentAge) / Count(StudentKey) From Student

Select avg(StudentAge) From Student

Select Max(StudentAge) From Student

Select Min(StudentAge) From Student

Select * From Student

Select Year(SessionDateKey) as [Year], Count(StudentKey) as Students 
from Session
Group by Year(SessionDatekey)

Select TutorKey, Count(StudentKey) as students
from Session
Group by tutorkey




Wednesday, November 13, 2013

Evening Web Example

the Web Form html and asp

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="ExampleWebPage.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1>Enter Quotes</h1>
        <p> Enter your favorite quotes  <asp:TextBox ID="txtQuote" runat="server"></asp:TextBox> </p>
        <p>
            <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" /></p>
        <p>
            <asp:Button ID="btnQuote" runat="server" Text="Get Quote" OnClick="btnQuote_Click" />
        <asp:Label ID="Label1" runat="server" Text="Label" 
            CssClass="response"></asp:Label></p>
        <asp:Button ID="btnGetAllQuotes" runat="server" Text="Get all Quotes" OnClick="btnGetAllQuotes_Click" />
        <asp:BulletedList ID="BulletedList1" runat="server"></asp:BulletedList>
    </div>
    </form>
</body>
</html>

The code behind the web page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    Quote q = new Quote();
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        //if the session exists
        //get the existing instance of the class
        //from the session and use it
        if (Session["quotes"] != null)
        {
            q = (Quote)Session["quotes"];
        }
        q.AddQuote(txtQuote.Text);
        Session["quotes"] = q;
        txtQuote.Text = ""; //clear textbox

    }
    protected void btnQuote_Click(object sender, EventArgs e)
    {
        //get the current instance saved in the session
        q = (Quote)Session["quotes"];
        //call its method
        Label1.Text = q.GetQuote();
    }
    protected void btnGetAllQuotes_Click(object sender, EventArgs e)
    {
        q = (Quote)Session["quotes"];
        BulletedList1.DataSource = q.Quotes;
        BulletedList1.DataBind();
    }
}

the Quote class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// 
/// Summary description for Quote
/// 
public class Quote
{

    // create a list object to store strings
    private List quotes;

    //initialize the list in the constructor
 public Quote()
 {
        quotes = new List();
 }

    //read only property
    public List Quotes
    {
        get { return quotes; }
    }

    //add quotes to the list
    public void AddQuote(string aQuote)
    {
        quotes.Add(aQuote);
    }

    //return a random quote
    public string GetQuote()
    {
        string quoteResult = null;
        Random rand = new Random();
        if (quotes.Count != 0)
        {
            int number = rand.Next(0, quotes.Count );
            quoteResult = quotes[number];
        }
        return quoteResult;
    }
}

the style sheet such as it is

body {
}

h1 {
    background-color:navy;
    color:white;
}

.response {
    color:green;
}

Tuesday, November 12, 2013

boreing stuff ASP.Net page

Here is the web page Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="BoreingStuff.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>Quote Generator</h1>
        <p>
            Enter a favorite Quote: 
            <asp:TextBox ID="txtQuote" runat="server"></asp:TextBox> <br />
            <asp:Button ID="btnEnter" runat="server" Text="Enter" OnClick="btnEnter_Click" />

        </p>
        <p>
            <asp:Button ID="btnGetQuote" runat="server" Text="Get Quote" OnClick="btnGetQuote_Click" />
            <asp:Label ID="lblResult" runat="server" Text="Label"></asp:Label>
        </p>
    </div>
    </form>
</body>
</html>

Here is the code behind Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    //create a new instance of the Quotes class
    Quotes q = new Quotes();

    protected void Page_Load(object sender, EventArgs e)
    {
        
    }
    protected void btnEnter_Click(object sender, EventArgs e)
    {
        //see if the session has something in it
        if (Session["quotes"] != null)
        {
            //if it does use it instead of a new Quotes object
            q = (Quotes)Session["quotes"];
        }
        //write the quote from the textbox into the list
        q.AddQuote(txtQuote.Text);
        //save the object to the session
        Session["quotes"] = q;
        //clear the textbox
        txtQuote.Text = "";
       
    }
    protected void btnGetQuote_Click(object sender, EventArgs e)
    {
        //recall the session and get the quote object
        q = (Quotes)Session["quotes"];
        //call the GetQuote method and assign the string
        //to the label
        lblResult.Text = q.GetQuote();
    }
}

Here is the Quotes.cs class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// 
/// Summary description for Quotes
/// this class takes quotes
/// and stores them in a list object
/// the list object behaves a lot like
/// an array but you don't have to 
/// give it a fixed size
/// 
public class Quotes
{

    //declaring a list object  
    //is generic syntax. It assigns a 
    //type for the list at runtime
    private List myQuotes;

 public Quotes()
 {
        //initialize the list in the constructor
        myQuotes = new List();
 }

    public List MyQuotes
    {
        //will let the user get the list
        get { return myQuotes; }
        
    }

    public void AddQuote(string quote)
    {
        //adds a quote to the list
        MyQuotes.Add(quote);
    }

    public string GetQuote()
    {
        //create a random object
            Random rand = new Random();
         // get a number between 0 and the number of elements
        //in the list (minus 1 to account for starting at 0)
            int index = rand.Next(0, MyQuotes.Count - 1);
        //return the quote at that index
            return myQuotes[index];
    }


}

And for what it's worth here is the boreingstuff.css file

body {
}
h1 {
    color:white;
    background-color:navy;
}

.testclass {
    color: green;
}

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("##.##");
        }


    }
}

Wednesday, October 30, 2013

WPF applicarion Evening

.Here is the windows form XML

<Window x:Class="MileageApplication.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" Name="MPGWindow">
    <Grid>
        <Label Content="Enter Beginning Mileage" HorizontalAlignment="Left" Margin="40,30,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="txtBeginMiles" HorizontalAlignment="Left" Height="23" Margin="208,30,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <Label Content="Enter Ending Mileage" HorizontalAlignment="Left" Margin="40,74,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="txtEndingMiles" HorizontalAlignment="Left" Height="23" Margin="208,74,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <Label Content="Enter Gallons" HorizontalAlignment="Left" Margin="50,116,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="txtGallons" HorizontalAlignment="Left" Height="23" Margin="208,119,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <Button x:Name="btnCalculate" Content="Calculate" HorizontalAlignment="Left" Margin="50,157,0,0" VerticalAlignment="Top" Width="75" Click="btnCalculate_Click"/>
        <Label x:Name="lblResult" Content="Label" HorizontalAlignment="Left" Margin="208,177,0,0" VerticalAlignment="Top" Width="131" Height="56"/>
        <Button x:Name="btnExit" Content="Exit" HorizontalAlignment="Left" Margin="50,213,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="-0.507,0.1" Click="btnExit_Click"/>

    </Grid>
</Window>


Here is 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 MileageApplication
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            MPGWindow.Background = new LinearGradientBrush(Colors.BlueViolet,
                Colors.AliceBlue, 45);
        }

        private void btnCalculate_Click(object sender, RoutedEventArgs e)
        {
            int bMiles;
            Mileage m = new Mileage();

            bool isGoodBegMiles = int.TryParse(txtBeginMiles.Text, out bMiles);
            if (isGoodBegMiles)
            {
                m.BeginMileage = bMiles;
            }
            else
            {
                MessageBox.Show("Enter a valid integer for beginning Miles");
                return;
            }

            m.EndMileage = int.Parse(txtEndingMiles.Text);
            m.Gallons = double.Parse(txtGallons.Text);
            double mpg = m.CalculateGasMileage();
            lblResult.Content = mpg.ToString();

            if (mpg > 40)
                lblResult.Background = new SolidColorBrush(Colors.Green);
            else if (mpg > 30)
                lblResult.Background = new SolidColorBrush(Colors.GreenYellow);
            else if (mpg > 20)
                lblResult.Background = new SolidColorBrush(Colors.Yellow);
            else
                lblResult.Background = new SolidColorBrush(Colors.Red);





        }

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }
    }
}


Here is the Mileage Class, the same as we had before with one change: the Namespace was changed to match the rest of the application.

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

namespace MileageApplication
{
    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 = 0;
            BeginMileage = 0;
            EndMileage = 0;
            Gallons = 0;
        }

        //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 { 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("##.##");
        }


    }
}

Here is a picture of the application running


Tuesday, October 29, 2013

Morning Class Example 2

View the Evening class post to see commented code

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

namespace ClassicExamples
{
    class Mileage
    {
        //private fields
        private int beginningMileage;
        private int endingMileage;
        private double pricePerGallon;
        private double gallons;

        public Mileage()
        {
            BeginningMileage = 0;
            EndingMileage = 0;
            Gallons = 0;
            PricePerGallon = 0;
        }

        public Mileage(int begin, int end, double gals)
        {
            BeginningMileage = begin;
            EndingMileage = end;
            Gallons = gals;
            PricePerGallon = 0;
        }

        //public properties
        public int EndingMileage
        {
            get { return endingMileage; }
            set {
                if (value > 0)
                    endingMileage = value;
                else
                {
                    endingMileage = -1;
                }
            }
        }
       

        public double Gallons
        {
            get { return gallons; }
            set { gallons = value; }
        }
       

        public double PricePerGallon
        {
            get { return pricePerGallon; }
            set { pricePerGallon = value; }
        }

      
        public int BeginningMileage
        {
            get { return beginningMileage; }
            set { beginningMileage = value; }
        }
       // public int EndingMileage { get; set; }

        //methods
        private int CalculateTotalMiles()
        {
            return EndingMileage - BeginningMileage;
        }

        public double CalculateMilesPerGallon()
        {
            int totalMiles = CalculateTotalMiles();
            double mPG = totalMiles / Gallons;
            return mPG;
        }

        public double CalculateMilesPerGallon(int begin, int end, double gals)
        {
            BeginningMileage = begin;
            EndingMileage = end;
            Gallons = gals;
            int totalMiles = CalculateTotalMiles();
            double mPG = totalMiles / Gallons;
            return mPG;

        }

        public void CalculateCostPerMile()
        {
            throw new System.NotImplementedException();
        }

        public override string ToString()
        {
            return "Your miles per gallon is " + CalculateMilesPerGallon().ToString();
        }
    }
}

Monday, October 28, 2013

Evening Mileage class Revised with comments

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

namespace ClassesExample
{
    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 = 0;
            BeginMileage = 0;
            EndMileage = 0;
            Gallons = 0;
        }

        //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 { 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("##.##");
        }


    }
}

Chapter five Assignments

Wednesday, October 23, 2013

First take at a class evening

Here is the Program class

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

namespace ClassesExample
{
    class Program
    {
        static void Main(string[] args)
        {
            //call the mileage class and make it new
            Mileage m = new Mileage();
            //for now we are just hard coding
            //values to show the point
            //here we are assigning values to the 
            //properties
            //m is the name we gave this instance of a class
            //the dot . is a membership operator
            //it shows what belongs to the Mileage class
            m.BeginMileage = 300;
            m.EndMileage = 600;
            m.Gallons = 7;
            //in the console writeline we are calling the public
            //method CalculateGasMileage()
            Console.WriteLine(m.CalculateGasMileage().ToString("#.##"));
            Console.ReadKey();
            
        }
    }
}


Here is the Mileage class --so far

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

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

        //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; }
        }
        private double gallons;

      
        public double Gallons
        {
            get { return gallons; }
            set { 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;
        }
    }
}

Here is a more complete version of the showtime diagram

Tuesday, October 22, 2013

Using the Random Object

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

namespace RandomNumbers2
{
    class Program
    {
        //this program is just a demonstration
        //of using the Random object.
        //when declared at class level
        //the random actually displays
        //different numbers in the loop below.
        //first you have to make the Random
        //object new
        Random rand = new Random();
        static void Main(string[] args)
        {
            Program p = new Program();
            //call display random
            p.DisplayRandom();
            //call random loop
            p.RandomLoop();
            Console.ReadKey();
        }

        int GetRandom()
        {
            //the Next method lets you set
            //the minimum (1) and the Maximum(100)
            //bounds for the number to be returned
            return rand.Next(1, 100);
        }

        void DisplayRandom()
        {
            //just display the random number returned
            Console.WriteLine("the random number is {0}" ,GetRandom());
        }

        void RandomLoop()
        {
            //declare an array
            int[] myArray=new int[6];
            //loop through the array and add random
            //numbers for each index
            for (int i = 0; i < myArray.Length; i++)
            {
                //add random to array
                myArray[i] = GetRandom();
            }
           
            //In the foreach loop you specifiy
            //the kind (int) of object stored in the
            //array or collection and it controls
            //the number of times you loop
            //looping once for each object of that type
            //in the array
            foreach (int j in myArray)
            {
                Console.WriteLine(j);
            }
        }
    }
}

Monday, October 21, 2013

Random and while loop for validation

a bit of a mess

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

namespace RandomNumbers
{
    class Program
    {
        int number;
        Random rand;
        static void Main(string[] args)
        {
            Program p = new Program();
            p.ValidateEntry();
            Console.ReadKey();
        }

        void GenerateRandomNumber()
        {
           rand = new Random();
           number = rand.Next(1, 1000);
            
            
        }

        void PopulateArray()
        {
        //    int[] grades = new int[5];
           GenerateRandomNumber();
        //    for (int i = 0; i < 5; i++)
        //    {
        //        rand.Next(0, 4);
        //        int x = rand.Next(10000, 100000);
        //        for (int j = 0; j < x; j++)
        //        {
        //        }
        //        grades[i] = number;
        //    }
        //    ReadArray(grades);
            number = rand.Next(1, 100);
            Console.WriteLine(number);
        }

        void ReadArray(int[] grades)
        {
            foreach (int i in grades)
            {
                Console.WriteLine(i);
            }
        }

        void ValidateEntry()
        {
            int[] myArray = new int[5];
            

            for (int i = 0; i < myArray.Length; i++)
            {
                int number = -1;
                while (number < 1 || number > 500)
                {
                    Console.WriteLine("Enter a number 1 and 500");
                    number = int.Parse(Console.ReadLine());
                    if (number < 1 || number > 500)
                    {
                        Console.WriteLine("invalid numbers");
                    }
                }
                myArray[i] = number;
               
            }

            ReadArray(myArray);
        }
    }
}

First Entity Relation Diagram(ERD)

Tuesday, October 15, 2013

Arrays and loops Morning

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

namespace loopyExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            //set up a string variable for the while loop
            string status = "yes";
            //loop as long as the status variable = "yes"
            while(status.Equals("yes"))
            {
                //call methods
                p.ArrayBasedOnVariable();
                p.CreateArray();
                p.AnotherWayToCreateAnArray();
                //check to see if user wants to continue
                Console.WriteLine("Continue yes/no");
                status = Console.ReadLine();
                
              status.ToLower();
            }
            //don't need readkey with the loop
            //Console.ReadKey();
        }

        void CreateArray()
        {
            //this just looks at how an array is structured
            //declare it with a type and []
            string[] movies = new string[4];
            //4 is the number of elements the array can contain
            //each array item is indexed
            movies[0] = "The Princess Bride";
            movies[1] = "Die Hard";
            movies[2] = "Breakfast at Tiffany's";
            movies[3] = "Galaxy Quest";
            //you can access an particular array item
            //by its index
            Console.WriteLine(movies[2]);

        }

        void AnotherWayToCreateAnArray()
        {
            //another way to declare and array
            string[] dogBreeds = new string[] { "collie", "poodle", "Labrador", "spaniel", "bull dog" };

            //a for loop to read through the array's items
            //int i is a counter we set it to 0 (all arrays begin with zero)
            //we keep looping until i is no longer less than the length
            //of the array. With every loop we increment i (add 1)
            for (int i = 0; i < dogBreeds.Length; i++)
            {
                Console.WriteLine(dogBreeds[i]);
            }
        }

        void ArrayBasedOnVariable()
        {
            //here we get the length of the array from the user
            Console.WriteLine("how many integers do you want to enter?");
            int size = int.Parse(Console.ReadLine());

            //size must have a value before you can use
            //the variable in the array
            int[] numbers=new int[size];

            //loop through the array and add numbers to it
            for (int i = 0; i < size;i++)
            {
                Console.WriteLine("enter an Integer");
                numbers[i] = int.Parse(Console.ReadLine());
           }
            Console.Clear(); //this just clears the stuff above

            //I calculate the total in two different ways
            //you only need to use one of them
            //the .Sum() and .Average() methods
            //exist only in C# . In most languages you
            //have to accumulate the values itself
            int total = 0;
            for (int i = 0; i < size;i++)
            {
               
                Console.WriteLine(numbers[i]);
                //the += is the same as total + total + numbers[i];
                total += numbers[i];
            }

            //this is the same as the Average() method
            double average = (double)total / numbers.Length;

            //this displays both sets of results. they are the same
            Console.WriteLine("total manually {0}", total);
            Console.WriteLine("Average Manually {0}", average);
            Console.WriteLine("*********************");
            Console.WriteLine("the total using Sum is {0}",numbers.Sum());
           Console.WriteLine("the average using Average is {0}",numbers.Average());


        }
    }

}

Monday, October 14, 2013

Arrays and loops

Here is the first set of array examples

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

namespace ArrayloopExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            //p. CreateArray();
           // p.CreateArray2();
           // p.CreateArrayWithVariable();
            p.CreateTwoDimensionalArray();
            Console.ReadKey();
        }

        void CreateArray()
        {
            //this creates and populates an array of movies
            string[] movies = new string[3];
            movies[0] = "Gravity";
            movies[1] = "Apollo 13";
            movies[2] = "Space Cowboys";

            Console.WriteLine("Enter a number 1 to 3");
            int number = int.Parse(Console.ReadLine());
            Console.WriteLine(movies[number - 1]);
        }

        void CreateArray2()
        {
            //this is another way to populate an array
            string[] books = new string[] { "American Gods", "Alchemist", 
                "Cat in the Hat", "IQ84", "SnowCraft" };

            Console.WriteLine("Enter a number 1 to 5");
            int number = int.Parse(Console.ReadLine());
            Console.WriteLine(books[number - 1]);
        }

        void CreateArrayWithVariable()
        {
            //this give an array a size using a variable
            //the variable must have a value before it can
            //be used in the array
            Console.WriteLine("How many items do you wish to store?");
            int number = int.Parse(Console.ReadLine());

            int[] myArray = new int[number];

            Console.WriteLine("the array has {0} elements", myArray.Length);
        }

        void CreateTwoDimensionalArray()
        {
            //this shows a 2 dimensional array
            string[,] books = new string[3, 2];
            books[0, 0] = "War and Peace";
            books[0, 1] = "Tolstoy";
            books[1, 0] = "The lord of the Rings";
            books[1, 1] = "Tolkein";
            books[2, 0] = "Enders Game";
            books[2, 1] = "Card";

            //Console.WriteLine("Select an author: Tolstoy, Tolkein or Card");
            //string author = Console.ReadLine();

            //this for loop loops through the array and displays
            //its contents in reverse (-- instead of ++)
            for (int i = 2; i >=0; i--)
            {
                //if (books[i, 1].Equals(author))
                //{
                    Console.WriteLine(books[i, 0] + ", " + books[i,1]);
                //}
            }

        }
    }
}

this one focuses more on loops

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

namespace LoopsandStuff
{
    class Program
    {

        static void Main(string[] args)
        {
            Program p = new Program();
            string status = "yes";

            //the while loop loops as long as status = yes
            while (status.Equals("yes"))
            {
            p.CreateArray();
            Console.WriteLine("Continue: yes / no");
            status = Console.ReadLine();
             status.ToLower(); //sets the reply to all lower case
            }
            //Console.ReadKey();
        }

        void CreateArray()
        {
            Console.WriteLine("How big do you want your array?");
            int size = int.Parse(Console.ReadLine());

            int[] numbers = new int[size];
//call method populate arrays and passes the array
            PopulateArray(numbers);
        }

        void PopulateArray(int[] num)
        {
            //loop through the array and add values
            for (int i = 0; i < num.Length; i++)
            {
                Console.WriteLine("Enter an integer");
                num[i] = int.Parse(Console.ReadLine());
            }
            ReadArray(num);
        }

        void ReadArray(int[] num)
        {
            Console.Clear();
         
            //loop through the array and display its contents
            for (int i=0; i < num.Length; i++)
            {
                Console.WriteLine(num[i]);
                
            }
            //use built in math functions to analyze array values
            Console.WriteLine("the sum is {0}", num.Sum());
            Console.WriteLine("the Average is {0}", num.Average());
            Console.WriteLine("the maximum value is {0}", num.Max());
            int range = num.Max() - num.Min();
            Console.WriteLine("the range is {0}", range);
           // int add = num[1] + num[2];
          //  Console.WriteLine("the sum of values 2 and 3 is {0}", add);
        }

    }
}

Requirements and Business Rules

Requirement is something a database has to do.

Data Requirements (what has to be in database)

:

It has to list local venues
(name, address, description , website? Restrictions, capacity)
It has to list acts (artists)
(name, description, genre(s), email, website?)
It has to list show times and show information
(times, date, address, restrictions, price,
admission requirements(cover charge or tickets)
Fan information
(name and email, genres and acts they are interested in)
Login table

Reporting Requirements (have to get out of database)

You must be able to:
Search venues to get lists of coming shows
Search by calendar
By area (neighborhood, city, zipcode)
By Act (name), genre,
By price (including free)
By Age restriction
Search fans who are interested in a particular genre or act
Administrative reports

Access and Security Requirements

Venues can enter and edit their own venue and
show information but they should not be able to edit or enter
for any other venue (login) (insert update)
Fans can register which means they can enter and their own
Info including bands and genres they want to follow
But nothing else (insert and update)
Artists enter and edit their own info/ genres (insert/ update)
Public can select artists, venues and shows

Admin all permission

(wish list)

Business Rules

Venues will be able to enter and edit their information and show information
Acts and fans have same rule
Local consists of defined zip codes
Only (local) artists can register
Venues (local) can list all acts at their venue even if not local
Artist list will be public
Venue list and shows will be public
Fan emails will be private
How long keep records?
Fan, artist (1 year after last show) and venue information
remains as long as accurate

Keys

Unique identifiers for each row primary key
Candidate keys (looking at data to determine which fields
Are potential keys)
Natural key—sconge01
Surrogate—auto-numbers
Composite key 3206 Fall 2013
Foreign Key
Artist

ArtistKeyArtistNameEmail
1 Adarna adrana@gmail.com

 

GenreKey ArtistKey GenreName
1 1 Alternative

Monday, October 7, 2013

Ifs and Switches

Here is the if and if else statement example

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

namespace IfStatementExamples
{
    class Program
    {
        /// 
        /// This program just shows how to use if
        /// and if else statements
        /// it also shows how to use tryParse
        /// to catch errors in entry
        /// 
        /// 
        static void Main(string[] args)
        {
            //initialize the program
            Program p = new Program();
            //call the GetTemperature method
            p.GetTemperature();
            Console.ReadKey();
        }

        void GetTemperature()
        {
            //set the temp variable
            int temp=0;
            //prompt the user
            Console.WriteLine("Enter the Temperature.");
            //this is the try parse. 
            //if the value entered on the console is a
            //valid integer it returns true to isInt and assigns
            //the value to the "out" parameter temp
            //if not, it returns false and ignores the out parameter
            bool isInt = int.TryParse(Console.ReadLine(), out temp);

            //so if it isn't true we want to tell them
            //and give them one more chance to enter
            //a good value
            if (isInt != true)
            {
                Console.WriteLine("Enter a valid integer");
                temp = int.Parse(Console.ReadLine());
            }
            //call the ReactToTemp method and pass it the temperature
            ReactToTemp(temp);

        }

        void ReactToTemp(int temperature)
        {
            //this method uses if and else if to evaluate the temperature
            //and change the console background based on the temperature
            if (temperature >= 100 )
            {
                Console.BackgroundColor = ConsoleColor.Red;
                Console.Clear();
                Console.WriteLine("Hot");
            }
            else if (temperature >= 80)
            {
                Console.BackgroundColor = ConsoleColor.DarkYellow;
                Console.Clear();
                Console.WriteLine("Warm");
            }
            else if (temperature >= 60)
            {
                Console.BackgroundColor = ConsoleColor.Green;
                Console.Clear();
                Console.WriteLine("Pleasent");
            }
            else if (temperature >= 30)
            {
                Console.BackgroundColor = ConsoleColor.Blue;
                Console.Clear();
                Console.WriteLine("Cool");
            }
            else
            {
                Console.BackgroundColor = ConsoleColor.Cyan;
                Console.Clear();
                Console.WriteLine("cold");
            }
        }

    }
}


Here is the switch example

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

namespace SwitchExample
{
    class Program
    {
        /// 
        /// this program shows an example of a switch
        /// structure. It takes a grade as an integer
        /// and returns a letter grade
        /// 
        
        static void Main(string[] args)
        {
            //initialize the program
            Program p = new Program();
            //call the method GetGrade();
            p.GetGrade();
            Console.ReadKey();
        }

        void GetGrade()
        {
            //Declare the variable grade
            int grade;
            //prompt the user
            Console.WriteLine("Enter your grade");
            //use the try parse to test the input--see
            //the explanation on the if example
            bool goodGrade = int.TryParse(Console.ReadLine(), out grade);
            if (!goodGrade)
            {
                //in this case we don't give them a second chance
                //we just tell them what's wrong and exit
                Console.WriteLine("Next time do a valid grade as an integer");
                return;
            }
            //call translate grade
            TranslateGrade(grade);
        }

        void TranslateGrade(int grade)
        {
            //create a string variable for the letter grade
            //and give it a default value
            string letterGrade ="Unavailable";
            //set up the switch. Cases have to be
            //exact values. No ranges or > < 
            switch (grade)
            {
                    //case 4 means literally the grade must be 4 to match
                case 4: //note the colon here.
                    letterGrade="A";
                    break;
                case 3:
                    letterGrade = "B";
                    break;
                case 2:
                    letterGrade = "C";
                    break;
                case 1:
                    letterGrade = "D";
                    break;
                case 0:
                    letterGrade = "F";
                    break;
                default:
                    letterGrade = "Undefined";
                    break;
            }
            Console.WriteLine("Your Letter grade is {0}", letterGrade);
        }


    }
}

Chapter Two Practices

Fields gathered from forms and reports

Band name
Time and Date
Location/ venue (name, address, contact)
Age restrictions
Web site
Contact information
Cover charge
Picture
Genre
Live/ dj
Description
Ticket information
Other acts (opening, main)
Bar 21 w/ID (make sure you understand the abbreviations and terms)

Stakeholders

Bands
Fans
Venues
Database admin
Ticket sellers

Interview

 

Question To Allotted Time
1. What would you most like to see from the database? Fans 10 minutes
2. Would you like to follow bands of a particular genre, or just the individual bands? Fans  
What kinds of genres do you follow? Fans  
4. What information do you need about a show? Fans  
5. How do you search for shows now? Fans 
6. Would you sign up for alerts for bands or genres?Fans 

Questionnaire

1. Would you like to follow bands of a particular genre, or just the 
individual bands?
           Yes____ No___
2. Would you sign up for alerts for individual bands?
           Yes____ No___
3. Would you sign up for alerts for different genres of music?
           Yes __ No ___
4. What do you consider to be a local band?
          a. One located in the greater Seattle area
          b. One located in the I5 corridor (Everett, Seattle, Tacoma)
          c. One located in the Northwest (Portland to Bellingham)
5. How often do you think you would access the database?
          a. Daily
          b. Weekly
          c. Monthly
          d. One in a while
          e. never

Job Shadowing

Some bands keep fan lists (emails) could you use?
Sometimes the opening act is unknown until close to the time of the performance.
May need to be generic

Wednesday, October 2, 2013

Math methods

So, here is the code we did in class. I commented it to try to make it clearer.

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

namespace MathExamples
{
    class Program
    {
        /*******************
         * this program creates
         * separate methods for 
         * each of the the basic math
         * operations
         * Steve Conger 10/2/2013 
         * *******************/

        int number1, number2;

        static void Main(string[] args)
        {
            //initialize the Program class and make
            //an instance of it in memory
            Program p = new Program();
            //call the GetNumbers() method
            p.GetNumbers();
            //call the Display() method
            p.Display();
            //pause for a key stroke
            Console.ReadKey();
        }

        //Get input
        void GetNumbers()
        {
            Console.WriteLine("Please enter the first integer");
            number1 = int.Parse(Console.ReadLine());

            Console.WriteLine("Please enter the second integer");
            number2 = int.Parse(Console.ReadLine());
        }

        int Addition()
        {
            //do addition and return the answer
            int answer=number1 + number2;
            return answer;
        }

        int Multiplication()
        {
            //do multiplication and return the answer
            int answer = number1 * number2;
            return answer;
        }

        int Subtraction()
        {
            //do subtraction and return the answer
            int answer = number1 - number2;
            return answer;
        }

        int Division()
        {
            //check to make sure the denominator
            //is not 0
            //the double equal signs == tests
            //for equality
            if (number2 == 0)
            {
                //if it is equal to 0 give a message
                //and just return zero for the answer
                Console.WriteLine("Can't Divide by zero");
                return 0;
            }
            //if the denominator is not 0 just do the 
            //division
            int answer = number1  / number2;
            return answer;
        }

        

        void Display()
        {
            //int sum = Addition();
            //display the answers. The method can be put directly
            //into the writeline because it returns a number
            //which can be displayed
            Console.WriteLine("the sum of {0}and {1} is {2}", 
                number1, number2, Addition());
            Console.WriteLine("the product of {0} and {1} is {2}", 
                number1, number2, Multiplication());
            Console.WriteLine("the difference of {0} and {1} is {2}",
                number1, number2, Subtraction());
            Console.WriteLine("the quotient of {0} and {1} is {2}",
               number1, number2, Division());
        }
    }
}

Monday, September 30, 2013

Operators, constants, methods, scope (1)

Here is our first program with the number of passengers per van declared as a constant. We us the modulus to return the remainder to make sure we don't leave anyone behind

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

namespace VanPoolExample
{
    class Program
    {
        //declare a constant
        const int MAXPASSENGERS = 11;

        static void Main(string[] args)
        {
            //Input
            Console.WriteLine("How many people do you need to Transport?");
            int passengers = int.Parse(Console.ReadLine());

            //Calculation
            int vans = passengers / MAXPASSENGERS;

            if (passengers % MAXPASSENGERS > 0)
            {
                vans += 1;
            }

            //output
            Console.WriteLine("You will need {0} vans", vans);

            Console.ReadKey();

        }
    }
}

Here is the cube program with methods

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

namespace methodExamples
{
    class Program
    {
        int number; //class variable class scope
        static void Main(string[] args)
        {
            Program p = new Program();
            p.GetNumber();
            
           Console.ReadKey();
        }//end main

        void GetNumber()
        {
            //input
            Console.WriteLine("enter a integer");
             number = int.Parse(Console.ReadLine());
             CalculateCube();
        }

        void CalculateCube()
        { 
           // calculation
            int cube = number * number * number;

         

            DisplayCube(cube);
        } //end calculate cube

        void DisplayCube(int cubedNumber)
        {
            //output
            Console.WriteLine("The cube of {0} is {1}", number, cubedNumber);

          
        }

    }//end class
}//end namespace

Wednesday, September 25, 2013

Statement of Work

Show Times: Local Shows and Acts

History:

It is often difficult to know where and when a local band or artist is performing. Most advertising for shows is ad hoc, consisting of bills posted on the street and small adds in free newspapers. To solve this we conceived of creating a database that would track all the local venues and shows.

Scope:

The Database will track local bands and shows. It will list the venues where the bands or artists perform. It will let fans register and be notified when an artist is playing or when a show’s act matches select genres. In order to accomplish this the database will also track artists and fans who choose to register. Artists are entered by the system administrator. Venues can enter their schedule information. Fans can self register to get notifications. Constraints:

The database will only track local artists and venues in the greater Seattle area. A local artist is one who resides mostly in the Seattle area.

Local artists will be listed but will not be allowed to add material to their information. The database will link to their homepage.

Objective:

To make it easier to locate artists and shows. To let fans receive notifications of shows that might interest them.

Schedule:

Gather information week 2
Deliverable: List of potential fields and entities
Requirements and business rules week 3
Deliverable: list of requirements and business rules
Logical Design. Week 4
Visio diagrams:
Normalization: week 5
Build the physical database add sample data
Test the database SQL
Security

Saturday, September 21, 2013

First Thoughts for Programming

Programming is difficult. It is not something you are born knowing. It is not something you usually learn when you are growing up. Programming languages are artificial. They serve to function as a bridge between human languages and machine language.

Programming languages are meant to have some of the features of human languages while maintaining the strict unambiguous logic required by computing machines.

Interestingly, computers don't understand the programming languages any better then you do at this point. A language must be complied, that is converted into the language of the machine before it can function.

Computers only understand 0's and 1's. on, off, magnetized, unmagnetized, switches open or closed. And a language must be compiled to a particular computer's processor and operating system to work.

Note: some languages, like C# or Java, do a precompile to a intermediate language that allow it to be more portable. The intermediate language is machine and Operating System neutral and can be ported to any machine. A run time (Java or .Net) then compiles the intermediate language to the actual machine.

There is usually a period of frustration when you first start programming. It seems alien and difficult and impossible. The important thing is, programming is something you can do with practice. You are smart enough. You can learn it with practice. The more you practice, the more you exercise your skills, the more you explore, the stronger your skills and instincts will grow.

You may find you like programming or you may find that you hate it, but you can learn it.

Either way it is valuable. Programming gives you a valuable insight into how computers work, and how all the things we take for granted on our computers, tablets and phones came to be.

Sunday, August 11, 2013

Business Intelligence

I am going to set up the Automart database as a Data warehouse. (I am using Automart because at home CommunityAssist is in a process of transformation and is too different from the version on your servers to be useful.) I have tried to reorganize the database into a "Star" structure consisting of a fact table surrounded by Dim or Dimension tables. Here is the diagram:

First we create the new database

Create Database AutomartDW
Go
use AutomartDW
Go

Then we create the tables

Create table DimVehicle
(
 VehicleID int primary key,
 VehicleMake nvarchar(255),
 VehicleYear nvarchar(4)
)
go
Create table DimCustomer
(
 CustomerKey int identity(1,1) primary key,
 LastName nvarchar(255),
 FirstName nvarchar(255),
 Email nvarchar(255),
 VehicleID int Foreign key references DimVehicle(VehicleID)
)

Create table DimVehicleService
(
 VehicleServiceKey  int identity(1,1) primary key,
 VehicleServiceID int,
 VehicleID int,
 LocationName nvarchar(255),
 ServiceName nvarchar(255),

)

go

Create Table DimDate
(
 DateKey int identity (1,1) primary key,
 ServiceDate Date,
 ServiceTime Time,
 sDay int,
 sMonth int,
 sYear int
)
go

Create table FactSales
(
 VehicleID int foreign Key references DimVehicle(VehicleID),
 DateKey int foreign key references DimDate(DateKey),
 VehicleServiceKey int foreign Key references DimVehicleService(VehicleServiceKey),
 CustomerKey int foreign key references DimCustomer(customerKey),
 ServicePRice money,
 DiscountPercent decimal(3,2),
 TaxPercent decimal(3,2)


)

Next we populate the tables. I am pretty sure of the Dim table inserts, but must confess a bit of uncertainty about how I populated the Fact Table

--start inserts into tables

Insert into DimVehicle(VehicleID, VehicleMake, VehicleYear)
Select vehicleID, VehicleMake, VehicleYEar from Automart.Customer.Vehicle

Insert into DimCustomer (LastName, FirstName, Email, VehicleID)
Select LastName, Firstname, Email, VehicleID
From Automart.dbo.Person p
Inner join Automart.Customer.Vehicle v
on p.Personkey=v.PersonKey
inner join Automart.Customer.RegisteredCustomer c
on c.PersonKey=p.Personkey

Insert into DimVehicleService(VehicleServiceID, VehicleID, LocationName, ServiceName)
Select vs.VehicleServiceID, VehicleID, LocationName, ServiceName
From Automart.Employee.VehicleService vs
Inner join Automart.Employee.VehicleServiceDetail vsd
on vs.VehicleServiceID=vsd.VehicleServiceID
inner join Automart.Customer.Location l
on vs.LocationID=l.LocationID
inner join Automart.Customer.AutoService a
on a.AutoServiceID=vsd.AutoServiceID

INsert into dimDate(ServiceDate, ServiceTime, sDay, sMonth, sYear)
Select ServiceDate, ServiceTime, Day(ServiceDate), Month(ServiceDate), Year(serviceDate) 
From Automart.Employee.VehicleService

Insert into FactSales(VehicleID, DateKey, VehicleServiceKey, CustomerKey, ServicePRice, DiscountPercent, TaxPercent)
Select dv.VehicleID, DateKey, VehicleServiceKey, CustomerKey, ServicePRice, DiscountPercent, TaxPErcent
From DimVehicle dv
inner Join DimCustomer dc
on dv.VehicleID = dc.VehicleID
inner join Automart.Employee.VehicleService vs
on dv.VehicleID=vs.VehicleID
inner join Automart.Employee.VehicleServiceDetail vsd
on vs.VehicleServiceID=vsd.VehicleServiceID
inner join DimVehicleService dvs
on vs.VehicleServiceID=dvs.VehicleServiceID
inner join Automart.customer.AutoService a
on vsd.AutoServiceID=a.AutoServiceID
inner join DimDate dd
on vs.ServiceDate=dd.ServiceDate 

Next we need to make sure we add the service user to the AutomartDW database

First open the SQL Server Configuration Manager and select SQL Server Analysis Services. Right Click on the properties. You will probably see something like this.

We want to change it to local services.

If it already looks like this, great. other wise change it. Oking this will cause a server restart. Say OK to the warning. Then return to Sql Server Management studio. Go to the Server Security folder and right click logins. Select New Login. In the login dialog click on search,and then advanced. Select NT Authority/Local Service as a login.

Then click OK, OK until you are back at the main dialog window. Click on the page User Mapping. Then check the box by AutomartDW and Check the roles DataReader, DataWriter

Click OK. Now we need to open Visual Studio Data tools. and Start a new Data Analysis Multidimensional cube project. Name it "AutomartAnalysisProject."

In the Solution Explorer right click on Data Sources and add a new Data source

Click OK and Next and then choose Use Service Account

Go Next and Finish. Now right click Data Source Views in the Solution Explored and Select New. Use the data source we just created.

On the next dialog of the wizard, add all the tables

Click Next and finish. You will see the designer with the tables.

Now right click on the Cubes folder and add a new cube

Use Existing tables

Click Next and then choose all the tables except sysDiagrams

click Next, Next and Finish. It wouldn't hurt at this time to build the solution. Then right click on the cube and select Process.

Click Run. You should see something like this when it is done.

Click Close, Close. Then click the Browser tab. Here you can drag in dimensions and calculations

Not very exciting, but Automart doesn't have much data. Also, I am not absolutely confident of my dimesion setup. I seemed to have missed the location. It should have been a dim table. Also I am not sure about how I populated the SaleFact table. The numbers displaying are correct, but some of the other measures produce wrong results. But this blog does give you an overview of the process.

You can still look at other measures and try to add KPIs and other aspects. Maybe sometime in the not too distant future I will do a blog where I take it from the cube and show how to apply statistics and KPIs to the results.