NHibernate Integration Facility - IConfigurationContributor

14. February 2009

Note: This short post is a self reminder about a feature that has just been added, I’ll probably use it in the documentation.

Our friend German Schuager has offered another cool feature, namely IConfigurationContributor. This interface allows implementors to change the Configuration instance _just before_ the ISessionFactory is created.

/// <summary>
/// Allows implementors to modify <see cref="Configuration"/>
/// </summary>
public interface IConfigurationContributor
{
    /// <summary>
    /// Modifies available <see cref="Configuration"/> instances.
    /// </summary>
    /// <param name="name">Name of the session factory</param>
    /// <param name="config">The config for sessionFactory</param>
    void Process(string name,Configuration config);
}


Implementors can modify the Configuration depending on the name.

, ,

Fluent Validation With ASP.NET MVC and Db4o

10. February 2009

UPDATE 3: Exception throwing for business rules is not a good practice, making this post almost useless.
UPDATE 2: Did you notice the duplication in event handling?
UPDATE 1: Jeremy Skinner was kind enough to respond to my feature request, please look at the first block. Thanks Jeremy!

I have been trying to implement validation for BlogSharp. There are several validation frameworks including Castle Validator but it didn’t feel good to put attributes on the entity itself. I wondered if there is a 3.5 style of doing it and thankfully Jeremy Skinner provided a good framework that uses Lambda Expressions which is called Fluent Validation. Its syntax is very similar to the that of Fluent NHibernate.

public class PostCommentValidator : ValidatorBase<PostComment>
{
    public PostCommentValidator()
    {
        RuleFor(x => x.Comment).NotEmpty();

        RuleFor(x => x.Email).NotEmpty();
        RuleFor(x => x.Email).EmailAddress();        RuleFor(x => x.Email).NotEmpty().And().EmailAddress();
        RuleFor(x => x.Web).Url().When(x=>!string.IsNullOrEmpty(x.Web));
    }
}


It is also easy to extend its validation capacities. All you need to do is to implement IPropertyValidator<T>. For my case, I needed to have Url validation and it was enough to inherit from RegularExpressionValidator.

public class UrlValidationRule<T>:RegularExpressionValidator<T>
{
    public UrlValidationRule():base(@"URLRegularExpressionHere")
    {
        
    }
}


You may also want to create an extension method in order to have a uniform syntax.

public static class UrlValidationExtension
{
    public static IRuleBuilderOptions<T, string> Url<T>(this IRuleBuilder<T, string> ruleBuilder)
    {
        return ruleBuilder.SetValidator(new UrlValidationRule<T>());
    }
}


There are some additions that i made in ValidatorBase<T>. Currently it returns ValidationResult, which has all the information about the validation process. I made it throw Exception in order not to deal with layering.

Nothing very special up to this point.

What I wanted to tell in detail today is how to implement validation using Db4o, Castle and Fluent Validation stack. Even though I was to do the validation at Service level, I decided that it may be better to have it at persistence level.

Db4o has events (did I mention that I like events?) that take place after and before various operations including Activate, Create, Update, Delete, Commit. The best place to implement this validation is to use the events Creating and Updating which are raised_before_ the updated/added object is stored back in Db4o. I needed a way to integrate them with my home made Db4o Facility that was inspired by Castle NHibernate Integration. I created an interface like the one below

public interface IDb4oInitializationHandler
{
    void HandleObjectContainerCreated(IExtObjectContainer extObjectContainer);
}


Implementors will be called just after the IObjectContainer so that we will have the opportunity to wire up our events. Currently you can’t specify a specific InitializationHandler for a specific container, but I plan to implement it soon.

public void HandleObjectContainerCreated(IExtObjectContainer extObjectContainer)
{
    var factory = EventRegistryFactory.ForObjectContainer(extObjectContainer);
    factory.Creating += ValidationHandler;
    factory.Updating += ValidationHandler;
}protected void ValidationHandler(object sender, CancellableObjectEventArgs args)
{
    try
    {
        ValidateObject(args.Object);
    }
    catch(ValidationException ex)
    {
        args.Cancel();
        throw ex;
    }
}


and in the handlers of the events, I check if the stored object has validator associated with it and then validate.

protected virtual void ValidateObject<T>(T obj)
{
    var type = obj.GetType();
    var validatorType=typeof (IValidatorBase<>).MakeGenericType(type);
    if(container.HasComponent(validatorType))
    {
        var validator = container.Resolve(validatorType) as IValidatorBase;
        validator.ValidateAndThrowException(obj);                
    }
}


