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.