Click here to Skip to main content
Email Password   helpLost your password?
Updated with links of Other Application Blocks 

Table of Contents

Introduction

Validation is one of the most important parts in any software project. Building flexible business validation is every one’s dream. Rather than writing frameworks from scratch to do these things, Microsoft validation blocks makes it a breeze. In this article we will discuss how validation application blocks help us to build flexible validations using validation application blocks. Its just a simple sixteen step process to put our business validation in action using validation blocks.

I have been writing and recording lot of architecture related videos on design patterns, UML , estimation and C# projects. You can see these videos here. In case you think I need improvement do drop me a mail at questpond@yahoo.com or questpond@questpond.com , I will definitely like to improve.

Other Application Blocks

Client side validation: - One of the short comings in VAB is that it does only server side validations. This article talks how we can leverage VAB for client side. Client side validation

Dynamic validation: - This article explains how to build dynamic validation on scenario basis. Dynamic validation

Policy Application blocks: - This article talks how to implement plug and play mechanism using Policy application blocks. Policy application block

Logging application block: - This article explains the 5 basic steps of how to use logging application blocks.
Logging application block

Data application: - This article talks about the four steps you need to implement data application blocks.
Data application block

Exception application block: - This application talks how we can use exception application blocks to log exception from project. Exception application block

Unity application block: - This application talks about Unity Application Block in DI and IOC.
Unity application block

UIP block: - This article talks about Reusable Navigation and workflow for both Windows and Web using Microsoft UIP blocks. UIP block

The problem

No business can work without validation. Software’s are made to make business automated so validation forms the core aspect for any software. Almost 80% projects in .NET implement validation as shown in figure below.

Figure: - Validation implemented

The above figure shows how business validations are implemented for a simple customer class. We have two properties customer code and customer name. Both of these properties are compulsory. So we have created a class called as ‘ClsCustomer’, with two set/get properties for customer code and customer name. If we find that customer code is empty in the set of the property we raise an error. The same methodology we have used for customer name.


Now we can consume the class in the ASPX UI as shown in figure ‘Business object consumed’. We have created the object, set the properties and in case there is error we have caught the same and displayed it in a label using try catch exception blocks.

Figure :- Business object consumed

This implementation looks good to some extent as we have put the business validation in the class and decoupled the UI from any business validation changes.

Let’s list down the common problems associated with the above methodology:-

Tangled validation: - If the validation rules changes we need to compile the whole class. As the entity and the validation layer are entangled in one class, changes in validation leads to compilation of the whole class. So out first goal should be decouple this validation logic from the entity class. When we say entity class we are referring to the ‘ClsCustomer’ class.

Figure :- Tangled validation

Figure :- Decoupling validations from the entity class

No need of compiling: - Validations are volatile entity. They change from time to time. If we can change validation constraints without compiling will lead to better maintenance of the system.

One go validation and results: - The second issue is validations are executed in every set of the property and errors are displayed one by one. It would be great if we can validate all the validation once and display all the errors once.

All these things can be achieved by using Microsoft validation application blocks.

The solution: - validation application blocks

Step 1:- Download the Enterprise library 4.0 from here.

Step 2:- Once you install it you should see the same in programs – Microsoft patterns and practices.

Before we move ahead to understand how validation application blocks works. We will first walkthrough fundamentally how validation application blocks decouples the validation from the entity classes. Validation application blocks stands in between the entity class the validation. Validations are stored in configuration files like web.config or app.config depending whether it’s a web application or a windows application. So the validation blocks reads from the configuration file the rules and applies it over the entity class. We can maintain these validations using the enterprise configuration screen provided by Microsoft blocks.

Figure: - Decoupling validations from entity classes

Now that we have understood how validation blocks will work. We will run through a example practically to understand the concept.

Step 3:- Once you have installed the block, click on Enterprise library configuration UI to define validation on the configuration file

Figure :- Loading Enterprise configuration screen

Step 4:- Click on open and browse to your web.config file and click the open button.

Figure :- Open the web.config file

Step 5:- Once you have opened the web.config file you should see a tree like structure as shown in figure ‘Add validation block’. Right click on the main tree and add the validation application block to your web.config file.

Figure :- Add validation application block

Step 6:- Once you have added the validation application block you should see a validation application block node. Right click on the node , select new and click the type menu.

Figure: - Add the assembly type

Step 7:- Once you have clicked on the type menu you should see a dialog box as shown in figure ‘Load assembly’.

Figure: - Load assembly

