Creating a Timestamp Interceptor in NHibernate


In a previous post, I gave an example of a Timestamp class and how one might create an ICompositeUserType to map it within NHibernate. Here I want to show of an example of an IInterceptor which will automatically populate the values for my Timestamp class. OnSave is for the inserts, and OnFlushDirty is for the updates. There are a bunch of other methods that you can tap into for different things, so check out the NHibernate docs.
 
public class TimestampInterceptor : EmptyInterceptor
{
    private const string TIMESTAMP_PROPERTY = "Timestamp";

    private readonly IDomainContext domainContext;
    private readonly ISystemClock clock;

    public TimestampInterceptor(IDomainContext domainContext, ISystemClock clock)
    {
        this.domainContext = domainContext;
        this.clock = clock;
    }

    public override bool OnSave(object entity, object id, object[] state, 
        string[] propertyNames, IType[] types)
    {
        var timestampable = entity as ITimestampable;

        if(timestampable == null)
            return false;

        var timestamp = GetTimestamp(state, propertyNames);

        timestamp.CreatedDateTime = clock.Now();

        if (domainContext.DomainUser != null)
            timestamp.CreatedByStaff = domainContext.DomainUser.StaffName;

        return true;
    }

    public override bool OnFlushDirty(object entity, object id, object[] currentState, 
        object[] previousState, string[] propertyNames, IType[] types)
    {
        var timestampable = entity as ITimestampable;

        if (timestampable == null)
            return false;

        var timestamp = GetTimestamp(currentState, propertyNames);

        timestamp.UpdatedDateTime = clock.Now();

        if(domainContext.DomainUser != null)
            timestamp.UpdatedByStaff = domainContext.DomainUser.StaffName;

        return true;
    }

    private static Timestamp GetTimestamp(object[] state, string[] propertyNames)
    {
        var timestamp = state[Array.IndexOf(propertyNames, TIMESTAMP_PROPERTY)] as Timestamp;

        if( timestamp == null )
        {
            timestamp = new Timestamp();
            state[Array.IndexOf(propertyNames, TIMESTAMP_PROPERTY)] = timestamp;
        }

        return timestamp;
    }
}
 
I haven’t run this through the ringers yet, so let me know if you spot some problems.
Technorati Tags: ,
A Simple Closure To Handle Try/Catch Around Transactions