Tuesday, December 13, 2011

ITC 222 Assignment 3

Aggregate Functions

Outcomes

Use SQL to retrieve database information


Problems

1. How many Ford vehicles are there? (Remember the LIKE operator)

2. What is the highest price for a service?

3. What is the lowest price for a service?

4. What is the average price for a service?

5. Although it doesn't make much sense, what it the total of all the service prices?

6. What is the count of cars served in each location?

7. list only the locations and counts of those locations that have served more than 15 customers

8. How many employees does each supervisor supervise?

9. What is the count of vehicles served on the first of March 2010?

10. What is the total number of vehicles served per month?


What I am looking for

I want to see the SQL that would answer each problem. I do not need to see the actual answers, though you can include them if you wish

Each problem is worth 1 point for a total of 10 points


What to turn in

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

ITC 222 Assignment 2

Scalar Functions

Outcomes

Use SQL to retrieve database information


The Problems

1. Select the distinct years in which employees were hired. Sort them so that the newest are on top

2. Display the names in person as (Last name, first name)

3. Return only the first word of each vehicle make

4. How many years difference is there between the newest and oldest hire date. (Just enter the dates manually. don't try to get them from the rows)

5. How many months are between the newest and oldest hires?

6. Format the phone numbers of the locations so they look like (206)555-1000

7. Format the prices of the auto services so that they have a $ sign

8.. Display the discount and tax percents in service detail as percents with a % sign. (You will have to multiply them by 100)


What I am looking for

I want to see the SQL for each problem

Each problem is worth 1 point except for 6 and 8 which are worth 2 points each for a total of 10 points


deally, copy and paste the code into a Google doc and share it with spconger@gmail.com. I will comment on the document

ITC 222 Assignment 1

Simple Select Statements

Outcomes

Use SQL to retrieve database information


The problems

1. List all the people in the person table.

2. List all the people in the person table in alphabetical order by last name

3. List all the people in reverse order. Alias each field.

4. List all the locations in Seattle.

5. List all the services with a price of over $100.

6. List all the last names of persons with the letters 'tan' in them.

7. List all the services provided between 3/1/2010 and 3/15/2010.

8. List all the employees who don't have supervisors

9. List all the employees who do have supervisors.

10. List all the employees who have supervisors and were hired in 2007 (between 1/1 and 12/31/2007)


What I am looking for

I want just the SQL statement. I don't need the results. None of the questions involve joins or other more advanced SQL.

Each question is worth 1 point for a total of 10 pts


What to turn in

Ideally, copy and paste the code into a Google doc and share it with spconger@gmail.com. I will comment on the document

Wednesday, December 7, 2011

ITC 220 Presentation

Here are the guidelines for the presentation:

1. Introduce the group members
2. Show your Entity Diagram of the database and explain briefly what tables you have developed and how the work
3. Explain what part of the project was the most challenging for the group and why
4. Explain what part of the project you are most proud of or excited about

Monday, December 5, 2011

ITC 220 Evaluation

The class evaluation will be Wednesday 12/7/2011

The URL is http://www.seattlecolleges.com/facultyevaluations

The course number is 3206

The password is "database" (no quotes)

The evaluation will be available between 10:30 AM and 11:30 AM.

View, Stored Procedures, Triggers

Here is the code for the Views, Stored Procedures and Triggers

Use CommunityAssist
Go
--this is a view. A view is used to provide
--a particular "view" of the data
--usually taylored to a particular set of users
--views are behave like tables
--they are really filtered queries. No
--data is actually stored in the view itself
Alter view vw_Employees
As
Select LastName [Last Name],
FirstName [First Name],
Street,
City,
[State],
Zip [zip code]
From Person p
inner join PersonAddress pa
on p.PersonKey=pa.PersonKey
Inner join Employee e
on e.PersonKey=p.PersonKey

--using the view like a table
Select * from vw_Employees

--the aliases in a view become the 
--actual column names
Select [Last Name], [First Name], Street
From vw_Employees

go
--a store procedure is an executable
--that consist of one or more sql statements
--they can be used to make dangerous
--commands like updates safe
Create proc usp_UpdateAddress
--parameters provided by the user
--probablly through a form
@PersonAddressKey int ,
@street nvarchar(255) ,
@City nvarchar(255),
@Zip nvarchar(10) 
AS --beginning of the procedure proper
--check to see the the address exists
if exists
 (Select PersonAddressKey 
 from PersonAddress
 Where PersonAddressKey = @PersonAddressKey)
Begin --if it does
--update the address with the new values
Update PersonAddress
Set Street = @Street,
City=@City,
Zip = @Zip
Where PersonAddressKey=@PersonAddressKey
End --end if true
Else --if false
--print a message
print 'Address doesnt exist'

Select * From Personaddress

--calling the stored procedure and 
--providing the parameter values
--the keyword exec is optional
exec usp_UpdateAddress
@PersonAddressKey = 70,
@Street='10 South Mann Street',
@City='Tacoma',
@Zip='98000'

Go
--triggers are procedures that execute 
--on an event
--the following executes on inserts into
--the Donation table
Alter trigger tr_DonationAmount on Donation
for Insert 
As
--check to see if the receipt table exists
--if not create it
If not exists
(Select name from sys.tables 
 where name='receipt')
Begin
Create Table receipt
(

DonationDate DateTime, 
DonationAmount money, 
PersonKey int, 
EmployeeKey int
)
End
--declare a variable
Declare @DonationAmt money
--assign a value to the variable from the inserted
--table. the Inserted table is a temporary table
--created to store insertions for the length of
--the transaction
Select @DonationAmt = DonationAmount from inserted
--check on the size of the new donation
if (@DonationAmt >=200)
Begin --if greater than 199
--insert it into the receipt table
Insert into receipt(
DonationDate, 
DonationAmount, 
PersonKey, 
EmployeeKey)
--the values to be inserted are selected
--from the inserted table
Select 
DonationDate, 
DonationAmount, 
PersonKey, 
EmployeeKey
From Inserted
End

--using the key
Insert into Donation(DonationDate, DonationAmount, 
PersonKey, EmployeeKey)
Values(GETDATE(),250,1, 1)

Select * From Receipt
Select * From Donation

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();


        }
    }
}

