Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, November 2, 2009

C# Unit Testing - Divide function div()



using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MyCal;

namespace CalcTestProject
{
/// <summary>
/// Summary description for UnitTest1
/// </summary>
[TestClass]
public class DivTest
{

#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Use TestInitialize to run code before running each test
// [TestInitialize()]
// public void MyTestInitialize() { }
//
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion

[TestMethod]
public void Test_ValidPositive()
{
//call method defined in the MyMath class
Assert.AreEqual(MyMath.Div("20","5"),"4.00");
Assert.AreEqual(MyMath.Div("25", "2"), "12.50");
Assert.AreEqual(MyMath.Div("20", "3"), "6.67");
Assert.AreEqual(MyMath.Div("2147483647", "2"), "1073741823.50");
}

[TestMethod]
public void Test_ValidNegative()
{
Assert.AreEqual(MyMath.Div("-40", "2"), "-20.00");
Assert.AreEqual(MyMath.Div("50", "-2"), "-25.00");
Assert.AreEqual(MyMath.Div("-4", "-2"), "2.00");
Assert.AreEqual(MyMath.Div("-2147483648", "-4"), "536870912.00");
}

[TestMethod]
public void Test_ValidZeroes()
{
Assert.AreEqual(MyMath.Div("0", "2"), "0.00");
Assert.AreEqual(MyMath.Div("2", "0"), "ERROR");
Assert.AreEqual(MyMath.Div("0", "0"), "ERROR");
}

[TestMethod]
[ExpectedException (typeof (FormatException))]
public void Test_CharFirstInput()
{
MyMath.Div("2aa", "4");

}

[TestMethod]
[ExpectedException(typeof(FormatException))]
public void Test_NotIntInput()
{
MyMath.Div("5.5", "2");
MyMath.Div("4", "2.2");
}

[TestMethod]
[ExpectedException(typeof(FormatException))]
public void Test_NotValidInput()
{
MyMath.Div("", "2");
MyMath.Div("22", "");
}

[TestMethod]
[ExpectedException(typeof(OverflowException))]
public void Test_RangeError()
{
MyMath.Div("2147483648", "2");
MyMath.Div("22", "-4147483467");
}

}
}

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.

C# - Understanding IComparable and IComparer

Check this link for an article about IComparable and IComparer.

Wednesday, July 29, 2009

C# UML Class Diagram




Click to enlarge...


Shape Class:


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

namespace ShapeInheritance
{
public abstract class Shape //enforce that abstract MUST BE OVERRIDEN
{
//fields
protected double xPos; //'protect' modifier used because we want all
protected double yPos; //subclasses will generally inherit those fields

//constructors
public Shape(double _xPos, double _yPos)
{
this.xPos = _xPos;
this.yPos = _yPos;
}

//methods
public abstract double Area(); //enforce that Area HAS TO BE OVERRIDEN BY SUB-CLASSES

public override string ToString()
{
return "Position : (" + xPos.ToString() + ", " + yPos.ToString() + ")\n";
}
}
}


Circle class:


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

namespace ShapeInheritance
{
public class Circle : Shape
{
//fields
private double radius;

//properties
public double Radius
{
get { return radius; }
set { radius = value; }
}

//constructors
public Circle() : base(0,0)
{
}

public Circle(double _xPos, double _yPos) : base(_xPos , _yPos)
{
}

public Circle(double _xPos, double _yPos, double _radius) : base(_xPos, _yPos)
{
this.radius = _radius;
}

//methods
public override double Area()
{
return Math.PI * Math.Pow(Radius, 2);
}

public override string ToString()
{
return base.ToString() + "\nradius : " + radius + "\nArea : " + Area().ToString("N2");
}
}
}


Cylinder class:


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

namespace ShapeInheritance
{
public class Cylinder : Circle
{
//fields
private double height;

//properties
public double Height
{
get { return height; }
set { height = value; }
}

//constructors
public Cylinder() : base(0,0)
{
}

public Cylinder(double _xPos, double _yPos, double _radius, double _height) : base(_xPos, _yPos, _radius)
{
height = _height;
}

//methods
public override double Area()
{
return (2 * base.Area()) + (2 * Math.PI * Radius * height);
}

public double Volume()
{
return Math.PI * Math.Pow(Radius,2) * height;
}

public override string ToString()
{
return base.ToString() + "\nHeight : " + height + "\nVolume : " + Volume().ToString("N2");
}

}
}


Form coding:


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

