0% found this document useful (0 votes)
17 views13 pages

M55339A Labguide Module02

The document outlines a lab exercise focused on refactoring a Class Enrollment application using C#. It includes tasks for creating reusable methods to edit, add, and delete student records, as well as implementing validation for student information to ensure data integrity. The exercise emphasizes improving code maintainability and user input validation for better application performance.

Uploaded by

Ahmed ElSangary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views13 pages

M55339A Labguide Module02

The document outlines a lab exercise focused on refactoring a Class Enrollment application using C#. It includes tasks for creating reusable methods to edit, add, and delete student records, as well as implementing validation for student information to ensure data integrity. The exercise emphasizes improving code maintainability and user input validation for better application performance.

Uploaded by

Ahmed ElSangary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

M55339A | All Modules

Module 2: C# Language Concepts

Lab: Extending the Class Enrollment Application

Scenario

You have been asked to refactor the code that you wrote in the lab exercises for module 1 into
separate methods to avoid the duplication of code in the Class Enrollment application.

Also, you have been asked to write code that validates the student information that the user
enters and to enable the updated student information to be written back to the database,
handling any errors that may occur.

Objectives

After completing this lab, you'll be able to:

 Refactor code to facilitate reusability.

 Write C# code that validates data entered by a user.

 Write C# code that saves changes back to a database.

Exercise 1: Refactoring the Enrollment Code

Scenario

In this exercise, you'll refactor the existing code to avoid writing duplicate code.

The application currently allows a user to edit a student's details by pressing Enter. Now, you
want users to be able to initiate the edit process by double-clicking a student in the list. You'll
begin by creating a new method that contains the code for editing a student's details. This will
avoid duplicating and maintaining the code in both event handlers. You'll then call the new
method from both the studentsList_MouseDoubleClick and StudentsList_Keydown events.
While doing this, you also decide to refactor the code for adding and deleting students into
separate methods, so that it can be called from other parts of the application if the need arises.
You'll then run the application and verify that users can press Enter or double-click a student to
edit the student's details, can press Insert to add a new student, and can press Delete to remove
a student.
Task 1: Copy the code for editing a student into the studentsList_MouseDoubleClick event
handler

1. Start Microsoft Visual Studio and from the E:\Allfiles\Mod02\Labfiles\Starter\Exercise


1 folder, open the School.sln solution.

2. In the code for the MainWindow.xaml.cs window, in the studentsList_KeyDown event,


locate the code for editing student details which is in the case Key.Enter block.

3. Copy the code in this block to the clipboard and then paste it into
the StudentsList_MouseDoubleClick method, so that it looks like the following:

4. private void studentsList_MouseDoubleClick(object sender, MouseButtonEventArgs e)

5. {

6. Student student = this.studentsList.SelectedItem as Student;

7.

8. // Use the StudentsForm to display and edit the details of the student

9. StudentForm sf = new StudentForm();

10.

11. // Set the title of the form and populate the fields on the form with the details of the
student

12. sf.Title = "Edit Student Details";

13. sf.firstName.Text = student.FirstName;

14. sf.lastName.Text = student.LastName;

15. sf.dateOfBirth.Text = student.DateOfBirth.ToString("d",


CultureInfo.InvariantCulture); // Format the date to omit the time element

16.

17. // Display the form

18. if (sf.ShowDialog().Value)

19. {

20. // When the user closes the form, copy the details back to the student

21. student.FirstName = sf.firstName.Text;


22. student.LastName = sf.lastName.Text;

23. student.DateOfBirth = DateTime.Parse(sf.dateOfBirth.Text,


CultureInfo.InvariantCulture);

24.

25. // Enable saving (changes are not made permanent until they are written back to
the database)

26. saveChanges.IsEnabled = true;

27. }

28. }

Task 2: Run the application and verify that the user can now double-click a student to edit
their details

1. Build the solution and resolve any compilation errors.

2. Change Kevin Liu's last name to Cook by pressing Enter in the main application window.

3. Verify that the updated data is copied back to the student list and that the Save
Changes button is now enabled.

4. Change George Li's name to Darren Parker by double-clicking his row in the main
application window.

5. Verify that the updated data is copied back to the student list.

6. Close the application.

