Showing posts with label Classwork. Show all posts
Showing posts with label Classwork. Show all posts

Friday, August 28, 2009

WHILE LOOP Stored Procedure - Class example

Add 5 new customers and date


ALTER PROCEDURE spAddCustomerIDtoOrdersFiveTimes
@CustID NCHAR(5)
AS
DECLARE @counter INT
SET @counter = 0

WHILE @counter < 5
BEGIN
INSERT INTO Orders (CustomerID, OrderDate)
VALUES (@CustID, DATEADD(day,@counter,GETDATE()))

SET @counter = @counter +1
END

RETURN


Calculate to new salary average


ALTER PROCEDURE spIncreaseSalUntilTargetReached
@target money
AS
DECLARE @avg MONEY
DECLARE @count INT

SET @count = 0
SELECT @avg = AVG(SAL) FROM EMP

WHILE @avg < @target
BEGIN
UPDATE EMP
SET SAL = SAL + 50

SELECT @avg = AVG(SAL) FROM EMP
SET @count = @count + 1
END

PRINT 'No of records updated: ' + CAST(@count AS VARCHAR(20))
PRINT 'Calculated AVG: ' + CAST(@avg AS VARCHAR(20))

RETURN

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, July 28, 2009

Demonstrating Inheritance in C# - The Animal Class

The Animal class:


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

namespace InheritanceAnimals
{
public class Animal
{
//fields
private bool legs;
private bool wings;

//properties
public bool Legs
{
get { return legs; }
set { legs = value; }
}
public bool Wings
{
get { return wings; }
set { wings = value; }
}

//constructors

public Animal(bool _legs, bool _wings)
{
this.legs = _legs;
this.wings = _wings;
}

//methods
public virtual string eat()
{
return " unknown";
}

public virtual string hair()
{
return " unknown";
}

public virtual string sound()
{
return " unknown";
}

public virtual string movement()
{
return " unknown";
}

}
}


The Bat class:


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

namespace InheritanceAnimals
{
public class Bat : Animal
{
//fields

//properties

//constructors
public Bat():base(true,true)
{
}


public override string eat()
{
return "fruit and insects";
}

public override string hair()
{
return "feathers";
}


public override string movement()
{
return "unknown";
}

public override string sound()
{
return "unknown";
}

public string take_off()
{
return "launches from the tree";
}

public string land()
{
return "hangs on a rafter";
}


}
}


The Hawk class:


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

namespace InheritanceAnimals
{
public class Hawk : Animal
{
//fields

//properties

//constructors
public Hawk():base(true,true)
{

}

public override string eat()
{
return "small animals";
}

public override string hair()
{
return "feathers";
}

public override string sound()
{
return "Screeches";
}

public override string movement()
{
return "unknown";
}

public string take_off()
{
return "glides";
}

public string land()
{
return "perches on a tree top";
}


}
}


The Monkey class:


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

namespace InheritanceAnimals
{
public class Monkey : Animal
{
//fields

//properties

//constructors
public Monkey() : base(true, false)
{

}

public override string eat()
{
return "fruit";
}

public override string hair()
{
return "fur";
}

public override string sound()
{
return "Chatters";
}

public override string movement()
{
return "jumps";
}
}
}


The Snake class:


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

namespace InheritanceAnimals
{
public class Snake : Animal
{
//fields

//properties

//constructors
public Snake(): base(false,false)
{
}

public override string eat()
{
return "rats";
}

public override string hair()
{
return "none";
}

public override string sound()
{
return "Hisses";
}

public override string movement()
{
return "slithers";
}

}
}


