Tuesday, December 7, 2010

Show and Tell Form for writing data with ADO

the xaml
<Window x:Class="Personform.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Label Content="Enter Last Name" Height="28" HorizontalAlignment="Left" Margin="53,35,0,0" Name="label1" VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="189,35,0,0" Name="txtLastName" VerticalAlignment="Top" Width="120" />
<Label Content="Enter First Name" Height="28" HorizontalAlignment="Left" Margin="53,83,0,0" Name="label2" VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="189,83,0,0" Name="txtFirstName" VerticalAlignment="Top" Width="120" />
<Button Content="Save" Height="23" HorizontalAlignment="Left" Margin="61,167,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>
</Window>

The Windows1.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Personform
{
///
/// Interaction logic for MainWindow.xaml
///

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
try
{
Person person = new Person(txtLastName.Text, txtFirstName.Text);
PersonWrite personWrite = new PersonWrite(person);
txtFirstName.Clear();
txtLastName.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
The person class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Personform
{
class Person
{
private string first;
private string last;

public Person(string fName, string lName)
{
FirstName = fName;
LastName = lName;
}

public string FirstName
{
get { return first; }
set { first = value; }
}

public string LastName
{
get { return last; }
set { last = value; }
}
}
}

the Person Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace Personform
{
class PersonWrite
{
private SqlConnection connect;
private Person pers;

public PersonWrite(Person p)
{
connect = new SqlConnection
("Data Source=localhost;initial catalog=CommunityAssist;integrated security=true");
pers = p;
WritePerson();
}

private void WritePerson()
{
try
{
string Sql = "Insert into Person(LastName, FirstName) Values (@last, @first)";
SqlCommand cmd = new SqlCommand(Sql, connect);
cmd.Parameters.AddWithValue("@last", pers.LastName);
cmd.Parameters.AddWithValue("@first", pers.FirstName);

connect.Open();
cmd.ExecuteNonQuery();
}
catch(SqlException)
{
Exception ex = new Exception("Your sql sucks");
throw ex;
}
catch (Exception ex)
{
throw ex;
}
finally
{
connect.Close();
}
}
}
}

Tuesday, November 30, 2010

ASP Example

Default.aspx
<%@ 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="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:Calendar ID="Calendar1" runat="server"
onselectionchanged="Calendar1_SelectionChanged">
<DayHeaderStyle CssClass="testClass" />
</asp:Calendar>
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>

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

Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string> myList= new List<string>();

myList.Add("One");
myList.Add("Two");
myList.Add("Three");
myList.Add("Four");

DropDownList1.DataSource = myList;
DropDownList1.DataBind();

Label1.Text = myList[2].ToString();


}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{

Label1.Text = Calendar1.SelectedDate.ToShortDateString();

if (Calendar1.SelectedDate.ToShortDateString() == "12/25/2010")
{
Label1.CssClass = "testClass";
Label1.Text = "Merry Christmas!";
}
else
{
Label1.CssClass = "";

}

// Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Hello this is an Alert')</SCRIPT>");

}
}

Stylessheet.cssbody
{
font-family:Verdana, Sans-Serif;
font-size:larger;
}
h1
{
font-size:150%;
color:Navy;
}

.testClass
{
color:Red;
}

Monday, November 29, 2010

ASP Page

Html and asp xml
<%@ 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>Calendar</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Calendar ID="Calendar1" runat="server" BackColor="White"
BorderColor="Black" BorderStyle="Solid" CellSpacing="1" Font-Names="Verdana"
Font-Size="9pt" ForeColor="Black" Height="250px" NextPrevFormat="ShortMonth"
Width="330px" onselectionchanged="Calendar1_SelectionChanged">
<SelectedDayStyle BackColor="#333399" ForeColor="White" />
<TodayDayStyle BackColor="#999999" ForeColor="White" />
<OtherMonthDayStyle ForeColor="#999999" />
<DayStyle BackColor="#CCCCCC" />
<NextPrevStyle Font-Bold="True" Font-Size="8pt" ForeColor="White" />
<DayHeaderStyle Font-Bold="True" Font-Size="8pt" ForeColor="#333333"
Height="8pt" />
<TitleStyle BackColor="#333399" BorderStyle="Solid" Font-Bold="True"
Font-Size="12pt" ForeColor="White" Height="12pt" />
</asp:Calendar>
<asp:Button ID="Button1" runat="server" Text="GetDate"
onclick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
</div>
</form>
</body>
</html>

Code behind
using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Drawing;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ArrayList myArray = new ArrayList();
myArray.Add("One");
myArray.Add("Two");
myArray.Add("Three");

//DropDownList1.DataSource = myArray;
//DropDownList1.DataBind();

if (!IsPostBack)
{
DropDownList1.Items.Add("one");
DropDownList1.Items.Add("two");
DropDownList1.Items.Add("three");
}


}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = Calendar1.SelectedDate.ToShortDateString();
}

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
//Style christmasStyle = new Style();
//christmasStyle.ForeColor = Color.Red;
Label1.Text = Calendar1.SelectedDate.ToShortDateString();
if (Calendar1.SelectedDate.ToShortDateString() == "12/25/2010")
{
Label1.ForeColor=Color.Red;
Label1.Text = "Merry Christmas";
}
}
}

Wednesday, November 17, 2010

Joins, Inserts, Updates, Deletes

Select SalesOrderID, Name,
orderQTy,UnitPrice,UnitPriceDiscount,LineTotal
From SalesLT.Product p
INNER JOIN SalesLT.SalesOrderDetail od
ON p.ProductID=od.ProductID

Select FirstName, LastName,
Phone, City, StateProvince
From SalesLT.Customer c
Inner join SalesLT.CustomerAddress ca
on c.CustomerID=ca.CustomerID
Inner Join Saleslt.Address a
on a.AddressID=ca.AddressID

--alternate way to join tables
Select FirstName, LastName,
Phone, City, StateProvince
From SalesLT.Address a,SalesLT.Customer c,
SalesLT.CustomerAddress ca
WHERE c.CustomerID=ca.CustomerID
AND a.AddressID=ca.AddressID

Select p.ProductID, SalesOrderDetailID
From SalesLT.Product p
Left outer Join SalesLT.SalesOrderDetail so
on p.ProductID=so.ProductID
Where SalesOrderDetailID is null

Select * from SalesLT.Customer

Use MagazineSubscription

Insert into Customer (CustLastName,
CustFirstName, CustAddress,
CustCity, CustState,
CustZipcode, CustPhone)
Values ('Smith', 'Pedro','1000 Somewhere',
'Seattle','WA','98001','2065551234'),
('Sanches', 'Pedro','1000 Elsewhere','Seattle',
'WA','98001','2065554321')

Select * from Customer
Where CustLastName='Smith' or CustLastName='Sanches'

Begin Tran

Update Customer
Set CustLastName='Jordan',
CustAddress='2000 South Mercer Street'
Where CustID=1

Select * From Customer

Commit Tran
Rollback tran

Select * from MagazineDetail
Update magazineDetail
Set SubscriptionPrice = SubscriptionPrice * 1.05

Select * From Customer

Delete From Customer
Where CustID=13

SQL Examples

Use AdventureworksLT

/*basic sql syntax
11/15/2010
Select statements*/
SELECT FirstName,LastName,Phone
FROM SalesLT.Customer;

--this uses the * wild card
Select *
from SalesLT.Customer;

Select ProductID
from SalesLT.SalesOrderDetail;

Select Distinct ProductID
From SalesLT.SalesOrderDetail;

