Showing posts with label Homework. Show all posts
Showing posts with label Homework. Show all posts

Thursday, September 3, 2009

PART 1 & 2 - SQL User Defined Functions - Homework solutions

Question 1
Create a function called fnGetTimeOnly to return the time part (hh:mm) of a DateTime value



ALTER FUNCTION dbo.fnGetTimeOnly(@datefield DATETIME)
RETURNS varchar(5)
AS
BEGIN
RETURN CONVERT(VARCHAR(2),
DATEPART(hh,@datefield)) + ':' + CONVERT(VARCHAR(2),DATEPART(mi,@datefield))
END

----------------------------------------------------

SELECT dbo.fnGetTimeOnly(GETDATE()) AS Expr1


Create a function called fnGetDateOnly to return the date part (dd/mm/yyyy) of a DateTime value



ALTER FUNCTION dbo.fnGetDateOnly
(@datefield DATETIME)
RETURNS VARCHAR(10)
AS
BEGIN
RETURN CONVERT(VARCHAR(2),DATEPART(dd,@datefield))+ '/' +
CONVERT(VARCHAR(2),DATEPART(mm,@datefield))+ '/' +
CONVERT(VARCHAR(4),DATEPART(yyyy,@datefield))
END

---------------------------------------------------------

SELECT dbo.fnGetDateOnly(NOW()) AS Expr1


Create a stored procedure called OrderDateTimeSpecific to return all order dates by splitting the date part and the time part into different columns. Use the functions created above in the stored procedure.



ALTER PROCEDURE dbo.OrderDateTimeSpecific

AS
SELECT dbo.fnGetDateOnly(OrderDate) AS OrderDate,
dbo.fnGetTimeOnly(OrderDate) AS OrderTime
FROM Orders
RETURN


Question 2
Create a function called fnContactInfo that returns a table containing all employees full name and their contact number



ALTER FUNCTION dbo.fnContactInfo()
RETURNS @contactInfoTable TABLE (fullname varchar(30), contactnumber varchar(24))
AS
BEGIN
INSERT INTO @contactInfoTable
SELECT FirstName + ' ' + LastName, HomePhone FROM Employees
RETURN
END


Create a query to return all values from the fnContactInfo function



SELECT fullname, contactnumber
FROM dbo.fnContactInfo() AS fnContactInfo_1


Question 3
Create a function called fnLastDay to get the last day in a month of a given date.



ALTER FUNCTION dbo.fnLastDay(@givendate DATETIME)
RETURNS VARCHAR(30)
AS
BEGIN
DECLARE @dayindex INT
DECLARE @lastday VARCHAR(30)
DECLARE @lastdate DATETIME

SET @lastdate = DATEADD(day, - 1, DATEADD(month, DATEDIFF(month, 0, @givendate) + 1, 0))
SET @dayindex = CONVERT(INT,DATEPART(weekday,@lastdate))

SELECT @lastday =
CASE @dayindex
WHEN 1
THEN 'Family Day Sunday'
WHEN 2
THEN 'Back to work Day Monday'
WHEN 3
THEN 'Movie night Tuesday'
WHEN 4
THEN 'Borrow money day Wednesday'
WHEN 5
THEN 'Shopping spree Thursday'
WHEN 6
THEN 'Binge drinking night Friday'
WHEN 7
THEN 'Activities day Saturday'
END


RETURN @lastday
END


Create a query to return all employees and their pay day last month, this month, and next month. The pay day is always the last day of the month.



SELECT LastName, FirstName,
dbo.fnLastDay(DATEADD(month, - 1, GETDATE())) AS PreviousMonthPayDay,
dbo.fnLastDay(GETDATE()) AS ThisMonthPayDay,
dbo.fnLastDay(DATEADD(month, 1, GETDATE())) AS NextMonthPayDay
FROM Employees


Question 4
Create a function called fnRoundCurrency to format the currency value into the correct monetary format. For e.g. 39.07 should be rounded to 39.10.



ALTER FUNCTION dbo.fnRoundCurrency(@currency MONEY)

RETURNS DECIMAL(10,2)
AS
BEGIN
RETURN CAST ((ROUND((@currency * 2),1) /10) *5 AS DECIMAL(10,2))
END


Modify the stored procedure created last week and call this function to format the new price of the first ten products into the right format.



ALTER PROCEDURE dbo.spShowCorrectPrice
AS
SELECT TOP 10 *,dbo.fnRoundCurrency(UnitPrice) as RoundedPrice FROM Products

RETURN


PART II
Create a table called Books in Northwind database containing BookID, ISBN, Publisher, Author, Year, Country, Category, Description.



CREATE TABLE Books
(
BookID INT,
ISBN VARCHAR(13),
Publisher VARCHAR(30),
Author VARCHAR(30),
Year INT,
Country VARCHAR(20),
Category VARCHAR(30),
Description VARCHAR(30),
CONSTRAINT pk_BookID PRIMARY KEY (BookID)
)


Question 1: FUNCTIONS TO CHECK CONSTRAINTS IN A TABLE DEFINITION
Create a function called fnValidISBN to check the value entered into ISBN field in the Books table. The following requirements are to check for valid ISBN:
ISBN numbers can contain 10 or 13 digits number.
Assuming that the company only accepts English-language publisher books, make sure that the ISBN follows the systematic pattern.
To check if the numbers entered are valid or not, use the formula and pattern in this webpage: http://en.wikipedia.org/wiki/International_Standard_Book_Number



ALTER FUNCTION dbo.fnValidISBN
(@isbn VARCHAR(13))
RETURNS INT
AS
BEGIN
DECLARE @result INT
DECLARE @isbn_ten INT
DECLARE @isbn_thirteen INT
DECLARE @isbn_sum INT
DECLARE @startpos INT
DECLARE @isbnlen INT


SET @isbn_ten = 9
SET @isbn_thirteen = 12
SET @isbn_sum = 0
SET @startpos = 1


SET @isbnlen = LEN(@isbn)

IF (@isbnlen = @isbn_ten)
BEGIN
WHILE (@startpos<= @isbn_ten+1)
BEGIN
SET @isbn_sum = @isbn_sum + (@isbn_ten * SUBSTRING(@isbn, @startpos, 1))
SET @startpos = @startpos + 1
END