And finally, the GUI form sourcecode:


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 InheritanceAnimals
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnShow_Click(object sender, EventArgs e)
{
Snake snake = new Snake();
Monkey monkey = new Monkey();
Bat bat = new Bat();
Hawk hawk = new Hawk();

string myresults = "";

myresults = "Snake (" + snake.Legs + " " + snake.Wings + ") eats " + snake.eat() + ", hair = " + snake.hair() + ", sound = " + snake.sound() + ", moves = " + snake.movement() +"\n\n";
myresults += "Monkey (" + monkey.Legs + " " + monkey.Wings + ") eats " + monkey.eat() + ", hair = " + monkey.hair() + ", sound = " + monkey.sound() + ", moves = " + monkey.movement() + "\n\n";
myresults += "Bat (" + bat.Legs + " " + bat.Wings + ") eats " + bat.eat() + ", hair = " + bat.hair() + ", sound = " + bat.sound() + ", moves = " + bat.movement() + ", takes off = " + bat.take_off() + ", lands = " + bat.land() + "\n\n";
myresults += "Hawk (" + hawk.Legs + " " + hawk.Wings + ") eats " + hawk.eat() + ", hair = " + hawk.hair() + ", sound = " + hawk.sound() + ", moves = " + hawk.movement() + ", takes off = " + hawk.take_off() + ", lands = " + hawk.land() + "\n\n";
lblResult.Text = myresults;
}

}
}

Thursday, June 4, 2009

Pretest - Allan's Store

Class as follows:



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

namespace AllanStore
{
public class ComputerSystem
{
//fields
private int barcode;
private string description;
private string model;
private double price;
private Brand brand;

//properties
public int Barcode
{
get { return barcode; }
set { barcode = value; }
}
public string Description
{
get { return description; }
set { description = value; }
}
public string Model
{
get { return model; }
set { model = value; }
}
public double Price
{
get { return price; }
set { price = value; }
}
public Brand Brand
{
get { return brand; }
set { brand = value; }
}

//constructors
public ComputerSystem()
{
}

public ComputerSystem(int _barcode, string _description, Brand _brand, string _model, double _price)
{
this.barcode = _barcode;
this.description = _description;
this.brand = _brand;
this.model = _model;
this.price = _price;
}

//methods
public override string ToString()
{
return "" + barcode.ToString() + ", " + description.ToString() + ", " + brand.ToString() + ", " + model.ToString() + ", $" + price.ToString() + "\n";
}


}
}


Enum as follow:


public enum Brand
{
Asus=0,
Dell=1,
Hp=2,
Acer=3
}


Form 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 AllanStore
{
public partial class Form1 : Form
{
//fields
private ComputerSystem[] computerArray = new ComputerSystem[10];

//properties
public ComputerSystem[] ComputerArray
{
get { return computerArray; }
set { computerArray = value; }
}

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

//methods - EVENTS
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult msg = MessageBox.Show("Are you sure?", "Exit", MessageBoxButtons.YesNo);
if (msg == DialogResult.Yes)
{
Close();
}
}

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

private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
if (checkAllFields() == true) //valid
{
ComputerSystem addObj = new ComputerSystem();
addObj.Barcode = int.Parse(txtBarcode.Text);
addObj.Price = double.Parse(txtPrice.Text);
addObj.Brand = (Brand)cmbBrand.SelectedItem;
addObj.Description = txtDescription.Text;
addObj.Model = txtModel.Text;

bool result = addSystem(addObj);

if (result == true)
{
MessageBox.Show("Computer System added!", "Added");
}
else
{
MessageBox.Show("Cannot Add, Array full!", "Cannot Add");
}

}
}

//methods - User defined
public void clearAllFields()
{
txtBarcode.Text = "";
cmbBrand.Text = "";
txtDescription.Text = "";
txtModel.Text = "";
txtPrice.Text = "";
}

public bool checkAllFields()
{
try
{
//fields errors
string errormessage = "";

if ((txtBarcode.Text == "") || (cmbBrand.Text == "") || (txtDescription.Text == "") || (txtModel.Text == "") || (txtPrice.Text == ""))
{
errormessage = "Please enter all fields";
}

//type errors
ComputerSystem testObj = new ComputerSystem();

testObj.Barcode = int.Parse(txtBarcode.Text);
testObj.Price = double.Parse(txtPrice.Text);
testObj.Brand = (Brand)cmbBrand.SelectedItem;

if (errormessage != "")
{
MessageBox.Show(errormessage, "Error occurred");
return false;
}
else
return true;


}
catch //catch type errors
{
MessageBox.Show("Please enter correct values in fields", "Error occurred");
return false;
}
}
public bool addSystem(ComputerSystem addObj)
{
for (int i = 0; i < computerArray.Length; i++)
{
if (computerArray[i] == null)
{
//perform add
computerArray[i] = addObj;
return true;
}
}
return false;
}

