Tuesday, November 29, 2011

ITC 172 Assignment 7 MVC

There are no practices with this assignment, just the MVC. It may seem overwhelming but is really much simpler than it looks.


Programming

Start a new ASP MVC2 web project

Add a model that uses LINQ to return a list of registered customers including their names (that means you will have to drag the Person table as well as the Registered Customer table onto the designer.)

Add a controller Named RegisteredCustomerController

Write the LINQ code to retrieve registered Customers

Add a View that displays the registered customers in a table

Add a tab to the menu in the Master page


What I am looking for

The model is worth 5 pts
The controller is worth 5 pts
The view is worth 5 pts
Modifying the Master and displaying the customers in a new tab 5 pts

The total is worth 20 points


To Turn in

Turn in all the code and markup you have done. (You don't need to post all the auto generated code and markup. Include a screenshot of the application running with the customers displayed. Put it all in a Google doc and share it with spconger@gmail.com

Morning ASP Examples

Here is the ASP source code


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="FinalProject.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
      <p> Enter your Name <asp:TextBox 
ID="txtName" runat="server"></asp:TextBox></p>
        <asp:Button ID="btnName" runat="server" Text="Click Me" 
            onclick="btnName_Click" />
        <asp:Label ID="lblResult" runat="server" Text="Label"></asp:Label>
        <asp:CheckBoxList ID="CheckBoxList1" runat="server">
            <asp:ListItem Value="3.25">Bread</asp:ListItem>
            <asp:ListItem Value="1.95">Eggs</asp:ListItem>
            <asp:ListItem Value="3">Milk</asp:ListItem>
            <asp:ListItem Value="1.59">Chili</asp:ListItem>
            <asp:ListItem Value="7.99">Beer</asp:ListItem>
        </asp:CheckBoxList>
        
        <asp:Button ID="Button1" runat="server" 
onclick="Button1_Click" Text="GetTotal" />
        
        <asp:Label ID="lblTotal" runat="server" 
Text="Label"></asp:Label>
        
    </div>
    </form>
</body>
</html>


Here is the code behind

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
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //if (!IsPostBack)
        //{
        //    CheckBoxList1.Items.Add("Red");
        //    CheckBoxList1.Items.Add("Green");
        //    CheckBoxList1.Items.Add("Blue");
        //}
    }
    protected void btnName_Click(object sender, EventArgs e)
    {
        lblResult.Text = "Hello " + txtName.Text;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        double total = 0;
        foreach (ListItem item in CheckBoxList1.Items)
        {
            if (item.Selected)
            {
                total += double.Parse(item.Value.ToString());
               
            }

            lblTotal.Text = "Your total is " + total.ToString("c"); 
        }
    }
}

Monday, November 28, 2011

ITC 172 Assignment 6

Practices

1. Add a textbox and a validation control that makes it a required field. Change the default message and show the ASP markup

2. Add a textbox and a regular expressions validation that validates that the textbox contains a valid email address

3. Assume you have a form with fields for last name and first name. Write the LINQ code to add them to the Person table in the AutoMart database


Programming

Start a new Empty Web Site and add a Web Form.

We are going to write a new customer and new vehicle to the Automart Database using LINQ. We are going to make the customer a registered customer. That means you will need to add the customer to the Person table, then to the RegisteredCustomer table and then add the Vehicle to the Vehicle table. All three tables are linked by the PersonKey.

Create the form with all the necessary fields. Validate the fields. Make Last name required. Make email required and also validate that it is a well formed email address. License plate and vehicle type and vehicle year should also be required.

Write the LINQ code to insert the new registered customer and vehicle. Use error trapping and add an error page to the project

Use CSS to style the web site


What I am looking for

The practices are worth 2 point each
The form textboxes and validation are worth 6 pts
The LINQ code is worth 5 points
The error trapping is worth 2 pts
The Css is worth 1


What to Turn in

Turn in all the ASP markup and the c# code in a Google Doc and share with spconger@gmail.com

ITC 172 Assignment Five

Practices

1. Create a LINQ query that returns all the last names and first names in the people table

2. Bind the results the query in one to a DropDownList