private void btnCircle_Click(object sender, EventArgs e)
{
Circle circle = new Circle(0, 0, 10);
lblText.Text = circle.ToString();
}

private void btnCylinder_Click(object sender, EventArgs e)
{
Cylinder cylinder = new Cylinder(0, 0, 10,10);
lblText.Text = cylinder.ToString();
}
}
}


Note:


1. Chain constructors are not used. Sub-constructors are calling the base constructor only.


2. Rectangle class not implemented.

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

Incomplete Entry : Exam - Tips for Programming with Classes

Hi guys

I'm compiling some tips, or a 'cheat-sheet', that could help all of us to get great marks for the C# exam due on Thursday 11th June.

You might want to check it from time to time as I will update this entry frequently. Please do not hesitate to ask questions or suggestions, this place is also a discussion area :)

A step-by-step tutorial on how to get 70%+ for the exam!

Contents
1. Getting started - writing the class!
2. Creating the Graphical User Interface - Form Level
3. Creating your array of objects writing your methods for add, delete, update, display and search!

Checklist


1. Writing the Class
After creating a class file with the appropriate name from the Solution Explorer, immediately change the class MODIFIER. You want the MODIFIER to be PUBLIC.


public class MyProperty


1.1. Separate your class file into following sections

1.1.1. Fields
This contains all the fields or elements that are innate to the object, i.e. required to define this object.
As a matter of fact, you ALWAYS want them to be PRIVATE, so that no other objects from other classes can 'see' the fields. That's what we call encapsulation.


private string suburb;
private int bedrooms;
private int price;


1.1.2. Properties
Properties are the 'getters' and 'setters' of the fields described in 2.1. They access those fields and modify their value.
You might want to use the 're-factor' function in Visual Studio to do this quickly.

Right-click on the private field (e.g. suburb), hover on Refactor, and click on Encapsulate field. Click OK on the following message boxes to use the default properties name.


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


1.1.3. Constructors
Usually, you will require to implement at least 2 constructors, the first one being the null constructor. In the exam, the other constructor will be stated, for example, asking you to use 3 fields to pass in the constructor.
Writing the null constructor is a good practice, even if not explicitly asked during examination. Your constructors will ALWAYS be PUBLIC.


public MyProperty()
{
}

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


1.1.4. Methods
This section will implement the functions, or methods, that will be required to accomplish a certain task.
You might be ask to override the ToString() method, which means that you will have to re-define the passing parameters of the ToString(), and change its code to adapt to a situation.
Note: You ALWAYS write your methods with PUBLIC modifiers.


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


Done with classes!

Back to the Table of Contents

2. Graphical User Interface - Form
Do as you are told in the exam, not too fancy design, but you will need those functions:
Add
Delete
Update
Display
Search

Note: Additional functions might be required, but you essentially need those.

Back to the Table of Contents

3. Creating your array of objects writing your methods for add, delete, update, display and search!
This is my favourite part!
You might want to know that we are done working with the class file, so everything that is being explained as from this section, is done in the FORM file or class.

3.1. Declaring your array
The first question would be to create an array of objects. Some students might be confused when declaring an array of objects. Just follow this rule of thumb:


ClassName[] arrayofObjects = new ClassName[10];


Of course, you might want to modify the length of the array to whatever figure required for the exam. I used 10. For those who didn't notice. :)

3.2. Add method (PUBLIC)
Return type: boolean
Passing parameters: the object to be added
Method signature: public bool addMethod(ClassName objectName)


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


How it works:
Before you can add an object to your array, you need to check if there is a free space or slot for the object to be added.
You loop through ALL items in the array.
If null (meaning that this space is unoccupied), you assign this array position to the object to be added.
You need to return a boolean to tell the caller that the method has been successful.

Combining the Add method with the form:
i. Create an instance of the class, also known as the object of the class.
ii. Assign all the values that have been entered by the user to the object's properties.
iii. Call the method and store it in a boolean variable.
iv. Do the necessary validation if addition has been successful or not.



MyProperty propObj = new MyProperty(); //create an object

//assign fields to user entered values
propObj.Suburb = txtSuburb.Text;
propObj.Bedrooms = int.Parse(txtBedrooms.Text);
propObj.Price = int.Parse(txtPrice.Text);

//call add function and store result in a boolean variable
bool bool_add = addProperty(propObj);

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



Back to the Table of Contents


Checklist
1) Only the fields defined in your class are PRIVATE. All other entries are PUBLIC.

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

}
}