Monday, October 31, 2011

Java Equivalent to ITC110 Assignment 5

Here is the java code


import java.util.Scanner;
public class GuessingGame {

 /**
  * This program presents a guessing game
  * where the computer randomly selects
  * a number between 0 and 1000
  * and the player gets 10 chances to guess
  * the player can play as many times
  * as he or she wants and the program
  * will list total wins and average score
  */
 int gameCounter=0;
 int[] scoreArray=new int[50];
 public static void main(String[] args) {
  //instantiate the class
  GuessingGame gg = new GuessingGame();
  //get the scanner
  Scanner reader = new Scanner(System.in);
  //initialize the variable for exiting
  int choice=1;
  //loop so the player can play until they choose
  //to quit
  do
  {
   //call the start of the game
  gg.Start();
  //increment the number of games
  gg.gameCounter++;
  System.out.println("Do you want to play again? 0 to quit");
  choice=reader.nextInt();
  
  }while (choice != 0);

 }
 
 private void Start()
 {
  //Call the method to get the random number
  double num=GetRandom();
  //the line below just for testing 
  //System.out.println((int)num);
  
  //cast the random number to an integer
  //and pass to the GetGuess method
  GetGuess((int)num);
 }
 
 private double GetRandom()
 {
  //Get the random number
  double number = Math.random()*1000;
  return number;
 }
 
 private void GetGuess(int number)
 {
  int score; //declare score counter
  Scanner reader = new Scanner(System.in);
  //loop backwards to keep score
  for(score=10; score > 0; score--)
  {
   System.out.println("Enter a quess between 0 and 1000");
   double guess=reader.nextDouble();
   
   //check the guesses
   if(guess > number)
    System.out.println("Your guess is too high");
   else if(guess < number)
    System.out.println("Your guess is too low");
   else
   {
    System.out.println("congratulations");
    break; //leave the loop if correct
   }
  }
  GetScores(score);//call the get scores method
 }
 
 private void GetScores(int score)
 {
  //output the current score
  System.out.println("Your current Score is " + score);
  //assign it to the scoreArray
  scoreArray[gameCounter]=score;
  //initialize the variable to get the totals
  int scoreTotal=0;
  //loop through the array to get the total

  for (int i=0;i<50;i++)
  {
   scoreTotal+=scoreArray[i];
  }
  //get the average casting it to a double to get decimal
  //pars
  double scoreAverage=(double)scoreTotal/(double)(gameCounter + 1);
  //pring out the results
  System.out.println("Your have played " + (gameCounter + 1) + "games");
  System.out.println("Your average score is " + scoreAverage);
 }

}

Here is a transcript of the console when the program is running


Enter a quess between 0 and 1000
500
Your guess is too low
Enter a quess between 0 and 1000
750
Your guess is too low
Enter a quess between 0 and 1000
875
Your guess is too high
Enter a quess between 0 and 1000
800
Your guess is too low
Enter a quess between 0 and 1000
850
Your guess is too high
Enter a quess between 0 and 1000
825
Your guess is too high
Enter a quess between 0 and 1000
812
Your guess is too low
Enter a quess between 0 and 1000
819
Your guess is too low
Enter a quess between 0 and 1000
822
Your guess is too low
Enter a quess between 0 and 1000

823
congratulations
Your current Score is 1
Your have played 1games
Your average score is 1.0
Do you want to play again? 0 to quit
1
Enter a quess between 0 and 1000
500
Your guess is too high
Enter a quess between 0 and 1000
250
Your guess is too low
Enter a quess between 0 and 1000
350
Your guess is too low
Enter a quess between 0 and 1000
425
Your guess is too low
Enter a quess between 0 and 1000
475
Your guess is too high
Enter a quess between 0 and 1000
450
Your guess is too high
Enter a quess between 0 and 1000
433
Your guess is too low
Enter a quess between 0 and 1000
444
Your guess is too high
Enter a quess between 0 and 1000
439
Your guess is too low
Enter a quess between 0 and 1000
441
Your guess is too high
Your current Score is 0
Your have played 2games
Your average score is 0.5
Do you want to play again? 0 to quit

