Showing posts with label Allan. Show all posts
Showing posts with label Allan. Show all posts

Monday, September 14, 2009

ASP.NET - Session time

To record the session time, two variables are initialised in the global application class Global.asax to hold the name of user and time of session.



<%@ Application Language="C#" %>

<script runat="server">

void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup

}

void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown

}

void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs

}

void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Session.Add("Name", null);
Session.Add("Time", null);

}

void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.

}

</script>


Now, in the first page (Default.aspx) which holds the textbox for the user name and the login button, the following code is written for the Click event of the login button. The variable Time in the Session object will store the date and time of the click.



protected void btnLogin_Click(object sender, EventArgs e)
{
Session["Name"] = txtName.Text;
Session["Time"] = DateTime.Now;
Response.Redirect("~/Default2.aspx");

}


In Default2.aspx, the name is displayed in the Form_Load event.
The button for logout will display the Session time.



protected void Page_Load(object sender, EventArgs e)
{
lblInfo.Text = Session["Name"].ToString();
}
protected void btnLogout_Click(object sender, EventArgs e)
{

lblInfo.Text = (DateTime.Now.Subtract(DateTime.Parse( Session["Time"].ToString()) )).Seconds.ToString();
}


Note: This code was written in class and has limitations. It will only display seconds. That is, 1 minute and 5 seconds will display as 5 seconds. I believe there are many ways to solve this problem. Please feel free to share your code.

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.

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

}
}

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!

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

}
}

Wednesday, June 3, 2009

Allan's Pre-test MyProperty

Below is the Property class.



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

namespace BASIC
{
public class MyProperty
{
//fields
private string suburb;
private int bedrooms;
private int price;

//properties
public string Suburb
{
get { return suburb; }
set { suburb = value; }
}

public int Bedrooms
{
get { return bedrooms; }
set { bedrooms = value; }
}

public int Price
{
get { return price; }
set { price = value; }
}

//constructors
public MyProperty()
{
}

public MyProperty(string _suburb, int _bedrooms, int _price)
{
this.suburb = _suburb;
this.bedrooms = _bedrooms;
this.price = _price;
}


//methods
//override ToString() method
public override string ToString()
{
string msg = "";
msg = suburb.ToString() + ", " + bedrooms.ToString() + ", " + price.ToString() + "\n";
return msg;
}
}
}


Below is the form 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 BASIC
{
public partial class Form1 : Form
{
//fields
private MyProperty[] propertyArray = new MyProperty[10];

//properties
public MyProperty[] PropertyArray
{
get { return propertyArray; }
set { propertyArray = value; }
}

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

#region methods
//methods

//check for valid fields
public bool checkAllFields()
{
try
{
if ((txtSuburb.Text != "") && (txtPrice.Text != "") && (txtBedrooms.Text != "") ) //check for empty fields
{
int testInt = int.Parse(txtPrice.Text);
testInt = int.Parse(txtBedrooms.Text); //if cannot parse, goto catch section and handle error

return true;
}
else
{
return false; //error occurred
}
}
catch
{
return false; //error occurred
}
}

//adds property
public bool addProperty(MyProperty propObj)
{
for (int i = 0; i < propertyArray.Length; i++)
{
if (propertyArray[i] == null)
{
propertyArray[i] = propObj;
return true;
}
}
return false;
}

//updates property
public bool updateProperty(MyProperty updatedObj)
{
for (int i = 0; i < PropertyArray.Length; i++)
{
if ((propertyArray[i] != null) && (propertyArray[i].Suburb == updatedObj.Suburb) && (propertyArray[i].Bedrooms == updatedObj.Bedrooms))
{
propertyArray[i] = updatedObj;
return true;
}
}

return false; //cannot find object
}

//delete property
public bool deleteProperty(string propName)
{
for (int i = 0; i < propertyArray.Length; i++)
{
if ((propertyArray[i].Suburb == propName) && (propertyArray[i] != null))
{
propertyArray[i] = null;
return true;
}
}
return false; //object not found
}

//get sum
public double getSum()
{
double sum = 0;
for (int i = 0; i < propertyArray.Length; i++)
{
if (propertyArray[i] != null)
{
sum += propertyArray[i].Price;
}
}
return sum;
}

//get average
public double getAverage()
{
double sum = 0;
double propitem = 0;
for (int i = 0; i < propertyArray.Length; i++)
{
if (propertyArray[i] != null)
{
sum += propertyArray[i].Price;
propitem++;
}
}
return (sum/propitem);//average
}

//get max
public double getMax()
{
double dMax = 0;

for (int i = 0; i < propertyArray.Length; i++)
{
if (propertyArray[i] != null)
{
if (propertyArray[i].Price >= dMax)
dMax = propertyArray[i].Price;
}
}
return (dMax);//Max
}

//get min
public double getMin()
{
bool arrayExist = false;
double dMin = 999999999;

for (int i = 0; i < propertyArray.Length; i++)
{
if (propertyArray[i] != null)
{
if (propertyArray[i].Price <= dMin)
dMin = propertyArray[i].Price;
arrayExist = true;
}
}
if (arrayExist == true)
{
return (dMin);//Min
}
else
{
return 0;
}
}

public void clearAllFields()
{
txtBedrooms.Text = "";
txtPrice.Text = "";
txtSuburb.Text = "";
}

#endregion

#region events
private void Form1_Load(object sender, EventArgs e)
{

}

private void addNewPropertyToolStripMenuItem_Click(object sender, EventArgs e)
{
if (checkAllFields() == true)
{
MyProperty propObj = new MyProperty();

propObj.Suburb = txtSuburb.Text;
propObj.Bedrooms = int.Parse(txtBedrooms.Text);
propObj.Price = int.Parse(txtPrice.Text);

bool bool_add = addProperty(propObj);

if (bool_add == true)
{
MessageBox.Show("Property added!");
clearAllFields(); //clears fields
}
else
{
MessageBox.Show("No more property can be stored in the array");
}

}
else
{
MessageBox.Show("Fields are not valid");
}
}

private void updatePropertyToolStripMenuItem_Click(object sender, EventArgs e)
{
if (checkAllFields() == true)
{
MyProperty updateProp = new MyProperty();

updateProp.Suburb = txtSuburb.Text;
updateProp.Price = int.Parse(txtPrice.Text);
updateProp.Bedrooms = int.Parse(txtBedrooms.Text);

if (updateProperty(updateProp)) //true
{
MessageBox.Show("Property updated!");
clearAllFields(); //clears fields
}
else //false
{
MessageBox.Show("Cannot find property for update!");
}

}
else
{
MessageBox.Show("Fields are not valid");
}
}

private void deletePropertyToolStripMenuItem_Click(object sender, EventArgs e)
{
bool deleteProp;
if (txtSuburb.Text != "")
{
deleteProp = deleteProperty(txtSuburb.Text);

if (deleteProp == true)
{
MessageBox.Show("Property deleted!");
clearAllFields(); //clears fields
}
else
{
MessageBox.Show("Cannot find property to delete");
}
}
else
{
MessageBox.Show("Please enter a Suburb name");
txtSuburb.Focus();
}
}

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

if (allPropList == "")
{
MessageBox.Show("No property found");
}
else
{
MessageBox.Show(allPropList);
}
}

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

private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Property Application. Pre-test example");
}

