.NET Framework Fundamentals Practice Lab – Visual Basic.NET

Work through this lab to get practice with the concepts taught in this tutorial. The completed project, with source code, is here: Lab 1 Project with Source Code in Visual Basic.NET.

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 Visual Basic.NET.
  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 Visual Basic.NET.

  1. Launch Visual Studio.
  2. Create a new WPF Application project in Visual Basic. 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:

Imports System.Text.RegularExpressions

Public Class Person
    Private _firstName As String
    Private _lastName As String
    Private _street As String
    Private _city As String
    Private _state As String
    Private _zip As String
    Private _phone As String
    Private _email As String
    Private _birthday As DateTime

    Public Property FirstName() As String
        Get
            Return _firstName
        End Get

        Set(ByVal value As String)
            If value.Length > 0 Then
                _firstName = value
            Else
                Throw New ArgumentOutOfRangeException("You must provide a first name.")
            End If
        End Set
    End Property

    Public Property LastName() As String
        Get
            Return _lastName
        End Get

        Set(ByVal value As String)
            If value.Length > 0 Then
                _lastName = value
            Else
                Throw New ArgumentOutOfRangeException("You must provide a last name.")
            End If
        End Set
    End Property

    Public Property Street() As String
        Get
            Return _street
        End Get

        Set(ByVal value As String)
            If value.Length > 0 Then
                _street = value
            Else
                Throw New ArgumentOutOfRangeException("You must provide a street.")
            End If
        End Set
    End Property

    Public Property City() As String
        Get
            Return _city
        End Get

        Set(ByVal value As String)
            If value.Length > 0 Then
                _city = value
            Else
                Throw New ArgumentOutOfRangeException("You must provide a city.")
            End If
        End Set
    End Property

    Public Property State() As String
        Get
            Return _state
        End Get

        Set(ByVal value As String)
            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])$") Then
                _state = value
            Else
                Throw New ArgumentOutOfRangeException("You must provide a two-character state abbreviation.")
            End If
        End Set
    End Property

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

    Public Property Zip() As String
        Get
            Return _zip
        End Get

        Set(ByVal value As String)
            If Regex.IsMatch(value, "^\d{5}(\-\d{4})?$") Then
                _zip = value
            Else
                Throw New ArgumentOutOfRangeException("You must provide a zip code in the format ##### or #####-####.")
            End If
        End Set
    End Property

    Public Property Phone() As String
        Get
            Return _phone
        End Get

        Set(ByVal value As String)
            If Regex.IsMatch(value, "^\d{3}-\d{3}-\d{4}$") Then
                _phone = value
            Else
                Throw New ArgumentOutOfRangeException("You must provide a phone number in the format ###-###-####.")
            End If
        End Set
    End Property

    Public Property Email() As String
        Get
            Return _email
        End Get

        Set(ByVal value As String)
            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})$") Then
                _email = value
            Else
                Throw New ArgumentOutOfRangeException("You must provide a valid e-mail.")
            End If
        End Set
    End Property

    Public Property Birthday() As DateTime
        Get
            Return _birthday
        End Get

        Set(ByVal value As DateTime)
            _birthday = value
        End Set
    End Property
End Class

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 Overrides Function ToString() As String
   Return [String].Format("{0}, {1}", LastName, FirstName)
End Function

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:

Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
    Return LastName.CompareTo(DirectCast(obj, Person).LastName)
End Function

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 Sub New()
End Sub

Public Sub New(ByVal __firstName As String, ByVal __lastName As String)
    FirstName = __firstName
    LastName = __lastName
End Sub

Public Sub New(ByVal __firstName As String, ByVal __lastName As String, ByVal __street As String, ByVal __city As String, ByVal __state As String, ByVal __zip As String)
    FirstName = __firstName
    LastName = __lastName
    Street = __street
    City = __city
    State = __state
    Zip = __zip
End Sub

Public Sub New(ByVal __firstName As String, ByVal __lastName As String, ByVal __street As String, ByVal __city As String, ByVal __state As String, ByVal __zip As String, _
     ByVal __birthday As DateTime, ByVal __phone As String, ByVal __email As String)
    FirstName = __firstName
    LastName = __lastName
    Street = __street
    City = __city
    State = __state
    Zip = __zip
    Birthday = __birthday
    Phone = __phone
    Email = __email
End Sub

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:
Dim people As 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 Sub Window1_Loaded_1(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
    peopleListBox.ItemsSource = people
End Sub

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
    Dim newPerson As 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 ex As Exception
    MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.[Error])
End Try

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: Lab 1 Project with Source Code in Visual Basic.NET.

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

Return to the .NET Framework 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>