0

Thursday, October 27, 2011

MultiDimensional Arrays

The simplest multidimensional array is a two dimensional array. You can think of a two dimensional array as a simple sort of table with columns and rows. The first dimension is the number of rows and the second dimension is the number of columns.

Here is an example of a two dimensional string array that keeps track of book titles and authors. It has 3 rows and 2 columns


 string[,] books = new string[3, 2];
           
            books[0, 0] = "War and Peace";
            books[0, 1] = "Tolstoy";
            books[1, 0] = "Lord of the Rings";
            books[1, 1] = "Tolkein";
            books[2, 0] = "Huckleberry Finn";
            books[2, 1] = "Twain";

Here is an example of a two dimensional array with 3 rows and 3 columns. Think of it as containing the height, width and length of a set of boxes

int[,] boxes = new int[3, 3];
            boxes[0, 0] = 4;
            boxes[0, 1] = 2;
            boxes[0, 2] = 3;
            boxes[1, 0] = 2;
            boxes[1, 1] = 2;
            boxes[1, 2] = 1;
            boxes[2, 0] = 3;
            boxes[2, 1] = 2;
            boxes[2, 2] = 5;

It is also possible to have arrays with more than two dimensions. Below is a three dimensional array.

int[, ,] space = new int[2, 2, 2];

            space[0, 0, 0] = 5;
            space[0, 0, 1] = 4;
            space[0, 1, 0] = 3;
            space[0, 1, 1] = 4;
            space[1, 0, 0] = 3;
            space[1, 0, 1] = 6;
            space[1, 1, 0] = 2;
            space[1, 1, 1] = 5;
            space[2, 0, 0] = 3;
            space[2, 0, 1] = 6;
            space[2, 1, 0] = 2;
            space[2, 1, 1] = 5;

Arrays can have more than 3 dimensions, but they rapidly get difficult to manage.

To display a multidimensional array, you access its indexes just as in an one dimensional array. Below is the full program that creates these arrays and displays all but the last one. If you would like a little chalange, you can add code to the display method to display the contents of the 3 dimensional array.


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

namespace MultidimensionalArrays
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            p.Display();
            Console.ReadKey();
        }

        private string[,] TwoDimensionalArray()
        {
            //define two dimensional Array
            //first number is number of rows
            //the second is number of columns
            string[,] books = new string[3, 2];
           
            books[0, 0] = "War and Peace";
            books[0, 1] = "Tolstoy";
            books[1, 0] = "Lord of the Rings";
            books[1, 1] = "Tolkein";
            books[2, 0] = "Huckleberry Finb";
            books[2, 1] = "Twain";

            return books;
        }

        private int[,] Another2DimensionalArray()
        {
            //think of an array that holds
            //the height, width, and length
            //of boxes
            //although it has 3 columns
            //it is still a two dimensional 
            //array
            int[,] boxes = new int[3, 3];
            boxes[0, 0] = 4;
            boxes[0, 1] = 2;
            boxes[0, 2] = 3;
            boxes[1, 0] = 2;
            boxes[1, 1] = 2;
            boxes[1, 2] = 1;
            boxes[2, 0] = 3;
            boxes[2, 1] = 2;
            boxes[2, 2] = 5;

            return boxes;

        }

        private int[, ,] ThreeDimensionalArray()
        {
            //think of 3 dimensionals as a cube
            //you can do more dimensions but it
            //gets beyond absurd
            int[, ,] space = new int[2, 2, 2];

            space[0, 0, 0] = 5;
            space[0, 0, 1] = 4;
            space[0, 1, 0] = 3;
            space[0, 1, 1] = 4;
            space[1, 0, 0] = 3;
            space[1, 0, 1] = 6;
            space[1, 1, 0] = 2;
            space[1, 1, 1] = 5;
            space[2, 0, 0] = 3;
            space[2, 0, 1] = 6;
            space[2, 1, 0] = 2;
            space[2, 1, 1] = 5;

            return space;
        }

        private void Display()
        {
            //you access the values in multidimensional arrays
            //just like regular ones, through their indexes

            string[,] mybooks = TwoDimensionalArray();
            Console.WriteLine("The second book is {0}, by {1}", 
                mybooks[1, 0], mybooks[1, 1]);
            Console.WriteLine("*********************************");
            // the loop below multiplies the contents
            //of the three columns together
            int[,] cubes = Another2DimensionalArray();
            int cubicInches = 0;
            for (int i = 0; i < 3; i++)
            {
                cubicInches = cubes[i, 0] * cubes[i, 1] * cubes[i, 2];
                Console.WriteLine("Box {0}, is {1} cubic inches", i+1, cubicInches);
            }
            Console.WriteLine("*********************************");
           
        }
    }
}

Wednesday, October 26, 2011

