Showing posts with label Class. Show all posts
Showing posts with label Class. Show all posts

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!

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

Friday, March 20, 2009

CSS - My two cents' worth

CSS Basics

1) How to use CSS?
You can use CSS in 3 ways:
  1. Using inline CSS means that you use your styling elements within the tags in the HTML. You will use the <style> tag to do so.
    e.g.
    <body style="background-color:blue; font-weight:bold">


  2. Using internal CSS means that you define all your styling elements for each tag you are using in the <head> section.
    e.g.

    <style type="text/css">
    <!--
    h1 { font-family:Times serif; color: #f00000; }
    -->
    </style>
  3. External Style Sheets: using a file with extension .CSS that will contain all the styling elements that you would normally put in the head section. This improves readability of your code and helps achieving separation of content from form/design.

2) How to use external CSS?
<head>
<link type=”text/css” rel=”stylesheet” href=”mystyle.css”>
</head>

3) How to use Classes?
Say for example, you want all your paragraphs <p> to be black, except for one paragraph that would be red.
The solution is to use a class, that will be applied for only this particular paragraph.
e.g.

p.warning {color: red;}

<p class="warning">This is red. </p>

Note: You can also create classes that will apply to any tag (generic classes).
e.g.
.mycolor{color: red;}

<p class=”mycolor”>A red body text.</p>

<h1 class=”mycolor”>A red headline.</h1>

4) What are IDs? What is the difference between IDs and Classes?
The ID selectors and generic classes are very similar, except for the fact the an ID is supposed to be used only once.
e.g.
#myID{color:green;font-size:10px}

<p id="myID">my green paragraph</p>
5) What if I want one paragraph to be in red, and one sentence of that paragraph in bold?
Well, we could use the <bold> tag which will contain the sentence, but it is not XHTML compliant and the bold tag is deprecated.
The solution is to use the <span> tag.
e.g.

.myBold{font-weight:bold}

<p>This paragraph has the browser default formatting, but <span class="myBold"> this sentence is bold, without making any change to the paragraph selector.</span> This sentence is back to browser default formatting for a paragraph tag. </p>