Monthly Archives: November 2008

Validation in ASP.NET MVC – part 2: custom server-side validation

This is a post in a series of posts. See also:

In the first post of this series, I showed how you can perform basic server-side validation on your model with help of the Castle Validator component. To summarize this post: the controller validates an object that is decorated with validation attributes with the help of an IModelValidator component and adds errors to the ModelState.

The first reason to abstract the validator was to prevent coupling of MVC controllers to the Castle Validators. But the abstraction also provides a very nice extension point. We can inject any kind of validator into the controller constructor as long as it implements the IModelValidator interface:

public LoginController(IAuthenticationService authenticationService, IModelValidator<LoginViewData> modelValidator)
{
    this._authenticationService = authenticationService;
    this.ModelValidator = modelValidator;
}

In the example above, the constructor requires an IModelValidator<LoginViewData> instance. In our case, Castle Windsor injects a CastleModelValidator<LoginViewData> instance that is registered in the container for IModelValidator<T>. We’re already seeing the first extension: the IModelValidator interface has a generic inheritor.

Extending the ModelValidator

In many scenario’s, property validation with the generic CastleModelValidator<T> will suffice, but sometimes you’ll need some extra validation. For example, when creating a new user, we want to check if the username doesn’t already exist. To perform this check, we created a UserModelValidator class that inherits CastleModelValidator<T>.

validation-custom

The CastleModelValidator<T> calls a virtual method PerformValidation() while validating via IsValid(). In UserModelValidator, this method is overriden and performs the check if the username is unique:

public class UserModelValidator : CastleModelValidator<User>
{
    private readonly IUserService _userService;

    public UserModelValidator(IUserService userService)
    {
        _userService = userService;
    }

    protected override void PerformValidation(User objectToValidate, ICollection<string> includeProperties)
    {
        // First validate the property values via the Castle validator.
        base.PerformValidation(objectToValidate, includeProperties);

        // Check username uniqueness.
        if (ShouldValidateProperty("UserName", includeProperties)
            && ! String.IsNullOrEmpty(objectToValidate.UserName))
        {
            if (this._userService.FindUsersByUsername(objectToValidate.UserName).Count > 0)
            {
                AddError("UserName", "UserNameValidatorNotUnique", true);
            }
        }
    }
}

Because the modelvalidators are registered in the Windsor Container, we can inject any kind of service or data access component into the validator and thus making it very easy to perform custom validation logic that needs to check the database, or check an external web service.

Tying things together

We want the UsersController to use the custom UserModelValidator when ValidateModel() is called. All we have to do is to add UserModelValidator to the constructor of the controller and we’re done:

public UsersController(IUserService userService, UserModelValidator userModelValidator)
{
    this._userService = userService;
    this.ModelValidator = userModelValidator;
}

Finally, this is how it looks in the browser. Nice to see the custom validation error nicely integrated with the rest of the errors.

image

Other extension possibilities

In this post we’ve seen an example where we extended our CastleModelValidator<T> to perform custom logic by calling another service. You might as well call a method on the object itself that is validated to perform custom business logic:

protected override void PerformValidation(MyClass objectToValidate, ICollection<string> includeProperties)
{
    base.PerformValidation(objectToValidate, includeProperties);

    if (! objectToValidate.CheckThatMyBizarreBusinessRuleIsValid())
    {
        AddError("MyProperty", "The object to validate is invalid.");
    }
}

You can also opt for plugging in a completely different library. CSLA fans can very easily implement their own version of IModelValidator<T>, or you could write an IModelValidator<T> implementation that uses the Validation Application Block from Enterprise Library.

The code

This is a series of posts that is directly inspired by Cuyahoga development. All code can be found in the Cuyahoga SVN trunk at https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk. The validation stuff sits in the Validation subdirectory of Cuyahoga.Core: https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk/Core/Validation. Note that Cuyahoga is work in progress. It’s not guaranteed that the code in SVN will be exactly the same as the sample code in this post.

Validation in ASP.NET MVC – part 1: basic server-side validation

Almost every single application has to deal with validating user input. With web applications, you can choose to do the validation on the client side or on the server side. In my opinion, validation should at least take place on the server side and optionally on the client side to improve the user experience. Therefore, I’m starting this series of posts with the basic needs: server-side validation.
For some background, also check the excellent post about validation by Steve Sanderson.

Validate the model and not the UI

In the past I used the ASP.NET WebForms validators. These do a proper job, but are also very much tied to the individual pages, so you have the validation logic scattered all over the place. For Cuyahoga 2, I really wanted a better solution where validation logic is centralized in the model (and removed from the UI layer).
There are already several solutions that make this possible. Microsoft PnP released the validation application block and recently (.NET 3.5 SP1), we have the DataAnnotations from ASP.NET Dynamic Data.

In Cuyahoga, we’re using the Castle Validator component to perform basic validation, mostly because we’re already using other components from the Castle stack and it just works fine. With Castle validators, you’re decorating properties of your Domain entities with attributes like:

[ValidateNonEmpty("UserNameValidatorNonEmpty")]
[ValidateLength(1, 50, "UserNameValidatorLength")]
public virtual string UserName
{
    get { return this._userName; }
    set { this._userName = value; }
}

