Monday, November 21, 2011

ITC 220 SQL

Here is the SQL we did in class

Use CommunityAssist

--basic Select statement

Select FirstName, LastName
From Person

/*This is a quick way but
your can't choose the
order the columns*/

 Select * From Person

--aliasing field names
Select FirstName as [First Name], lastName as [Last Name]
From Person 

--returns only unique instances
Select Distinct EmployeeKey from Donation

--Calulations
Select DonationKey, DonationDate, DonationAmount, 
DonationAmount *.9  as Charity, DonationAmount * .1 as maintainance
From Donation

--ordering the output
Select DonationKey, DonationDate, DonationAmount, 
DonationAmount *.9  as Charity, DonationAmount * .1 as maintainance
From Donation
Order by DonationDate, DonationAmount Desc

--where Clause
Select * From PersonAddress
Where City='Kent'

Select DonationKey, donationDate, donationAmount
From Donation
Where DonationAmount > 500

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

--like searches for patterns 
--% any number of characters
--_one character
Select * From Person where LastName Like 'Tan%'

Select * From Donation 
Where DonationDate between '3/15/2010' and '4/15/2010'

--use is with nulls
Select * From PersonAddress Where Apartment is Not Null

Select * from PersonAddress where City ='Bellevue' or City = 'Kent'

Select * From PersonAddress Where Apartment 
is not null and  not City  = 'Seattle'

--scalar functions are in line functions

Select Distinct MONTH(DonationDate) From Donation
Select DAY(DonationDate) From Donation
Select YEAR(DonationDate) from Donation

Select DATEDIFF(dd, '11/21/2011','5/1/2012')

--aggregate functions work accross multiple rows

Select COUNT(Personkey) from Person
Where LastName Like 'B%'

Select MAX(DonationAmount) From Donation

Select MIN(DonationAmount) From Donation

Select SUM(DonationAmount) From Donation

Select AVG(donationAmount) from Donation


Select Month(DonationDate) as Month,
SUM(DonationAmount) as total
From Donation
Group by MONTH(donationDate)

Select EmployeeKey, 
SUM(DonationAmount) as total
From Donation
Group by EmployeeKey

Select EmployeeKey, 
SUM(DonationAmount) as total
From Donation
Group by EmployeeKey
Having SUM(donationAmount) > 2000

--Join

Select lastName, firstname, Street, City, [State],Zip
From Person 
Inner Join PersonAddress
On Person.PersonKey=PersonAddress.PersonKey

--tables aliased
Select lastName, firstname, Street, City, [State],Zip
From Person p
Inner Join PersonAddress pa
On p.PersonKey=pa.PersonKey

Select lastName, firstname, Street, City, [State],Zip, ContactInfo as HomePhone
From Person p
Inner Join PersonAddress pa
On p.PersonKey=pa.PersonKey
Inner Join PersonContact pc
on p.PersonKey=pc.PersonKey
Where ContactTypeKey=1

--Insert update Delete

Insert into Person(LastName, FirstName)
Values('Blackmore','John'),
('More', 'Black')


Select * From Person

Update Person
Set LastName='BlueBeard',
FirstName='Jake'
Where PersonKey=53

Begin tran

Update Person
Set FirstName='Jason'
Where PersonKey=1

rollback tran
commit Tran

Delete from Person
Where PersonKey=52

Thursday, November 17, 2011

ITC 172 Assignment One

Practices

We will do the practices together

1. Write a method that gets an integer from a text box and returns the cube of that number

2. Have three buttons share the same click event. In the event get the text of the button and display it on a label. (Just give me the code for the event)

3. Write the code to store a the value of a variable of type double in a Session.

4. Write the code to retrieve the variable in 3 from the session.

5. Write a method to clear a text box.

6. Create a simple HTML table with two columns and 3 rows


Programming Assignment

One of my students was asked to write a calculator in ASP.Net for a job interview. She was unsure how to do it. I want to make sure you will know how.

Create a calculator that has the 10 number keys (make each number key a button. All 10 keys should share the same event.)