IF (11-@isbn_sum%11) = SUBSTRING(@isbn,10,1)
SET @result = 0 --Success
ELSE
SET @result= 1 --Failure
END

ELSE IF (@isbnlen = @isbn_thirteen+1)
BEGIN
WHILE (@startpos <= @isbn_thirteen)
BEGIN
IF @startpos % 2 <> 0
BEGIN
SET @isbn_sum = @isbn_sum + (1 * SUBSTRING(@isbn, @startpos, 1))
SET @startpos = @startpos + 1
END
ELSE
BEGIN
SET @isbn_sum = @isbn_sum + (3 * SUBSTRING(@isbn, @startpos, 1))
SET @startpos = @startpos + 1
END
END


IF (10 - @isbn_sum % 10) = SUBSTRING(@isbn,13,1)
SET @result = 0 --Success
ELSE
SET @result= 1 --Failure
END

ELSE SET @result = 1

RETURN @result
END


---------------------------------------------

SELECT dbo.fnValidISBN(9780306406156) AS Expr1

Monday, August 24, 2009

SQL Northwind DB - Stored Procedures

1. Create a stored procedure to search employees by the first few letters in their last name.


CREATE PROCEDURE dbo.spSearchEmployeebyLName
@LName nvarchar(20)

AS
SET @LName = @LName + '%'
SELECT * FROM Employees
WHERE LastName LIKE @LName
RETURN


2. Create a stored procedure to create a new product and a new category by passing the CategoryName, ProductName, and the status (Discontinued) is False.


CREATE PROCEDURE spCreateNewProduct

@CategoryName nvarchar(15),
@ProductName nvarchar(40),
@Status bit = 'False'

AS
DECLARE @CatID INT;

INSERT INTO Categories (CategoryName)
VALUES ( @CategoryName )
SET @CatID=@@IDENTITY

INSERT INTO Products (ProductName, CategoryID, Discontinued)
VALUES (@ProductName, @CatID, @Status)

RETURN


3. Create a stored procedure to show the stock level of every product in the Products table. For unit stock under 20, the stock level is low. Unit stock above 100, the stock level is high. For the rest, the stock level is medium.


CREATE PROCEDURE spShowStockLevel

AS
SELECT ProductID, ProductName, UnitsInStock,
CASE
WHEN UnitsInStock <20
THEN 'LOW'
WHEN UnitsInStock >100
THEN 'HIGH'
ELSE
'MEDIUM'
END
AS StockLevel
FROM Products
RETURN


4. Create a stored procedure to display the territory status for each territory in Territories table. Territories id that starts with 9 is considered as big cities. Territories id starts with 0 or 1 is considered as small cities. Territories id starts with 2 to 6 is considered as other cities. Territories id starts with 7 or 8 is considered as popular cities.


CREATE PROCEDURE spShowTerritoryStatus

AS
SELECT TerritoryID, TerritoryDescription,
CASE
WHEN TerritoryID LIKE '9%'
THEN 'big cities'
WHEN TerritoryID LIKE '[0-1]%'
THEN 'small cities'
WHEN TerritoryID LIKE '[2-6]%'
THEN 'other cities'
WHEN TerritoryID LIKE '[7-8]%'
THEN 'big cities'
END
AS TerritoryStatus
FROM Territories

RETURN


5. Create a stored procedure to find the new price of the first 10 products in Products table. The new price will be calculated based on the amount of percentage inputted into the procedure. The output should show the old and the new prices.


CREATE PROCEDURE spFindNewPrice
@Percentage DECIMAL
AS
SELECT ProductID, ProductName, UnitPrice,
NewUnitPrice = ROUND(( ( (@Percentage/100) +1 ) * UnitPrice ),2)
FROM Products
RETURN

Tuesday, August 11, 2009

Homework - IComparable and IComparer - A step-by-step tutorial

1) Define your class City, as usual.


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

namespace CityCompare
{
public class City
{
//fields
private string name;
private string state;

//properties
public string Name
{
get { return name; }
set { name = value; }
}
public string State
{
get { return state; }
set { state = value; }
}

//constructors
public City() { } //null constructor
public City(string _name, string _state)
{
this.name = _name;
this.state = _state;
}

//override toString method
public override string ToString()
{
return name + ", " + state;
}
}
}


2) We need IComparable to our class to provide for a simple sorting capability
We need to provide a simple sorting capability to the code. We make use of the interface IComparable. To do that, we need to tell the class to implement the interface IComparable. Just add a column (:) and the interface name next to the class name.


public class City : IComparable


3) IComparable Sorting capability - The CompareTo function
Now, we need to implement IComparable CompareTo function to provide the default sort order. We add the following code to our class:


//IComparable.CompareTo needs to be implemented
//to provide default sort order. Make it public
public int CompareTo(Object obj)
{
City c = (City)obj; //cast Object type to City object
return string.Compare(this.name, c.name);
}


4) Writing your tester class with an ArrayList
In this tutorial, I used the Form1 class as the tester class. The tester class will populate the Arraylist with values.
A listbox is made available on the form so that the cities are listed there.
Also, a button that shows "Simple Sort" is available and uses the ArrayList.Sort() method and does not require any additional implementation.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections; //add this line to use ArrayList


