1

  • This is an open-book test. You may use the text book “Be Sharp with C#” as well as the built-in Help in Visual Studio. NO other sources, written or electronic, are allowed.
  • Create a folder on the T-drive with your surname and student number, e.g. Blignaut_2010111213. Save each one of the following three questions as three separate projects in this folder.

Question 1 (Arrays, files, methods, parameters)

Use Notepad or another text editor and enter a series of integers into a text file – one number per line. Develop a program that will read the numbers from the file and then display statistics on the data as in the example. Make provision for the fact that some of the entries in the text file may be invalid numeric values.

1.1Design the form as in the example.(5)

1.2Write the code for the browse button ().

-Display a dialog box and request the user to select a file. The dialog should have a filter that will allow only text files (*.txt) to be displayed.

-Enter the full path and file name in the text box.

-Call a method that will copy all data in the file to the list box.

-Call a method that will put all valid numbers in an integer array.

-Call a method that will display the statistics as in the example.

The code for the Click event handler of this button is given below in pseudocode format:

if (user selected Open in dialog box)

{

Enter file name in text box

Read text file

Declare integer array for Numbers

Get numbers

DisplayStats(Numbers);

}(10)

1.3Write the method ReadTextFileto copy all data from the text file to the list box. Ensure that the file exists. The method will get the file name as a parameter. (12)

1.4Write the method GetNumbersthat will get all valid numbers from the list box and put them in the integer array that is passed to it as reference parameter. The array should be sorted before it is returned. (12)

1.5Write the method that will return an intwith the sum of the numbers.(8)

1.6Write the method DisplayStatsthat will display all statistics as in the example. This method should call another method to calculate the sum of the numbers. The entire method is given below with some missing parts. You can just copy it to your project and fill in the two missing parts. (3)

privatevoidDisplayStats(...... )

{

int n = Numbers.Length;

intiSmallest = Numbers[0];

intiLargest = Numbers[n - 1];

intiSum = Sum(Numbers);

doubledMean = ...

lblCount.Text = "n = " + n.ToString();

lblSmallest.Text = "Smallest = " + iSmallest.ToString();

lblLargest.Text = "Largest = " + iLargest.ToString();

lblRange.Text = "Range = " + (iLargest - iSmallest).ToString();

lblSum.Text = "Sum = " + iSum.ToString();

lblMean.Text = "Mean = " + dMean.ToString("0.00");

}

[45]

Question 2 (OO development)

Consider a system that will allow the user to enter and save plant details.

2.1Develop a form as in the example.(3)

2.2Develop a class CPlant. The class will be used as base class for all types of plants and no objects of CPlantwill be instantiated.

2.2.1Provide a read/write property for the scientific name of the plant.

2.2.2Provide a protected data member for the height of the plant (double). Provide a read-only property for this data member.

2.2.3Provide a public method, SetHeight, that will return no value and mustbe overridden by sub-classes. The method should have one parameter that will be used to assign a value to the height of the plant. (13)

2.3Develop two sub-classes, CTreeand CFlowerthat will inherit from CPlant.(4)

2.3.1In both sub-classes, override the method SetHeightof the base class. The methods should enforce the rules that the height must be more than 0 and that trees can not be taller than 20 m and flowers can not be taller than 2 m. If this is not true, a height of 0 should be assigned and an appropriate message should be displayed. (Hint: The MessageBoxclass is available in the System.Windows.Formsnamespace.) (8)

2.4In the base class, CPlant:

2.4.1Develop a publicinstance method, Save, that will return a boolvalue to indicate if the save operation was successful or not. The method should receive the file name as a string parameter and save the object's data members to a binary file. The first character in the file should be a 'T'or 'F'depending on whether the instance belongs to a CTreeor CFlowersub-class. Thereafter, the scientific name and height of the plant should be saved. The method should return false if there was a problem with the save operation or if the plant’s height is 0. (16)