private void btnAdd_Click(object sender, EventArgs e)
{
addToolStripMenuItem_Click(sender, e);
}

private void Form1_Load(object sender, EventArgs e)
{
cmbBrand.Items.Add(Brand.Acer);
cmbBrand.Items.Add(Brand.Asus);
cmbBrand.Items.Add(Brand.Dell);
cmbBrand.Items.Add(Brand.Hp);
}

private void btnSearch_Click(object sender, EventArgs e)
{
searchToolStripMenuItem_Click(sender, e);
}

private void searchToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
ComputerSystem foundObj = new ComputerSystem();
foundObj = searchSystem(txtBarcode.Text);

if (foundObj == null)
{
MessageBox.Show("Cannot find Computer System", "No search found");
}
else
{
MessageBox.Show("System found");
txtBarcode.Text = foundObj.Barcode.ToString();
txtDescription.Text = foundObj.Description;
txtModel.Text = foundObj.Model;
txtPrice.Text = foundObj.Price.ToString();
cmbBrand.Text = foundObj.Brand.ToString();
}


}
catch
{
MessageBox.Show ("Barcode not valid", "Error");
}

}

public ComputerSystem searchSystem(string sbarcode)
{
try
{
int barcode = int.Parse(sbarcode);

for (int i = 0; i < computerArray.Length; i++)
{
if ((computerArray[i] != null) && (computerArray[i].Barcode == barcode)) //found match
{
return computerArray[i];
}

}
return null;
}
catch
{
return null;

}
}

private void btnUpdate_Click(object sender, EventArgs e)
{
updateToolStripMenuItem_Click(sender, e);
}

public bool updateSystem(string sbarcode, ComputerSystem updateObj)
{
try
{
int barcode = int.Parse(sbarcode);
for (int i = 0; i < computerArray.Length; i++)
{
if ((computerArray[i] != null) && (computerArray[i].Barcode == barcode))
{
computerArray[i] = updateObj;
return true;
}
}
return false;
}
catch
{
return false;
}
}

private void updateToolStripMenuItem_Click(object sender, EventArgs e)
{
if (checkAllFields() == true)
{
ComputerSystem updateObj = new ComputerSystem();
updateObj.Barcode = int.Parse(txtBarcode.Text);
updateObj.Price = double.Parse(txtPrice.Text);
updateObj.Brand = (Brand)cmbBrand.SelectedItem;
updateObj.Description = txtDescription.Text;
updateObj.Model = txtModel.Text;

bool updateresult = updateSystem(txtBarcode.Text, updateObj);

if (updateresult == true)
{
MessageBox.Show("System successfully updated");
}
else
{
MessageBox.Show("Cannot update system", "Error");
}
}
}

private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
bool deleteresult = deleteSystem(txtBarcode.Text);
if (deleteresult == true)
{
MessageBox.Show("System deleted");
clearAllFields();
}
else
{
MessageBox.Show("Cannot find system", "Delete failed");
}
}

public bool deleteSystem(string sbarcode)
{
try
{
int barcode = int.Parse(sbarcode);

for (int i = 0; i < computerArray.Length; i++)
{
if ((computerArray[i] != null) && (computerArray[i].Barcode == barcode))
{
computerArray[i] = null;
return true;
}
}
return false;
}
catch
{
return false;
}
}

private void btnDelete_Click(object sender, EventArgs e)
{
deleteToolStripMenuItem_Click(sender, e);
}

private void btnDisplayAll_Click(object sender, EventArgs e)
{
displayAllToolStripMenuItem_Click(sender, e);
}

