Dear visitor, thanks for stopping by! If you want, you can follow all updates on Snowball.be via RSS. You can also follow me on Twitter or Facebook. More interesting posts from other Microsoft Regional Directors can be found at The Region.
Gill Cleeren     .net | C# | Enterprise Library     January 7, 2007    

For some of my latest projects, I have been using Enterprise Library for the Data Access Layer (combined with other technologies).
The week before Christmas, Tom Hollander, who leads development of the Enterprise Library, announced the first CTP of the enterprise library V3.0.
This weekend, I decided to do a first test drive with it, since a lot of features that are now included (or will be included in the final release) seem very useful in the creation of enterprise applications.
In this tutorial, I will explain the Validation Application Block, a complete new application block included in version 3 of the library. I’ll create some samples on how you can use the Validation block and I’ll also create a custom validator.

Installation of the enterprise library V3.0

As you probably guessed, to start using the EntLib V3.0, you should install the files. You can get the CTP from the all-new CodePlex.com site, entirely devoted to Enterprise Library. You should of course have Visual Studio 2005 installed on your PC. If you want to use the Guidance Packages, you’ll also need the Guidance Automation Extensions. You can read any further requirements in the Readme included in the download.
When installed, you can find the library under Microsoft Patterns and Practices. As you can see, one of the items there is the Enterprise Library Source Code Installer. You can use this to create more than one “working copies” of the code included in the EntLib. Run this, you’ll be needing this if you want to follow along with this tutorial. I extracted the files to “C:\EntLib3Src”.
In the folder, go to App Blocks à Src à Validation and open the project file you find here (Validation.csproj). To finish the installation, build the project. You’ll now have the DLLs needed to use the Validation Application Block.

OK, but what is this Validation block then?

Before I begin with the explanation on how to use the Validation Block, let me first introduce you to what it actually does and where it can be used.