Select *
From SalesLT.SalesOrderDetail;

Select ProductID, OrderQTY,
UnitPrice, UnitPriceDiscount,
(OrderQty * UnitPrice)[Unit Total]
from SalesLT.SalesOrderDetail
Order by ProductID DESC, (OrderQty * UnitPrice)Desc;

--Select with where clause

Select * from SalesLT.Address
Where City='Bothell'

Select * from SalesLT.SalesOrderDetail
Where UnitPrice <= 100

Select * From SalesLT.Customer
Where Lastname Like 'Bre_er'

Select * From SalesLT.Address
Where City='Bellevue' or City='Dallas'
Order by City

Select * from SalesLT.Customer
Where LastName Not Like 'G%'
And (CompanyName Like '%bike%'
Or CompanyName Like '%cycle%')

Select * From SalesLT.SalesOrderHeader
Where SalesOrderID Between 71774 and 71784

Select * From SalesLT.SalesOrderHeader
Where CreditCardApprovalCode Is Not Null

Select Distinct MONTH(OrderDate) as [Month],
YEAR(OrderDate) AS [Year], Day(OrderDate) as [Day]
from SalesLT.SalesOrderHeader

--aggregate functions
--count avg sum max min
Select COUNT(ProductID) From SalesLT.SalesOrderDetail

Select SUM(Linetotal) from SalesLT.SalesOrderDetail
Select Avg(Linetotal) from SalesLT.SalesOrderDetail
Select Max(Linetotal) from SalesLT.SalesOrderDetail
Select Min(Linetotal) from SalesLT.SalesOrderDetail

Select ProductID,UnitPrice, Count(ProductID)
from SalesLT.SalesOrderDetail
Group by ProductID, unitprice
Having Count(productID) <= 3
Order by ProductID

Tuesday, November 16, 2010

More WPF Events and features

The XAML
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Background>
<ImageBrush />
</Window.Background>
<Grid Background="{x:Null}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="254*" />
<ColumnDefinition Width="249*" />
</Grid.ColumnDefinitions>
<RadioButton Content="Red" Height="16" HorizontalAlignment="Left" Margin="77,56,0,0" Name="radioButton1" VerticalAlignment="Top" Checked="radioButton1_Checked" />
<RadioButton Content="Green" Height="16" HorizontalAlignment="Left" Margin="80,88,0,0" Name="radioButton2" VerticalAlignment="Top" Checked="radioButton2_Checked" />
<RadioButton Content="blue" Height="16" HorizontalAlignment="Left" Margin="80,126,0,0" Name="radioButton3" VerticalAlignment="Top" Checked="radioButton3_Checked" />
<StackPanel Height="119" HorizontalAlignment="Right" Margin="0,48,55,0" Name="stackPanel1" VerticalAlignment="Top" Width="235" Grid.ColumnSpan="2" />
<Button Content="FormBackground" Height="23" HorizontalAlignment="Left" Margin="58,214,0,0" Name="button1" VerticalAlignment="Top" Width="119" Click="button1_Click" MouseEnter="button1_MouseEnter" />
<TextBox Grid.ColumnSpan="2" Height="23" HorizontalAlignment="Left" Margin="237,221,0,0"
Name="textBox1" VerticalAlignment="Top"
Width="120"
GotFocus="textBox1_GotFocus" LostFocus="textBox1_LostFocus"/>
</Grid>
</Window>

The events

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

namespace WpfApplication2
{
///
/// Interaction logic for MainWindow.xaml
///

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Background = new SolidColorBrush(Colors.White);
}

private void radioButton1_Checked(object sender, RoutedEventArgs e)
{
stackPanel1.Background = new SolidColorBrush(Colors.Red);
}

private void radioButton2_Checked(object sender, RoutedEventArgs e)
{
stackPanel1.Background = new SolidColorBrush(Colors.Green);
}

private void radioButton3_Checked(object sender, RoutedEventArgs e)
{
stackPanel1.Background = new SolidColorBrush(Colors.Blue);
}

private void button1_Click(object sender, RoutedEventArgs e)
{
this.Background = new LinearGradientBrush(Colors.Goldenrod, Colors.GreenYellow, 50);
}

private void button1_MouseEnter(object sender, MouseEventArgs e)
{
button1.Background = new SolidColorBrush(Colors.Purple);
}

private void textBox1_GotFocus(object sender, RoutedEventArgs e)
{
textBox1.Background = new SolidColorBrush(Colors.Navy);
textBox1.Foreground = new SolidColorBrush(Colors.White);
button1.Visibility = Visibility.Collapsed;
}

private void textBox1_LostFocus(object sender, RoutedEventArgs e)
{
button1.Visibility = Visibility.Visible;
MessageBox.Show("Come back here!");
}
}
}

Monday, November 15, 2010

WPF Form Events

The xaml code
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<RadioButton Height="16" Margin="26,32,132,0" Name="radioButton1" VerticalAlignment="Top" Checked="radioButton1_Checked">Red</RadioButton>
<RadioButton Height="16" Margin="26,55,132,0" Name="radioButton2" VerticalAlignment="Top" Checked="radioButton2_Checked">Green</RadioButton>
<RadioButton Height="16" Margin="30,81,128,0" Name="radioButton3" VerticalAlignment="Top" Checked="radioButton3_Checked">Blue</RadioButton>
<StackPanel Margin="0,18,17,0" Name="stackPanel1" Height="105" HorizontalAlignment="Right" VerticalAlignment="Top" Width="116" MouseEnter="stackPanel1_MouseEnter" />
<Button Height="23" HorizontalAlignment="Left" Margin="30,0,0,92" Name="button1" VerticalAlignment="Bottom" Width="75" Click="button1_Click" MouseEnter="button1_MouseEnter">Button</Button>
<TextBox Height="23" Margin="34,0,124,49"
Name="textBox1" VerticalAlignment="Bottom" LostFocus="textBox1_LostFocus" GotFocus="textBox1_GotFocus"/>
<Button Height="23" HorizontalAlignment="Right" Margin="0,0,58,92" Name="button2" VerticalAlignment="Bottom" Width="75" Click="button2_Click">Random Color</Button>
</Grid>
</Window>

the code for the various events

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

namespace WpfApplication1
{
///
/// Interaction logic for Window1.xaml
///

public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}

//these occur whenever the radiobutton is checked
private void radioButton1_Checked(object sender, RoutedEventArgs e)
{
stackPanel1.Background = new SolidColorBrush(Colors.Red);
}

private void radioButton2_Checked(object sender, RoutedEventArgs e)
{
stackPanel1.Background = new SolidColorBrush(Colors.Green);
}

private void radioButton3_Checked(object sender, RoutedEventArgs e)
{
stackPanel1.Background = new SolidColorBrush(Colors.Blue);
}

//this occurs when the button is clicked by a mouse
private void button1_Click(object sender, RoutedEventArgs e)
{
radioButton1.IsChecked = false;
radioButton2.IsChecked = false;
radioButton3.IsChecked = false;
stackPanel1.Background = new SolidColorBrush(Colors.White);
}

//this happens when the mouse enters the area of the button control
private void button1_MouseEnter(object sender, MouseEventArgs e)
{
button1.Background = new SolidColorBrush(Colors.Yellow);
}

//this doesn't work
private void stackPanel1_MouseEnter(object sender, MouseEventArgs e)
{
button1.Background = new SolidColorBrush(Colors.WhiteSmoke);
}