private void displayAllToolStripMenuItem_Click(object sender, EventArgs e)
{
string myComputers = "";
for (int i = 0; i < computerArray.Length; i++)
{
if (computerArray[i] != null)
{
myComputers += computerArray[i].ToString();
}
}

MessageBox.Show(myComputers, "Computer Lists");
}

private void btnAbout_Click(object sender, EventArgs e)
{
AboutBox1 about = new AboutBox1();
about.Show();
}

private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
{
btnAbout_Click(sender, e);
}

}
}

Thursday, May 21, 2009

Car Array, Finding the cars by max and min seats available



private void FindCarButton_Click(object sender, EventArgs e)
{
//Initialise Cars
Car[] cars = rental.GetAllCars();

//Reset listbox
CarsListBox.Items.Clear();

int iMin = int.Parse(MinTextBox.Text);
int iMax = int.Parse(MaxTextBox.Text);
Car[] carsfound = rental.GetCarsByPassengers(iMax, iMin);

for (int i = 0; i < carsfound.Length; i++)
{
if (carsfound[i] != null)
CarsListBox.Items.Add(carsfound[i].Model);
}
}




//method #2 - GetCarsByMaxPassengers
public Car[] GetCarsByPassengers(int max, int min)
{
Car[] cars = new Car[15];
for (int i = 0; i < carArray.Length ; i++)
{
if ((carArray[i].NoPassengers >= min) && (carArray[i].NoPassengers + 1 <= max))
{
cars[i] = carArray[i];
}
}
return cars;
}

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

Thursday, May 7, 2009

Allan's Classwork - Employee class

Just change the following codes to the Employee class file:



//methods
public double CalcWages(double hw)
{
double wages = hw * payRate;
return CalcTaxes(wages);
}

private double CalcTaxes(double Wages)
{
return (Wages * 0.85);
}

Wednesday, May 6, 2009

Shanti's Web Classwork

Question 1 - Countdown


<!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>
</head>
<body>
<script type="text/javascript">

var num = prompt("Enter number > 0", "0");

while ((num <=0) || (isNaN(num)==true))
{
var num = prompt("Enter number > 0", "0");
}

for (var i=0; i<num; i++)
{
alert("Starting in " + (num-i));
}
alert ("Roll Film!");
</script>
</body>
</html>

Question 2 - Multiplication


<!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>
</head>
<body>
<script type="text/javascript">
document.write("<table><tr><td colspan=10><h1>Multiplication Table</h1></td></tr>");

for(var i = 1; i <= 10; i++)
{
document.write("<tr>");
for (var j = 1 ; j <= 10; j++)
{
document.write("<td>" + i + " * " + j + " = " + (i * j) + "</td>");
}
document.write("</tr>");
}


document.write("</table>");
</script>
</body>
</html>


Question 3 - Online Reservation



<!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>
</head>
<body>
<script type="text/javascript">
function assignSeat()
{

for (var i = 1; i <= 5; i ++)
{
if (document.getElementById(i).title == "a")
{
document.getElementById(i).src= "seat_select.png";
if (confirm("Seat " + i + " is available. Accept? "))
{
document.getElementById(i).src = "seat_unavail.png";
document.getElementById(i).title = "u";
break;
}
else
{

}
document.getElementById(i).src= "seat_avail.png";
}
}

}
</script>

<img src="seat_avail.png" alt = "1" id="1" title = "a" />
<img src="seat_avail.png" alt = "2" id="2" title = "a" />
<img src="seat_avail.png" alt = "3" id="3" title = "a" />
<img src="seat_avail.png" alt = "4" id="4" title = "a" />
<img src="seat_avail.png" alt = "5" id="5" title = "a" />
<br />
<input type="button" value="Reserve Seat" onclick="assignSeat()" />

</body>
</html>

Monday, May 4, 2009

Shanti's Classwork - Rectangle Class

Code without the implementation for the Point object.
Class Definition for Rectangle:


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

