Hosting - .Net Code

C#/Visual Basic Exercise 5 – Solution

For the solution to this exercise, let’s start by creating the tools we will need, that is, the classes and the Console Application.

There will be two classes, the validator and the Client. Remember to name classes with a singular name because it will be the representation of one object of this type.

You should now have a ready console application as well as two classes like the following.

Visual Basic

Visual Basic solution explorer

C#

Solution Explorer

Client

Visual Basic

Option Strict On
Option Explicit On

Public Class Client

End Class

C#

namespace Exercise5
{
    public class Client
    {

    }
}

Validator

Visual Basic

Option Strict On
Option Explicit On

Public Module Validator

End Module

C#

namespace Exercise5
{
    public static class Validator
    {

    }
}

As you can probably notice, my Validator class is static (we use a Module in Visual Basic) which makes sure that there is only one instance of this class (module) in the software. Another advantage of this approach will be that we can call this class without instanciating it, that is, by calling Validator.MyMethod() directly! A static class (module) might apply if we want to use the Validator in multiple places but be careful not to use too many static classes (modules)! Also, both classes are public (because we want to be able to use them from our Program class).

If we review our steps, we have step 1, 2 and 5 completed! It’s time to add some Properties to the Client class. We need to add FirstName, LastName, Email, Address and PhoneNumber.

Client Class

Visual Basic

Option Strict On
Option Explicit On

Public Class Client
    'Properties
    Public Property FirstName As String
    Public Property LastName As String
    Public Property Email As String
    Public Property Address As String
    Public Property PhoneNumber As String

    'Constructors
    Public Sub New(FirstName As String,
                   LastName As String,
                   Email As String,
                   Address As String,
                   PhoneNumber As String)
        Me.FirstName = FirstName
        Me.LastName = LastName
        Me.Email = Email
        Me.Address = Address
        Me.PhoneNumber = PhoneNumber
    End Sub

    Public Sub New()
        FirstName = "Alexandre"
        LastName = "Sauve"
        Email = "test@test.com"
        Address = "450 testing St."
        PhoneNumber = "8888888888"
    End Sub

    'ToString method override (for user friendly client output)
    Public Overrides Function ToString() As String
        Return "First Name: " & FirstName & vbCrLf &
               "Last Name: " & LastName & vbCrLf &
               "Email: " & Email & vbCrLf &
               "Address: " & Address & vbCrLf &
               "Phone Number: " & PhoneNumber & vbCrLf
    End Function
End Class

C#

namespace Exercise5
{
    public class Client
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
        public string PhoneNumber { get; set; }

        public Client(string FirstName,
                      string LastName,
                      string Email,
                      string Address,
                      string PhoneNumber)
        {
            this.FirstName      = FirstName;
            this.LastName       = LastName;
            this.Email          = Email;
            this.Address        = Address;
            this.PhoneNumber    = PhoneNumber;
        }

        public Client()
        {
            FirstName   = "Alexandre";
            LastName    = "Sauve";
            Email       = "Test@hotmail.com";
            Address     = "450 Test St.";
            PhoneNumber = "2833939292";
        }

        public override string ToString()
        {
            return "FirstName: " + FirstName + "\n" + 
                   "LastName: " + LastName + "\n" + 
                   "Email: " + Email + "\n" + 
                   "Address: " + Address + "\n" + 
                   "PhoneNumber: " + PhoneNumber;
        }
    }
}

I added the two requested constructors as well, one parameters and one default. Why is there the this. keyword before my properties in the Client constructor? That’s because I am using the same names for my local variables and my parameters, the compiler isn’t sure which one is which so I have to be a bit more specific and tell it that I want the property set to the value of the local variable. Finally, I decided to add all string parameters since the phone number might have different implementation and because I don’t want to do a lot of validation since we’re talking about classes and not validation!

I decided to add the ToString() method for convenience when we will want to display the Client class properties in the console.

Our client class is now complete and ready to be used in our program.

Validator Class

The validator class is meant to offer a few methods to validate components of the user input. It would be a better idea to separate the validation if we had more forms to validate, but we are still going to use this class in case we want to add more in the future. The input we are going to validate are : PhoneNumber (simply the length) and the email using a regular expression.

Visual Basic

Option Strict On
Option Explicit On

Imports System.Text.RegularExpressions

Public Module Validator
    Public Function FieldIsEmpty(ByVal Value As String) As Boolean
        If String.IsNullOrEmpty(Value) Then
            Return True
        End If
        Return False
    End Function

    Public Function PhoneNumberIsValid(ByVal PhoneNumber As String) As Boolean
        If PhoneNumber.Length = 10 Then
            Return True
        End If
        Return False
    End Function

    Public Function EmailIsValid(ByVal Email As String) As Boolean
        If Regex.IsMatch(Email, "^[^@]+@[^@]+\.[^@]+$") Then
            Return True
        End If
        Return False
    End Function
End Module

C#

using System.Text.RegularExpressions;

namespace Exercise5
{
    public static class Validator
    {
        public static bool FieldIsEmpty(string Value)
        {
            if (String.IsNullOrEmpty(Value))
                return true;
            return false;
        }

        public static bool PhoneNumberIsValid(string PhoneNumber)
        {
            if (PhoneNumber.Length == 10)
                return true;
            return false;
        }

