Archive for the ‘Validation’ tag
Validation Framework – Enterprise Library Validation Block
In previous
posts I wrote about validation AOP-style, using Policy Injection or Depency Injection (Unity). I am a true believer that this form of validation is the way to go.
That said, what kind of validation do you really need?
User Input Validation is probably the first thing that pops up into your mind, and that is indeed an important one. But, in fact, validation can be applied to almost every layer. That’s why they call it a cross cutting concern and AOP makes sense.
That’s not what I mean. I am talking about using validators here. You probably know the available ASP.NET validators, like shown in above picture.
But you know what? Although User Input Validation is important, sooner or later the data will be persisted to a database. And if your database accepts varchar(10) only, then “Thunderbird” is not such a good idea to type.
In short, you are in need of a StringLengthValidator.
Of course you can create you own simple validation rules engine, but fortunately it is also an out-of-the-box validator of Microsoft’s validation block.
Difficult? Not at all, when following these simple steps:
- Download and install Microsoft Enterprise Library 5.0
- Create a project
- Add a reference to the assemblies “Enterprise Library Validation Application Block” and – not to forget – “System.ComponentModel.DataAnnotations”
- In your class, add the namespace: Microsoft.Practices.EnterpriseLibrary.Validation, et voilá
using System;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
public class Customer
{
[StringLengthValidator(0, 10)]
public string CustomerName;
public Customer(string name)
{
this.CustomerName = name;
}
}
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer("Thunderbird");
Validator<Customer> validator = ValidationFactory.CreateValidator<Customer>();
ValidationResults results = validator.Validate(customer);
if (!results.IsValid)
{
foreach (ValidationResult result in results)
{
Console.WriteLine(result.Message);
}
}
}
}
Simple Validation Rules Engine
Sometimes, you want to do some simple validation. For example, data should not exceed the reserved storage size for the field in the database.
In this example CustomerName must be less than 10 characters. So, the client code should look like this:
Customer customer = new Customer();
// customer name must be less than 10 characters
customer.CustomerName = this.textBox1.Text;
// Validation facade
ValidationResults results = Validation.Validate<Customer>(customer);
// populate listbox with validation results
foreach (ValidationResult result in results)
{
this.listBox1.Items.Add(result.Message);
}
The customer name is filled with input from a textbox. The complete customer object is validated using a validation facade. Finally, a list box is populated with the validation results.
Use of a facade simplifies use of validation in the client. The facade itself looks like this:
public static class Validation
{
public static ValidationResults Validate<T>(T validationobject)
{
Validator<T> validator = ValidationFactory.CreateValidator<T>();
ValidationResults results = validator.Validate(validationobject);
return results;
}
}
But wait! This looks exactly like the Validation Application Block. That’s a coincidence!
Indeed. Since the callings are similar you easily can replace the plumbing with the real stuff later on if you want.
But be aware that there is a small difference. This simplified version does not use attributes, but self validation by implementing an ISelfValidation interface.
public interface ISelfValidation
{
void Validate(ValidationResults results);
}
The object in question implements ISelfValidation as follows:
class Customer : ISelfValidation
{
public string CustomerName { get; set; }
public void Validate(ValidationResults results)
{
int maxLength = 10;
string validationString = CustomerName;
ValidateStringLength(results, validationString, maxLength);
}
// this can be put into a helper class if you want
private static void ValidateStringLength(ValidationResults results, string validationstring, int maxlength)
{
if (validationstring.Length > maxlength)
{
results.Add(new ValidationResult(String.Format("Length must be less than {0}", maxlength)));
}
}
}
This way simple validation becomes very easy. So, kids please do try this at home.
Download(s) : [Download not found]
How-to AOP: Validation with Unity
With the introduction of Unity v1.2 it is now possible to do aspect oriented programming (AOP) using Unity in a way that is similar to Policy Injection. You can read all about it in my former post How-to AOP: Validation with Policy Injection, where I showed how-to AOP using Validation with the Policy Injection Application Block (PIAB).
The example of today is a rework of the previous Policy Injection example, so most code remains unchanged. Most important exercise is that the invoking code in the method Save of the facade CustomerManager is changed so – surprise, surprise – Unity does the AOP work instead of Policy Injection.
Unfortunately, out-of-the-box Unity does not have something like an ArgumentValidationException.
So, some extra code has to be written, mostly to make Unity do its AOP thing work. To stay in line with the PIAB example, some behavior of the Policy Injection ValidationCallHandler is mimiced: when validation fails, an exception is thrown.
Of course, you can reuse the ArgumentValidationException of PIAB, but then you still need PIAB. For this example, I am an Unity purist and create something myself that looks like an ArgumentValidationException, smells like an ArgumentValidationException, in fact is called an…
… EntityValidationException.
Yeah right, I gave it a different name for educational purposes so you wouldn’t think: Wow, Unity also has this powerful way of handling validation. What a great piece of work this Unity is!
Well, maybe Policy Injection will fully integrated in the next version of Unity. Maybe not.
First, you have to change the code in the method Save of CustomerManager to use Unity:
public bool Save(Customer customer)
{
bool IsValid = false;
IUnityContainer container = new UnityContainer();
container.AddNewExtension();
container.RegisterType().Configure().SetInterceptorFor(new InterfaceInterceptor());
IRepository action = container.Resolve();
try
{
action.Save(customer);
}
catch (EntityValidationException ex)
{
ValidationResults results = ex.ValidationResults;
// ...
}
return IsValid;
}
Essentially, this is the most important part of the exercise. As you can see, Unity uses an interception mechanism for the AOP behavior. As in the Policy Injection example, an interface is needed for registering the type. Unity has no built-in ValidationCallHandler like Policy Injection, so you have to create one yourself. This is not very difficult, see below:
public interface IRepository
{
[EntityValidation]
void Save(Customer customer);
}
EntityValidation is a concrete HandlerAttribute:
public class EntityValidationAttribute : HandlerAttribute
{
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new EntityValidationHandler();
}
}
A HandlerAttribute needs to return a concrete class which implements ICallHandler:
public class EntityValidationHandler : ICallHandler
{
public int Order { get; set; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
Customer customer = input.Arguments[0] as Customer;
ValidationResults results = Validation.Validate(customer);
if (results.Count == 0)
{
return getNext()(input, getNext);
}
else
{
throw new EntityValidationException(results);
}
}
}
Lastly, you need an exception to mimic the ArgumentValidationException:
[Serializable]
public class EntityValidationException : Exception, ISerializable
{
readonly private ValidationResults validationResults;
public EntityValidationException(ValidationResults validationResults)
{
this.validationResults = validationResults;
}
protected EntityValidationException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
this.validationResults = (ValidationResults)info.GetValue("EntityValidationException.validationResults", typeof(ValidationResults));
}
public ValidationResults ValidationResults
{
get { return validationResults; }
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("EntityValidationException.validationResults", validationResults);
}
}
That’s most of it. Nice, huh? To be honest with you: I slightly prefer Policy Injection over Unity Interception. Why? It feels like the subtle difference Policy Injection is AOP and Unity supports AOP. It’s just a feeling.
How-to AOP: Validation with Policy Injection
Validation of user input is very important. A lot of our users are very environmentally aware and throw all kinds of garbage in (= garbage out). So you probably better use extensive validation for all your dataclasses (or Business Entities, if you like). A consequence is that you have to invoke validation almost everywhere in your business logic. That’s a lot of boooooring repetitive work.
To me this smells like a cross-cutting ‘AOP’ concern, i.e. use Policy Injection.
In the following example of validation “the AOP way” I show you how to use Validation with Policy Injection, which are both part of Enterprise Library.
For simplicity we are going to validate a very simple Customer class, which still is very realistic. Even in the real world you can come across some really simple customers, like this one:
“I do not want to pay a penny extra for validation. When I buy me an application I expect that you deliver one fully validated without errors in it. So if you want validation, please do it at your own expense.”
Yes, this customer is in heavily need of managing customer expectation, but that’s a different story.
The how-to example is build around a Factory Design pattern (Customer, interface IRepository, and concrete class CustomerRepository) and accessed via Facade pattern (CustomerManager). I use a facade here, because then you do not not have to reference parts of Enterprise Library in your client code. Enterprise Library can stay within a single class library together with the other stuff. Isolation of the chosen technical implementation. In this way we can easily replace it with a better implementation, if we don’t like Policy Injection any more.
public class Customer
{
string m_FullName;
[StringLengthValidator(5)]
public string FullName
{
get { return m_FullName; }
set { m_FullName = value; }
}
}
The property FullName is decorated with a validation attribute StringLengthValidator. Upon validation it is checked if the length of the string does not exceed 5. I know, silly validation.
The client code is as follows, it just calls the CustomerManager facade:
CustomerManager mgr = new CustomerManager(); Customer customer = new Customer(); customer.FullName = "thisisaverylongname"; bool IsValid = mgr.Save(customer);
The CustomerManager façade:
public bool Save(Customer customer)
{
bool IsValid = false;
IRepository ctr = PolicyInjection.Create();
try
{
ctr.Save(customer);
IsValid = true;
}
catch (ArgumentValidationException ex)
{
ValidationResults results = ex.ValidationResults;
// ...
}
return IsValid;
}
Finally, the interface IRepository and its concrete class CustomerRepository:
//IRepository interface:
interface IRepository
{
[ValidationCallHandler]
void Save(Customer customer);
}
class CustomerRepository : IRepository
{
void IRepository.Save(Customer customer)
{
// Saving logic...
}
}
With this concrete example at hand you should have a start of and be able to experiment a little bit with validation the AOP way.
If you need some extra help with the above example or have a strong opinion towards use of the Policy Injection, just leave a comment.