//this happens when you click out of the text box to do something else
private void textBox1_LostFocus(object sender, RoutedEventArgs e)
{
textBox1.Text = sender.ToString();
textBox1.Background = new SolidColorBrush(Colors.White);
MessageBox.Show("Come Back here");
}

//this happens when you click into the text box to type something
private void textBox1_GotFocus(object sender, RoutedEventArgs e)
{
textBox1.Background = new SolidColorBrush(Colors.Thistle);
}

//this randomly assigns a color to the stackpanel
private void button2_Click(object sender, RoutedEventArgs e)
{
//create an array of colors
Color[] myColors = new Color[4];
myColors[0] = Colors.Peru;
myColors[1] = Colors.SaddleBrown;
myColors[2] = Colors.Salmon;
myColors[3] = Colors.SeaShell;

//get a random number
Random rand = new Random();
int x = rand.Next(0, 3);

//set the background color of the stackpanel using the array
stackPanel1.Background = new SolidColorBrush(myColors[x]);
}



}
}

Wednesday, November 10, 2010

Detatching Files

To detatch a database
Before you can detatch a database you must make sure that all windows that connect to the database are closed.
In Management Studio, in the Object Explorer
Right click on the database
Choose "Tasks"
Choose "Detach"
Just click OK on the following dialog. Don't check any boxes.
Use the operating system file manager to navigate to the database files.
Usually they are under C:\Program Files\Microsoft SQL Server\..\mssql1\Data\
The dots are for a variable folder name. What it is depends on your installation
Copy both the .mdf and the .log file. You will need them both.
To Reattach
In Management Studio, right click on "Databases" in the Object Explorer
Choose "Attach"
In the Dialog box click "Add"
use the next dialog box to navigate to where your files are
(to attach them they must be in a "root" level folder. That means they can't be on the desktop or in my documents.)
Once you have located the files click OK.
It should reattch the database for use

Tuesday, November 9, 2010

More array stuff

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

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

void CreateArray()
{
int[] myArray = { 1, 3, 5, 20, 51, 3, 2 };
Console.WriteLine(myArray[3].ToString());

//double[,,] myArrayTwo = new double[5,2,1];
//myArrayTwo[0,0, 0] = 2.3;
//myArrayTwo[0,0 ,1] = 2;
//myArrayTwo[0,1, 0] = 4;
//myArrayTwo[0,1, 1] = 4.5;

//string[,] books = new string[3, 2];
//books[0, 0] = "Lord of the Rings";
//books[0, 1] = "Tolkein";
Console.WriteLine("How many scores do you want to enter?");
int number = int.Parse(Console.ReadLine());
int[] scores =new int[number];
FillArray(scores);


}

void FillArray(int[] myScores)
{
for (int i = 0; i < myScores.Length; i++)
{
Console.WriteLine("enter a score");
myScores[i]=int.Parse(Console.ReadLine());
}
DisplayArray(myScores);
}

void DisplayArray(int[] allScores)
{
int sum = 0;
int counter = 0;
foreach (int i in allScores)
{
counter++;
Console.WriteLine("the score for hole {0} is {1}",counter,i.ToString());
sum += i; //sum = sum + i
}

double average = (double)sum / allScores.Length;

Console.WriteLine("The sum of the scores is {0}", sum);
Console.WriteLine("the average of the scores is {0}", average);
Array.Sort(allScores);
Console.WriteLine("the highest score is {0}", allScores.Max());
Console.WriteLine("The Second highest score is {0}", allScores[allScores.Length-2]);
}

void ArraylistExample()
{
ArrayList myList = new ArrayList();
myList.Add("Don't Panic");

List<string> genericArray = new List<string>();

}
}
}

Monday, November 8, 2010

Kilometers Conversion

Conversion.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConvertToKilometers
{
class Conversion
{
//private fields
private double miles;
private const double CONVERTFACTOR = 1.6;

//default constructor
public Conversion()
{
Miles = 0;
}

//overloaded constructor
public Conversion(double totalMiles)
{
Miles = totalMiles;
}

//public property
public double Miles
{
get { return miles; }
set { miles = value; }
}

//public method

public double Convert()
{
return Miles * CONVERTFACTOR;
}


}
}


Display.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConvertToKilometers
{
class Display
{
private double totMiles;

public void GetMiles()
{
bool isNumber;
Console.WriteLine("Enter the Miles");
isNumber = double.TryParse(Console.ReadLine(), out totMiles);
if (isNumber==false )
{
Console.WriteLine("Must be a number");
return;
}
}//end getmiles

public void DisplayKilometers()
{
Conversion c = new Conversion(totMiles);
Console.WriteLine("{0} is equal to {1} Kilometers", totMiles.ToString(), c.Convert().ToString());
}


}
}


Program.cs

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

namespace ConvertToKilometers
{
class Program
{
static void Main(string[] args)
{
Display d = new Display();
d.GetMiles();
d.DisplayKilometers();
Console.ReadKey();
}
}
}

Thursday, November 4, 2010

Code for Tip calculator


Xaml

<Window x:Class="TipCalculatorMark2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="417" Width="525">
<Grid Height="346">
<Label Content="Enter the total meal amount" Height="28" HorizontalAlignment="Left" Margin="50,30,0,0" Name="label1" VerticalAlignment="Top" FontSize="16" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="309,36,0,0" Name="txtMeal" VerticalAlignment="Top" Width="120" Background="#FF1CE9BB" FontSize="16" />
<RadioButton Content="10%" Height="16" HorizontalAlignment="Left" Margin="72,93,0,0" Name="rdoTenPercent" VerticalAlignment="Top" FontSize="16" />
<RadioButton Content="15%" Height="16" HorizontalAlignment="Left" Margin="72,129,0,0" Name="rdoFifteen" VerticalAlignment="Top" FontSize="16" />
<RadioButton Content="20%" Height="16" HorizontalAlignment="Left" Margin="72,167,0,0" Name="rdoTwenty" VerticalAlignment="Top" FontSize="16" />
<RadioButton Content="Other" Height="16" HorizontalAlignment="Left" Margin="72,207,0,0" Name="rdoOther" VerticalAlignment="Top" FontSize="16" />
<TextBox Background="#FF1CE9BB" FontSize="16" Height="23" HorizontalAlignment="Left" Margin="163,207,0,0" Name="txtOther" VerticalAlignment="Top" Width="120" />
<Button Content="GetTip" Height="23" HorizontalAlignment="Left" Margin="63,0,0,41" Name="button1" VerticalAlignment="Bottom" Width="75" Click="button1_Click" />
<Label Content="Label" Height="103" HorizontalAlignment="Left" Margin="163,243,0,0" Name="lblResults" VerticalAlignment="Top" Width="276" FontSize="16"/>
</Grid>
</Window>

mainwindow code


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

namespace TipCalculatorMark2
{
///
/// Interaction logic for MainWindow.xaml
///

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
//Get input
double tipChoice = 0;
double totalMeal = 0;
bool test = double.TryParse(txtMeal.Text, out totalMeal);

if (test == false)
{
MessageBox.Show("Enter a valid number. No $ sign.");
txtMeal.Clear();
return;

}

if (rdoTenPercent.IsChecked==true)
{
tipChoice = .10;
}
if (rdoFifteen.IsChecked == true)
{
tipChoice = .15;
}
if (rdoTwenty.IsChecked == true)
{
tipChoice = .2;
}

if (rdoOther.IsChecked==true)
{
bool test2 = double.TryParse(txtOther.Text, out tipChoice);

if (test2 == false)
{
MessageBox.Show("Enter a valid percentage, no % sign.");
txtOther.Clear();
return;
}
}
Tip t = new Tip(totalMeal, tipChoice);
lblResults.Content = "The Tax on the meal is : "
+ t.CalculateTax().ToString("c") + "\n" +
"the Tip amount is: " + t.CalculateTip().ToString("c")
+ "\nThe total due is: " + t.CalculateTotal().ToString("c");


}
}
}