namespace CityCompare
{
public partial class Form1 : Form
{
//fields
private ArrayList cities = new ArrayList();

//properties
public ArrayList Cities
{
get { return cities; }
set { cities = value; }
}

//constructors
public Form1()
{
InitializeComponent();
}

//methods
//Populate the listbox
public void PopulateListBox()
{
//clear listbox
lisCitiesList.Items.Clear();

//Populate the listbox
foreach (Object item in cities)
{
lisCitiesList.Items.Add(item.ToString());
}
}

//Populate the ArrayList with cities and states
public void PopulateArrayList()
{
cities.Add(new City("Sydney", "New South Wales"));
cities.Add(new City("Albury", "New South Wales"));
cities.Add(new City("Armindale", "New South Wales"));
cities.Add(new City("Bathurst", "New South Wales"));
cities.Add(new City("Blue Mountains", "New South Wales"));
cities.Add(new City("Palmerston", "Northern Territory"));
cities.Add(new City("Darwin", "Northern Territory"));
cities.Add(new City("Melbourne", "Victoria"));
cities.Add(new City("Perth", "Western Australia"));
cities.Add(new City("Albany", "Western Australia"));
cities.Add(new City("Canning", "Western Australia"));
cities.Add(new City("Gosnells", "Western Australia"));
cities.Add(new City("Hobart", "Tasmania"));
cities.Add(new City("Hobart", "AnotherState"));
}

//events
private void Form1_Load(object sender, EventArgs e)
{
//Populate cities arraylist
PopulateArrayList();

//Populate listbox
PopulateListBox();
}

private void btnNormalSort_Click(object sender, EventArgs e)
{
cities.Sort();
PopulateListBox(); //refresh list
}

}
}


5) Sort list of cities first by state name, then by city name, without modifying the implementation of the City class
As Alan stated, you cannot redefine the CompareTo method. Let's stick to the requirement and define a CityComparer class that implements the Comparator<City> interface.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections; //add this line to use interface IComparer

namespace CityCompare
{ //STEP 2
public class CityComparer: IComparer //we use this IComparer as it gives
//additional comparison mechanisms
{
//we need to implement the interface member Compare(obj,obj)
//from the interface IComparer
public int Compare(Object a, Object b) //make it public
{
City c1 = (City)a; //cast Object to City
City c2 = (City)b; //cast Object to City

return String.Compare(c1.State, c2.State); //State is a string,
//hence we use String.Compare
}

//StateSort method
//sorts the ArrayList elements by state
public static IComparer StateSort()
{
return (IComparer)new CityComparer();
}
}
}


6) Call the method StateSort to sort by state in the Form1 class.


private void btnCityComparer_Click(object sender, EventArgs e)
{
cities.Sort(CityComparer.StateSort()); //STEP 3
PopulateListBox(); //refresh list
}

All done! Suggestions and comments are welcome.

Wednesday, July 22, 2009

Understanding the concept of 1 to 1 relationship, and applying it to C#

Given the constraint that one object (Player) cannot exist without another object (Play Game), a one-to-one relationship representation in C# would mean that only one game per player, and without any game, we cannot have any player (makes perfect sense).

Tutorial to set up the One-to-One relationship
1) Set up the one-to-one relationship
Create your two independent forms (Form1 and Form2 by default) by adding them to your project in Visual Studio.
Now, you need to create a dependency between those two forms. I am using forms Game (Form1) and Player (Form2).

In Player (Form2) form where you would usually declare your fields,


//fields
//create the dependency to Game Form
private Game myGameForm;


Apply the same logic to the Form1 class, or the Game class.


//fields
//create the dependency to Play Form
private Play myPlayForm;


2) Create the dependency that Form2 cannot exist without Form1.

We want the Play object to exist only if we have a Game.


//fields
//create the dependency to Play Form
private Play myPlayForm;

public Game()
{
myPlayForm = new Play(this);//create a Play form if the game exists
InitializeComponent();
}



Obviously, we cannot have a player if we do not have the game. To enforce this constraint, we make use of the constructor for the Form2, so that Form2 (or Game), will only be created if a Form1 object (Game) is not passed as an argument to the constructor.


//fields
//create the dependency to Game Form
private Game myGameForm;

public Play(Game gameform)
{
InitializeComponent();
myGameForm = gameform;//assign the object myGameForm to the argument gameform
}


So what did we exactly do? We said that if a Game exists, then the player also exists.

3) Show the second Form2 (Player) when the button on Form1 (Game) is clicked.


private void btnPlay_Click(object sender, EventArgs e)
{
myPlayForm.Show();
}


Run your code. On clicking the button from Form1 (Game), you will see the new form Player appear. You're on the right track. That's all we need to know to assign 1-to-1 dependency with constraints!

End of Tutorial


This was the first part of the question. The rest is very easy and will require the use of Random. I've included the full code of the application below.

The Game Class


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace OneToOne
{
public partial class Game : Form
{
//fields
//create the dependency to Play Form
private Play myPlayForm;

//constructor
public Game()
{
myPlayForm = new Play(this);//create a Play form if the game exists
InitializeComponent();
}

//events
private void btnPlay_Click(object sender, EventArgs e)
{
myPlayForm.Show();
}

//methods
public void showValue(int maxval)
{
lblMax.Text = "Max Number is " + maxval.ToString()+ ".\n\nRestart game to play again";
}
}
}


The Play Class


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace OneToOne
{
public partial class Play : Form
{
//fields
//create the dependency to Game Form
private Game myGameForm;
private int myNum = 0;
private int iCounter = 0;

//properties
public int MyNum
{
get { return myNum; }
set { myNum = value; }
}

public int ICounter
{
get { return iCounter; }
set { iCounter = value; }
}

//constructor
public Play(Game gameform)
{
InitializeComponent();
myGameForm = gameform; //assign the object myGameForm to the argument gameform
}

//events
private void btnClick_Click(object sender, EventArgs e)
{
showValue();
}

//methods
public void showValue()
{
Random myRan = new Random(); //create a myRan variable of type Random (Class)
int iRan = myRan.Next(100); //gets a random number from 0 - 100
iCounter++;

if (iCounter <= 3) //can click only 3 times
{
lblNum.Text = iRan.ToString(); //display random value on form
if (iRan >= myNum)
{
myNum = iRan;
}
}
else
{
MessageBox.Show("Cannot click more than 3 times. Turn has ended");
//prevent user from clicking more than 3 times
btnClick.Enabled = false;

//send the max value to Form1 or GameForm
myGameForm.showValue(myNum);
//hide this form
this.Hide();

//show the previous form
myGameForm.Show();

}
}
}
}


I hope that helps!

Sunday, May 24, 2009

Shanti C# - Card Class - Homework Part 1

The Card class question, as a continuation from Misa's previous post (well, it's more like the prequel, cos this is part 1 :) ).

