Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » Learn .NET » 16 steps to write flexible business validation in C# using Validation Blocks

16 steps to write flexible business validation in C# using Validation Blocks

Validation is one of the most important parts in any software project. Building flexible business validation is every one’s dream.

Author Rank :
Page Views : 16753
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


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.

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 Client side validation using Validation Application blocks

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Shivprasad
I am currently a CEO of a small E-learning company in India. We are very much active in making training videos , writing books and corporate trainings. You can visit about my organization at www.questpond.com and also enjoy the videos uploaded for Design patter, FPA , UML , Project and lot. I am also actively involved in RFC which is a financial open source madei in C#. It has modules like accounting , invoicing , purchase , stocks etc.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
Two limitations occur to me by Vishal On August 27, 2009

Hi Shiv,

Thanks for submitting such a informative article which is short and precise and hence easier to understand.
Two limitations, however, occur to me here:
1) Performance: Since validation run on the object and not on the UI elements, think of complex screen which may contain lots of UI elements. In this case we will have to first copy the Ui values to object so that validation can run on it. This may impact the performance.
2) Security: Since the validation rules get copied to .config file in plain text this exposes the business rules and also make them alterable  by people with not good intentions.

Just want to have your opinion on this and any solutions you mar recommend to overcome them.

Vishal

Reply | Email | Modify 
Good Word Nice by mostafa On August 29, 2009
Nice Work
Reply | Email | Modify 
Testing by bala On September 3, 2009
Reply | Email | Modify 
External Validation by John On July 13, 2010
I have read another article about validation with xml definition. There you need set required object/property class into xml and run Validate when you need. You can find more info on it here  .Net validation
Reply | Email | Modify 
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.