Tip Class

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

namespace TipCalculatorMark2
{
class Tip
{
//private fields
private double mealAmount;
private double tipPercent;
private const double TAXRATE = .09;

//constructors
public Tip()
{
MealAmount = 0;
TipPercent = 0;
}

public Tip(double total, double percent)
{
MealAmount = total;
TipPercent = percent;

}

//public properties
public double MealAmount
{
get { return mealAmount; }
set { mealAmount = value; }

}

public double TipPercent
{
get { return tipPercent; }
set
{
if (value >= 1)
{
tipPercent = value / 100;
}
else
{
tipPercent = value;
}
}
}

//public methods
public double CalculateTax()
{
return MealAmount * TAXRATE;
}

public double CalculateTip()
{
return MealAmount * TipPercent;
}

public double CalculateTotal()
{
return MealAmount + CalculateTip() + CalculateTax();
}

}
}

Wednesday, November 3, 2010

Arrays

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

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

void SimpleArray()
{
//one way to declare and initilize

int[] myArray = { 3, 45, 3, 14, 50 };
//always start counting at 0;
Console.WriteLine(myArray[3].ToString());
myArray[3] = 100;


// Console.WriteLine(myArray.Length);

int[] myArray2 = new int[5];
myArray2[0] = 23;
myArray2[1] = 22;

}

void CollectScores()
{
Console.WriteLine("how many scores do you want enter");
int number = int.Parse(Console.ReadLine());

double[] scores = new double[number];

for (int i = 0; i < number; i++)
{
Console.WriteLine("Enter a score");
scores[i] = double.Parse(Console.ReadLine());
}

CalculateAverages(scores);


}

void CalculateAverages(double[] rawScores)
{
double sum = 0;
//for every double value in the array
//scores which stores doubles
foreach (double score in rawScores)
{
Console.WriteLine(score.ToString());
sum += score;
}
Console.WriteLine("**********************");
Console.WriteLine("The sum is {0} ", sum);
double average = sum / rawScores.Length;
Console.WriteLine("The average is {0}", average.ToString("c"));
}
}
}

Monday, November 1, 2010

Package Class



Window1.xaml
<Window x:Class="PackageCalculator.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="377">
<Grid Height="268">
<Label Height="28" HorizontalAlignment="Left" Margin="20,31,0,0" Name="label1" VerticalAlignment="Top" Width="120">Enter the Weight</Label>
<TextBox Height="23" Margin="0,31,99,0" Name="txtWeight" VerticalAlignment="Top" HorizontalAlignment="Right" Width="120" />
<RadioButton Height="16" HorizontalAlignment="Left" Margin="48,87,0,0" Name="rdoOvernight" VerticalAlignment="Top" Width="120" >Overnight</RadioButton>
<RadioButton HorizontalAlignment="Left" Margin="48,112,0,0" Name="rdoTwoDay" Width="120" Height="16" VerticalAlignment="Top">Two Day</RadioButton>
<RadioButton Height="16" HorizontalAlignment="Left" Margin="50,0,0,106" Name="rdoGround" VerticalAlignment="Bottom" Width="120">Ground</RadioButton>
<Button Height="23" Margin="136,0,0,71" Name="btnShipping" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="75" Click="btnShipping_Click">Get Shipping</Button>
<Label Height="28" Margin="42,0,73,18" Name="lblShippingPrice" VerticalAlignment="Bottom">Label</Label>
</Grid>
</Window>

Here is the Code for Windows1.xaml.cs

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

namespace PackageCalculator
{
///
/// Interaction logic for Window1.xaml
///

public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}

private void btnShipping_Click(object sender, RoutedEventArgs e)
{
//get the weight from textbox
double weight = double.Parse(txtWeight.Text);
//initilize the shipmethod variable
string shipMethod = null;
//checking to see which shipping method
//they have selected
if (rdoOvernight.IsChecked == true)
{
shipMethod = rdoOvernight.Content.ToString();
}

if (rdoTwoDay.IsChecked == true)
{
shipMethod = rdoTwoDay.Content.ToString();
}

if (rdoGround.IsChecked == true)
{
shipMethod = rdoGround.Content.ToString();
}

//initialize the Package class with the
//second constructor, passing it the values
Package pack = new Package(weight, shipMethod);
//call the CalculateShippingPrice of the class
//and store the result returned in the variable price
double price = pack.CalculateShippingPrice();
//display the results in the label on the form

lblShippingPrice.Content = "the shipping price is " + price.ToString("c");
}


}
}
Here is the package class

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

namespace PackageCalculator
{
class Package
{

//fields are class level variables
//that describe the class
//private by default, but stating it
//makes it obvious
private double weightInOunces;
private string shippingMethod;
private double shippingPrice;

//default constructor
public Package()
{
WeightInOunces = 0;
ShippingMethod = null;
ShippingPrice = 0;
}

//second constructor
public Package(double weight, string method)
{
WeightInOunces = weight;
ShippingMethod = method;
ShippingPrice = 0;
}


//public properties expose your
//private variables
//you control how they are exposed
//properties don't have ()
//they don't take arguments

public double WeightInOunces
{
set { weightInOunces = value; }
get { return weightInOunces; }
}//end property

public string ShippingMethod
{
set { shippingMethod = value; }
get { return shippingMethod; }
}//end property

public double ShippingPrice
{
set { shippingPrice = value; }
get { return shippingPrice; }
}

//this is a method to calculate shiping price
//it must have a parenthesis
//even if it doesn't have arguments
public double CalculateShippingPrice()
{
if (WeightInOunces <= 8)
{
ShippingPrice = 1;
}
else if (WeightInOunces <= 16)
{
ShippingPrice = 2;
}
else if (WeightInOunces <= 32)
{
ShippingPrice = 5;
}
else
{
ShippingPrice = 10;
}

if (ShippingMethod == "Overnight")
{
//*= means the same as
//ShippingPrice=ShippingPrice * 3
ShippingPrice *= 3;
}

if (ShippingMethod == "Two Day")
{
ShippingPrice *= 2;
}

return ShippingPrice;
}

} //end class
}//end namespace

More about Classes

First, a class is an abstract representation of an object. . .

A class can contain:
* fields
* properties
* methods
* constructors

Fields are class level variables. They describe a class. For instance, a Student class would have fields like studentID, name, email, major, gpa, etc. Fields should be kept private, which means nothing outside the class can see them or change them. This is part of encapsulation.

Properties are a special kind of method that are used to expose the private variables to other classes. Most properties contain two other methods: a Set which allows the user to change the value of the field, and a Get method that returns the value of the field. A property can just have a Get or just a Set. Additionally the programmer can add some validation to the property.

The idea of a property is to control access to the internal fields or variables. A property is marked by having no parenthesis at the end. (All other method and class initiations must have parenthesis.)

Methods are just as you have used them in the past. They do the work of the class. Each method must have a return type even if it is void. Methods can take parameters or not as needed. Any method with a return type other than void must have a return statement that returns a value of that type. Just like in the console apps we have done, each method should do one thing, though that thing could be complex. If you want other classes to be able to use the method you should declare it public.