private void displayTotalToolStripMenuItem_Click(object sender, EventArgs e)
{
double sum = getSum();
MessageBox.Show("Total Property Price : $ " + sum.ToString());
}

private void displayAverageToolStripMenuItem_Click(object sender, EventArgs e)
{
double average = getAverage();
MessageBox.Show("Total Average Price : $ " + average.ToString());
}

private void displayMaxToolStripMenuItem_Click(object sender, EventArgs e)
{
double max = getMax();
MessageBox.Show("Max Price : $ " + max.ToString());
}

private void displayMinToolStripMenuItem_Click(object sender, EventArgs e)
{
double min = getMin();
MessageBox.Show("Min Price : $ " + min.ToString());
}

#endregion

}
}

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

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

Thursday, April 9, 2009

Pre-Test :)



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 myPreTest
{
public partial class Form1 : Form
{
int iMin = 0;
int iMax = 0;
string[] sCarModel = { "Dodge Viper", "Ford Mustang", "Ford Thunderbird", "Pontiac Grandprix", "Ford Windstar", "Dodge RAM Van", "Blue Bird Mini Bus" };
int[] iMaxStringNo = { 2, 3, 4, 6, 8, 10, 16 };

public Form1()
{
InitializeComponent();
}

private void btnExit_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you really want to close the application?", "Exiting Application", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
Close();
}

}

private void Form1_Load(object sender, EventArgs e)
{

}