2.4.2Develop a static method, Open, that will receive the file name as parameter and return an object of CPlant. The method should read the data of an object from the file. If the first character is a 'T', it should instantiate and return an instance of CTree. If the first character is an'F', it should instantiate and return an instance of CFlower. In both cases, the scientific name and height of the plant must be assigned upon instantiation. (19)

2.5In the form:

2.5.1Write the click event handler of the Savebutton. Declare an object, plant, of CPlant. If the Flowerradio button is checked, an instance of CFlowermust be instantiated and assigned to plant. If the Treeradio button is checked, an instance of CTreemust be instantiated and assigned to plant. The scientific name must be assigned upon instantiation. Call the method plant.SetHeightto set the height of the plant to the value as indicated in the text box. Call the method plant.Saveto save the plant to the file "Plant.bin" (hard coded). Display an appropriate message to indicate whether the save operation succeeded or not. (12)

2.5.2Write the click event handler of the Openbutton. Call the static method CPlant.Open("Plant.bin")and assign its return value to an object, plant, of CPlant. Determine whether the plant is a tree or flower and check the appropriate radio button. Fill the two text boxes from the plant's properties. (8)

[83]

Question 3 (Database access)

A Microsoft Access database, "RaceResults.accdb", will be given to you. It contains the results of a half marathon and full marathon. Develop an interface with which the results can be queried as in the example.

3.1Design the form as in the example.(5)

3.2Write a method, DisplayAllData, that will display all data in the grid. Call the method from the click event handler of the refresh button . You may not use any components that are not visible during run-time from the toolbox. All such components must be instantiated in the code. (10)

3.3Write a method, DisplaySomeData, that will display only the data as selected by the user through the check boxes and radio buttons on the form. If the text box for surname is not empty, all check boxes and radio buttons must be ignored and all athletes with a surname that contains the text in the text box must be displayed. You may copy the common parts of code from the DisplayAllDatamethod. Replace the call to DisplayAllDatain the refresh button with a call to DisplaySomeData. (15)

[30]

MEMORANDUM

Question 1

1.1Form design 

Form name, e.g. CfrmStats

All controls have names (except labels) 

1.2 privatevoidbtnBrowse_Click(object sender, EventArgs e)

{

dlgOpen.InitialDirectory = Application.StartupPath;

dlgOpen.Filter = "Text files (*.txt)|*.txt"; 

dlgOpen.FileName = "";

if (dlgOpen.ShowDialog() == DialogResult.OK) 

{

txtFileName.Text = dlgOpen.FileName; 

ReadTextFile(dlgOpen.FileName); 

int[] Numbers = newint [2]; 

GetNumbers(ref Numbers); 

DisplayStats(Numbers); 

}

}

1.3privatevoidReadTextFile(stringsFile)

{

try 

{

lstbxNumbers.Items.Clear();

using (StreamReader f = newStreamReader(sFile)) 

{

while (!f.EndOfStream) 

lstbxNumbers.Items.Add(f.ReadLine());

}

}

catch (Exception error) 

{

MessageBox.Show(error.Message, "CLASS LIST"); 

}

}

1.4privatevoidGetNumbers(refint[] Numbers)

{

intiNumber, n = 0;

foreach (string s inlstbxNumbers.Items) 

{

if (int.TryParse(s, outiNumber)) 

{

n++;

Array.Resize(ref Numbers, n); 

Numbers[n - 1] = iNumber; 

}

}

Array.Sort(Numbers); 

}

1.5privateint Sum(int [] Numbers)

{

intiSum = 0; 

foreach (intiNumberin Numbers) 

iSum += iNumber; 

returniSum; 

}

1.6privatevoidDisplayStats(int[] Numbers)

