Category Archives: Cuyahoga

Castle Cuyahoga

Hidden jewels in the Castle stack: Transaction Services

In Cuyahoga, we’re using a lot of components from the Castle stack. Some of the most brilliant components are the transaction services combined with the automatic transaction facility.

With this post, I’m trying to bring some well-deserved attention to these undervalued components.

The Context

Today, I was working on management of sites. In Cuyahoga 2.0, every site has its own set of content folders and templates. Now when creating a new site, we have to perform the following steps:

  1. Save the new site object in the database;
  2. Create a folder structure for the new site;
  3. Copy the selected system template objects to the new site and save in the database;
  4. Copy the template files that belong to the copied template objects to the templates folder of the site.

All steps have to be completed before we can start management of the new site, like adding pages and custom templates. Obviously, you’d like this series of steps to be completed  in a single transaction, so when something goes wrong somewhere, we don’t end up with a broken site.

As you might have noticed, the transaction also includes file operations and we all have probably experienced situations where the database and the file system were out of sync because something went wrong, either in the database, or with the file system.

Enter Castle Transactions

Castle Transaction Services makes it possible to run any arbitrary piece of code within the scope of a transaction. Components that are called in a transaction can support those transactions by requesting the current transaction via a transaction manager. This makes it very easy to write your own components that are transaction-aware.

Transactional file operations: don’t let the database and file system go out of sync

For file operations, we created a simple service that performs common file operations like writing new files, copying files and creating folders. When performing an operation, the service checks if there is a current transaction and if so, the actual operation is delegated to a class that performs the actual transactional operation. An excerpt of our transactional fileservice:

public void CopyFile(string filePathToCopy, string directoryToCopyTo)
{
    ITransaction transaction = ObtainCurrentTransaction();
    if (transaction != null)
    {
        FileWriter fileWriter = new FileWriter(this._tempDir, transaction.Name);
        transaction.Enlist(fileWriter);
        fileWriter.CopyFile(filePathToCopy, directoryToCopyTo);
    }
    else
    {
        File.Copy(filePathToCopy, Path.Combine(directoryToCopyTo, Path.GetFileName(filePathToCopy)), true);
    }
}

In the example above, the FileWriter class performs the transactional file operations by implementing an IResource interface that has three methods: Start(), RollBack() and Commit(). The CopyFile() method copies the file to a temporary location. When the transaction manager commits the transaction, the Commit() method of the FileWriter is called and the file is copied from the temporary location to the actual location. RollBack() removes the temporary file.

The complete implementation of the file service can be found in Cuyahoga SVN at https://cuyahoga.svn.sourceforge.net/svnroot/cuyahoga/trunk/Core/Service/Files. Note that the implementation is very basic and there’s much room for improvement but it already saved us lots of time when we didn’t have to clean up the mess when something went wrong.

Automatic transactions

One of the really great features of the Castle transaction services is that you just have to decorate your method with an attribute and everything is executed within the context of a transaction:

[Transaction(TransactionMode.RequiresNew)]
public virtual void CreateSite(Site site, string siteDataRoot, IList<Template> templatesToCopy, string systemTemplatesDirectory)
{
    // 1. Save new site object in the database.
    ..

    // 2. Create site directories.
    ..

    // 3. Copy template objects to new site and save in database.
    ..

    // 4. Copy template files to site templates directory.
    ...
}
ASP.NET MVC Cuyahoga

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.

ASP.NET MVC Cuyahoga

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.

Cuyahoga General

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.