Constructors, like properties, are also special methods. Constructors are used for initializing a class. In a constructor you can provide initial values for the field variables. You can also call any methods that need to run before the class is used. For example, you might call a method that connects to a database, so that when the class is used it is ready to read or write from the database. You can have more than one constructor. It is possible to overload constructors (or any other method) by creating a method with the same name but a different signature. The signature consists of the number and data types of the arguments.

Here are two constructors for the Student Class:


public Student()
{
StudentID=null;
StudentName=null;
GPA=0;
}

public student(string studID)
{
StudentID=studID;
StudentName=null;
GPA=0;

}



Constructors are marked by having the same name as the class and by having no return type.

If you don't create a constructor, .Net will create a default constructor for you that will initialize all your variables to 0 or null. If you create a constructor, any constructor, .Net will not create a default constructor and you will have to do all your own initializing.

Wednesday, October 27, 2010

Classes and radiobuttons

Here is the form:



Here is the radiobutton code:

private void button1_Click(object sender, RoutedEventArgs e)
{
if (radioButton1.IsChecked==true)
{
MessageBox.Show("the tip is 10%");
}
if (radioButton2.IsChecked==true)
{
MessageBox.Show("the tip is 15%");
}
if (radioButton3.IsChecked==true)
{
MessageBox.Show("the tip is 20%");
}
}

Tuesday, October 26, 2010

Object Oriented Programming

Object oriented programming arose out of the desire to create a more natural method for dealing with large coding projects. Rather than try to manage huge numbers of individual methods, code was broken up into objects. These objects reflected the acutal structure of the things the programmer was working with. For instance, a point of sale application might have objects for customer, item, sale, etc. Objects can also be used for systems and networks: things like connection objects. In the programming environment, forms are objects, as are buttons and text boxes, etc.

A class is the abstract description of an object. A class describing a customer, for instance, describes an ideal customer, not any particular customer.
Classes can contain fields (class level variables), properties, methods, constructors, and events.

There are four basic principles of Object oriented programming:

Abstraction
Objects should be abstractions of things. They should represent typical or generic descriptions of things.

Polymorphism
Polymorphism refers to the the ability of objects to behave differently in differnt contexts. For example the + sign between two numbers adds the numbers, between two strings it concatinates the strings. It behaves differently depending on context.

Polymorphism is primarily achieved through two techniques: Overloading and overwriting methods.

Inheritance
Inheritance allows you to derive a new object from an existing one and automatically get all the public variables, methods and properties of the parent. It promotes code reuse.

Encapsulation
Encapsulation is the principle that every object should be as self contained as possible. It should contain all that it needs to functions and be as independent as possible from other objects. The idea is that an object should be like a component or a lego, that you can plug in whereever you need and have it work.

Here is a picture of the form running:


Here is the Xaml for the form

<Window x:Class="MileageWithClass.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Background="Blue">
<Grid>
<Label Content="Enter total Miles" Height="28" HorizontalAlignment="Left" Margin="47,40,0,0" Name="label1" VerticalAlignment="Top" Foreground="White" FontSize="16" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="234,40,0,0" Name="txtMiles" VerticalAlignment="Top" Width="120" FontSize="16" />
<Label Content="Enter the total gallons" Height="28" HorizontalAlignment="Left" Margin="25,87,0,0" Name="label2" VerticalAlignment="Top" Foreground="White" FontSize="16" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="234,93,0,0" Name="txtGallons" VerticalAlignment="Top" Width="120" FontSize="16" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="64,172,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>
</Window>

Here is the Mileage Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MileageWithClass
{
public class Mileage
{

//empty constructor
public Mileage()
{
NumberOfMiles = 0;
NumberOfGallons = 0;
PricePerGallon = 0;
}

//overloaded constructor
public Mileage(double miles, double gallons)
{
NumberOfMiles = miles;
NumberOfGallons =gallons;
PricePerGallon = 0;
}
//private fields
private double numberOfMiles;

//public properties that expose private fields
public double NumberOfMiles
{
get
{
return numberOfMiles;
}
set
{
numberOfMiles = value;
}
}

private double numberOfGallons;

public double NumberOfGallons
{
get { return numberOfGallons; }
set { numberOfGallons = value; }
}

private double pricePerGallon;

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

//public method
public double CalculateMileage()
{
return NumberOfMiles / NumberOfGallons;
}

//overloaded method
public double CalculateMileage(double miles, double gallons)
{
NumberOfMiles = miles;
NumberOfGallons = gallons;
return NumberOfMiles / NumberOfGallons;
}


}
}

Here is the code for the button in the form

private void button1_Click(object sender, RoutedEventArgs e)
{
//Mileage mileage = new Mileage();
//mileage.NumberOfMiles = double.Parse(txtMiles.Text);
//mileage.NumberOfGallons = double.Parse(txtGallons.Text);


Mileage m = new Mileage(double.Parse(txtMiles.Text),
double.Parse(txtGallons.Text));

double milesPerGallon = m.CalculateMileage();

MessageBox.Show("the miles per gallon is "
+ milesPerGallon.ToString());
}

Monday, October 25, 2010

Entity Relation Diagram

Here is the diagram we did for the DVD

Thursday, October 21, 2010

Error Trapping

Here is the code that shows error trapping (AM Class)

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

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

void BadDivision()
{
double number;
double number2;
bool b1, b2;

try
{
Console.WriteLine("Enter a number");
b1 = double.TryParse(Console.ReadLine(), out number);

if (b1 == false)
{
Console.WriteLine("You must enter a real number");
return;
}

Console.WriteLine("Enter a second number");
b2 = double.TryParse(Console.ReadLine(), out number2);

if (b2 == false)
{
Console.WriteLine("You must enter a real number");
return;
}

if (number2 == 0)
{
throw new DivideByZeroException();
}

double quotient = number / number2;

Console.WriteLine("the quotient is {0}", quotient);
}//end try
catch (DivideByZeroException divError)
{
Console.WriteLine(divError.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

}
}
}

Tuesday, October 19, 2010

Random and Loops

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

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

void GetRandom()
{
Random rand = new Random();

for (int counter = 1; counter <= 10; counter++)
{
int number = rand.Next(1, 1000);
Console.WriteLine(number.ToString());
}

int number2 = 1;
int counter2 = 0;
while (counter2 <= 10)
{
Console.WriteLine("Enter a number, 0 to quit");
number2 = int.Parse(Console.ReadLine());
counter2++;
}
}
}
}

Thursday, October 14, 2010

What do we know so far?

What do we know about Namespaces?

  • Namespaces are a bloc that begin and end with curly braces


  • Namespaces contain classes

  • Namespaces are used to group similar things and keep things that should be separate, separate



What do we know about classes?

  • A classes are blocks that begin and end with curly braces


  • classes can contain methods(including special methods such as properties and events) and variable declarations


  • All methods and variable declarations must be inside of a class


  • A class is an abstract definition of an object



What do we know about Main()?

  • Main is a special method. It is the starting point of any C# program


  • As a method it is a block statement that begins and ends with curly braces


  • because Main is always static it is loaded immediately into memory and executes first


  • Also because it is static, we must instantiate (declare) the class it is in to load the other methods in the class into memory


  • Best practice is to only put the minimal amount of code to start the program into Main