namespace SimpleCard
{
public class SimpleCard
{
//fields
private int cardValue; //instance variable

public const int ACE = 1;
public const int TWO = 2;
public const int THREE = 3;
public const int FOUR = 4;
public const int FIVE = 5;
public const int SIX = 6;
public const int SEVEN = 7;
public const int EIGHT = 8;
public const int NINE = 9;
public const int TEN = 10;
public const int JACK = 11;
public const int QUEEN = 12;
public const int KING = 13;

public static int CardInASet = 13;

//properties
//cardValue
public int CardValue
{
get { return cardValue; }
set { cardValue = value; }
}

//constructors
public SimpleCard() //null constructor
{
cardValue = 1;
}

public SimpleCard(int _cardValue)
{
cardValue = _cardValue;
}

public SimpleCard(string _cardValueName)
{
switch (_cardValueName)
{
case "ACE":
cardValue = 1;
break;
case "TWO":
cardValue = 2;
break;
case "THREE":
cardValue = 3;
break;
case "FOUR":
cardValue = 4;
break;
case "FIVE":
cardValue = 5;
break;
case "SIX":
cardValue = 6;
break;
case "SEVEN":
cardValue = 7;
break;
case "EIGHT":
cardValue = 8;
break;
case "NINE":
cardValue = 9;
break;
case "TEN":
cardValue = 10;
break;
case "JACK":
cardValue = 11;
break;
case "QUEEN":
cardValue = 12;
break;
case "KING":
cardValue = 13;
break;
}
}

//methods
//instance method
public string getCardName()
{
string cardName = "";
switch (cardValue)
{
case 1:
cardName = "ACE";
break;
case 2:
cardName = "TWO";
break;
case 3:
cardName = "THREE";
break;
case 4:
cardName = "FOUR";
break;
case 5:
cardName = "FIVE";
break;
case 6:
cardName = "SIX";
break;
case 7:
cardName = "SEVEN";
break;
case 8:
cardName = "EIGHT";
break;
case 9:
cardName = "NINE";
break;
case 10:
cardName = "TEN";
break;
case 11:
cardName = "JACK";
break;
case 12:
cardName = "QUEEN";
break;
case 13:
cardName = "KING";
break;
}//end switch

return cardName;
}

public string getInfo()
{
string cardInfo = "";
switch (cardValue)
{
case 1:
cardInfo = "ACE " + cardValue.ToString();
break;
case 2:
cardInfo = "TWO " + cardValue.ToString();
break;
case 3:
cardInfo = "THREE " + cardValue.ToString();
break;
case 4:
cardInfo = "FOUR " + cardValue.ToString();
break;
case 5:
cardInfo = "FIVE " + cardValue.ToString();
break;
case 6:
cardInfo = "SIX " + cardValue.ToString();
break;
case 7:
cardInfo = "SEVEN " + cardValue.ToString();
break;
case 8:
cardInfo = "EIGHT " + cardValue.ToString();
break;
case 9:
cardInfo = "NINE " + cardValue.ToString();
break;
case 10:
cardInfo = "TEN " + cardValue.ToString();
break;
case 11:
cardInfo = "JACK " + cardValue.ToString();
break;
case 12:
cardInfo = "QUEEN " + cardValue.ToString();
break;
case 13:
cardInfo = "KING " + cardValue.ToString();
break;
}//end switch

return cardInfo;
}
}
}


This part is the form implementation:
namespace SimpleCard
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
if (txtCard.Text != "")
{
try //for integer
{
int iCardVal = int.Parse(txtCard.Text.ToString().Trim());

if (iCardVal > 0 && iCardVal <= 13)
{
SimpleCard myCard = new SimpleCard(iCardVal);
MessageBox.Show("Card is " + myCard.getInfo());
}
else
MessageBox.Show("Card does not exist");

}
catch //for string
{
string myCardName = txtCard.Text.ToString().Trim().ToUpper();
SimpleCard myCard = new SimpleCard(myCardName);
MessageBox.Show("Card is " + myCard.getInfo());
}

}
else
{
MessageBox.Show("Enter a value");
txtCard.Focus();
}
}

private void btnDisplayAllCards_Click(object sender, EventArgs e)
{
string myCardNames = "";
for (int i = 1; i <= 13; i++)
{
SimpleCard card = new SimpleCard(i);
myCardNames += " " + card.getCardName();
}
MessageBox.Show(myCardNames);

}
}
}

Monday, May 11, 2009

Shanti C# Homework - Time Class

For all those students who didn't attend class today :)


OOP – Creating a Class Exercise 2
Create the following class and its fields, properties, constructors, and methods. The Time class is used to
represent duration of time in hours, minutes, and seconds.
STEP 1: Create the Time class
STEP 2: Define the fields
STEP 3: Define the properties
STEP 4: Define the constructors (null and with arguments)
STEP 5: Time class should have at least the following methods:
A method to show the information in the following format: hh:mm:ss
A method to add seconds into the Time. For example: 01:02:03 plus 12 seconds is equal to
01:02:15.
A method to find the sum of two Time values. For example: 01:02:03 plus 11:22:33 is equal to
12:24:36.
A method to check if two Time values are equal. For example: 01:02:03 and 01:02:03 are equal.
STEP 6: Create the user interface (form) where a user can input the hours, minutes, and
seconds, display the information in presentable format (hh:mm:ss), find the sum of two
Time values, add seconds into the Time, and compare two Time values.

STEP 7: Consider the following scenario and modify the specification of Time class if
necessary:
Can the hours, minutes, and seconds be negative values?
Are there maximum and minimum values for hours, minutes, and seconds?
How many different ways are there to create a Time object? Can the Time object be
created by specifying only the hours and/or the minutes?
What happens when you add some seconds into a Time value and the seconds part
of the Time value exceeds 59 seconds? For example: Should the result of this
operation (01:00:59 plus 2 seconds) be 01:00:61 or 01:01:01?
What happens when you add two Time values and the minutes and seconds part of
the Time value exceeds 59? For example: Should the result of this operation
(01:50:50 plus 02:20:30) be 03:70:80 or 04:11:20?

Sunday, May 10, 2009

Shanti C# - Rectangle and Point Class - Complete