3. Write a LINQ query that takes the city from a drop down list and returns the locations for that city

4. Add A try catch to number 3

5. Write the code to redirect an error message to an error page

6. Write the code to display the error message on the error page

7. Write the ASP markup to display a location Name, Address and City in a ListView control


Programming

Create a new Empty web site. Add a Web Form. Add a DropDownList and a ListView control. The drop down list will contain a distinct list of vehicle types. When a user chooses one of the vehicle types the ListView will display all the vehicles of that type. Use a LINQ query to fill the DropDownList, and another to fill the ListView. Add error checking to the code. Make a separate error page to display any errors. Use CSS to style the pages.


What I am looking for

Practices are worth 1 point each.
Filling the DropDownList is worth 2 pts
Filling the View List is worth 5 points
Error checking and error page is worth 4 pts
The CSS is worth 1 point

The total is worth 20 pts


To Turn in

Paste your code into a Google doc and share it with spconger@gmail.com

Wednesday, November 23, 2011

ITC 172 Final Project

Outcomes

Create basic programming structures

Create interactive web pages with data bound controls

Connect to databases with ADO

Understand and implement secure coding techniques

Research relevant programming techniques

Work Effectively in groups


The Project

This is best done in groups of 3 or 4

Create a web application for Automart Customers.

The main page should have a banner for automart, and should show all the locations and their addresses. It should also advertise all the services available. Registered customers should be able to log in, choose a vehicle and see all the services that have been provided for that vehicle. If a customer is not registered, it should allow them to register themselves and their vehicle.

You can use any of the tools and techniques we have used in the assignments. The project should contain at least one control or technique we haven't looked at in class. Research it through books or the web and note where you got your information (in a comment in the code)

Use CSS to Style the application. I will not judge on the quality of the styling--only that you have attached a style sheet and used some of the styles.

Keep minutes for your group that list who contributes what to the project


What I am looking For

Presenting locations and addresses from Database 5pts
Presenting Automart Services offered from Database 5pts
Customer login 5 pts
Returning Vehicle services 5pts
Registering new Customer and vehicle 10 pts
New control or technique 10 pts
Css Stylsheet and styling 5 pts
Participation in group 5 pts

The total project is worth 50 points

What to turn in.

Paste the markup, CSS, and C# into a Google doc and share with spconger@gmail.com. I will also sit with each group and review the completed project

ITC 172 Assignment Four

Outcomes

Make interactive Web pages with Data bound controls

Understand and implement secure coding techniques

Research relevant programming techniques


Practices

1. Given a DataSet named ds. Write the code that would bind it to a DataViewGrid control.

2. You have made a web reference to a service that provides the capital of any state. You have named it StateCapitalService. It has a method GetCapital(string state). Write the code that would invoke this method and display its results.


Programming

Open a new ASP.Net Web Application.

Go to http://www.webservicex.net/WS/wscatlist.aspx Click on the link for "Standards and Lookup Data", then scroll down to "USA Zip Code Information." Add a Web Reference to this Service. Use the Method "Get Info By City." This returns a DataSet of all the zip codes in a given city. You will need a text box to get the name of the city. Invoke the method and bind the DataSet to a ViewGrid

Add a second web service of your choice and display the results

Take a look at this modification of the assignment. You must load the results of the zip code web service into an XML file before you can load it into the DataSet.


What I am looking for

The first practice is worth 2 points
The second practice is worth 3 points
In the programming assignment adding the web service 3 pts
Creating the form for input and output 2 pts
Calling the method 2 pts
Binding the resulting DataSet to the View Grid 3 pts
Adding, invoking and displaying a second web service 5 pts

The whole is worth 20 pts

To turn in

Copy the c# code into a Google Doc and share with spconger@gmail.com

ITC 172 Assignment Two

Outcomes

Connect to databases with ADO

Make interactive Web pages with Data bound controls

Understand and implement secure coding techniques


Practices

We will do the practices together

1. Show the code to create and instantiate a new ADO connection object that connects to a database named MagazineTracker using integrated security.

