.NET Framework Fundamentals Practice Lab – C#

Work through this lab to get practice with the concepts taught in this tutorial. The completed project, with source code, is here: Lab1 Source Code Project in C#.

Lab Scenario

You are a developer for Fabrikam, Inc., a small glass business that repairs windows, mirrors, and glass tables. Your task is to create an application that will allow your sales staff to track customers, including their address, phone number, and e-mail. You should do as much error-checking as possible. For example, you should verify that any e-mail address entered by a user is valid.

To achieve your goals, you will create a class that represents a person. Then, you will create properties for the address, phone number, e-mail, and birth date. Finally, you will create a WPF user interface that allows users to enter in information about a user.

Exercise 1: Create the Person Class

Your manager has asked you to create a class that tracks important information about customers.

The main tasks for this exercise are:

  1. Create a WPF Application in C#.
  2. Create the Person class.
  3. Override the ToString method.
  4. Implement the IComparable interface.
  5. Add constructors

Task 1: Create a WPF Application in either C#.

  1. Launch Visual Studio.
  2. Create a new WPF Application project in either Visual C#. Name the application Directory.

Task 2: Create the Person class

  1. Add a class to the project named Person.
  2. Add the following private properties to the new class:
  • _firstName (of type String)
  • _lastName (of type String)
  • _street (of type String)
  • _city (of type String)
  • _state (of type String)
  • _zip (of type String)
  • _phone (of type String)
  • _email (of type string)
  • _birthday (of type DateTime)
  1. Add public properties for each of the private properties. In the Get function, return the value from the corresponding private property. In the Set function, write code to validate the value. Use regular expressions to validate the state, zip code, and e-mail—this will require you to add the System.Text.RegularExpressions namespace. You can search the Internet to find examples of pre-written regular expressions to validate each of these fields. Throw an ArgumentOutOfRangeException exception if the input is invalid.

The code should resemble the following:

class Person
{
	private string _firstName;
	private string _lastName;
	private string _street;
	private string _city;
	private string _state;
	private string _zip;
	private string _phone;
	private string _email;
    private DateTime _birthday;

	public string FirstName
	{
		get
		{
			return _firstName;
		}

		set
		{
			if (value.Length > 0)
				_firstName = value;
			else
				throw new ArgumentOutOfRangeException("You must provide a first name.");
		}
	}

	public string LastName
	{
		get
		{
			return _lastName;
		}

		set
		{
			if (value.Length > 0)
				_lastName = value;
			else
				throw new ArgumentOutOfRangeException("You must provide a last name.");
		}
	}

	public string Street
	{
		get
		{
			return _street;
		}

		set
		{
			if (value.Length > 0)
				_street = value;
			else
				throw new ArgumentOutOfRangeException("You must provide a street.");
		}
	}

	public string City
	{
		get
		{
			return _city;
		}

		set
		{
			if (value.Length > 0)
				_city = value;
			else
				throw new ArgumentOutOfRangeException("You must provide a city.");
		}
	}

	public string State
	{
		get
		{
			return _state;
		}

		set
		{
			if (Regex.IsMatch(value, @"^(?-i:A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$"))
				_state = value;
			else
				throw new ArgumentOutOfRangeException("You must provide a two-character state abbreviation.");
		}
	}

	// Regular expressions taken from: http://msdn.microsoft.com/en-us/library/hs600312%28VS.80%29.aspx

	public string Zip
	{
		get
		{
			return _zip;
		}

		set
		{
			if (Regex.IsMatch(value, @"^\d{5}(\-\d{4})?$"))
				_zip = value;
			else
				throw new ArgumentOutOfRangeException("You must provide a zip code in the format ##### or #####-####.");
		}
	}

	public string Phone
	{
		get
		{
			return _phone;
		}

		set
		{
			if (Regex.IsMatch(value, @"^\d{3}-\d{3}-\d{4}$"))
				_phone = value;
			else
				throw new ArgumentOutOfRangeException("You must provide a phone number in the format ###-###-####.");
		}
	}