Step 8:- Click on load assembly and browse to the assembly DLL to which you want to apply validations.

Figure: - Browse the assembly

Step 9 :- Select the class in the assembly as shown in figure select class.

Figure :- Select class

Step 10:- Once you have loaded the assembly, you should see a new node ‘MyRules’ as shown in figure ‘Choose members’. Right click on ‘MyRules’ ? new and choose members.

Figure: - Choose members

Step 11:- Once you have clicked the choose members menu you will be popped up with a property selector box as shown in figure ‘Select properties’. In the customer class we have two properties on which we want to apply validations one is the customer name and the other is the customer code. So we will select both the properties and click ok.

Figure: - Choose properties

Step 12:- Once you have selected the properties you can see both the properties in the UI. To apply validation right click on let’s say customer code property. You will now see list of validations which you can apply on the property. This tutorial will not go in details about all the validations. If you are interested in the same you can read about it more on http://msdn.microsoft.com/en-us/library/cc309336.aspx  . For the current scenario we will select range validator.

Figure: - Select range validator

Step 13:- Once you have selected range validators, you will see the below property box for range validators. In this particular scenario we need that both the property i.e. customer code and customer name should not be empty. So in the lower bound we will put 1 , which signifies that at least one character is needed. In the lower bound type we have selected as inclusive, which means the lower bound check is compulsory. In the message template put the error message which you want to display in case there are issues.

Figure: - Range validator properties

Step 14 :- In the default rule select the rule which you have just made. If it’s none validations will not fire.

Figure: - Select rule

If you are done just save everything and watch your web.config which is now modified with the validation tags. You will see both the validation i.e. customer name and customer code in XML format inside the <validation> tag. The best part of the config file is now you can change the validation in the config file itself.You guessed right… no recompiling , no installation and completely decoupled.

Figure: - Web.config with validation tags

Step 15:- Ok, now that we are done with putting the validation in the web.config file. Its time to write the code which will read from the config file and apply to our entity class. So the first thing we need to reference the validation application block in our assembly references and include the name spaces in our clsCustomer class.

Figure: - Reference validation application blocks

Figure: - Import the validation namespace

Step 16:- Once you are done with adding the namespaces its time to fire the validation. Below is the code snippet which shows how the validation application block fires the validation using the web.config file. First step create the customer object and set the property. In the second step we tell to the validation static class to validate the object. The validation static class returns validation results. This validation results are nothing but error failures in case the validation fails. In the final step we have looped through the validation results to display the error.

Figure: - The validation code

Ok, now that we are done its time to see the action. You can see in the UI we have just set empty properties and it showed me both the business validations errors from the collection.

Figure :- Validation in action

The other problem with validation is that it only does server side you can read my tutorial how we can generate client side validators using validation engine at ApplicationBlock.aspx

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralNice work
Kuldip Rindani
1:12 13 Aug '09  
Nice work, you really changed my idea on coding entity validation from scratch.
GeneralCode?Never put code why
devnet247
20:24 16 Mar '09  
Hi,
I like some of your articles,even though at times some of them they are so basic that you cannot use them.

As a user of this fantastic site i have learnt so much mainly because people published code examples rather than theory.

I think you would get a better response to your article if you were to upload the code as well, unless you just want it as pointer to your website.

why you dont put the code? to be honest we cannot tell whether something actullay works can we?

thanks a lot

GeneralRe: Code?Never put code why
Shivprasad koirala
21:05 16 Mar '09  
I will definetly make it a point to put source code.In all recent articles i have started putting in source code. Agreed until we do not show something substantial we can never know if it works.Agreed and noted.

Footprints on the sand are not made by sitting at the shore.

Generalgreat article
Donsw
19:35 25 Jan '09  
Great article, one thing you might do in the future is enlarge some of your screen shots. they are small to read. Big Grin
GeneralGood one
.netruler
7:08 18 Dec '08  
Hey Siva.. Thanks and very useful article.. By the way what tool do u use to capture the images,..?
GeneralRe: Good one
Shivprasad koirala
19:35 18 Dec '08  
SnagIT , I love it especially the torn effect.

Footprints on the sand are not made by sitting at the shore.

GeneralString Hint
djhayman
16:10 18 Nov '08  
Hi,

Just noticed something in your code above:

public string CustomerName
{
set
{
if (value.Length == 0)
{
throw new Exception("Customer name is compulsory");
}
_strCustomerName = value;
}
get...
}