The calculator should have 4 functions: Addition, Subtraction, Multiplication, and Division. When you click one of the four operators above, the program should store the number that was in the text box and clear it to make it ready for the next entry. It will also need to store the operator.

There should be a calculate or "=" button that does the operation whether add, subtract, multiply or divide and returns the result to the textbox. The calculator should also have a clear button to clear the textbox.

I would suggest using an html table to arrange the calculator.

You can add a style sheet to refine the display.


What I am looking for

Form layout 2 pts
using one method to handle all the numeric buttons 4 pts
Saving temporary variables in session states 4 pts
Addition multiplication and subtraction and Division 8 pts pts (1 pt each)
Clear button 2 pt

the total is worth 20 points


What to turn in

Post all the html asp and c# code in a Google doc and share it with spconger@gmail.com

ITC 172 Assignment One

Outcomes

Create basic programming structures

Create interactive web pages with data bound controls

Practices

In each of these, provide the code snippet requested by the question. You do not have to provide the whole project and surrounding code.

1. Define an array that has the values "red, green, blue, yellow, white, black and brown"

2. Write the code that binds the array in one to a DropDownList.

3. Write the code to retrieve the text of the selected item from the DropDownlist

4. Add a calendar control to a web page, a button, and a label. Write the code so that when you click the button the current date shows in the label.

5. Write the code that would redirect the user to a second web page if they click a button.

6. Make an external style sheet that sets the color of the h2 element to Green. Attach the style sheet to the Web Form. (show the style sheet entry for h2, and the html for attaching the style sheet).

7. Write the code to pass the variables in a http Get

8. Write the coed to retrieve variables from an http Get string


Programing Assignment

Create a web form for Students to sign up for counseling appointments. It should have a calendar control. It should also have a drop down list that is bound to an array with the following elements : Class Selection, Degree audit, Initial interview, personal issues. The user should enter their name, choose the reason for the visit from the DropDownList and select a date from the Calendar. When they click the button to make an appointment, you should check to makes sure all three elements are there, then pass them to a second page which shows their name, the Date, the type of appointment requested and confirms the appointment.


What I am looking for

The practices are worth 1 point each

In the assignment:
the array----2pts
binding the array to the drop down list control---2pts
Getting the selected date from the calendar--1pt
Passing the information to the second page---2pts
Displaying the information on the second page--2pts
A working web app--3pts

The whole thing is worth 20 points


What to turn in

Use your school google docs account or a personal google docs account and copy all the code, the html/asp markup and the C# into a document. Share it with spconger@gmail.com. I will write comments and grades on the document.

Wednesday, November 9, 2011

Java Equivalent of ITC 110 Assignment 6

Here is the code for the BMI Class


public class BMI {

 /**
  * This class calculates Body
  * Mass Index
  */
 //fields
 private int weight;
 private int feet;
 private int inches;
 private int totalHeightInInches;
 
 //constructors
 public BMI(){
  weight=0;
  feet=0;
  inches=0;
  totalHeightInInches=0;
 }
 
 public BMI(int weightInPounds, int heightInFeet, int additionalInches)
 {
  SetWeight(weightInPounds);
  SetHeightInFeet(heightInFeet);
  SetRemainingInches(additionalInches);
  totalHeightInInches=0;
 }
 
 //mutators and accessors
 public void SetWeight(int w)
 {
    weight=w;
 }
 
 public int GetWeight()
 {
  return weight;
 }
 
 public void SetHeightInFeet(int ft)
 {
  feet=ft;
 }
 
 public int GetHeightInFeet()
 {
  return feet;
 }
 
 public void SetRemainingInches(int inch)
 {
  inches=inch;
 }
 
 public int GetRemainingInches()
 {
  return inches;
 }
 
 //methods
 
 private void CalculateTotalHeightInInches()
 {
  totalHeightInInches=(feet*12)+inches;
 }
 
 public double CalculateBMI()
 {
  CalculateTotalHeightInInches();
  return (double)GetWeight() * 703/(double)
    (totalHeightInInches * totalHeightInInches);
 
 }
 