	public string Email
	{
		get
		{
			return _email;
		}

		set
		{
			if (Regex.IsMatch(value, @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$"))
				_email = value;
			else
				throw new ArgumentOutOfRangeException("You must provide a valid e-mail.");
		}
	}

    public DateTime Birthday
    {
        get
        {
            return _birthday;
        }

        set
        {
            _birthday = value;
        }
    }
}

Task 3: Override the ToString method

  1. Override the default ToString method. When ToString is called, return the last name and first name of the Person instance, separated by a comma and a space. The ToString method is largely a convenience; in this lab, it will be used to display instances of People added to a list box.

The code should resemble the following:

public override string ToString()
{
	return String.Format("{0}, {1}", LastName, FirstName);
}

Task 4: Implement the IComparable interface

  1. If you do not implement the IComparable interface, arrays of your class cannot be sorted. Implement the IComparable interface to sort the class by last name. Sorting is discussed in more detail in Module 3, so you don’t need to have a complete understanding of it now. It is important, however, to understand how to implement an interface.

The code should resemble the following:

class Person : IComparable
{
// Previous declarations ommited 

	public int CompareTo(object obj)
	{
		return LastName.CompareTo(((Person)obj).LastName);
	}
}

Task 5: Add constructors

  1. Classes automatically have default constructors that take no parameters and leave all properties as null. When using a class with only the default constructor, you can create an instance of it, and then define each of the parameters individually. However, it’s often easier to provide one or more constructors that allow code to define parameters when creating a new instance of the class. For the people class, create constructors that accept the following parameters:
  • No parameters
  • FirstName and Last Name
  • FirstName, Last Name, Street, City, State, and Zip
  • FirstName, Last Name, Street, City, State, Zip, Birthday, PhoneNumber, and Email

The constructors should resemble the following:

public Person()
{
}

public Person(string __firstName, string __lastName)
{
	FirstName = __firstName;
	LastName = __lastName;
}

public Person(string __firstName, string __lastName, string __street, string __city, string __state, string __zip)
{
	FirstName = __firstName;
	LastName = __lastName;
	Street = __street;
	City = __city;
	State = __state;
	Zip = __zip;
}

public Person(string __firstName, string __lastName, string __street, string __city, string __state, string __zip, DateTime __birthday, string __phone, string __email)
{
	FirstName = __firstName;
	LastName = __lastName;
	Street = __street;
	City = __city;
	State = __state;
	Zip = __zip;
	Birthday = __birthday;
	Phone = __phone;
	Email = __email;
}

Exercise 2: Create the User Interface

Task 1: Add text boxes

  1. Your application will allow users to enter information about a customer. Therefore, you should add a TextBox for each public field in the Person class. Name each TextBox something meaningful, such as lastNameTextBox. To make it easier, add a label for each TextBox, and tell the user the format they must enter data in. For the birthday, you can use a single text box, and call Convert.ToDateTime to convert the user’s input into an instance of DateTime. Convert.ToDateTime accepts a variety of different data formats, including mm/dd/yyyy.

Task 2: Add a list box.

  1. At the bottom of the form, add a ListBox. This ListBox will display each of the Person instances the user has created. Name the ListBox peopleListBox.

Task 3: Add a button.

  1. Add a Button to the form. When the user clicks the Button, the application will create an instance of the Person class. You will add this code in the next Exercise. Name the button something meaningful, such as addButton.

The user interface should resemble the following:

Exercise 3: Write the Code

Task 1: Create an ArrayList

  1. Add the System.Collections namespace to your main Window1 code file.
  2. In the Window1 class, create an empty instance of ArrayList named people. ArrayList can store many instances of the Person class. The ArrayList class, and other types of collections, are discussed more in Module 3. The new instance should resemble the following:
ArrayList people = new ArrayList();
  1. Now, generate an event handler for the Window1.Loaded event. In the XAML view, double-click the title bar of Window1 to have Visual Studio automatically generate the event handler. In Window1_Loaded, set the peopleListBox.ItemsSource property to your new instance of people. This causes the list box you added to display the contents of the people ArrayList. The Window1_Loaded event handler should resemble the following:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    peopleListBox.ItemsSource = people;
}

Task 2: Handle the Button.Click event

  1. Double-click the addButton to allow Visual Studio 2008 to automatically generate the event handler.
  2. In the addButton_Click code, create an instance of the Person class called newPerson. Use the values in each TextBox to create the instance. For the birthday, you can call Convert.ToDateTime to convert the birthday the user entered into an instance of DateTime.
  3. Add the instance of newPerson to the people ArrayList.
  4. Call people.Sort to sort the ArrayList by the last name (as defined by your IComparable implementation).
  5. Call the peopleListBox.Items.Refresh method to update the user interface.
  6. Finally, place all the code you wrote in this task in a try block. Catch any exceptions and display the Exception.Message string in a message box so the user is aware of the nature of the proble.m.

The code for the addButton.Click event handler should now resemble the following:

try
{
    Person newPerson = new Person(firstNameTextBox.Text,
		lastNameTextBox.Text,
		streetTextBox.Text,
		cityTextBox.Text,
		stateTextBox.Text.ToUpper(),
		zipTextBox.Text,
		Convert.ToDateTime(birthdayTextBox.Text),
		phoneTextBox.Text,
		emailTextBox.Text);
    people.Add(newPerson);
    people.Sort();
    peopleListBox.Items.Refresh();
}
catch (Exception ex)
{
	MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}

Exercise 4: Run Your Application

Task 1: Verify that your application rejects errors

  1. Run your application. First, click the Add button without entering any data. Verify that a message box appears and displays a useful error to the user.
  2. Now, type valid information for every field except the zip code field. In the zip code field, enter in several letters, which is invalid for a zip code in the United States. Click the Add button, and verify that the application displays a useful error message to the user.
  3. Enter a valid zip code. This time, enter an invalid phone number, and click the Add button. Verify that the application displays a useful error message to the user.

Task 2: Verify that sorting works

  1. Now, enter valid information in all fields to add several instances of the People class. Verify that they are added to the list box, and that the list box is sorted by last name regardless of the order in which you enter the names.

Completed Project Source Code

Having trouble getting it to run? The completed project, with source code, is here: Lab1 Source Code Project in C#.

Return to the .NET Framework Fundamentals Tutorials Table of Contents.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>