Note that it’s also possible to decorate DTO’s or presentation models or whatever you want to call these data containers. In Cuyahoga for example, we have a LoginViewData class that is only used in the UI layer, that is also decorated with validator attributes. If we have a validation infrastructure we might as well (ab)use it :) .

IModelValidator

So how are we going to use the Castle validators with ASP.NET MVC?

First we have to make a decision where we want to validate the model. You can do this in the controller or in the service layer (if you one). Some people suggest doing validation in the data access layer but I think the responsibility of a data access layer is persisting and retrieving the model and nothing else.

I’ve chosen to validate the model from the controller because it’s a little bit more convenient as you don’t have to throw exceptions across layers and translate those exceptions to error messages for the user. For validation, all controllers inherit from a base controller that has a ValidateModel() method. This controller also has an instance of an IModelValidator interface to perform the actual validation, so we don’t pollute the controller too much with validation logic and also prevent coupling to a specific implementation.

validation-controller

At this point, the controller can validate, but to use the Castle validators we have to implement IModelValidator and pass that to the controller. But first: a base controller doesn’t know which type to validate, but a concrete controller does (assuming we’re only validating one concrete type in a controller) and therefore we created the IModelValidator<T> interface. The CastleModelValidator<T> class implements this interface.

Because we’re using the Castle Windsor IoC container we can wire everything together in the controller constructor:

public class LoginController : BaseController
{
    private readonly IAuthenticationService _authenticationService;
    /// <summary>
    /// Create and initialize an instance of the LoginController class.
    /// </summary>
    /// <param name="authenticationService">The authentication service</param>
    /// <param name="modelValidator">The IModelValidator for LoginViewData</param>
    public LoginController(IAuthenticationService authenticationService, IModelValidator<LoginViewData> modelValidator)
    {
        this._authenticationService = authenticationService;
        this.ModelValidator = modelValidator;
    }
}

In the container is the registered that when asked for an instance of IModelValidator<T>, the container should return an instance of CastleModelValidator<T>. The constructor in the code above, receives an instance of CastleModelValidator<LoginViewData>and sets the ModelValidator of the base controller.

How it works: the login screen

The Login action of the LoginController performs validation after populating a LoginViewData instance via TryUpdateModel():

public ActionResult Login(string returnUrl)
{
    var loginUser = new LoginViewData();
    try
    {
        if (TryUpdateModel(loginUser) && ValidateModel(loginUser))
        {
             // do authentication and exception handling

ValidateModel() automatically adds all errors to the ASP.NET MVC ModelState, so we have to do very little to actually display the validation errors:

login

The code

This is a series of posts that is directly inspired by Cuyahoga development. All code can be found in the Cuyahoga SVN trunk at https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk. Please note that all ASP.NET MVC stuff sits in the Manager subdirectory of the Cuyahoga.Web: https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk/Web/Manager.

A new experiment

Last week, I started to do some serious Cuyahoga development again and I’m going to try a new development methodology: blog-driven-development. A few days of development brought up so many interesting things, so I decided that I might as well write about them (in fact, I already started it because this post was also triggered by Cuyahoga development).

In the near future, I’ll be writing about the following topics:

  • adding an ASP.NET MVC application to your legacy Webforms application;
  • running the same legacy application in IIS 7.0 integrated mode;
  • a multi-part post about validation with Castle validators and ASP.NET MVC;
  • any other interesting topic that comes up during development.

NHibernate criteria queries across multiple many-many associations

Recently, I ran into an issue with NHibernate Criteria queries. The scenario is the following:

double-many-many

User has a many-many association with Role and Role has a many-many association with Site. I simply wanted all users that belong to a given site (and a whole slew of other optional parameters, therefore the Criteria query).

With hql this is simple:

select distinct u from User u join u.Roles r join r.Sites s where s.Id = :siteId

With a criteria query, it appeared a little bit harder. First I tried this:

ICriteria crit = session.CreateCriteria(typeof(User))
    .CreateCriteria("Roles") // traverse into Roles
        .CreateCriteria("Sites") // traverse into Sites
            .Add(Expression.Eq("Id", siteId);

Note the absence of the distinct keyword anywhere in the query. A nice Cartesian Product was the result due to the joins on the linking tables. Some googling showed that we can get distinct results with Criteria queries by applying the DistinctRootEntityResultTransformer via Criteria.SetResultTransformer() but that all happens in memory and not in the database query (call me old-fashioned, but I’d like my database results properly filtered :) ).

Finally, I found the solution in using subqueries:

ICriteria crit = session.CreateCriteria(typeof(User));

DetachedCriteria roleIdsForSite = DetachedCriteria.For(typeof (Role))
    .SetProjection(Projections.Property("Id"))
    .CreateCriteria("Sites", "site")
    .Add(Expression.Eq("site.Id", siteId.Value));

DetachedCriteria userIdsForRoles = DetachedCriteria.For(typeof(User))
    .SetProjection(Projections.Distinct(Projections.Property("Id")))
    .CreateCriteria("Roles")
        .Add(Subqueries.PropertyIn("Id", roleIdsForSite));

crit.Add(Subqueries.PropertyIn("Id", userIdsForRoles));

Yes, that’s an insane amount of code to do something that simple, but it works and the generated SQL is highly efficient :) . Notice the distinct projection in the second DetachedCriteria (userIdsForRoles).

I’d really appreciate it if somebody has any suggestions for improvement.