Midterm code

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

namespace ExamExample
{
    class Program
    {
        const int SIZE = 50;
        static void Main(string[] args)
        {
            Program p = new Program();
            p.CreateArrays();
            p.PauseIt();
        }

       

        private void CreateArrays()
        { 
            int[] numbers= new int[SIZE];
            FillArray(numbers);

        }

        private void FillArray(int[] numbers)
        {
            Random rand = new Random();
            for (int i = 0; i < SIZE; i++)
            {
                numbers[i] = rand.Next(1, 100);
            }
            GetEvenNumbers(numbers);
        }

        private void GetEvenNumbers(int[] numbers)
        {
            int evenCount = 0;
            int oddCount = 0;

            for (int i = 0; i < SIZE; i++)
            {
                if (numbers[i] % 2 == 0)
                {
                    evenCount++;
                }
                else
                {
                    oddCount++;
                }

            }
            Console.WriteLine("There were {0} even numbers and {1} odd numbers", evenCount, oddCount);
           
        }

        private void PauseIt()
        {
            Console.WriteLine("\n\nPress any key to exit");
            Console.ReadKey();
        }

       
    }
}


Tuesday, October 25, 2011

Random

Here is the random Function

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

namespace RandomExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Random rand = new Random();
            int number=rand.Next(1, 1000);

            Console.WriteLine(number);

            Console.ReadKey();
        }
    }
}

Assignment4 Morning Class


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

namespace Assignment4Morning
{
    class Program
    {
        /// 
        /// This program calculates GPAs
        /// Based on grades and credits
        /// entered
        /// Steve Conger 10/25/2011
        /// 
      
        static void Main(string[] args)
        {
            Program p = new Program();

            string quit = "y";
            while (quit != "n")
            {
                p.CreateGPAArrays();
                Console.WriteLine("Continue y/n?");
                quit = Console.ReadLine();
               quit= quit.ToLower();
            }
            //Console.ReadKey();
        }//end main

        private void CreateGPAArrays()
        {
            Console.WriteLine("Enter how many grades you want to enter");
            int number = int.Parse(Console.ReadLine());

            double[] grades = new double[number];
            int[] credits = new int[number];

            FillGPAArrays(grades, credits);
        }//end Create

        private void FillGPAArrays(double[] grades, int[] credits)
        {
            for (int index = 0; index < grades.Length; index++)
            {
                double grade=0;
                
                do
                {
                    Console.WriteLine("enter grade");
                    grade = double.Parse(Console.ReadLine());
                    if (grade < 0 || grade > 4)
                    {
                        Console.WriteLine("Grades must be between 0 and 4");
                        
                    }
                } while (grade < 0 || grade > 4);
                grades[index] = grade;

                Console.WriteLine("enter Credits");
                credits[index] = int.Parse(Console.ReadLine());

            
            }//end for
            CalculateGPA(grades, credits);
        }//end Fill

        private void CalculateGPA(double[] grades, int[] credits)
        {
            double weight=0;
            int totalCredits = 0;

            for (int index = 0; index < grades.Length; index++)
            {
                weight += grades[index] * credits[index];
                totalCredits += credits[index];
            }

            //alternate way to sum credits
            //c# 4.0 and above only
            int total = credits.Sum();

            double gpa = weight / totalCredits;

            Console.WriteLine("Your GPA is {0}", Math.Round(gpa,1));
            
        }


    }//end class
}

Monday, October 24, 2011

Assignment 4


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

namespace Assignment4
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            string quit = "y";
            while (quit != "n")
            {
                p.CreateArrays();
                Console.WriteLine("Do you want start over? n to quit");
               quit=Console.ReadLine();
                quit.ToLower();
            }
            Console.ReadKey();
        }

        private void CreateArrays()
        {
            Console.WriteLine("How many Grades do you want to enter");
            int number = int.Parse(Console.ReadLine());

            double[] grades = new double[number];
            double[] credits = new double[number];

            FillArrays(grades, credits);
            

        }

        private void FillArrays(double[] grades, double[] credits)
        {
            for (int counter = 0; counter < grades.Length; counter++)
            {
                double grade = 0;
                do
                {
                    Console.WriteLine("Enter a Grade");
                    grade = double.Parse(Console.ReadLine());
                    if (grade <= 0 || grade > 4)
                    {
                        Console.WriteLine("Grades must be between 0 and 4");
                    }

                } while (grade <= 0 || grade > 4);
                grades[counter]=grade;

                Console.WriteLine("Enter the Credits");
                credits[counter] = double.Parse(Console.ReadLine());
            }//end for
            CalculateGPA(grades, credits);
        }//end fill arrays

        private void CalculateGPA(double[] grades, double[] credits)
        {
            double totalCredits = 0;
            double weight = 0;

            for (int counter = 0; counter < grades.Length; counter++)
            {
                weight+=grades[counter] * credits[counter];
                totalCredits += credits[counter];
            }//end for

            
            
            double gpa = weight / totalCredits;

            Console.WriteLine("Your GPA is {0:F1}", gpa);
        }

    }//end class
}