 public String BMIEvaluation(){
  double b = CalculateBMI();
  String eval="";
  if (b > 30)
   eval="Obese";
  else if (b >24.9)
   eval="Overweight";
  else if (b > 18.4)
   eval="Normal";
  else
   eval="Underweight";
  
  return eval;
   
 }
 
 
 
}


Here is the program class with the main. You could make a display class that is called by the main. That would be a better structure, but I did not specify that as a requirement

import java.util.Scanner;
public class Program {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Scanner scan=new Scanner(System.in);
  
  System.out.println("Enter your wieght in pounds");
  int lbs = scan.nextInt();
  
  System.out.println("enter your height in feet");
  int ft = scan.nextInt();
  
  System.out.println("enter any Remaining inches");
  int inch = scan.nextInt();
  
  BMI bmi = new BMI(lbs, ft, inch);
  double b = bmi.CalculateBMI();
  
  System.out.println("Your BM! is " + b);
  String badNews=bmi.BMIEvaluation();
  System.out.println(badNews);

 }

}

Here is the output



Enter your wieght in pounds
180
enter your height in feet
5
enter any Remaining inches
10
Your BM! is 25.824489795918367
Overweight

Tuesday, November 8, 2011

Model View Control (MVC)

Overview

Model View Control is an object oriented programming pattern. It consists of three parts. (Each part can consist of more than one class.). The pattern has the advantage of clearly separating responsibilities and concerns.

Model

The model's responsibility is connecting to and dealing with data. This can be done with LINQ, as in our example, or with Data Entities or with classic ADO.Net

Controller

The controller acts as an intermediary between the data and the display of the data in a view

View

The view consist of html designed to display the data

The Tutorial

Open Visual Studio and select New Project. Select ASP. MVC 2 Web Project

Go ahead and create a test project, though we will not be looking at it right now

You will end up with the following in your Solution pane

In the code window you have the code for the Home Controler

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

namespace VehicleMVC.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            return View();
        }
    }
}

We will ignore it for now

First we will build the model.

Right Click on the model folder and from the context menu choose Add, New. Select "Data" in the object dialog and then "Linq to SQL classes"

Name the Linq to SQL "Vehicles.dbml" and click OK

If it is not open already, from the View menu select "Server Explorer"

If you do not have an existing connection to Automart Database, add one. If you do have a connection you can skip the next 3 steps

Right click on Data Connections and select Add Connection

Choose SQL Server for a data source

Type "Localhost" for the name of the server and select "Automart" as the database

Press OK

Expand the node for the new connections. Expand Tables. Locate the table Vehicles and drag it onto the designer

Save the Designer

In the Solutions pane, right click on the Controller folder and select Add controller. Name it "VehicleController."

Add the following using line to the top. It connects the controller with the data model

using VehicleMVC.Models;

Change the method name to VehicleView and then add code as shown below

        public ActionResult VehicleView()
        {
           VehiclesDataContext dc = new VehiclesDataContext();
           var cars = from v in dc.vehicles
                      orderby v.VehicleYear
                      select v;
            return View(cars);
        }

Right click in the method and select Add View

Add a page directive on the view to import the data model

<%@ Import Namespace="VehicleMVC.Models" %>

Modify the content 2 section. Add this foreach loop

<h2>Vehicles Served</h2>
    <ul>
    <%foreach (vehicle v in (IEnumerable)ViewData.Model)
      { %>
      <li><%= v.LicenseNumber%> | <%= v.VehicleMake%> | <%= v.VehicleYear%></li>
      <%} %>
    </ul>

The whole page looks like this

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import Namespace="VehicleMVC.Models" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
 VehicleView
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Vehicles Served</h2>
    <ul>
    <%foreach (vehicle v in (IEnumerable)ViewData.Model)
      { %>
      <li><%= v.LicenseNumber%> | <%= v.VehicleMake%> | <%= v.VehicleYear%></li>
      <%} %>
    </ul>

</asp:Content>

Now we will modify the main master page to add a new tab and display the view

find and open the Site.Master under Views/Shared in the Solution Explorer