7. Review the code you have just written, and notice that we now have two identical
sections of code.

It's poor coding style to have repeated blocks of code. Apart from the fact that it's not very
efficient, it gives rise to a number of problems around maintainability. You should refactor the
repeated code, and the usual method is to extract a method. We'll do that in the next task.

Task 3: Refactor the logic that edits, adds, and deletes a student

1. Select all the code inside the StudentsList_MouseDoubleClick method (excluding the
opening and closing brackets).
2. Right click the mouse and choose Quick Actions and Refactorings... (or use
choose Edit in the menu and then choose Refactor). Then choose Extract Method.

3. The Rename: New Method alert will pop up and you can the type the
name editStudent for the method name, and then click the Apply button to dismiss the
popup.

If you prefer, you can also do this manually, without using the Visual Studio refactoring tools. If
you can type fast, it can be quicker to just type out the code directly.

4. Verify that your code now looks like the following:

5. private void studentsList_MouseDoubleClick(object sender, MouseButtonEventArgs e)

6. {

7. editStudent();

8. }

9.

10. private void editStudent()

11. {

12. Student student = this.studentsList.SelectedItem as Student;

13.

14. // Use the StudentsForm to display and edit the details of the student

15. StudentForm sf = new StudentForm();

16.

17. // Set the title of the form and populate the fields on the form with the details of the
student

18. sf.Title = "Edit Student Details";

19. sf.firstName.Text = student.FirstName;

20. sf.lastName.Text = student.LastName;

21. sf.dateOfBirth.Text = student.DateOfBirth.ToString("d",


CultureInfo.InvariantCulture); // Format the date to omit the time element

22.
23. // Display the form

24. if (sf.ShowDialog().Value)

25. {

26. // When the user closes the form, copy the details back to the student

27. student.FirstName = sf.firstName.Text;

28. student.LastName = sf.lastName.Text;

29. student.DateOfBirth = DateTime.Parse(sf.dateOfBirth.Text,


CultureInfo.InvariantCulture);

30. studentsList.Items.Refresh();

31.

32. // Enable saving (changes are not made permanent until they are written back to
the database)

33. saveChanges.IsEnabled = true;

34. }

35. }

36. In the studentsList_KeyDown event handler, locate the code for editing student details
which is in the case Key.Enter block (not including the break statement), and replace it
with a call to editStudent();.

37. Verify that the beginning of the code for studentsList_KeyDown resembles the
following:

38. private void studentsList_KeyDown(object sender, KeyEventArgs e)