and here is the code for doing random numbers


 static void Main(string[] args)
  {
            
            Random rand = new Random();
            int number = rand.Next(1, 10);
            Console.WriteLine(number);
            Console.ReadKey();

   }

Thursday, October 20, 2011

Java Equivalent of ITC110 Assignment 4

This is an assignment that deals with loops and arrays. It uses two array one for Grades and one for Credits. The purpose of the program is to calculate a GPA. The arrays are created in one method and then passed to another where they are filled in a for loop. Then they are passed to a third method where the arrays are multiplied together and summed to get the GPA.

Two other loops are added. One, a while loop in main, lets the user repeat the program as often as they wish. They enter 0 to exit. The other, a do loop, is used in the FillArrays method to make sure the grade is between 0 and 4. It will not allow the user to continue until they have entered a grade in the valid range. The grade is not written to the array until it is valid.

Here is the Java code


import java.util.Scanner;

public class GPACalculator {

 /**
  * This program calculates a GPA 
  * to do so it uses parallel arrays
  * one for grades and one for credits
  * it checks to make sure grades are
  * between 0 and 4
  * this program is the java equivalent
  * of ITC110 assignment 4
  * Steve Conger !0/20/2011
  */
 //declare the scanner globally
 Scanner reader = new Scanner(System.in);
 
 public static void main(String[] args) {
  GPACalculator calc=new GPACalculator();
  int choice=1;
  while(choice !=0)
  {
   calc.CreateArrays();
   System.out.println("Do you want to enter more grades: 0 to exit");
   choice=calc.reader.nextInt();
  }
  
 }
 
 private void CreateArrays()
 {
  
  System.out.println("How many grades do you want to enter?");
  int number=reader.nextInt();
  
  //declare the arrays
  double[] grades = new double[number];
  double[] credits=new double[number];
  
  //call the FillArrays method
  FillArrays(grades, credits);
 }
 
 private void FillArrays(double[] grades, double[]credits)
 {
  //loop through and fill the arrays)
  for(int i=0;i<grades.length; i ++)
  {
   //the do loop makes sure the grade is in 
   //the proper range
   double grade=0;
   do
   {
   System.out.println("Enter the grade");
   grade=reader.nextDouble();
   if(grade<0 || grade>4)
   {
    System.out.println("Grades must be between 0 and 4");
   }
   }while (grade<0 || grade>4);
   grades[i]=grade;
   System.out.println("Enter the credits");
   credits[i]=reader.nextDouble();
  }
  //call the CalculateGPA method
  CalculateGPA(grades, credits);
 }
 
 private void CalculateGPA(double[] grades, double[]credits)
 {
  double weight=0;
  double totalCredits=0;
  
  for(int i=0;i<grades.length; i ++)
  {
   weight += grades[i] * credits[i];
   totalCredits += credits[i];
  }
  
  double gpa = weight / totalCredits;
  System.out.println("Your GPA is " + gpa);
  
 }
 

}

Wednesday, October 19, 2011

Consuming a Simple Web Services

This blog leads you through the process of consuming a simple web service. In it we will find a web service that provides global weather reports based on city and country and we will reference that web service in our own ASP.Net form and create our own little app that uses it.

Go to this url to get Free web services: http://www.webservicex.net/WS/wscatlist.aspx

Click on global weather

Click on get weather

Copy WSDL Schema Location http://www.webservicex.net/globalweather.asmx?WSDL

Open Visual Studio

Create a new website

Go to the Website menu, And select add web reference

Paste the schema location in the URL text box

Change the name of the web service name to net.globalweather.www

Add the web service add a labels and textboxes for city name and country and a button and a label to the web form



<%@ 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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1>Global Weather</h1>
      <p> 
         <asp:Label ID="Label2" runat="server" Text="Enter City"> 
        </asp:Label><asp:TextBox ID="txtCity" runat="server"></asp:TextBox> 
      </p>
      <p>
        <asp:Label ID="Label3" runat="server" Text="Enter Country">
        </asp:Label><asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
      </p>
      <p>
        <asp:Button ID="Button1" runat="server" Text="Get Weather" />
       </p>
       <p>
        <asp:Label ID="lblWeather" runat="server" Text="Label"></asp:Label>
        </p>
    </div>
    </form>
</body>
</html>

Double click the buttom in design mode to get to the C# code window

In the buttonI_click method enter the following code

 protected void Button1_Click(object sender, EventArgs e)
 {
     GlobalWeather gw = new GlobalWeather();
     string weather = gw.GetWeather(txtCity.Text, txtCountry.Text);
     lblWeather.Text = weather;
 }

Note how little code it takes to process this. The web service tells you when you add it that this method requires two string arguments (city and country) and that it returns a string. Some webservices can be more complex, but most are fairly straight forward to use

Here is a picture of the form running

Tuesday, October 18, 2011

Java Equivalent to C# Assignment 3


package Income;
import java.util.Scanner;

public class NetIncomeCalculator {