{

doubledMean = iSum * 1.0 / n; 

Question 2

2.1Form design 

Form name, e.g. CfrmPlants

All controls have names (except labels) 

2.2abstractclassCPlant

{

2.2.1 publicstringScientificName { get; set; }

2.2.2 protecteddoubledHeight;

publicdouble Height 

{

get { returndHeight; } 

}

2.2.3 publicabstractvoidSetHeight(double _Size);

2.3classCTree : CPlant

{

publicoverridevoidSetHeight(double _Height)

{

dHeight = 0; 

if (_Height > 0 & _Height <= 20) 

dHeight = _Height; 

else

System.Windows.Forms.MessageBox.Show("Invalid size"); 

}

} //CTree

classCFlower : CPlant

{

publicoverridevoidSetHeight(double _Height)

{

dHeight = 0;

if(_Height > 0 & _Height <= 2)  (only difference)

dHeight = _Height;

else

System.Windows.Forms.MessageBox.Show("Invalid size");

}

} //CTree

2.4.1 publicbool Save(string Filename)

{

if (this.dHeight > 0)

{

try

{

using (FileStreamstrm = newFileStream(Filename, FileMode.Create))

{

using (BinaryWriter writer = newBinaryWriter(strm))

{

writer.Write(thisisCTree ? 'T' : 'F');

writer.Write(this.ScientificName);

writer.Write(this.dHeight);

}

}

returntrue;

}

catch { returnfalse; }

}

else

returnfalse;

} //Save

2.4.2 publicstaticCPlant Open(string Filename)

{

using (FileStreamstrm = newFileStream(Filename, FileMode.Open))

{

using (BinaryReader reader = newBinaryReader(strm))

{

charcType = reader.ReadChar();

string _ScientificName = reader.ReadString();

double _Height = reader.ReadDouble();

if (cType == 'T')

returnnewCTree { ScientificName = _ScientificName,

dHeight = _Height };

else

returnnewCFlower { ScientificName = _ScientificName,

dHeight = _Height };

}

}

} //Open

} //CPlant

2.5.1 privatevoidbtnSave_Click(object sender, EventArgs e)

{

CPlant plant = null; 

if (radFlower.Checked)

plant = newCFlower { ScientificName = txtScientificName.Text };

else

plant = newCTree { ScientificName = txtScientificName.Text };

plant.SetHeight(double.Parse(txtSize.Text)); 

if (plant.Save("Plant.bin")) 

MessageBox.Show("Saved successfully."); 

else

MessageBox.Show("Could not save plant.");

} //btnSave_Click

2.5.2privatevoidbtnOpen_Click(object sender, EventArgs e)

{

CPlant plant = CPlant.Open("Plant.bin"); 

radTree.Checked = plant isCTree; 

radFlower.Checked = plant isCFlower; 

txtScientificName.Text = plant.ScientificName; 

txtSize.Text = plant.Height.ToString("0.00"); 

} //btnOpen_Click

Question 3

3.1Design 

Form name, e.g. CfrmRaceResults

All controls, except labels, have names 

3.2privatevoidDisplayAllData()

{

stringConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;"

+ "Data Source=RaceResults.accdb"; 

OleDbConnectioncn = newOleDbConnection(ConnectionString); 

stringsql = "SELECT * FROM Results "; 

OleDbDataAdapterda = newOleDbDataAdapter(sql, cn); 

DataTabletbl = newDataTable();

da.Fill(tbl); 

dgvResults.DataSource = tbl; 

} //DisplayAllData

3.3 stringsql = "SELECT * FROM Results "; 

if (txtSurname.Text == "") 

{

//- Filter type of race

if (radFull.Checked) 

sql += "WHERE Race = 'Full' "; 

else

sql += "WHERE Race = 'Half' "; 

//- Filter gender

sql += " AND (Gender = 'N' "; 

if (chkFemale.Checked) 

sql += "OR Gender = 'F' "; 

if (chkMale.Checked) 

sql += "OR Gender = 'M' "; 

sql += ") ";

//- Order by position or surname

if (radPosition.Checked) 

sql += "ORDER BY Pos"; 

else

sql += "ORDER BY Surname, Name, Pos"; 

}

else

//Search all races, all genders for the surname

sql += "WHERE Surname LIKE '%" + txtSurname.Text + "%' "; 