What do we know about Methods?

  • Methods are blocks used to separate the work that a program does.


  • As blocks they begin and end with curly braces

  • A method always has a return type. Void is a return type that means the
    method does not return a value.


  • A method that is not void must have a return statement


  • The return statement is always the last statement in a method, any code after a return statement will never execute


  • Methods can take arguments(parameters) that pass values from one method to another (but they don't have to.)


  • A method must be called from somewhere if it is to do its work


  • You call a method by naming it and providing any arguments it requires


  • once a method has executed all its statements the program flow returns to the place where the method was called


  • If the method returns a value other than void, you can assign that value to a variable to store and use in the calling method



What do we know about variables?

  • Variables are used to store temporary values that the program needs to do its work


  • A variable must be declared, to do that you state its type and then its name

    double number;


  • A variable must be assigned a value before you can use it.

    number=10;


  • Variables have "Scope", that means there are limits to where their values can be accessed and how long they are in memory


  • The general rule is that a variable has the scope of the block in which it was declared. (between the curly braces of the block)


  • So a variable declared at the class level can be accessed by any method in the class.

  • A variable declared in a method has method scope and can only be accessed by statements in that method


  • A variable declared in an if block has a value that can only be accessed within the if statement




What do we know about statements?


  • Statements are actual lines of commands that do the work of the program.


  • All statements end with a semi colon


  • Statements can only exist in methods.



What do we know about objects?

You can access the methods and properties of an object by giving

the object name or object instance name, typing a dot . and choosing the

method from the intellisense list: Console.WriteLine(); p.Display()


A Sample Program:




Let's create a program to calculate tips for a meal. We won't worry for

now about calculating taxes or doing tips for services or taxies. We will

just focus on tips for meals.


First Let's walk through the Program Planner.


What are the input's that we will need? We will need the cost of the meal

and the percent tip we wish to offer.


Secondly we need to know what the output is. We will want to

see the cost of the meal, the amount of the tip, and the total of

the meal and the tip together.


To get from inputs to outputs we need to do two calculations.

First we get the amount of the tip by multiplying it times the percentage.

Next we add the amount of the tip to the meal amount to get the grand total.


This is the place to think about methods. Think about the tasks you

need to do. There should be a method for each task. In the case of the tips

program we need to:


  • get the meal amount and tip percent
  • >

  • calculate the tip


  • calculate the total


  • Display the results



So we need four methods in addition to the Main(). If it helps

it might be a good idea to lay out the method signatures first

like this:


class Program()

{

static void Main()

{

}


void GetInfo()

{

}


double CalculateTip(double total, double percent)

{

}


double CalculateTotal(double mTotal, double tipAmount)

{

}


void Display(double mt, double mtip, double grandTotal)

{

}

}
}


When you set up the methods think about what parameters you have to pass

or what variables you have to declare. It doesn't have to be perfect. You can adjust

it as you go. The trick is to keep the logic forefront in you mind: First we need to get

the information, next we calculate the tip, then we calculate the total with the tip,

then we display the results. If you hold tight to the logic the syntax issues shouldn't

be so difficult to deal with and overcome.


Below is the whole code with comments:


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;


namespace TipCalculator

{

//this class calculates the amount of a tip

//give the total cost of the meal

//and the percent of the tip the user

//wishes to give

//Steve Conger

//Sample program

//10/14/2010


class Program

{

static void Main(string[] args)

{

Program p = new Program(); //load the Program class

p.GetInformation(); //call the starting method

Console.ReadKey(); //pause the program

}


void GetInformation()

{

//this method gathers all the information

//program needs both from the Console

//for meal and percent

//and from other methods

Console.WriteLine("Enter the total meal cost");

double mealTotal = double.Parse(Console.ReadLine());

Console.WriteLine("Enter the percent tip");

double tipPercent = double.Parse(Console.ReadLine());


//call the Calculatetip method and send it the mealTota

//and the tip percent

//it returns a value stored in the variable tip

double tip = CalculateTip(mealTotal, tipPercent);


//call the CalculateTotal method passing it the mealTotal

//and tip amount that we got back from the previous method

double totalWithTip = CalculateTotal(mealTotal, tip);


//send it all to Display()

DisplayResults(mealTotal, tip, totalWithTip);

}

double CalculateTip(double total, double percent)
{

double tipAmount;

//here we test to see if they sent the percent as a decimal

//or a whole number

//if it is a whole number we divide it by 100

//to turn it into a decimal

if (percent > 1)

{

tipAmount=total * (percent /100);

}

else

{

//otherwise we just multiply the total by the percentage

tipAmount= total * percent;

}

return tipAmount;

}



double CalculateTotal(double mTotal, double tipAmt)

{

//in this method we just add the meal amount and the tip

return mTotal + tipAmt;

}


void DisplayResults(double mt, double mtip, double grandTotal)

{

//the console clear does what it says it clears the console

Console.Clear();


//below we just display the values we passed from GetInfo

Console.WriteLine("*******************************");

Console.WriteLine("the meal total is {0}", mt.ToString("c"));

Console.WriteLine("the tip amount will be {0}", mtip.ToString("c"));

Console.WriteLine("the total due is {0}", grandTotal.ToString("c"));

}

}

}

Wednesday, October 13, 2010

If then examples (morning)

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

namespace ifmethod
{
class Program
{
/*Steve Conger
* 10/12/2010
* Assignment x
* */

static void Main(string[] args)
{
Program p = new Program();
// p.Display();
p.GetDegrees();
Console.ReadKey();
}//end main

int Remainder(int num1, int num2)
{
int modulus;
modulus= num1 % num2;
return modulus;
}//end remainder

void Display()
{

int numberOne, numberTwo;
bool good, isInt;

Console.WriteLine("enter a number");
good = int.TryParse(Console.ReadLine(), out numberOne);

//if (good == false)
//{
// Console.WriteLine("You must Enter an integer");
// return; //end method display
//}
//else
// {
//do something else
//}


Console.WriteLine("enter another number");
isInt = int.TryParse(Console.ReadLine(), out numberTwo);

//this is a way to do it in one statement
//the || means or
if (good == false || isInt == false)
{
Console.WriteLine("You must Enter an integer");
return; //end method display
}

int remain = Remainder(numberOne, numberTwo);

Console.WriteLine("the remainder of {0} divided by {1} = {2}", numberOne.ToString(),
numberTwo.ToString(), remain.ToString());

// SumOfRemainder(remain);

}

void Weather(int degrees)
{
if (degrees >= 100)
{
Console.WriteLine("way too hot");
}
else
if (degrees >= 80)
{
Console.WriteLine("hot");
}
else
if (degrees >= 60)
{
Console.WriteLine("Just right");
}
else
if (degrees >= 40)
{
Console.WriteLine("autumnal");
}
else
{
Console.WriteLine("cold");
}


}

void GetDegrees()
{
Console.WriteLine("Enter a temperature");
int temp = int.Parse(Console.ReadLine());

Weather(temp);
}

//void SumOfRemainder(int r)
//{
// Console.WriteLine(r.ToString());
//}

}//end program class
}//end namespace

Monday, October 11, 2010

IF ELSE IF ELSE

Here is starter code for the assignment;

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