Rectangle Class



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

namespace RectangleClass
{
public class Rectangle
{
//fields
private int length = 0;
private int width = 0;
private Point corner = new Point(0,0);

//properties
public int Length
{
get { return length; }
set { length=value; }
}
public int Width
{
get { return width; }
set { width = value; }
}
public Point Corner
{
get { return corner; }
set { corner = value; }
}

//constructors
public Rectangle()
{
}
public Rectangle(int _length, int _width, Point _corner)
{
length = _length;
width = _width;
corner = _corner;
}

//methods
public int getArea()
{
return length * width;
}

public int getPerimeter()
{
return (length + width) * 2;
}

public void increaseLength(int _lengthIncrease)
{
length = length + _lengthIncrease;
}

public void increaseWidth(int _widthIncrease)
{
width = width + _widthIncrease;
}

public string getCenter()
{
corner.setPoint(length / 2, width / 2);
return corner.ToString();
}

public string getTopRight()
{
corner.setPoint(length, 0);
return corner.ToString();
}

public string getBottomLeft()
{
corner.setPoint(0, width);
return corner.ToString();
}

public string getBottomRight()
{
corner.setPoint(length, width);
return corner.ToString();
}

public string getAllPoints()
{
string sAllPoints = "";
sAllPoints = "Center = " + getCenter() + "\n" +
"Top Right = " + getTopRight() + "\n" +
"Bottom Left = " + getBottomLeft() + "\n" +
"Bottom Right = " + getBottomRight();

return sAllPoints;

}
}
}


Point Class (Used to override the ToString() function) - optional



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

namespace RectangleClass
{
public class Point
{
//fields
private int x, y;

// Default constructor:
public Point()
{
x = 0;
y = 0;
}

// A constructor with two arguments:
public Point(int x, int y)
{
this.x = x;
this.y = y;
}

// Override the ToString method:
public override string ToString()
{
return (String.Format("({0},{1})", x, y));
}

public void setPoint(int _x, int _y)
{
this.x = _x;
this.y = _y;
}
}

}





Form Coding



Rectangle myRec1 = new Rectangle(0, 0, new Point());

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

}

private void btnGetLength_Click(object sender, EventArgs e)
{
CheckFields();
MessageBox.Show("Length is " + myRec1.Length);
}

private void btnGetWidth_Click(object sender, EventArgs e)
{
CheckFields();
MessageBox.Show("Width is " + myRec1.Width);
}

private void btnArea_Click(object sender, EventArgs e)
{
CheckFields();
MessageBox.Show("Area is " + myRec1.getArea());
}

private void btnPerimeter_Click(object sender, EventArgs e)
{
CheckFields();
MessageBox.Show("Area is " + myRec1.getPerimeter());
}

private void CheckFields()
{
myRec1.Length = 0;
myRec1.Width = 0;

if (txtLengthInc.Text != "")
myRec1.increaseLength(int.Parse(txtLengthInc.Text));
if (txtWidthInc.Text != "")
myRec1.increaseWidth(int.Parse(txtWidthInc.Text));

if (txtLength.Text != "")
myRec1.Length = myRec1.Length + int.Parse(txtLength.Text);
if (txtWidth.Text != "")
myRec1.Width = myRec1.Width + int.Parse(txtWidth.Text);

}

private void btnCenter_Click(object sender, EventArgs e)
{
CheckFields();

MessageBox.Show ("Center : " + myRec1.getCenter());
}

private void btnTopRight_Click(object sender, EventArgs e)
{
CheckFields();

MessageBox.Show("Top Right : " + myRec1.getTopRight());
}

private void btnBottomLeft_Click(object sender, EventArgs e)
{
CheckFields();

MessageBox.Show("Bottom Left : " + myRec1.getBottomLeft ());
}

private void btnButtonRight_Click(object sender, EventArgs e)
{
CheckFields();

MessageBox.Show("Bottom Right : " + myRec1.getBottomRight());
}

private void btnAllPoints_Click(object sender, EventArgs e)
{
CheckFields();

MessageBox.Show(myRec1.getAllPoints());
}

Wednesday, April 29, 2009

Stick Figure Storyboard with Javascript

Assume that all pictures are in the same folder with the HTML page...





<!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>
<title>Story Board</title>
<script type="text/javascript">

var scene = 0;

function changeImg(num)
{

if (scene==0)
{
alert("Your journey begins at a fork in the road.");
scene=1;
}
else if (scene==1)
{
if(num==1)
{
alert("You have arrived at a cute little house in the woods.");
scene=2;
}
else if (num ==2)
{
alert("You are standing on the bridge overlooking a peaceful stream.");
scene=3;
}
}
else if (scene==2)
{
if(num==1)
{
alert("Peeking through the window, you see a witch inside the house.");
scene=4;
}
else if (num ==2)
{
alert("Sorry, a witch lives in the house and you just became part of her stew.");
scene=5;
}
}
else if (scene==4)
{
if(num==1)
{
scene=8;
}
else if (num ==2)
{
alert("Sorry, a witch lives in the house and you just became part of her stew.");
scene=5;
}
}
else if (scene==5)
{
scene=0;

}
else if (scene==3)
{
if(num==1)
{
alert("Sorry, a troll lives on the other side of the bridge and you just became his lunch.");
scene=6;
}
else if (num ==2)
{
alert("Your stare is interrupted by the arrival of a huge troll.");
scene=7;
}
}
else if (scene==6)
{
scene=0;
}
else if (scene==7)
{
if(num==1)
{
alert("Sorry, a troll lives on the other side of the bridge and you just became his lunch.");
scene=6;
}
else if (num ==2)
{
scene=9;
}
}
document.getElementById("img").src ="scene"+scene+".png";

}
</script>
</head>
<body>
<div style="margin: 0 auto; text-align:center">
<img src="scene0.png" alt="Choose your path" id="img"/>
<br />
<input type="button" id="decision1" value="1" onclick="changeImg(1)" />
<input type="button" id="decision2" value="2" onclick="changeImg(2)" />
</div>
</body>
</html>

Monday, April 27, 2009

Phonebook for Shanti - 27/04

I made use of 3 forms for this question.