What if I go "customer.CustomerName = null;"? Your code will end up throwing "Object reference not set to an instance of an object" on the "if (value.Length == 0)" line, rather than "Customer name is compulsory".

Best to do it like this:

if (string.IsNullOrEmpty(value))
{
throw new Exception("Customer name is compulsory");
}

GeneralLearning ASP.Net- help me!!!
xuandu
4:10 18 Nov '08  
Oh !
My name is Du, I want to learning ASP. Net but I don't known how I do. can you help me to begin ?

I have learning PHP, ASP

my website : http://nhieulam.comConfused

welcom to my website : http://nhieulam.com
Forum free download templates, code project,photo stocks, Ebook,

GeneralGood Article
Samer Abu Rabie
23:15 17 Nov '08  
Validation of entities is always has been a concern ... whatever lots of ways to do it ... I think this one is good ... and should be considered heavly.

Good Article Mr. Shivprasad

Sincerely Samer Abu Rabie

Note: Please remember to rate this post to help others whom reading it.


Generalreally good idea?
christoph braendle
23:24 4 Nov '08  
in my opinion, a business object always should know itself if it is valid or not.
(adaption: why should I ask someone else if i like something or not).

AOP seems an alternative that can meet this idea, or what I think is better;
building an AOP like faktory that is injecting the rules.

Anyway, good and clear article, i really love the way you guide through the steps Smile

Cheers Christoph
GeneralRe: really good idea?
Dmitri Nesteruk
23:38 4 Nov '08  
I agree. What is presented in this article seems like overkill - it's too much for small applications. I'd go with the typical mutator validation behavior, and for anything more complex I'd throw in PostSharp.

Thanks for the article, though.

Dmitri
GeneralPart 2?
Mark Henke
8:42 14 Oct '08  
You should expand this tutorial to show haw you can use the same config to utilize the Enterprise UI validation controls that act like regular asp.net validation controls.
GeneralRe: Part 2?
Shivprasad koirala
16:09 16 Oct '08  
I have written a article which explains how we can read the config file and generate ASP.NET validations
http://www.codeproject.com/KB/aspnet/ApplicationBlock.aspx[^]

When i die i die programming

GeneralRe: Part 2?
Mark Henke
4:30 17 Oct '08  
Thanks for sharing!
QuestionHow to store the validation rules in multiple configuration files?
wil_blank_c
5:42 14 Oct '08  
Hi Shivprasad, I'm working with Validation Application Block (Enterprise Application Block 3.1). I need to keep the rules on multiple configuration files. For example, in your demonstration, you work with the class Customer, I work with three classes: Customer, Order and Invoice. I need that for every class there is a configuration file with their respective rules, but I do not know how to make all this work together. I am grateful for your attention.

Thanks...!!!
Wilson Carchi A.
AnswerRe: How to store the validation rules in multiple configuration files?
Mark Henke
8:45 14 Oct '08  
I beleive you can access multiple config file or section. I think there is a method Validate.ValidateFromConfig or Validate.OpenFromConfig instead of Validate.Validate() that will use the default app or web.config or create by a different ruleset!!! You can have multiple rulesets per class!

Good luck
AnswerRe: How to store the validation rules in multiple configuration files?
Shivprasad koirala
16:13 16 Oct '08  
The rule get stored in web.config file itself. I think you can create new rulsets for every one. It will complicate the thing if you try putting it in different files

When i die i die programming

GeneralThanks
kodali ranganadh
22:20 6 Oct '08  
good one ... it makes easier

Kodali

GeneralUseful stuff.
Rajesh Pillai
0:05 1 Oct '08  
Nice piece of information. Sometimes "small things could have big impact on the way we do things.".

Thanks.

Enjoy Life,
Rajesh Pillai
http://rajeshpillai.blogspot.com/
http://simply-url.blogspot.com/



GeneralAdvice
Warrick Procter
13:17 30 Sep '08  
Good article.
Two things that in my opinion would improve your article.

1. Always have a brief but detailed article 'description' as it is shown in the list of articles. Never just repeat the title like you have done as it does not encourage me to read your article because it does not tell me anything about it.

2. Always have some code associated with the article as a demo. I don't think it matters with this article but there are a number of peasants out there that don't actually read the articles, they just want to rip off the code.

Good luck.
Regards, Warrick

Troft not lest ye be sponned on the nurg! (Milligan)

GeneralNice
Dinesh Mani
1:07 30 Sep '08  
A very nice way to handle business data validations! Thanks for showcasing it here!


Last Updated 16 Mar 2009 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010