2. Show the code to create and instantiate a New ADO connection that connects to a database named MagazineTracker using SQL authentication with a username of "salesperson" and a password of "P@ssw0rd1"

3. Create a new SQL command object that gets all the data from the table Magazine.

4. Create the code to retrieve the data from the Magazine table and store it in a dataset. Bind the dataset to a ViewGrid

5. Use Css to Style a ViewGrid

6. Show the code to update a customer address

7. Show the code to throw an error

8. Show the code for redirecting an error to a web page


Programming

Overview

This web site uses the Automart web site. It will have 5 web forms.

This assignment is big and has many pieces.The goal is to give you a good overview of how to use ADO to build a web site. The project is broken into five parts. You should complete and test each part before moving to the next. I will help. Also, this program also the model for the LINQ assignment, which will do all the same things but with different tools.

The first form will be the opening page. It will show the locations of the Automart stores and a list of the services provided. It will also have a login control. That allows the user to login and see their registered vehicles. The login control uses the registered customer email as a user name and the password in the Customer.RegisteredCustomer table as their password. If they successfully log in, they will be redirected to the second web Form which greets them by name and shows them a list of their registered vehicles (usually only one). A button on this page when clicked will allow them to edit their information.

Under the login control on the first web form is a button for unregistered customers, that when clicked redirects them to a web form which allows them to enter their first and last name, email, vehicle license number, vehicle make, vehicle year and password. At the bottom of the form a submit button should write all these to the database. When successful the customer should be congratulated and encouraged to login.

When the edit information button on the second web form is clicked it should redirect them to a web form where all their information is retrieved into editable text boxes. After they have made changes, the changes should be submitted to the database.

The last page is error page where the user will be redirected if there is an error in the process. We will put error trapping and validation throughout the assignment.

Part one (getting the Locations and services)

Create a new empty web site. Add A Web Form and a Style Sheet. Use ADO programming objects to connect to the Automart Database and return a list of locations with their addresses and services. (Use a separate gridview for each)

Use Css to Style the ViewGrid.

Part two (Login and get customer and vehicle information)

We are going to do this correctly, in an object oriented way. First, create a new class called Customer. It should have fields for PeronKey, LastName, Firstname, email and password. Password should be write only. Create a second class for Vehicle. It should contain fields for Personkey, vehicle license number, vehicle make and vehicle year.

Add a login control to the first web form

In the login authenticate method connect to the Customer.RegisteredCustomer table. Match the email and password. IF it does match store the personkey in a Session variable, and redirect the user to the second form.

Create a new class called ManageCustomer

Add a method called GetCustomer that takes the person key as a parameters that queries the database and returns a customer Object

Create a second new class called ManageVehicle

Add a method called GetVehicle which also takes the personkey as a parameter and which returns a vehicle object

In the page load of the second web form, get the person key from the session variable and use it to query the Person, Vehicle and Registered Customer tables to pull of all the customer information.

Display their names, and the vehicle information

Part Three (Register New Customer).

Create a new mehtod in the class ManageCustomer called AddCustomer that takes a customer Object as a parameter and To the ManageVehicle class another method AddVehicle that takes a Vehicle object as a parameter.

On the web page create a form that allows a customer to enter all the appropriate fields. Use the validation controls to require fields and make sure the email is well formed. Have them enter the pass word twice. Use the compare validation control to make sure the passwords match.

When the customer clicks the submit button the contents of the text boxes should be assigned to the customer and vehicle objects respectively. Pass those objects to the RegisterCustomer Class.

Provide the customer some feedback on whether the submission was successful or not

Part Four (Updating information)

The good news is you have already done most of the work for this

The webform should look a lot like the web form you did for the new customer registration

You can use the Manage classes you have already created to retrieve the data from the database.

In each Manage class, add another method UpdateCustomer, UpdateVehicle, respectively.


Part Five

Add Try catches to each part of the code that could generate a error. Throw the errors from the class to the web page where they should be redirected to an error page.

What I am looking for