 /**
  * This program calculates gross pay
  * and net pay given deductions in 
  * Social Security, medicare and a bus
  * pass. It uses else if statments
  * to determine the rate of deduductions
  * This is the equivalent of
  * Assignment three in C# in ITC 110
  * Steve Conger 10/18/2011
  */
 
 //declaring constants
 //final double SOCIALSECURITY = .09;
 //final double MEDICARE=.03;
 final int BUSPASS=25;
   
 public static void main(String[] args) {
  //declare and instantiate the class
  //to load it (main being static is
  //already loaded into memory
  NetIncomeCalculator netcalc = new NetIncomeCalculator();
  //call the starting method
  netcalc.Display();
 }
 
 private void Display()
 {
  //get input
  //the scanner is an object to read from the console
  Scanner reader = new Scanner(System.in);
  System.out.println("Enter the number of hours worked");
  double hours = reader.nextDouble();
  System.out.println("Enter your rate per hour");
  double rate=reader.nextDouble();
  
  //call the methods to do the calculations
  double grossPay=CalcIncome(hours, rate);
  double socialSec = CalcSocialSecurity(grossPay);
  double medicare = CalcMedicare(grossPay);
  double netPay=CalcNetPay(grossPay, socialSec, medicare);
  
  //outputs
  System.out.println("Your gross income is " + grossPay);
  System.out.println("Your Social Security deduction is " + socialSec);
  System.out.println("Your Medicare deduction is " + medicare);
  System.out.println("Your Bus pass deduction is " + BUSPASS/4);
  System.out.println("Your net pay is " + netPay);
 }
 
 private double CalcIncome(double hrs, double rt)
 {
  double gross=0;
  //check to see if the hours are more than forty
  //if they are pay time and a half for overtime
  //if not just pay the rate of pay
  if (hrs > 40)
  {
   gross=rt * (40 + ((hrs-40)*1.5));
  }
  else
  {
   gross = rt * hrs;
  }
  return gross;
 }
 
 private double CalcSocialSecurity(double gPay)
 {
  double ss =0;
  if (gPay >= 5000)
   ss=.4;
  else if (gPay >= 4000 )
   ss=.35;
  else if (gPay >=3000)
   ss=.25;
  else if (gPay >=2000)
   ss=.2;
  else if (gPay > 1000)
   ss=.12;
  else
   ss=.09;
  
  return gPay * ss;
 }
 
 private double CalcMedicare(double gPay)
 {
  double med=0;
  if (gPay >=5000)
   med=.2;
  else if (gPay >= 2000)
   med=.1;
  else
   med=.05;
  return gPay * med;
 }
 
 private double CalcNetPay(double gPay, double ss, double med)
 {
  return gPay - (ss + med + (BUSPASS/4));
 }

}

Morning Arrays and loops


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

namespace ArraysAndLoops2
{
    class Program
    {
        /// 
        /// This program will create an array
        /// populate and array
        /// Display it
        /// sum and average the contents
        /// 
       
        static void Main(string[] args)
        {
            Program p = new Program();
            string choice="y";
            while (choice != "n" && choice != "N")
            {
                p.CreateArray();
                p.ParallelArrays();
                Console.WriteLine("Do you want enter more payments? Y/N");
                choice = Console.ReadLine();
            }
            Console.ReadKey();
        }

        private void CreateArray()
        {
            //double[] payments = new double[5];
            //payments[0] = 234.5;
            //payments[1] = 45.6;
            //payments[2] = 100;
            //payments[3] = 37.98;
            //payments[4] = 223;

            //int[] ray;
            //ray = new int[] { 45, 2, 3, 7, 22 };

            Console.WriteLine("How many payments do you want to enter");
            int number = int.Parse(Console.ReadLine());

            double[] payments = new double[number];

            for (int i = 0; i < number; i++)
            {
                Console.WriteLine(payments[i]);
            }//end for

            FillArray(payments, number);
        }//end create array

        private void FillArray(double[] paymnts, int size)
        {
            for (int i = 0; i < size; i++)
            {
                Console.WriteLine("Enter Payment");
                paymnts[i] = double.Parse(Console.ReadLine());
            }// end for
            DisplayArray(paymnts, size);
        }//end of Fill array

        private void DisplayArray(double[] pmts, int size)
        {
            Console.WriteLine("************************\n");
          
            //Console.Clear();
            for (int i = 0; i < size; i++)
            {
                Console.WriteLine(pmts[i]);
            }//end for
            SumAndAverage(pmts, size);
        }//end Display

        private void SumAndAverage(double[] pay, int size)
        {
            double total = 0;
            for (int i = 0; i < size; i++)
            {
                total += pay[i]; //total=total + pay[i] -= *= %= /=
            }
            Console.WriteLine("The total is {0}", total);
            double average = total / pay.Length;
            Console.WriteLine("the average is {0}", average);
        }//end sum and average