namespace RectangleClass
{
class Rectangle
{
//fields
private int length = 0;
private int width = 0;

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

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

//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;
}
}
}


UI Form



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 RectangleClass
{
public partial class Form1 : Form
{
Rectangle myRec1 = new Rectangle(0, 0);

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)
{
MessageBox.Show("Width is " + myRec1.Width);
}

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

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

private void CheckFields()
{

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

}


}
}

Thursday, April 2, 2009

C# Classwork - Allan - Book Seat

This question is taxing if you want to validate everything, like check if booking has already made, smoker/non smoker and the seat validation.



Another problem concerns the display of the seat arrangement, as shown in the picture.


Check it out for yourself...



private void btnBook_Click(object sender, EventArgs e)
{
try{
int iSeatNo = 0;
iSeatNo = int.Parse(txtSeat.Text);
if (iSeatNo <= 10)
{

}
else
{
MessageBox.Show("Seat Number not valid");
txtSeat.Clear();
txtSeat.Focus();
}

if ((iSeatNo <= 5) && (iSeatNo > 0) && (radSmoke.Checked == true))
{
if (book[iSeatNo - 1] == false)
{
book[iSeatNo - 1] = true;
grpSmokingArea.Controls[iSeatNo-1].Text = "BOOKED";
grpSmokingArea.Controls[iSeatNo-1].ForeColor = Color.Red;
lblInfo.Text = "You have booked Seat # " + iSeatNo + " \nin the
Smoking Area"
;
}
else
{
MessageBox.Show("Seat already taken");
}
}
else if (radSmoke.Checked== true)
{
MessageBox.Show("Seat allowed in non-smoking section only");
txtSeat.Clear();
txtSeat.Focus();
return;
}

/* Non Smoking */
if ((iSeatNo > 5) && (iSeatNo <= 10) && (radNoSmoke.Checked == true))
{
if (book[iSeatNo - 1] == false)
{
book[iSeatNo - 1] = true;
grpNonSmokingArea.Controls[iSeatNo - 6].Text = "BOOKED";
grpNonSmokingArea.Controls[iSeatNo - 6].ForeColor = Color.Red;
lblInfo.Text = "You have booked Seat # " + iSeatNo + " \nin the Non
Smoking Area"
;
}
else
{
MessageBox.Show("Seat already taken");
}
}
else if (radNoSmoke.Checked== true)
{
MessageBox.Show("Seat allowed in smoking section only");
txtSeat.Clear();
txtSeat.Focus();
return;
}


}

catch
{
MessageBox.Show("Please enter correct Seat Number");
txtSeat.Text = "";
txtSeat.Focus();
}
}

Wednesday, March 25, 2009

Have Your Say!

If you are copying-pasting, the file organisation is as follows:
  1. .myHTML.html
  2. .mysay.css
  3. /images/bg.png
  4. /images/textbg.gif


HTML

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="yoursay.css" />
<title>Have your Say!</title>
</head>
<body>
<div id="wrapper">
<div id="formcontrols">
<form action="" method="post">
Name
<br/>
<input type="text" name="myname" size="30" id="eachcontrol" />
<br/><br/>
Email
<br/>
<input type="text" name="myemail" size="30" id="eachcontrol" />
<br/><br/>

http://
<br/>
<input type="text" name="myhttp" size="30" id="eachcontrol" />
<br/><br/>


Comments
<br/>
<textarea name="myComments" rows="2" cols="23" id="eachcontrol" >
</textarea>
<br/><br/>

<input type="button" name="preview" value="PREVIEW" class=
"previewbtn"
/>
<br/><br/>

Remember details?<br/>
<input type="checkbox" name="chkremember" />
<br/><br/>
</form>
</div>
<div id="myColumn">
<h3>HAVE YOUR SAY</h3>
<div id="content">
<p>Feel free top publish your thoughts but please be judicious
when communicating I am.</p>
<p>Gravatars are enabled. Go get yourself one.</p>
<p>All the cool kids use Textile.</p>
<p>Email address is required but will not be posted or
distributed.</p>
</div>
</div>
</div>
</body>