From Tom Hollander’s Blog:
The Validation Application Block will include a comprehensive library of common validation rules that apply to primitive data types. For example, we'll include rules like string length, numeric range, date range, regular expressions and so on. However your applications will typically deal with more complex objects such as Customers or Orders (yes, here at Microsoft we assume every application is based on Northwind ;-), so while the built-in Validators should be great building blocks, you'll need to do some additional work to specify how these primitive rules apply to more complex objects. We plan on letting you do this in two primary ways: in configuration (which is ideal if you want the rules to be easily changed after deployment), or in code (which allows better encapsulation of rules and ensures the behavior won't change unless the code does).

You can do validation using configuration, or you can do it in code. In this tutorial, I’ll be focusing on the code-approach using attributes, mainly because there is no support yet in the “Enterprise Library Configuration-tool” for this at this moment.

Included in the library are a number of often needed validations: “not null”, string length, null… You can take a look at the included validators in the project you built earlier under Validation à Validators. In the final release, more will be added. In the first part of this tutorial, I’ll be using some of these to show you how it works.
Of course, this collection will never be enough for full-scale enterprise applications, so you have the possibility to write your own validators, as I’ll show later in this tutorial.

I’m convinced about the VAB! How can I use it?

OK, now that you know what the block is about, let’s start using it. As said, in this first part of my tutorial, I’ll use some of the included validators.

Create a new project in Visual Studio (I used a Winforms project and named it TestValidationApplicationBlock). While you’re at it, add a class library to the solution (for example: BLCustomers). This will be used as Business Layer in the sample application, and the objects in this layer will need to be validated using the Validation Application Block.

In the class library, add a new class, Customer for example. Add 2 properties, name and email for example (you can of course take whatever you want).

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using MyCustomValidators;

namespace BLCustomers
{
    public class Customer
    {
        private string name;
        private string email;

        public Customer() { }

        public Customer(string name, string email)
        {
            this.name = name;
            this.email = email;
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public string Email
        {
            get { return email; }
            set { email = value; }
        }
   }
}

To enable validation on this class, we first need to reference the necessary DLLs in this project. Right-click the “class library project” and select “Add reference”. Browse to where you built the enterprise library validation project, and in the bin folder, you’ll find 3 DLLs (Microsoft.Practices.EnterpriseLibrary.Common.dll, Microsoft.Practices.EnterpriseLibrary.Validation.dll and Microsoft.Practices.ObjectBuilder.dll). Reference these, and also create a reference to System.Configuration (which you’ll find under the .net tab).

Now, we want to add some validation on the name and email properties of the Customer class. As said, we’ll use attributes on the properties. For example, we want the name to be a string with a length greater than 0, and we want both the email and the name to be not null.

For this, we add the NotNullValidator and StringLengthValidator as attributes. The StringLengthValidator is overloaded: the first number stands for the lowerbound (we don’t want it to have a length of zero) and the second is the upperbound.
Notice the extra “using” to be able to use the Validator attributes.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using MyCustomValidators;

namespace BLCustomers
{
    public class Customer
    {
        private string name;
        private string email;

        public Customer() { }

        public Customer(string name, string email)
        {
            this.name = name;
            this.email = email;
        }

        [NotNullValidator]
        [StringLengthValidator(1, 100)]
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        [NotNullValidator]
        public string Email
        {
            get { return email; }
            set { email = value; }
        }
   }
}

At the moment, nothing actually triggers this validation yet. We can do this in several ways.
The simplest manner is using the Validation façade, included in the VAB, as shown next.

I have created a very simple interface in the Forms project, where the user can enter a name and email, as shown below.

1.JPG

In the click-event of the Validate button, the Customer instance is created. After that, the ValidateCustomer method is called, which is a method in the business layer. 

        private void btnValidate_Click(object sender, EventArgs e)
        {
            Customer customer = new Customer(txtName.Text, txtEmail.Text);

            MessageBox.Show(customer.ValidateCustomer());
        }


Now, let’s take a look at the actual validation. This is performed in the business layer in the Customer class. Let’s look at the code.

        public string ValidateCustomer()
        {
            ValidationResults results = Validation.Validate(this);
            string message = string.Empty;

            if (!results.IsValid)
            {
                // if this is not valid, we'll loop through the results to create the message
                foreach (ValidationResult result in results)
                {
                    message += result.Message;
                }
            }
            if(message.Equals(string.Empty))
            {
                message = "The input is valid!";
            }
            return message;
        }

The ValidationResults is a collection of ValidationResult objects. When the Validate method is called, each attribute on every property is checked, and whenever one does not validate correctly, a new instance of ValidationResult is added to the collection. After the validation, you can loop through the collection to check the messages that were added (sort of “exception-messages” that are added). If all validation goes well, the IsValid method will return true.


This concludes the first way of doing validation: we have not used the configuration files (which is however done very often with the enterprise library). We did use attributes and the Validate method to check if the object was valid.

I said “the first way”… That means there are more ways of performing validation without using the configuration files? Yes, there is. In fact, this second method will look more familiar if you have used previous versions of the enterprise library.
Other application blocks often make use of Factory methods (like for example the data access application block). The VAB also has a way of doing this.

public string ValidateCustomerWithFactoryMethod()
        {
            string message = string.Empty;

            IValidator<Customer> validatorCustomer = ValidationFactory.CreateValidator<Customer>();

            ValidationResults results = validatorCustomer.Validate(this);

            if (!results.IsValid)
            {
                // if this is not valid, we'll loop through the results to create the message
                foreach (ValidationResult result in results)
                {
                    message += result.Message;
                }
            }
            if (message.Equals(string.Empty))
            {
                message = "The input is valid!";
            }
            return message;
        }


The result of the above code is the same.

Creating your own Validators

Up until now, we have used only the built-in validators. Nevertheless these are useful, a day will come (and if you’re developing large applications, it will come soon…) that they will not suffice. Therefore, the architecture of the VAB is open so you can easily create your own validators.
In this second part, I’ll show you how.

Let’s assume that we want to create an email validator. For the sake of simplicity, we’ll have it check if the string contains an “@” character.

To start, let’s create an additional project in our solution named MyCustomValidators. Make this project a class library too. Add the same references as you did with the BLCustomers project.

Create a class named EmailValidatorAttribute. This will be the attribute we’ll be adding to our Customer object later on.
For a class to be used as an attribute, it must among others things, inherit from Attribute. We’ll have it inherit from ValidatorAttribute, that already inherits from Attribute.

public sealed class EmailValidatorAttribute : ValidatorAttribute
    {
        public override IValidator CreateValidator()
        {
            return new EmailValidator(this.GetMessageTemplate());
        }
    }

Now, let’s create the actual EmailValidator class, which is where the actual validation will take place.

    public class EmailValidator : ValidatorBase
    {
        public EmailValidator()
            : this(null)
        { }

        public EmailValidator(string messageTemplate)
            : base(messageTemplate)
        { }

        protected override void DoValidate(object target, ValidationResults validationResults)
        {
            try
            {
                string converted = (string)target;
                if (!converted.Contains("@"))
                {
                    this.AddResult(validationResults, new ValidationResult(this.MessageTemplate));
                }
            }
            catch
            {
                this.AddResult(validationResults, new ValidationResult(this.MessageTemplate));
            }
        }

        protected override string GetDefaultMessageTemplate()
        {
            return "This is not a valid emailaddress since it does not contain the @ character";
        }
    }

It inherits from ValidatorBase, and overrides 2 methods in particular: DoValidate and GetDefaultMessageTemplate.
In the DoValidate method, the actual validation is done: here, I have written a few lines of simple code to check whether the passed string contains a “@”.
If the string does not include this character (and is therefore not an email address), a new instance of ValidationResult is added to the collection. The message that is included here is the string returned from GetDefaultMessageTemplate.

Now, we can use our own attribute. Return to the Customer class and add the EmailValidator-attribute to the email property.

        [NotNullValidator]
        [StringLengthValidator(1, 100)]
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

When you run the application again, and you enter a string without a @ as email, you’ll get a message window with the message you included in the EmailValidator class.


I hope this will help you understand the Validation Application Block. If you have any questions, please feel free to post them.

  Posted on: Sunday, January 07, 2007 9:51:16 PM (Romance Standard Time, UTC+01:00)   |   Comments [4]
         
4/16/2014   3:04:49 PM
 Welcome to Snowball.be
Hello and welcome to snowball.be!

My name is Gill Cleeren, I'm a Microsoft Regional Director and an MVP ASP.NET.
On Snowball.be, you'll find all kind news and articles on .net, ASP.NET, WPF, Silverlight and Microsoft in general.
More on me can be found on my about page.

Should you have any questions, don't hesitate to contact me by Send mail to the author(s) .

 Partner sites
 Most popular tags
.net (124) .net 3.0 (6) .net 3.5 (18) .NET 4 (18) .NET Show (1) ADO.net (4) ASP.net (53) ASP.net AJAX (4) ASP.NET MVC (3) Atlas (12) Azure (2) Blend (2) Book (6) Book review (4) C# (43) Case studies (1) Chopsticks (3) Community (10) Community Day (16) Consoles (1) Database (1) DevDays09 (4) DotNetNuke (4) Efficiency (57) Enterprise Library (5) Events (62) Expression (7) Games (3) Hardware (9) Internet (18) IT (1) jQuery (1) LightSwitch (3) Links (11) LINQ (4) Mac (2) Metro (1) Microsoft (75) Mix 07 (6) Mix 08 (4) Mix 09 (1) Mix 11 (1) Movies (4) MVP (5) MVP Summit 2008 (3) mvvm (1) NDCOslo (1) Office 2007 (10) Other (8) PDC (22) PDC2008 (10) Personal (36) ppt (9) Programming (52) Programming tools (22) Regional Director (2) Silverlight (143) Silverlight Advent Calendar (24) sl4 (44) SL5 Data and Services Cookbook (2) Slide decks (13) Snowball (13) Software (20) Microsoft (25) Speaking (15) SQL Server (10) TechDays (13) TechEd (14) telerik (6) Telerik (6) TFS (1) Twitter (1) Vista (73) Vista Tricks (9) Visual Studio.net (38) Visug (33) VS2010 (8) Wallpaper (2) WCF (2) Webcasts (9) Webinars (5) Windows (41) Windows 7 (5) Windows 8 (3) Windows Azure (2) Windows Mobile (3) Windows Phone 7 (2) WinFX (17) WinRT (2) WP7 (2) WPF (40) XAML (24)

 On this page
 This site
 Archives
Navigation
 Sitemap
 Blogroll OPML
 Disclaimer

All content is property of www.snowball.be. Nothing on this site can be copied or published elsewhere, unless otherwise stated.

This site is made by Gill Cleeren.

Questions? Opinions? Send mail to the author(s) E-mail