        private void ParallelArrays()
        {
            int[] myArray1 = new int[] { 2, 3, 54, 6, 8 };
            int[] myArray2 = new int[] { 3, 5, 2, 12, 4 };

            for (int i = 0; i < myArray1.Length; i++)
            {
                Console.WriteLine(myArray1[i] * myArray2[i]);
            }
        }

    }//end class
}

Monday, October 17, 2011

Loops and Arrays

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

namespace ArraysAndLoops
{
    class Program
    {

        /*This program will have three methods
         * one to create an array
         * one to populate it
         * and one to display it
         */
        static void Main(string[] args)
        {
            Program p = new Program();
            string exit = "y";
            while (exit != "n" && exit !="N")
            {
                p.CreateArray();
                Console.WriteLine("Do you want to continue y/n");
                exit = Console.ReadLine();
            }
            p.PauseIt();
        }

        //this method
        //creates an array
        private void CreateArray()
        {

            Console.WriteLine("How many payments do you want to enter?");
            int number = int.Parse(Console.ReadLine());
            double[] payments= new double[number];

            FillArray(payments, number);

            //double[] pmts = new double[] { 12.95, 34, 21.4, 43 };
            //payments[0] = 255;
            //payments[1] = 34.5;
            //payments[2] = 44.5;
            //payments[3] = 34;
            //payments[4] = 34.5;


        }

        private void FillArray(double[] payArray, int size)
        {
            //for loop
            for (int i=0; i < size; i++)
            {
                Console.WriteLine("Enter a payment");

                payArray[i] = double.Parse(Console.ReadLine());
            }//end for
            DisplayArray(payArray, size); //call DisplayArrayMethod
           
        }//end fill array

        private void DisplayArray(double[] pmt, int size)
        {
            Console.WriteLine("***********************");
            int x = 0;
            while (x < size)
            {
                Console.WriteLine(pmt[x]);
                x++;

                /*
                 * +=  (number += 10) same as (number= number + 10);
                -= minus (number -=10) same as (number=number-10)
                -- decrement subtract one each time
                *= (number *=10) same as (number=number*10)
                %=(number %=10) same as (number=number%10)
                /=(number /=10) same as (number=number/10)
                  */
            }//end while
            Sum(pmt, size);
        } //end display

        private void Sum(double[] payment, int size)
        {
            double total = 0;
            for (int i = 0; i < size; i++)
            {
                total += payment[i];
                //weight = grades[i] * credits[i];
            }
            double average = total / size;
            Console.WriteLine("the total is {0}", total);
            Console.WriteLine("the Average is {0}",average);
        }

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



    }//end class
}

Arrays

An array says your book, "represents a fixed number of elements of the same type." An array, for instance can be a set of integers or a set of doubles or strings. The set can be accessed under a single variable name.

You use square brackets [] to signify an array. The following declares an array of integers with 5 elements

int[] myArray=new int[5];

Each element in an array has an index number. We can use these indexes to assign or access values in an array. Indexes always begin with 0

myArray[0]=5;
myArray[1]=12;
myArray[2]=7;
myArray[3]=74;
myArray[4]=9;

Console.WriteLine("The fourth element of the array is {0}",myArray[3]);

Here is another way to declare an array. This declaration declares a string array and assigns the values at the moment when the array is created