</html>




CSS

body
{
font-family:Verdana;
font-size:16px;
color:#ffffff;
margin:0 auto;

}

h3{
width:350px;
border-width: 0px 0px 3px 0px;
border-style:dashed;
font-size:30px;
padding:12px;
text-align:center;
background-color:orange;
margin:10px 0px 10px 0px;
padding:2px 2px 5px 2px;
}

#wrapper
{
margin:50px;
float:left;
background-image:url('images/bg.png');
background-repeat:repeat;
width:700px;
}

#formcontrols
{
width:280px;
float:left;
padding:10px;
}

#myColumn{
width:380px;
float:left;

}

#content{
margin-left:30px;
width:300px;
float:left;
}

#eachcontrol
{
background-image:url('images/textbg.gif');
background-repeat:repeat;
}

.previewbtn
{
border:3px solid;
border-color: #ffffff #000000 #000000 #ffffff;
color:#ffffff;
background-image:url('images/bg.png');
background-repeat:repeat;
padding:7px 20px 7px 20px;
}

Monday, March 23, 2009

Shanti C# -> Morse Code

Same coding as in previous entry (English Spanish Translator):

Declaring and initialising the variables:
string[] sText = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
"M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1", "2",
"3", "4", "5", "6", "7", "8", "9", "0" };
string[] sMorse = {". -","- . . .
","- . - .","- . . ",".",". . - .","- - .",". . . .",". . ",". - - -","- . -",".
- . .","- -","- .","- - -",". - - .","- - . -",". - . ",". . .","-",". . - ",".
. . -",". - -","- . . -","- . - -","- - . .",". - - - -",". . - - -",". . . -
-",". . . . -",". . . . .","- . . . .","- - . . .","- - - . .","- - - - .","- -
- - -"};


On form load,

for (int i = 0; i < sMorse.Length;
i++)
{
cmbText.Items.Add(sText[i]);
lisMorse.Items.Add(sMorse[i]);
}


Making both controls dependent on user-choice:
private void cmbText_SelectedIndexChanged(object sender, EventArgs
e)
{
int iIndex = cmbText.SelectedIndex;
lisMorse.Text =
sMorse[iIndex];
}

private void lisMorse_SelectedIndexChanged(object sender, EventArgs
e)
{
int iIndex = lisMorse.SelectedIndex;
cmbText.Text =
sText[iIndex];
}


Enjoy!

Shanti C# -> English - Spanish Translator

In the class definition, you might want to declare and initialise the two global string variables

string[] sEng = {"arm","body","ear","eye","face","foot/feet","finger","hair","hand","head","leg","mouth","neck",
"nose","stomach","tooth/teeth"};
string[] sSpan = {"brazo","cuerpo","oreja","ojo","cara","pie/s","dedo","pelo","mano","cabeza","pierna","boca",
"cuello","nariz","est\u00F3mago","diente/s"};



Note the character in orange, which is the unicode that represents the spanish character.



Now, we bind the arrays to the controls (I use a combo box and a list box).

for (int i = 0; i < sEng.Length; i++)
{
cmbEng.Items.Add(sEng[i]);
lisSpan.Items.Add(sSpan[i]);
}

for (int i = 0; i < sMorse.Length; i++)
{
cmbText.Items.Add(sText[i]);
lisMorse.Items.Add(sMorse[i]);
}


Finally, we put the coding behind the index selection of the combobox and listbox respectively, so that when you click on an english term, the spanish translation is offered, and vice-versa:

private void cmbEng_SelectedIndexChanged(object sender, EventArgs e)
{
int iIndex = cmbEng.SelectedIndex;
lisSpan.Text =
sSpan[iIndex];
}

private void lisSpan_SelectedIndexChanged(object sender, EventArgs e)
{
int iIndex = lisSpan.SelectedIndex;
cmbEng.Text = sEng[iIndex];
}



That's it, compile, run and learn Spanish :)