Each part is worth 10 points for a total of 50 points
In part one, Listing the services is 4 pts, listing the locations 4 points, css styling 2 pts.
In part two logging in 2 pts, creating the classes 6 points, displaying the welcome 2 pts
In Part three input form 2 pts, validation 3 points, inserting new customer 5 pts
In Part four web form 2 points, retreiving information 2 pts, class methods for update 3 points, successful update 2 points
For part five. Throwing errors back to pages 3 pts, Location and handling errors 5 pts, Error page 2 pts

The total is worth 20 points


To turn in

copy all the markup code, C# and CSS into a Google doc and share it with spconger@gmail.com

Monday, November 21, 2011

Color Change Code

Here is the code for changing color

 private void button1_Click(object sender, RoutedEventArgs e)
  {
        
     label1.Background = new LinearGradientBrush(Colors.DarkSlateBlue, 
Colors.SkyBlue, 45);
     label1.Foreground = new SolidColorBrush(Colors.White);
     this.Background = new LinearGradientBrush(Colors.Gold, 
Colors.Silver, 30);
  }

Styling ASP.Net with CSS

With ASP.Net you can set control properties to get colors and effects you want, but it is generally a better idea to use CSS to style your pages.

Setting the properties results in an inline style in the rendered HTML. This works and it is legal, but it it makes for a very hard to maintain web site. When you use in-line styles, it means if you want to change your sites look, you have to go to every single page and modify its controls separately. On the other hand, if you use CSS, you can change the whole look of a web site by editing just the one CSS file.

All web Controls render into xhtml before being displayed in the browser. So you can write CSS for the resulting xhtml objects rather than the ASP control itself. A GridView control, for instance, renders into a perfectly normal xhtml table. You can style it by styling the table elements. Below is an example of some CSS for styling a table that will apply to the DataGrid output. Note, it is not particularly sophisticated. It just shows the basics:

th
{
 font-weight:bold;
 color:White;
 background-color:Navy;
 border:solid,2px,White;
 padding-left:5px;
 padding-right:5px;
 
}

td
{
 border:solid,2px,Black;
 padding-left:5px;
 padding-right:5px;
}

Here is a picture of the styled table

You can also assign a CSS class to the cssStyle attribute of any ASP.Net control. Here is a simple Css class

.textback
{
 background-color:Teal;
}

Here is the ASP markup for applying the style

 <asp:TextBox ID="TextBox1" runat="server" CssClass="textback"></asp:TextBox>

Here is what it looks like when running

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

Wednesday, November 2, 2011

Class Examples (Evening)

Here is our Box class


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

namespace ClassExamples
{
    public class Box
    {
        //fields
        private double height;
        private double width;
        private double depth;

        //default constructor
       //a constructor has the same name
       //as the class and no return type
        public Box()
        {
            Height = 0;
            Width = 0;
            Depth = 0;
        }

       //overloaded constructor
        public Box(double h, double w, double d)
        {
            Height = h;
            Width = w;
            Depth = d;
        }
        
        #region properties

        public double Width
        {
            get { return width; }
            set { width = value; }
        }
        
       
        public double Depth
        {
            get { return depth; }
            set { depth = value; }
        }

        public double Height
        {
            get 
            {
                return height;
            }
            set
            {
                height = value;
            }
        
        }
        #endregion

        //class method 
        public double CalculateVolume()
        {
            return height * width * depth;
        }
    }
}

Here is the main class where we called the Box class and assigned properties


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

namespace ClassExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.BackgroundColor = ConsoleColor.DarkMagenta;
            //Console.WriteLine("Hello");

            //initialize the new box class 
            //using the default constructor
            Box b = new Box();
            //set the property values
            b.Height = 5.1; //all use the set of the property
            b.Depth = 6;
            b.Width = 4;

            //call the method
            double volume = b.CalculateVolume();

            //these are using the get part of the properties
            Console.WriteLine("The volume of a box with a height of {0} and a width of {1} and a depth of {2} has a volume of {3} cubic feet", b.Height, b.Width, b.Depth, volume);

            //initialize a second Box instance
            //useing the overloaded constructor
            Box b2 = new Box(4, 5, 2);

            Console.WriteLine("The volume of box 2 is {0} cubic feet", b2.CalculateVolume());
           
            Console.ReadKey();


        }
    }
}