string[ ] weekdays =new string[ ]
       {"Monday","Tuesday","Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

The values are still indexed 0 to 6


Array work naturally with loops. You can easily use a loop to assign values:


for (int i=0; i<size;i++)
{
     Console.WriteLine("Enter an Integer");
     myArray[i]=int.Parse(Console.ReadLine());

}

Arrays can be passed as a parameter to methods and they can be returned by a method.

private void CreateArray()
{
    double[ ] payments = new double[5];
    FillArray(payments, 5);
}

private void FillArray(double[ ] pmts, int size)
{
    int x=0;
   while (x < size)
  {
     Console.WriteLine("Enter Payment Amount");
     pmts[x]=double.Parse(Console.ReadLine());
     x++;
  }
}

Apps

The term "app" is short for application, but it has come to have a special meaning when applied to mobile devices such as phones, mp3 players and tablets. To some extent, these apps, like the term, are abbreviated. They are streamlined to run on the limited resources of a phone or tablet. That isn't to say that some of them aren't quite complex, but no matter how sophisticated, they must run within the constraints of the device they are on.

The question is how important is it for a student to get into the app market, and, if it is important, what skills do they need to get a foot in the door.

Apps have become big business, just as a decade ago every company had to have a web site, now every company has to have an app on your phone. Apps are rapidly becoming the predominate way of accessing the internet.

In September 2010 Chris Anderson wrote an article for Wired called The Web is Dead, Long Live the Internet In it he said:

 Over the past few years, one of the most important shifts in the digital world has been the move from the wide-open Web to semiclosed platforms that use the Internet for transport but not the browser for display. It’s driven primarily by the rise of the iPhone model of mobile computing, and it’s a world Google can’t crawl, one where HTML doesn’t rule. And it’s the world that consumers are increasingly choosing, not because they’re rejecting the idea of the Web but because these dedicated platforms often just work better or fit better into their lives (the screen comes to them, they don’t have to go to the screen). The fact that it’s easier for companies to make money on these platforms only cements the trend. Producers and consumers agree: The Web is not the culmination of the digital revolution.

And the shift is only accelerating. Within five years, Morgan Stanley projects, the number of users accessing the Net from mobile devices will surpass the number who access it from PCs. Because the screens are smaller, such mobile traffic tends to be driven by specialty software, mostly apps, designed for a single purpose. For the sake of the optimized experience on mobile devices, users forgo the general-purpose browser. They use the Net, but not the Web. Fast beats flexible.

http://www.wired.com/magazine/2010/08/ff_webrip/all/1

Sara Perez in Read Write Moblie notes: Native data applications, such as those installed on smartphones like the iPhone and devices running Android, now account for 50% of all mobile data volume according to a new report from Finnish mobile analytics company Zokem. In a global smartphone study released this month, the company found that while the mobile Web browser was still the most popular smartphone "app," the use of native apps outside the browser is growing faster than mobile browsing itself.

Cisco networks notes the following:

Global mobile data traffic grew 2.6-fold in 2010, nearly tripling for the third year in a row. The 2010 mobile data traffic growth rate was higher than anticipated. Last year's forecast projected that the growth rate would be 149 percent. This year's estimate is that global mobile data traffic grew 159 percent in 2010

Last year's mobile data traffic was three times the size of the entire global Internet in 2000. Global mobile data traffic in 2010 (237 petabytes per month) was over three times greater than the total global Internet traffic in 2000 (75 petabytes per month).

Mobile video traffic will exceed 50 percent for the first time in 2011. Mobile video traffic was 49.8 percent of total mobile data traffic at the end of 2010, and will account for 52.8 percent of traffic by the end of 2011.

http://www.cisco.com/en/US/solutions/collateral/ns341/ns525/ns537/ns705/ns827/white_paper_c11-520862.html

Companies are advertising for programmers to create apps. Typically they want people who can program for Apple's IOS and also for Android. Some also want Window's phone developers. Simply Hired had scores of listing for IPhone developer and nearly equal listings for Android developers. There were several listings for Windows phones as well.

The financial model for these apps is still developing. Many are free. They either generate no revenue for the app creator or they generate revenue by incorporating advertisements. Company based apps are usually free, the app itself being a form of advertising. Many other free apps are "lite" versions which encourage you to upgrade to a more feature rich version for a price. Some apps are sold at a 99 cent level. If an app takes off and is downloaded often enough this can add up to significant revenue. Other, usually serious productivity apps, such as Quick Office, charge comparatively large fees for download. But even these fees are miniscule compared to the prices of comparable software for the PC. An expensive app might be priced around 25 dollars, whereas its pc equivalent would be hundreds.

For a student, then there would seem to be two opportunities. One would be to work for a company that wants to build and distribute apps to support its business customers and processes. Another is to build their own apps and try to sell them in the app stores.


Skills Required to Create Apps

First let's consider what apps do:

  • They must use disk and memory resources efficiently since these are limited on mobile devices
  • They must surrender focus gracefully, especially on phones where they must recede to allow the phone call to take precedence.
  • They must thread processes to allow both foreground and background processing
  • They often store data locally for short terms (some for longer)
  • They usually read from and write to cloud data sources
  • They need to refresh on receiving focus
  • They usually keep the location and status of the user
  • Most apps listen for data and can pass alerts to the user
  • They need a simple, clear GUI
  • Many scale to the device with a different look on a phone than a tablet

Let's be clear, to develop apps a programmer still needs all the basic programming skills. He or she must know how to use programming structures such a selection, repetition and arrays. He or she must know how to create appropriate methods, etc. In addition they should have a good understanding of object oriented principles especially inheritance, since much mobile programming involves extending objects that are provided by the development kit.

Additionally, a developer should learn to thread applications, separating foreground and background operations. This is an important skill for surrendering focus to a phone call or another application

The developer should know how to find and access services, both on the phone and the cloud. These include the GPS services and various data services

Basic database skills for storing and retrieving data are also valuable.


Specific Platform requirements

IPhone| IPad| IPod

The tools for IOS development are only available on the MAC. IOS Apps are developed in Object C using XCode. All apps must be processed and approved by Apple and distributed through Apple's AppStore

Here is Apple's">Developer site

Here is an example of Objective C code for a hello world IPhone app

Android

The primary tools for Android are Java and xml through the Android SDK. There are several possible distributors for Android Apps, the largest of which is Google. You can also self distribute if you wish.

Here is the link to the Android Developers guide

Windows Phones

Windows phones use Silverlight with its XAML xml and C# or alternatively XBoxes XNA platform with C#.

Here is Microsoft's phone development site

It is also possible to create phone apps in all these platforms using HTML5. HTML5 apps are run through the phones browser. Microsoft has announced that its next OS, Windows 8 will work across hardware platforms and be based on HTML 5 and JavaScript. I am still unclear as to what that implementation will look like.


This is just a draft of the topic. I will try to expand on it more over time. Please feel free to comment and suggest additions or changes