private void btnFindCar_Click(object sender, EventArgs e)
{
if (CheckAllFields()) //all fields are valid
{
try
{
iMin = int.Parse(txtMin.Text);
iMax = int.Parse(txtMax.Text);

for (int i = 0; i < sCarModel.Length; i++)
{
if ((iMaxStringNo[i] <= iMax) && (iMaxStringNo[i] >= iMin))
{
string sModelandMax = "" + sCarModel[i] + " - Max: " + iMaxStringNo[i] + " people";
lisModels.Items.Add(sModelandMax);
}
}
}
catch
{
MessageBox.Show("Please enter a integer values for Maximum and Minimum fields", "Integer values required", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}

}



}

/******************************* FUNCTION LIST *****************************/
private bool CheckAllFields()
{
if (txtCustomerName.Text == "")
{
MessageBox.Show("Please enter a customer name", "Customer Name missing", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
txtCustomerName.Focus();
return false;
}
else if ((txtCustomerName.Text.Contains("0"))||(txtCustomerName.Text.Contains("1"))||(txtCustomerName.Text.Contains("2"))||(txtCustomerName.Text.Contains("3"))||(txtCustomerName.Text.Contains("4"))||(txtCustomerName.Text.Contains("5"))||(txtCustomerName.Text.Contains("6"))||(txtCustomerName.Text.Contains("7"))||(txtCustomerName.Text.Contains("8"))||(txtCustomerName.Text.Contains("9")))
{
MessageBox.Show("Please enter a customer name with Alphabets only", "Customer Name error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtCustomerName.Focus();
return false;
}
else if (txtMin.Text == "")
{
MessageBox.Show("Please enter Minimum passengers", "Minimum Passengers number missing", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
txtMin.Focus();
return false;
}
else if (txtMax.Text == "")
{
MessageBox.Show("Please enter Maximum passengers", "Maximum Passengers number missing", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
txtMax.Focus();
return false;
}
else
{
return true;
}
}

private void btnReserveCar_Click(object sender, EventArgs e)
{
try
{
if (CheckAllFields() == true)
{
if (lisModels.Text != "")
{
string sResult = "Customer Name: " + txtCustomerName.Text + "\n" +
"Number of Passengers requested: " + iMin + " Minimum, " + iMax + " Maximum\n" +
"Selected Car: " + lisModels.Text;

MessageBox.Show(sResult, "Reservation Made", MessageBoxButtons.OK, MessageBoxIcon.Information);

lblReservations.Text += DateTime.Now.ToShortDateString().ToString() + "\n" + sResult + "\n\n";
}
else
{
MessageBox.Show("Please choose a car model", "No car model selected", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
catch
{
MessageBox.Show("Unable to make reservation - Please check all input", "Error in Reservation", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

}
}

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

Friday, March 27, 2009

Monetary System - Version 2 - Using arrays & for loops - the proper way

Misa devised a brillant way to use arrays, loops and the TableLayoutPanel control to tackle the problem stated in the previous entry (version 1).  


But first, let's understand one important design concept, the TableLayoutPanel control.
We are used to display informations using labels, but we also found out the limitations of this control. With labels, it is very difficult to predict the display of the string or text being output. For example, a label might contain multiple lines of text (we might use '\n' for new lines, or '\t' for tabs).

With TableLayoutPanel, the organisation of any controls including labels, is made easier.
The TableLayoutPanel is just a series of rows and columns, analogous to a table.

One of the main advantage of using the TableLayoutPanel is that you can refer to each control in  a cell, just like an array. An array of controls, found in the Table. We will use that concept in this code.


For example, you might want to contain a list of Coins you have, and the number of coins, each represented on a different row, with separate columns for each category. You can do it with labels only, but the best design solution is to use the TableLayoutPanel with labels.

 

In this scenario, Coins are on the top row, whereas the numbers are below the respective coins, bottom row.  We create the table TableLayoutPanel1.


In design view, the table is set as follows, with 4 normal labels, one in each cell.

Now the nice part. You can actually refer to the labels in an 'array-like' fashion. For example, 

TableLayoutPanel1.Controls[0] will refer to label2.
TableLayoutPanel1.Controls[1] will refer to label3.
TableLayoutPanel1.Controls[2] will refer to label4.
TableLayoutPanel1.Controls[3] will refer to label5.
So this is why we should be using arrays and loops in this question. 
This is the end of the explanation on why we should use the TableLayoutPanel control. 


This is the final code for the home work.

   1:  int[] coins = { 50, 20, 10, 5 };
   2:  int[] numbers = { 0, 0, 0, 0 };
   3:  int iAmount = int.Parse(txtAmount.Text);
   4:  int iCoinsNum = 0;  //stores the number of coins used
   5:   
   6:  iAmount %= 100; //Get the 2 last digits
   7:   
   8:  for (int i = 0; i < coins.Length; i++)
   9:  {
  10:      numbers[i] = iAmount / coins[i];    //gets the number of particular coin in amount
  11:      iAmount = iAmount % coins[i];       //gets the remainder
  12:      tableLayoutPanel1.Controls[i].Text = coins[i] + " cent \n" + numbers[i];
  13:      //display the coins value and amount, in each label per column in the TableLayoutPanel
  14:      iCoinsNum += numbers[i];            //accumulates the amount of coins
  15:  }
  16:   
  17:  if (iCoinsNum == 0) //check if any coin was required
  18:  {
  19:      btnReset_Click(sender, e);
  20:      lblCoinsNum.Text = "No coins required.";
  21:  }
  22:  else
  23:  {
  24:      lblCoinsNum.Text = "" + iCoinsNum + " coins required.";
  25:  }



Note: The order of the Coins array is important, as you want to divide the 50c coins first before moving to the 20c coins, and so on.


Screenshots of design and runtime application