In the site master under the div "menucontainer" add another list item so that the menu looks like this

 <div id="menucontainer">
            
     <ul id="menu">              
          <li><%= Html.ActionLink("Home", "Index", "Home")%></li>
          <li><%= Html.ActionLink("About", "About", "Home")%></li>
          <li><%= Html.ActionLink("Vehicles","VehicleView","Vehicle") %></li>
      </ul>
            
 </div>

The first item is the text for the tab, the second the name of the view file, the third the folder it is in.

Run the program. It can take quite awhile to compile the first time

If all goes well (an unlikely event) you should see the following web page

Click the vehicle tab and you should see the vehicles listed by year

Monday, November 7, 2011

More Classes

Here are the classes we did for the evening session.

Program.cs


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

namespace MultiClassExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Display dis = new Display();
            //Mileage m = new Mileage();


            //m.BeginningMiles = 1000;
            //m.EndingMiles = 1450;
            //m.Gallons = 25;
            //m.PricePerGallon = 3.71;

            //Console.WriteLine("Your miles per gallon are {0:F2}", m.MilesPerGallon());
            //Console.WriteLine("The cost per Mile is {0:C}", m.CostPerMile());

            //Mileage m3 = new Mileage(2000, 2400);
            //m3.Gallons = 20;
            //Console.WriteLine("The MPG is {0}", m3.MilesPerGallon());


            //Mileage m2 = new Mileage(12000, 12500, 25);
            //Console.WriteLine("The MPG is {0}", m2.MilesPerGallon());

            //Console.ReadKey();
        }
    }

    //I could write a new class right here
}

Display.cs


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

namespace MultiClassExample
{
    class Display
    {
        Mileage m; 

        public Display()
        {
            m = new Mileage();
            GetInputs();
            ShowOutputs();
            PauseIt();
        }

        private void GetInputs()
        {
            Console.WriteLine("This program calculates MPG");

            Console.WriteLine("Enter the Beginning Miles");
            m.BeginningMiles = double.Parse(Console.ReadLine());

            Console.WriteLine("Enter the Ending Miles");
            m.EndingMiles = double.Parse(Console.ReadLine());

            Console.WriteLine("Enter the Gallons");
            m.Gallons = double.Parse(Console.ReadLine());

        }

        private void ShowOutputs()
        {
            Console.WriteLine("the Miles perGallon is {0}", m.MilesPerGallon());
        }

        private void PauseIt()
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }//end PauseIt

    }
}

Mileage.cs


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

namespace MultiClassExample
{
    public class Mileage
    {
        //fields
        double beginningMiles;
        double endingMiles;
        double pricePerGallon;
        double gallons;

        public Mileage()
        {
            beginningMiles=0;
             endingMiles=0;
            pricePerGallon=0;
            gallons=0;
        }

        public Mileage(double begMiles, double endMiles)
        {
            beginningMiles = begMiles;
            endingMiles = endMiles;
            pricePerGallon = 0;
            gallons = 0;
        }

        public Mileage(double begMiles, double endMiles, double gals)
        {
            beginningMiles = begMiles;
            endingMiles = endMiles;
            pricePerGallon = 0;
            gallons = gals;
        }
     
        #region Properties

        public double BeginningMiles
        {
            get { return beginningMiles; }
            set { beginningMiles = value; }
        }
        

        public double EndingMiles
        {
            get { return endingMiles; }
            set { endingMiles = value; }
        }
        

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

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

        //methods
        private double GetTotalMileage()
        {
            return EndingMiles - BeginningMiles;
        }

        public double MilesPerGallon()
        {
            return GetTotalMileage() / Gallons;
        }

        public double CostPerMile()
        {
            return PricePerGallon / MilesPerGallon();
        }
            
    }
}

Normalization Practices

Here is the diagram for the DVD.

This diagram reflects the process of going through Normal form 1, where we found and removed the multivalued attributes.Once removed they have many to many relationships with the main Entity, so we needed to create linking tables rejoin them. There are no functional dependencies or transient dependencies, so the diagram is already in normal form 3