The exception is caught at the Controller, then is passed to the ModelState.

try
{
    postService.AddComment(comment);
}
catch(ValidationException vex)
{
    this.ModelState.AddValidationExceptionToModel("comment",vex);
}
            


AddValidationExceptionToModel is an extension method

public static void AddValidationExceptionToModel(this ModelStateDictionary model, string prefix,ValidationException exception)
{
    var errors=exception.Errors;
    foreach (var error in errors)
    {
        model.AddModelError(string.Format("{0}.{1}",prefix,error.PropertyName), error.Message);
    }
}

 

The result is the following:


It is as easy as this, thanks to the extensibility of Db4o and Fluent Validation frameworks.

If you like it, don't forget to kick and/or shout it

kick it on DotNetKicks.com Shout it

, ,

Castle Custom Component Activators

3. February 2009

I have already said here that  I love Castle and how excited I am  about its extensibility. This post will be another one that talks about Castle Microkernel extensibility.

When you try to resolve a component from microkernel, it goes through several steps. It firsts find the appropriate IHandler instance which manages component states and coordinates component creation/destruction that is associated with the service requested. Handler then calls ILifestyleManager in order to get the object requested. The ILifestyleManager manages the lifestyle of the service, and there are several built-in ILifestyleManagers in Castle.

  1. Singleton(Default)
    Only one instance is created and subsequent calls to Resolve method will get the same instance.
  2. Transient
    Every call gets different instance of the service.
  3. PerWebRequest
    A call creates the instance if it is not created for the current web request. Can only be used in ASP.NET environment
  4. Pooled
    Makes a pool of component instance.
  5. Thread
    A call will create the object if it hasn’t been created for that thread. Otherwise, previously created object will be returned.

 

The ILifestyleManager then calls ComponentActivator in order to create object when necessary.

It has been suggested in Castle Development group that NHibernateIntegrationFacility should lazily initialize ISessionFactory. It is really a good idea and it was something that I had in mind but forgot somehow. German offered that a proxy is registered to container and via this proxy this lazy load could be achieved. This was a good idea but I thought there should be a better way in Castle to handle this kind of situation. Then I remembered something called ComponentActivator and even though I didn’t use it previously, its name gave some idea.

Previously the session factory initialized when the NH facility is initialized,

ISessionFactory sessionFactory = cfg.BuildSessionFactory();
Kernel.AddComponentInstance( id, typeof(ISessionFactory), sessionFactory ); 

Instead of this, I created custom ComponentModel that sets the CustomComponentActivator which will be used to create the object instance

var model = new ComponentModel(id, typeof(ISessionFactory), typeof(Empty));
model.LifestyleType = LifestyleType.Singleton;
model.ExtendedProperties[Constants.SessionFactoryConfiguration] = cfg;
model.CustomComponentActivator = typeof (SessionFactoryActivator);
Kernel.AddCustomComponent( model );

I will have access to that ComponentModel in the activator, and since I provide cfg(Nhibernate.Cfg.Configuration) via ExtendedProperties, I’ll be able to initiate the SessionFactory.

public class SessionFactoryActivator : DefaultComponentActivator
{
    public SessionFactoryActivator(ComponentModel model, IKernel kernel,
        ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction)
        : base(model, kernel, onCreation, onDestruction)
    {

    }
    public override object Create(CreationContext context)
    {
        var configuration = Model.ExtendedProperties[Constants.SessionFactoryConfiguration]
                            as Configuration;
        return configuration.BuildSessionFactory();
    }
}

I really liked this approach that Castle had. I’d like to know if there’s a better of way achieving this specific scenario.

kick it on DotNetKicks.com

, , ,

The moment of day – Fluent NHibernate

1. February 2009

I’ve been working with Paul Batum for a while on Fluent NHibernate. He’s working on semantic model while I am trying to make it work against NHibernate mapping meta. I’ve tried several times but i didn’t like the things I had, I was almost retiring from FNH. Below is the mapping that I first tried to make work.

public class PersonMap : ClassMap<Person>
{
    public PersonMap()
    {
        Id(x => x.Id);
        Map(x => x.Name)
            .WithLengthOf(30)
            .CanNotBeNull();
        Map(x => x.Age)
            .CanNotBeNull();
    }
}


And thankfully made it work.

This made my day, and you can’t guess how happy I am.