namespace Assignment3Help
{
class Program
{
double grossPay;

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

double CalculateGrossPay(double rate, double hours)
{
return rate * hours;
}

void Display()
{
Console.WriteLine("Enter the Rate");
double rate = double.Parse(Console.ReadLine());
Console.WriteLine("Enter the hours");
double hours = double.Parse(Console.ReadLine());
grossPay = CalculateGrossPay(rate, hours);
Console.WriteLine("The Gross pay is {0}", grossPay.ToString("c"));
}//end display

double SocialSecurity()
{
//at or above 5000 30%
//at or above 3000 25%
//at or above 2000 20%
//at or above 1000 15%
//at or above 800 10%
//below 800 0%
double socialSecurity;
if (grossPay >= 5000)
{
socialSecurity = grossPay * .3;
}
else if ( grossPay >=3000)
{
socialSecurity = grossPay * .25;
}
else if (grossPay >= 2000)
{
socialSecurity = grossPay * .2;
}
else if (grossPay >= 1000)
{
socialSecurity = grossPay * .1;
}
else
{
socialSecurity = 0;
}
return socialSecurity;

}

}//class
}

The other code we did
using System;
using System.Collections.Generic;
using System.Text;

namespace OperationsPractice
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
//p.Display();
Console.WriteLine("Enter a temperature");
int temp = int.Parse(Console.ReadLine());
p.IfElseExample(temp);
Console.ReadKey();
}//end main

private int Addition(int num1, int num2)
{
return num1 + num2;
}//end add

private void Display()
{
int number1=0;
int number2;
bool isInt1;
bool isInt2;

Console.WriteLine("Enter the first number");
isInt1 = int.TryParse(Console.ReadLine(), out number1);
if (isInt1 == false)
{
Console.WriteLine("You must enter an integer");
//Console.ReadKey();
return;
}//end if

Console.WriteLine("Enter the Second number");
isInt2 = int.TryParse(Console.ReadLine(), out number2);

if (isInt2 == false)
{
Console.WriteLine("You must enter an integer");
//Console.ReadKey();
return;
}//end if
int sum=Addition(number1, number2);
Console.WriteLine("the sum is {0}", sum );
}//end display

private void IfElseExample(int number)
{
if (number >= 100)
{
Console.WriteLine("It is too hot");
}
else if (number >= 80)
{
Console.WriteLine("Hot");
}
else if (number >= 60)
{
Console.WriteLine("Just right");
}
else if (number >= 40)
{
Console.WriteLine("cool");
}
else
{
Console.WriteLine("Cold");
}

//if(number != 3)
//{
// if (number > 5)
//{
//return;
//}
//else
//{
//}
// }
//else
//{
//do something else
//}
}
}//end class
}//end namespace

Thursday, October 7, 2010

Code for Assignment 2

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

namespace Assignment2
{
class Program
{

double grossPay;

static void Main(string[] args)
{
Program prog = new Program();
prog.GetNumbers();
Console.ReadKey();
}

void GetNumbers()
{
Console.WriteLine("Enter the Rate");
double rate = double.Parse(Console.ReadLine());
Console.WriteLine("Enter the hours");
double hours = double.Parse(Console.ReadLine());
CalculateGross(rate, hours);
CalculateTotalDeductions();
}

void CalculateGross(double rt, double hrs)
{
grossPay = rt * hrs;
Console.WriteLine("The Product is {0}", grossPay.ToString("c"));
}

double CalculateSocialSecurity()
{
return grossPay * .2;
}

double CalculateMedicare()
{
return grossPay * .05;
}

void CalculateTotalDeductions()
{
double ss = CalculateSocialSecurity();
double md = CalculateMedicare();
double totalDeductions = ss + md;
Console.WriteLine("the total deductions are {0}", totalDeductions.ToString("c"));
}

}//class
}

Tuesday, October 5, 2010

MethodExamples Morning

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

namespace MethodExamples
{
class Program
{

static void Main(string[] args)
{
Program prog = new Program();
//prog.BasicOperators();
prog.UseGetRemainder();
}//end main

private void BasicOperators()
{
double number;
int num1=7, num2=34, num3=12;
string myName = "Steve Conger";

//The basic operators are * / + - %
// other operators ++ -- += -= *= /= %= < > != ==

number = 756.77;
double sum = number + num1;
int total = (int)number + num1;

Console.WriteLine("the double sum is {0}", sum.ToString());
Console.WriteLine("The integer total is {0}", total.ToString());

Console.ReadKey();


}//end basic operators

private int GetRemainder(int numberOne, int numberTwo)
{
int remainder;
remainder = numberOne % numberTwo;
return remainder;
}

private void UseGetRemainder()
{
Console.WriteLine("Enter your first number");
int number1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter your second number");
int number2 = int.Parse(Console.ReadLine());

int myRemainder = GetRemainder(number1, number2);

Console.WriteLine("the remainder of {0} and {1} is {2}", number1.ToString(),
number2.ToString(), myRemainder.ToString());

Console.ReadKey();

}

}//end class program
}//end namespace

Monday, October 4, 2010

operators and methods: afternoon.

Here is the code we did in class

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

namespace methodExamples
{
class Program
{
double number = 0;
static void Main(string[] args)
{
//* / + - %
Program p = new Program();
// p.BasicOperators();
p.UseCube();
Console.ReadKey();

}

private void BasicOperators()
{
int x=6, y=8;
double a, b;
a = 12.34;
b = 3.75;


double sum = a + b;
double difference = a - b;
double product = a * b;

int quotient = y / x;
int remainder = y % x;

Console.WriteLine("The sum is {0}", sum.ToString());
Console.WriteLine("The difference {0}", difference.ToString());
Console.WriteLine("The product is {0}", product.ToString());
Console.WriteLine("The quotient of integer {0}, and {1} is {2}", y.ToString(), x.ToString(), quotient.ToString());
Console.WriteLine("The remainder is {0}", remainder.ToString());


}//end method BasicOperators

private double Cube(double number)
{
double cubeNumber=number * number * number;
return cubeNumber;
}

private void UseCube()
{

Console.WriteLine("Enter a number");
double myNumber = double.Parse(Console.ReadLine());
double myCube = Cube(myNumber);
Console.WriteLine("The cube of {0} is {1}", myNumber.ToString(), myCube.ToString());
}
}//end class
}//end namespace

Class Activities

Today in class we broke into scenario groups. Each group should send me their names and what topic they are working on. Additionally groups should begin working on the thing to do associated with their scenario, specifically deciding what the big topics are and composing a statement of work (or at least a statment of scope).

There was also time to begin the individual practices. We will go over the practices on Wednesday and start chapter 2.

Things are due as you finish them. I am not very strict about due dates. But we will continue moving on and it can be easy to get behind. Ideally things should be turned in about a week after we cover them.

Thursday, September 30, 2010

First assignment Morning class

Here is the program planner

What is the main purpose of your program?
To calculate miles per gallon and cost per mile
What is the output for your program?
miles per gallon
Cost per mile