FORM 1:
The first form contains all the buttons for the Phonebook application.




The code for FORM 1 is as follows:



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PhoneProgram
{
public partial class frmAddressBook : Form
{
public static int iCount = 0;
public static string[,] sName = { { "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" } };
public static string sFriendModify = "";

frmAddForm addForm = new frmAddForm();
Prompt promptForm = new Prompt();

public frmAddressBook()
{
InitializeComponent();
}

private void btnAdd_Click(object sender, EventArgs e)
{
addForm.ShowDialog();

cmbName.Items.Clear();
//add new items
for (int i = 0; i < 10; i++)
{
if ((sName[i, 0] != "") || (sName[i, 0] != null))
{
//cmbName.Items.Add(sName[i,0]);
cmbName.Items.Add(sName[i, 0].ToString());
}
}
}

private void btnFind_Click(object sender, EventArgs e)
{
if (cmbName.Text != "")
{
for (int i = 0; i < 10; i++)
{
if (sName[i, 0] == cmbName.Text)
{
MessageBox.Show(sName[i, 0].ToString() + " has phone number " + sName[i, 1].ToString(), sName[i, 0].ToString() + " Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

return;
}
}

//reached end of array for search
{
MessageBox.Show(cmbName.Text.ToString() + " was not found. ", cmbName.Text.ToString() + " Not Found", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

}
else
{
MessageBox.Show("No friend selected", "Select a Friend to find", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

private void btnCount_Click(object sender, EventArgs e)
{
int iFriends = 0;
for (int i = 0; i < 10; i++)
{
if (sName[i, 0] != "")//empty
{
++iFriends;
}
}

MessageBox.Show("You have " + iFriends + " friends in your Address Book.", iFriends.ToString() + " Friends Found", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

private void btnModify_Click(object sender, EventArgs e)
{
if (cmbName.Text == "")
{
MessageBox.Show("No friend selected", "No friend selected to modify", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
//modify
sFriendModify = cmbName.Text;
promptForm.ShowDialog();
}
}

private void btnDelete_Click(object sender, EventArgs e)
{
if (cmbName.Text == "")
{
MessageBox.Show("No friend selected", "No friend selected to modify", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
for (int i = 0; i < 10; i++)
{
if (cmbName.Text == sName[i, 0])
{
cmbName.Items.Remove(sName[i, 0].ToString());
//perform delete
sName[i, 0] = "";
sName[i, 1] = "";
MessageBox.Show("Contact Details deleted", "Contact Details deleted", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;

}
}
}
}
}
}




FORM 2:
The second form will enable the user to enter name and phone number in the Phonebook.



Code is as follows:




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PhoneProgram
{
public partial class frmAddForm : Form
{
public frmAddForm()
{
InitializeComponent();
}

private void btnCancel_Click(object sender, EventArgs e)
{
frmAddForm.ActiveForm.Close();
}

private void btnConfirm_Click(object sender, EventArgs e)
{
if (fnValidate() == 0)
{
for (int i = 0; i < 10; i++)
{
if ((frmAddressBook.sName[i, 0] == "") || (frmAddressBook.sName[i, 0] == null)) //empty element
{
frmAddressBook.sName[i, 0] = txtName.Text.Trim();
frmAddressBook.sName[i, 1] = txtPhone.Text.Trim();

txtName.Text = "";
txtPhone.Text = "";
MessageBox.Show("Friend added", "AddressBook Updated", MessageBoxButtons.OK, MessageBoxIcon.Information);

//update combobox


return;
}
}

/* Array Full */
MessageBox.Show("Address Book is Full", "Address Book Full", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

/***********************Function Lists *************************/
private int fnValidate()
{
if (txtName.Text == "")
{
MessageBox.Show("Enter a Name", "Name missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtName.Focus();
return -1;
}


if (txtPhone.Text != "")
{
try
{
int iPhoneNum = int.Parse(txtPhone.Text);
if ((txtPhone.Text.Length > 10) || (txtPhone.Text.Length < 8))
{
MessageBox.Show("Phone Number is not valid", "Invalid Phone Number", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtPhone.SelectAll();
return -1;
}
}
catch
{
MessageBox.Show("Phone Number is not valid", "Invalid Phone Number", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtPhone.SelectAll();
return -1;
}

return 0; //success
}
else
{
MessageBox.Show("Enter a Phone Number", "Enter Phone Number", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtPhone.Focus();
return -1;
}

}
}
}


FORM 3:
The third and last form enables the user to enter a phone number for the purpose of modifying an existing contact's phone number.





Code is as follows:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PhoneProgram
{
public partial class Prompt : Form
{
public Prompt()
{
InitializeComponent();
}

private void btnModify_Click(object sender, EventArgs e)
{
if (txtPhoneNum.Text != "")
{
try
{
int iPhoneNum = int.Parse(txtPhoneNum.Text);
if ((txtPhoneNum.Text.Length > 10) || (txtPhoneNum.Text.Length < 8))
{
MessageBox.Show("Phone Number is not valid", "Invalid Phone Number", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtPhoneNum.SelectAll();
return;
}
}
catch
{
MessageBox.Show("Phone Number is not valid", "Invalid Phone Number", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtPhoneNum.SelectAll();
return;
}

//modify phone number

for (int i = 0; i < 10 ; i++)
{
if (frmAddressBook.sName[i, 0] == frmAddressBook.sFriendModify)
{

frmAddressBook.sName[i, 1] = txtPhoneNum.ToString().Trim();

MessageBox.Show(frmAddressBook.sName[i, 0].ToString() + ", Phone Number is updated to " + txtPhoneNum.Text.ToString(), "Phone Number Updated", MessageBoxButtons.OK, MessageBoxIcon.Information);
Prompt.ActiveForm.Close();
}
}

}
else
{
MessageBox.Show("Enter a Phone Number", "Enter Phone Number", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtPhoneNum.Focus();
return;
}
}

private void btnCancel_Click(object sender, EventArgs e)
{
Prompt.ActiveForm.Close();
}

private void Prompt_Load(object sender, EventArgs e)
{
lblFriendName.Text = frmAddressBook.sFriendModify.ToString();
}
}
}

Saturday, April 18, 2009

Amit's NPV, Payback, ROI

NPV/Payback table as follows (Click to Enlarge) :



We can deduce that the payback period is 4 years.



ROI table as follows (Click to Enlarge) :



I am not too sure what is the difference between ROI Total and ROI Annual. Anybody knows?
I know for a fact that ROI is just a percentage...

Shanti Javascript Holiday Homework

Howdie!

The javascript output is as follows:

0
10
10
0
-5
3
0
NaN
value=54
9=value
0.5
2
0.5
Infinity
-Infinity
NaN
5
NaN
one=2 two=2
one=2 two=1
false
false
false
false
true
true
false
true
true
true
true
false
true
true
false
false
false
true
false
false
null
null
false
0
0
false
0


undefined
undefined
true
false
1
undefined





The HTML code can be found below:


<html>
<head>
</head>

<body>
<pre>
<script type="text/javascript">
document.writeln("1" * "0");
document.writeln("1" + 0);
document.writeln(1 + "0");
document.writeln("1"* "0");
document.writeln(- - -5);
document.writeln(true ? 3 : false ? 5 : 0);
document.writeln("1" * false);
document.writeln("1" * "false");
document.writeln("value=" + 5 + 4);
document.writeln(5 + 4 + "=value");
document.writeln(2/4);
document.writeln(4.0/2.0);
document.writeln(2.0/4);
document.writeln(5/0);
document.writeln(-5/0);
document.writeln(0/0);
document.writeln(+ "5");
document.writeln(+ "a");
var one=1; var two=++one; document.writeln("one=" + one + " two=" + two);
var one=1; var two=one++; document.writeln("one=" + one + " two=" + two);
document.writeln(5==="5");
document.writeln("hello" === "HELLO");
document.writeln(NaN === 5);
document.writeln(NaN === NaN);
document.writeln(null===null);
document.writeln(undefined===undefined);
document.writeln(null===undefined);
document.writeln(null==undefined);
document.writeln("1" == true);
document.writeln("1" ==1);
document.writeln(1==true);
document.writeln("Z" < "A");
document.writeln("Z" < "a");
document.writeln("Zelda" < "Zoo");
document.writeln("zelda" < "Zoo");
document.writeln(true < 1);
document.writeln(1 < "true");
document.writeln("11" < "3");
document.writeln("11" < 3);
document.writeln("one" <3);
document.writeln(null && true);
document.writeln(null && false);
document.writeln(false && null);
document.writeln(0 && true);
document.writeln(0 && false);
document.writeln(false && 0);
document.writeln(true && 0);
document.writeln("" && true);
document.writeln("" && false);
document.writeln(undefined && true);
document.writeln(undefined && false);
document.writeln(!!5);
document.writeln(!!null);
document.writeln(null ? 0 : 1);
document.writeln(void (1+2));
</script>
</pre>

</body>

</html>

Monday, April 6, 2009

Pizza Hot!

Free publicity to the pizza house :)




Some interesting things I found while doing this:

1) Scroll bar required when the order list is too long
2) Window should resize on Adding a pizza to the order

Everything is in the code. It might be confusing so let me know if you need some help on that.

PS: I am using some methods/functions. They work like events, so I don't think you'll struggle with understanding that :)





using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int[] iPostCode = { 2000, 2002, 2312, 2492, 2121, 2765};
string[] sSuburb = { "City", "Chippendale", "Rose Hill", "Balmain", "Edgecliff", "Bondi" };
int[] iPizzaQuantity = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int iOrder = 0;
string sPizzaOrdered= "";
double dPizzaPrice = 0.0;
double dTotalAmount = 0.0;
string sPizzaExtras = "";

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
fnClearForm();
fnLoadDefaultValues();
}


/* Update Suburb on PostCode change */
private void cmbPostCode_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < iPostCode.Length; i++)
{
if (iPostCode[i].ToString() == cmbPostCode.Text)
{
txtSuburb.Text = sSuburb[i];
}
}
}

private void btnAddPizza_Click(object sender, EventArgs e)
{

if (fnValidateAllFields() == 0)
{
fnResizeMax();

string sOrder = "Order #" + lblOrder.Text + " Date: " + lblDate.Text +
"\n\nClient Name: " + txtFName.Text + " " + txtLName.Text ;

double dPizzaCost = fnCountPizzaCost();

dTotalAmount += dPizzaCost;

string sDetails = cmbQuantity.Text.ToString() + " - " + sPizzaOrdered + " - $" + dPizzaCost;
sDetails += "\n" + sPizzaExtras;

lblPizzaSummary.Text +="\n\n" + sDetails;
lblResult.Text = sOrder;
sPizzaExtras = ""; //reset the pizza toppings and extra
lblSubTotal.Text = dTotalAmount.ToString("F2");
lblTax.Text = (dTotalAmount * 0.13).ToString("F2");
lblGrandTotal.Text = (dTotalAmount * 1.13).ToString("F2");

}

}


private void radLarge_CheckedChanged(object sender, EventArgs e)
{
sPizzaOrdered = "Large";
dPizzaPrice = 25;
}

private void radRegular_CheckedChanged(object sender, EventArgs e)
{
sPizzaOrdered = "Regular";
dPizzaPrice = 18;
}

private void radSmall_CheckedChanged(object sender, EventArgs e)
{
sPizzaOrdered = "Small";
dPizzaPrice = 15;
}

private void radPersonal_CheckedChanged(object sender, EventArgs e)
{
sPizzaOrdered = "Personal";
dPizzaPrice = 11;
}

private void btnExit_Click(object sender, EventArgs e)
{
Close();
}

private void btnClear_Click(object sender, EventArgs e)
{
fnClearForm();
fnLoadDefaultValues();
fnResizeMin();
}


private void radVisa_Click(object sender, EventArgs e)
{
MessageBox.Show("Request to see ID and Visa Card", "Visa Verification", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtCC.Enabled = true;
txtCVC.Enabled = true;
dtpExpDate.Enabled = true;
txtCC.BackColor = Color.White;
txtCVC.BackColor = Color.White;
dtpExpDate.BackColor = Color.White;
}

private void radMasterCard_Click(object sender, EventArgs e)
{
MessageBox.Show("Request to see ID and MasterCard", "Mastercard Verification", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtCC.Enabled = true;
txtCVC.Enabled = true;
dtpExpDate.Enabled = true;
txtCC.BackColor = Color.White;
txtCVC.BackColor = Color.White;
dtpExpDate.BackColor = Color.White;
}

private void radDebit_Click(object sender, EventArgs e)
{
MessageBox.Show("Customer may swipe card now", "Debit", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtCC.Enabled = false;
txtCVC.Enabled = false;
dtpExpDate.Enabled = false;
txtCC.BackColor = Color.Black;
txtCVC.BackColor = Color.Black;
dtpExpDate.BackColor = Color.Black;
}

private void radCheque_Click(object sender, EventArgs e)
{
MessageBox.Show("-Please request ID\n-Verify address on Cheque\n-Write LIC # on Cheque\n-Write Phone Number on Cheque", "Cheque Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtCC.Enabled = false;
txtCVC.Enabled = false;
dtpExpDate.Enabled = false;
txtCC.BackColor = Color.Black;
txtCVC.BackColor = Color.Black;
dtpExpDate.BackColor = Color.Black;
}

private void radCash_Click(object sender, EventArgs e)
{
txtCC.Enabled = false;
txtCVC.Enabled = false;
dtpExpDate.Enabled = false;
txtCC.BackColor = Color.Black;
txtCVC.BackColor = Color.Black;
dtpExpDate.BackColor = Color.Black;
}



/******************************* FUNCTIONS LIST ***************************/
private void fnClearForm()
{
txtFName.Clear();
txtLName.Clear();
txtApt.Clear();
txtPhone.Clear();
txtStreet.Clear();
txtSuburb.Clear();
lblDate.Text = "";

chkAnchovies.Checked = false;
chkOnion.Checked = false;
chkPepperoni.Checked = false;
chkSausage.Checked = false;

radCheeseNo.Checked = false;
radCheeseYes.Checked = false;
radLarge.Checked = false;
radPersonal.Checked = false;
radRegular.Checked = false;
radSmall.Checked = false;

cmbQuantity.Items.Clear();
cmbPostCode.Items.Clear();

lblResult.Text = "";
lblPizzaSummary.Text = "";
sPizzaExtras = "";

lblSubTotal.Text = "";
lblTax.Text = "";
lblGrandTotal.Text = "";

dTotalAmount = 0;

txtCC.Enabled = false;
txtCVC.Enabled = false;
dtpExpDate.Enabled = false;
txtCC.BackColor = Color.Black;
txtCVC.BackColor = Color.Black;
dtpExpDate.BackColor = Color.Black;
}


private void fnLoadDefaultValues()
{
lblDate.Text = DateTime.Now.ToString();
lblOrder.Text = (++iOrder).ToString();

radCheeseNo.Checked = true;
radCash.Checked = true;

/* Load Combo values for PostCode */

for (int i = 0; i < iPostCode.Length; i++)
{
cmbPostCode.Items.Add(iPostCode[i]);
}

for (int i = 0; i < iPizzaQuantity.Length; i++)
{
cmbQuantity.Items.Add(iPizzaQuantity[i]);
}
}


private int fnValidateAllFields()
{
if (txtFName.Text == "")
{
MessageBox.Show("Enter first name", "Field Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtFName.Focus();
return -1;
}
if (txtLName.Text == "")
{
MessageBox.Show("Enter last name", "Field Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtLName.Focus();
return -1;
}
if (txtApt.Text == "")
{
MessageBox.Show("Enter appartment number", "Field Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtApt.Focus();
return -1;
}
if (txtStreet.Text == "")
{
MessageBox.Show("Enter street address", "Field Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtStreet.Focus();
return -1;
}

if (txtPhone.Text == "")
{
MessageBox.Show("Enter phone number", "Field Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtPhone.Focus();
return -1;
}

if (txtSuburb.Text == "")
{
MessageBox.Show("Enter suburb", "Field Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtSuburb.Focus();
return -1;
}

if (cmbPostCode.Text == "")
{
MessageBox.Show("Enter Postcode", "Field Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
cmbPostCode.Focus();
return -1;
}

if (cmbQuantity.Text == "")
{
MessageBox.Show("Enter Quantity", "Field Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
cmbQuantity.Focus();
return -1;
}

if ((chkAnchovies.Checked == false) && (chkOnion.Checked == false) && (chkPepperoni.Checked == false) && (chkSausage.Checked == false))
{
MessageBox.Show("Choose at least 1 topping", "Field Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
chkSausage.Focus();
return -1;
}

return 0; //success
}


private void btnPlaceOrder_Click(object sender, EventArgs e)
{
if (fnValidateAllFields() == -1)
MessageBox.Show("Please click Add Pizza before placing Order", "Order Rejected", MessageBoxButtons.OK, MessageBoxIcon.Warning);
else
MessageBox.Show("Order has been placed", "Order Confirmed", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

private double fnCountPizzaCost()
{
double dPizzaOnlyPrice = int.Parse(cmbQuantity.Text) * dPizzaPrice;

if (chkAnchovies.Checked == true)
{
dPizzaOnlyPrice += 0.75;
sPizzaExtras += "Anchovies\n";
}

if (chkSausage.Checked == true)
{
dPizzaOnlyPrice += 0.75;
sPizzaExtras += "Sausage\n";
}
if (chkPepperoni.Checked == true)
{
dPizzaOnlyPrice += 0.75;
sPizzaExtras += "Pepperoni\n";
}
if (chkOnion.Checked == true)
{
dPizzaOnlyPrice += 0.75;
sPizzaExtras += "Onion\n";
}
if (radCheeseYes.Checked == true)
{
dPizzaOnlyPrice += 0.50;
sPizzaExtras += "Extra Cheese\n";
}

return dPizzaOnlyPrice;

}


private void fnResizeMax()
{
Form1.ActiveForm.Size = new Size(700, 762);
}


private void fnResizeMin()
{
Form1.ActiveForm.Size = new Size(399, 762);
}
}
}