39. {

40. switch (e.Key)

41. {

42. // If the user pressed Enter, edit the details for the currently selected student

43. case Key.Enter:

44. editStudent();

45. break;
46.

47. // If the user pressed Insert, add a new student

48. case Key.Insert:

You will get compilation errors, because the following cases depended on the code earlier in the
switch statement. Now that this code has been moved into another method, we'll need to fix
this.

49. In the case Key.Insert block, change the line:

50. sf = new StudentForm();

to:

var sf = new StudentForm();

51. In the case Key.Delete block, change the line:

52. student = this.studentsList.SelectedItem as Student;

to:

var student = this.studentsList.SelectedItem as Student;

53. In the same way, refactor the code in the case Key.Insert code block in
the studentsList_KeyDown method into a method called addStudent that takes no
parameters.

54. Call this method from the case Key.Insert code block in
the studentsList_KeyDown method.

55. In the same way, refactor the code in the case Key.Delete code block in
the studentsList_KeyDown method into a method called removeStudent that takes a
student as a parameter.

56. Call this method from the case Key.Delete code block in
the studentsList_KeyDown method.

57. Verify that your studentsList_KeyDown method looks like the following:

58. // When the user presses a key, determine whether to add a new student to a class,
remove a student from a class, or modify the details of a student

59. private void studentsList_KeyDown(object sender, KeyEventArgs e)

60. {
61. switch (e.Key)

62. {

63. // If the user pressed Enter, edit the details for the currently selected student

64. case Key.Enter:

65. editStudent();

66. break;

67.

68. // If the user pressed Insert, add a new student

69. case Key.Insert:

70. addStudent();

71. break;

72.

73. // If the user pressed Delete, remove the currently selected student

74. case Key.Delete:

75. removeStudent();

76. break;

77. }

78. }

Task 4: Verify that students can still be added and removed from the application

1. Build the solution and resolve any compilation errors.

If needed, you can verify your changes by looking at the completed solution in E:\Allfiles\
Mod02\Labfiles\Solution\Exercise 1\School\MainWindow.xaml.cs.

2. Run the application.

3. Add a new student by pressing the Insert key to display the new student in the Class
3C window, and verify that it contains no data.

4. Enter details for Dominik Dubicki, whose date of birth is 02/03/2006, and verify that the
new student is added to the student list.
5. Delete the student Run Liu and verify that the prompt window appears and the student
is removed from the student list.

6. Close the application.

Task 5: Debug the application and step into the new method calls

1. Add a breakpoint at the start of the switch statement in


the studentsList_KeyDown method.

2. Debug the application.

3. Edit the row for Kevin Liu by pressing Enter.

4. Step over the code, watching the Call Stack window and the Locals window, until you
reach the editStudent method call, and then step into that method.

5. Step out of the editStudent method.

6. Cancel editing the student's details, and then continue debugging.

7. Add a new student by pressing the Insert key.

8. Step over the code until you reach the addStudent method call, and then step into that
method.

9. Step out of the addStudent method.

10. Cancel adding a new student, and then continue debugging.

11. Delete the row for George Li by pressing Delete.

12. Step over the code until you reach the removeStudent method call, and then step into
that method.

13. Step out of the removeStudent method.

14. Cancel deleting the student.

15. Stop debugging the application.

16. In Visual Studio, delete all breakpoints and then close the solution.

Results : After completing this exercise, you should have updated the application to refactor
duplicate code into reusable methods.

Exercise 2: Validating Student Information

Scenario
In this exercise, you'll write code that validates the information that a user enters for a student.
Up until this point, almost anything can be entered as student data, and fields can be left blank.
This means, for example, that a student could be added to the student list with no last name or
with an invalid date of birth. You'll write code to check that when adding or editing a student,
the first name and last name fields for the student contain data. You'll also write code to check
that the date of birth entered is a valid date and that the student is at least five years old (you
might have noticed previously that you could enter an invalid date, resulting in the application
crashing). Finally, you'll run the application and test your validation code.

Task 1: Run the application and observe that student details that are not valid can be entered

1. In Visual Studio, from the E:\Allfiles\Mod02\Labfiles\Starter\Exercise 2 folder, open


the School.sln solution.

2. Build the solution and resolve any compilation errors.

3. Run the application.

4. Press Insert to display the new student window.

5. Leave the First Name and Last Name boxes empty, and type 10/06/3012 in the Date of
Birth text box.

6. Click OK and verify that a new row has been added to the student list, containing a blank
first name, blank last name, and a negative age.

7. Close the application.

Task 2: Add code to validate the first name and last name fields

1. In the StudentForm.xaml.cs code, at the beginning of the ok_Click method, add a


statement to check if the First Name text box is empty, and if it is empty, display a
message box with the caption Error and the text The student must have a first name,
and then exit the method:

2. // Check that the user has provided a first name

3. if (String.IsNullOrEmpty(this.firstName.Text))

4. {

5. MessageBox.Show("The student must have a first name", "Error",

6. MessageBoxButton.OK, MessageBoxImage.Error);

7. return;
8. }

9. In the ok_Click method, add another statement to check if the Last Name text box is
empty, and if it is empty, display a message box with the caption Error and the text The
student must have a last name, and then exit the method:

10. // Check that the user has provided a last name

11. if (String.IsNullOrEmpty(this.lastName.Text))

12. {

13. MessageBox.Show("The student must have a last name", "Error",

14. MessageBoxButton.OK, MessageBoxImage.Error);

15. return;

16. }

Task 3: Add code to validate the date of birth

1. In the ok_Click method, in the StudentForm.xaml.cs code, add a statement to check if


the Date of Birth text box contains a valid date, and otherwise display a message box
with the caption Error and the text The date of birth must be a valid date, and then exit
the method:

2. // Check that the user has entered a valid date for the date of birth

3. DateTime result;

4. if (!DateTime.TryParse(this.dateOfBirth.Text, out result))

5. {

6. MessageBox.Show("The date of birth must be a valid date", "Error",

7. MessageBoxButton.OK, MessageBoxImage.Error);

8. return;

9. }

10. In the ok_Click method in StudentForm.xaml.cs code, add a statement to calculate the
student's age in years , and check that it is greater than five, otherwise display a
message box with the caption Error and the text The student must at least 5 years old,
and then exit the method:

11. // Verify that the student is at least 5 years old


12. TimeSpan age = DateTime.Now.Subtract(result);

13. if (age.Days / 365.25 < 5)

14. {

15. MessageBox.Show("The student must be at least 5 years old", "Error",

16. MessageBoxButton.OK, MessageBoxImage.Error);

17. return;

18. }

Task 4: Run the application and verify that student information is now validated correctly

1. Build the solution and resolve any compilation errors.

2. Run the application.

3. Press Insert to display the new student window.

4. Leave the First Name, Last Name, and Date of Birth text boxes empty.

5. Click OK, verify that an error message appears containing the text The student must
have a first name, and then close the error message.

6. Type Darren in the First Name text box, and then click OK.

7. Verify that an error message appears containing the text The student must have a last
name, and then close the error message.

8. Type Parker in the Last Name text box, and then click OK.

9. Verify that an error message appears containing the text The date of birth must be a
valid date, and then close the error message.

10. Type 10/06/3012 in the Date of Birth text box, and then click OK.

11. Verify that an error message appears containing the text The student must be at least 5
years old, and then close the error message.

12. Amend the date to 10/06/2006, click OK, and then verify that Darren Parker is added to
the student list with an age appropriate to the current date.

13. Close the application.

14. In Visual Studio, close the solution.

Results : After completing this exercise, student data will be validated before it is saved.
Exercise 3: Saving Changes to the Class List

Scenario

In this exercise, you'll write code that saves changes in the student list to the database. The
database is using SQLite, which is a small, self-contained, file-based database engine. It's a good
option for simple applications that don't require a sophisticated relation database engine at the
back-end, or for use as an application file format to persist application state.

Currently, every time the user closes and opens the application, they are presented with the
original student list as it existed when they first ran the application, regardless of any changes
they may have made. You'll write code to save changes back to the database when the user
clicks the Save Changes button. Finally, you'll run your application and verify that the changes
you make to student data are persisted between application sessions.

Task 1: Verify that data changes are not persisted to the database

1. In Visual Studio, from the E:\Allfiles\Mod02\Labfiles\Starter\Exercise 3 folder, open


the School.sln solution.

2. Build the solution and resolve any compilation errors.

3. Run the application.

4. Change Kevin Liu's last name to Cook by pressing Enter in the main application window

5. Verify that the updated data is copied to the student list and that the Save
Changes button is enabled.

6. Click Save Changes.

7. Delete the student George Li, and then click Save Changes.

8. Close the application.

9. Run the application again and verify that it displays the original list of students. The
changes that you just made have not been persisted.

10. Close the application.

Task 2: Add code to save changes back to the database

1. Add code to perform the following tasks when a user clicks Save Changes:

o Call the SaveChanges method of the schoolContext object.

o Disable the Save Changes button.


2. Verify that your saveChanges_Click method looks like the following:

3. // Save changes back to the database and make them permanent

4. private void saveChanges_Click(object sender, RoutedEventArgs e)

5. {

6. schoolContext.SaveChanges();

7. saveChanges.IsEnabled = false;

8. }

Task 3: Run the application and verify that data changes are persisted to the database

1. Run the application.

2. Change the last name of Kevin Liu to Cook.

3. Verify that the Save Changes button is enabled.

4. Click on Save Changes and verify that the button is now disabled.

5. Remove the student George Li.

6. Verify that the Save Changes button is enabled.

7. Click on Save Changes and verify that the button is now disabled.

8. Close the application.

9. Run the application again.

10. Verify that the changes have been persisted, and that the first student is still called Kevin
Cook and George Li has not been restored to the class.

Note: If you want to reset the database to its initial state, you can delete the school.db file and
it will be recreated with the initial values when the application is next run.

11. Close the application.

Results: After completing this exercise, modified student data will be saved to the database.

You might also like