        public static bool EmailIsValid(string Email)
        {
            if (Regex.IsMatch(Email, "^[^@]+@[^@]+\\.[^@]+$"))
                return true;
            return false;
        }
    }
}

The first method simply verifies if the provided value is null or empty and return true if that`s not the case and false if that is the case. Why is the method inverted like this? That’s because of the name I chose, FieldIsEmpty -> yes (true), if it’s not empty, it’s going to return false. If you prefer to have the IsValid – True and IsInvalid – False pattern, you can rename the method FieldIsNotEmpty. You will then have to be careful in the main processing because every call to this method will be inverted for you.

You should notice that all the methods are static since this is a static class (that doesn’t mather in Visual Basic since it’s a Module, this is done implicitly), all methods must have the static modifier. The second method, PhoneNumberIsValid, verifies that the phone number is a 10 digits phone number, nothing out of the ordinary and not the best validation but it will do for our example.

The third method uses a Regular expression, I will talk a bit more about regular expressions in another tutorial but for now you must know that the string sent as a parameter to the IsMatch method and that looks like hieroglyphs is what the email will be tested against. If it passes, the method returns True and if it fails, the method returns False. You may notice that I added a special using (imports in Visual Basic) to access the Regex class because it is contained in another namespace (or container if you prefer).

We got both our classes done and the steps 3, 4, 6, 7 are complete! We’re now ready for user input.

User Input

Visual Basic

Option Strict On
Option Explicit On

Module Program
    Sub Main()
        'Validate all input fields to retrieve information from the user about the client
        Dim FirstName As String = String.Empty
        While Validator.FieldIsEmpty(FirstName)
            Console.WriteLine("Please enter the client first name: ")
            FirstName = Console.ReadLine()
        End While

        Dim LastName As String = String.Empty
        While Validator.FieldIsEmpty(LastName)
            Console.WriteLine("Please enter the client last name: ")
            LastName = Console.ReadLine()
        End While

        Dim Email As String = String.Empty
        While Validator.FieldIsEmpty(Email) Or
              Not Validator.EmailIsValid(Email)
            Console.WriteLine("Please enter the client email: ")
            Email = Console.ReadLine()
        End While

        Dim Address As String = String.Empty
        While Validator.FieldIsEmpty(Address)
            Console.WriteLine("Please enter the client address: ")
            Address = Console.ReadLine()
        End While

        Dim PhoneNumber As String = String.Empty
        While Validator.FieldIsEmpty(PhoneNumber) Or
              Not Validator.PhoneNumberIsValid(PhoneNumber)
            Console.WriteLine("Please enter the client phone number: ")
            PhoneNumber = Console.ReadLine()
        End While

        'Create a new client object to store the client values
        Dim NewClient As New Client(FirstName,
                                    LastName,
                                    Email,
                                    Address,
                                    PhoneNumber)

        'Display the client in the console with our implemented ToString method
        Console.Write(NewClient.ToString())
        Console.ReadKey()
    End Sub
End Module

C#

using System;

namespace Exercise5
{
    class Program
    {
        static void Main(string[] args)
        {
            //Validate and store all client input values
            string FirstName = String.Empty;
            while(Validator.FieldIsEmpty(FirstName))
            {
                Console.WriteLine("Please enter the client first name: ");
                FirstName = Console.ReadLine();
            }

            string LastName = String.Empty;
            while (Validator.FieldIsEmpty(LastName))
            {
                Console.WriteLine("Please enter the client last name: ");
                LastName = Console.ReadLine();
            }

            string Email = String.Empty;
            while (Validator.FieldIsEmpty(Email) ||
                   !Validator.EmailIsValid(Email))
            {
                Console.WriteLine("Please enter the client email: ");
                Email = Console.ReadLine();
            }

            string Address = String.Empty;
            while (Validator.FieldIsEmpty(Address))
            {
                Console.WriteLine("Please enter the client address: ");
                Address = Console.ReadLine();
            }

            string PhoneNumber = String.Empty;
            while (Validator.FieldIsEmpty(PhoneNumber) ||
                  !Validator.PhoneNumberIsValid(PhoneNumber))
            {
                Console.WriteLine("Please enter the client phone number: ");
                PhoneNumber = Console.ReadLine();
            }

            //At this point we have all the required information, we can create our object!
            Client NewClient = new Client(FirstName,
                                          LastName,
                                          Email,
                                          Address,
                                          PhoneNumber);

            //Display the client with the ToString method
            Console.Write(NewClient.ToString());
            Console.ReadKey();
        }
    }
}

Each validation phase is similar, we will accept user input until the result satisfies the stated conditions by using a while loop. You can use this strategy whenever you want to force the user to input a correct value in the console. Lastly, we create our client with all the gathered information and use the ToString() method from our newly created user to display its properties.

This exercise was a little more complicated than what we’ve done so far. I strongly suggest that you take more time to understand what is going on and give this code some testing on your own. Don’t be afraid to use breakpoints and look things up on the Internet.

Here is the final result

Result Exercise 5

I you have any questions related to this exercise, feel free to post them in the comments!

Youtube

Visual Basic

C#

Next article C#/Visual Basic - Windows Forms (Part 1)
Previous article C#/Visual Basic Exercise 5 - All about classes!

Related posts

0 Comments

No Comments Yet!

You can be first to comment this post!

Leave a Comment

Your data will be safe! Your e-mail address will not be published. Also other data will not be shared with third person. Required fields marked as *