What is the input needed to get that output?
total miles (beginning and ending miles
price per gallon
total gallons

What steps are required to convert the input into the output (algorithm)?
Miles per gallon = total miles / total gallons
cost per mile= price per gallon/miles per gallon

How will you test that the output is correct?
Test it against data where you know answer

Here is the WPF form xaml:

<:Window x:Class="GasCalculator.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Background="#FF8F8FE3">
<Grid>
<Label Content="Total Miles" Height="38" HorizontalAlignment="Left" Margin="21,25,0,0" Name="label1" VerticalAlignment="Top" Width="144" FontSize="18" />
<TextBox Height="23" HorizontalAlignment="Right" Margin="0,33,212,0" Name="txtTotalMiles" VerticalAlignment="Top" Width="120" />
<Label Content="Price Per Gallon" FontSize="18" Height="38" HorizontalAlignment="Left" Margin="21,79,0,0" Name="label2" VerticalAlignment="Top" Width="144" />
<TextBox Height="23" HorizontalAlignment="Right" Margin="0,87,212,0" Name="txtPricePerGallon" VerticalAlignment="Top" Width="120" />
<Label Content="Total Gallons" FontSize="18" Height="38" HorizontalAlignment="Left" Margin="21,123,0,0" Name="label3" VerticalAlignment="Top" Width="144" />
<TextBox Height="23" HorizontalAlignment="Right" Margin="0,0,212,157" Name="txtTotalGallons" VerticalAlignment="Bottom" Width="120" />
<Button Content="Calculate" Height="29" HorizontalAlignment="Left" Margin="35,189,0,0" Name="btnCalculate" VerticalAlignment="Top" Width="75" Click="btnCalculate_Click" />
<Label Content="Label" Height="38" HorizontalAlignment="Left" Margin="162,191,0,0" Name="lblMilesPerGallon" VerticalAlignment="Top" Width="264" FontSize="18" />
<Label Content="Label" Height="33" HorizontalAlignment="Left" Margin="162,235,0,0" Name="lblCostPerMile" VerticalAlignment="Top" Width="245" FontSize="18" />
</Grid>
</Window>

Here is the c# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace GasCalculator
{
///
/// Steve Conger
/// Assignment 1
/// 9/30/2010
/// This program calculate miles per gallon
/// and price per mile
///

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void btnCalculate_Click(object sender, RoutedEventArgs e)
{
//get input
double totalMiles= double.Parse(txtTotalMiles.Text);
double pricePerGallon = double.Parse(txtPricePerGallon.Text);
double totalGallons = double.Parse(txtTotalGallons.Text);

//transform input to output
double milesPerGallon = totalMiles / totalGallons;
double pricePerMile = pricePerGallon / milesPerGallon;

//output the results
lblMilesPerGallon.Content = "The miles per gallon is " + milesPerGallon.ToString();
lblCostPerMile.Content = "The cost per mile is " + pricePerMile.ToString("c");

}


}
}

Wednesday, September 29, 2010

Assignment 1

Here is the xaml code
<Window x:Class="Assignment1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="436" Width="479">
<Grid Background="CornflowerBlue">
<Label Height="28" HorizontalAlignment="Left" Margin="25,40,0,0" Name="label1" VerticalAlignment="Top" Width="132">Enter Beginning Miles</Label>
<TextBox Height="22" Margin="183,40,153,0" Name="txtBeginningMiles" VerticalAlignment="Top" />
<Label Height="28" HorizontalAlignment="Left" Margin="38,88,0,0" Name="label2" VerticalAlignment="Top" Width="120">Enter Ending Miles</Label>
<TextBox Height="23" Margin="185,88,153,0" Name="txtEndingMiles" VerticalAlignment="Top" />
<Label Height="28" HorizontalAlignment="Left" Margin="38,135,0,0" Name="label3" VerticalAlignment="Top" Width="120">Cost Per Gallon</Label>
<TextBox Height="23" Margin="185,135,153,0" Name="txtCostPerGallon" VerticalAlignment="Top" />
<Label HorizontalAlignment="Left" Margin="38,181,0,189" Name="label4" Width="120">Number of Gallons</Label>
<TextBox Margin="185,181,153,194" Name="txtGallons" />
<Button Height="23" HorizontalAlignment="Left" Margin="49,0,0,135" Name="button1" VerticalAlignment="Bottom" Width="75" Click="button1_Click">Calc</Button>
<Label Height="28" HorizontalAlignment="Left" Margin="49,0,0,88" Name="label5" VerticalAlignment="Bottom" Width="120">Miles Per Gallon</Label>
<Label Height="28" Margin="196,0,142,88" Name="lblMilesPerGallon" VerticalAlignment="Bottom">Label</Label>
<Label Height="28" HorizontalAlignment="Left" Margin="49,0,0,50" Name="label6" VerticalAlignment="Bottom" Width="120">Cost per Mile</Label>
<Label Height="28" Margin="0,0,142,50" Name="lblCostPerMile" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="119">Label</Label>
</Grid>
</Window>

Here is the C Sharp code
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Assignment1
{
///
/// Steve Conger
/// 9/29/2010
/// Assignment 1
///

public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
//get the input
double beginningMiles;
beginningMiles = double.Parse(txtBeginningMiles.Text);
double endingMiles = double.Parse(txtEndingMiles.Text);
double costPerGallon = double.Parse(txtCostPerGallon.Text);
double gallonsPurchased = double.Parse(txtGallons.Text);

//converting input to output
double totalMiles = endingMiles - beginningMiles;
double milesPerGallon = totalMiles / gallonsPurchased;
double costPerMile = costPerGallon / milesPerGallon;

//output
lblMilesPerGallon.Content = milesPerGallon.ToString();
lblCostPerMile.Content = costPerMile.ToString("c");
}
}
}

Monday, September 27, 2010

Hello world

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

namespace Hello
{
/*
* this is a hello world program
* it doesn't do much
* steve conger 9/27/2010 */
/// <summary>
///
/// </summary>
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello all you Martians");
Console.ReadKey();
}//end main
}//end class
}//end namespace

Monday, September 6, 2010

Program Preliminaries

For every program I am going to ask you to fill out a worksheet. This is meant to be a way to help you start thinking about the program and what you need to do to write it. It may seem like busy work, but thinking through these questions can save you a lot of time and frustration in the long run. Here is an example of the form filled out for a simple program that tests whether a number is even or odd:


Program Planner


What is the main purpose of your program?
To determine if a number is odd or even
What is the output for your program?
It will return the string "Even" if the number is even, or "Odd" if the number is odd
What is the input needed to get that output?
An integer number
What steps are required to convert the input into the output (algorithm)?
the number input modulus 2
if the remainder is 0 then the output is "Even"
otherwise the output is "Odd"
How will you test that the output is correct?
I will enter an even number to make sure the output is correct, then I will enter an odd number to determine the same.
A non integer number will crash the program
What objects will you use?
Console and Integer


Additionally I will ask you to put a comment header on every program that tells what the assignment is, a brief description of the program, your name and the date. It will look something like this:

/*********************************
* Assignment x
* This program determines if a number
* is even or odd
* Steve Conger
* September 30, 2010
***********************************/

Thursday, August 19, 2010

Monday, August 16, 2010

Data Analysis

This excercise should develop a simple analysis cube.

Before beginning we need to add the local service user to the AdventureworksDW Database. Open the security folder for AdventureworksDW and right click on Users.
Select New User. In the login dialog box click on the button by logins and find the local service login. Give the user a name. In the database roles click on the datareader role. Click ok.

Creating a cube


1. Open the Business Intellegence studio
2. Choose FILE /New Project
3. Choose an Analysis Service Project
4. In the Solution Explorer right click on Data Sources
5. Choose New Data Source
6. Next
7. Click the New ...




8. configure the connection



9. Next. Choose Use Service Account



10. Next/Finish
11. In the Solution Explorer Right click on the Data Source View Folder.
12. Choose a new data source view
13. Next
14 Add all the tables and click next



15. Next. Review the tables. Finish
16. In the Solution Explorer right click on Cubes and choose New Cube
16. Next
17. Choose "Use existing tables"
18. Next. Select "FactInternetSales" Next
19. Accept what's there.
20. Next, Next, Next
21. Finish.
22. Right click the cube and select process.
23. A dialog says the cube seems out of date etc, say yes
24. Click Run
25. If all goes well and the cube deploys click close and close again
26. Click Browser
27. Drag fields onto the cube as shown in the illustration below



28. Feel free to add or subtract other fields from the cube