Linq.Specifications - The Project

In the past few weeks I have revisited the specification pattern using Linq. I have teased it, toyed with it and tricked it up. And today I announce the public availability of a project demonstrating my current thoughts. You can grab the solution from Google Code at http://code.google.com/p/linq-specifications.

I have no doubt that improvements can and will be made if this generates any wider adoption. For now, it suits what I am currently working on quite nicely. YMMV.

Below is a class diagram of the current core of the project. Use it as a quick reference but be sure to check out the code for a more in-depth view. 

Shortly I will do up a few examples on the project wiki that will flesh out some of the gotchas I have come across already and I need some more testing around some of the elements. For now, however, I just wanted to get this out in the wild. Feel free to comment/flame. I look forward to any feedback.

kick it on DotNetKicks.com

October 18, 2008 10:25 by steven.burman
E-mail | Permalink | Comments (9) | Comment RSSRSS comment feed

Basic NHibernate session management with Autofac

Using the container scoping capablity of Autofac makes NHibernate session management a breeze. Obviously this only handles the most basic session-per-request scenario but we know that can cover a large percentage of most peoples requirements anyway. I am sure other containers could get to this functionality as well, but I was blown away by how easy it was aith Autofac. Below is my session management configuration:

            builder.Register<NHibernateInstance>().SingletonScoped();
            builder.Register(c => c.Resolve
<NHibernateInstance>().CreateSession()).As<ISession>().ContainerScoped();
            builder.RegisterGeneric(typeof (Repository
<>)).As(typeof (IRepository<>)).ContainerScoped();

So the key points are:

  1. Plug in the Autofac HttpHandler for ASP.Net integration by following the instructions here
  2. Have a singleton instance of the NHibernate session factory (housed in my NHibernateInstance class)
  3. Have a method on that singleton registered instance that returns an ISession (CreateSession in my example)
  4. Configure a container scoped instance of the NHibernate ISession, thus ensuring that the created instance will not cross request boundaries
  5. Have the container dynamically inject the ISession into your IRepository implementation

For more information on container scoping in Autofac for ASP.Net web applications check out the Autofac wiki article.

August 19, 2008 14:11 by steven.burman
E-mail | Permalink | Comments (3) | Comment RSSRSS comment feed

Linq Expressions, The Specification Pattern and Repositories - Part 3

In the previous to parts to this series (here and here) I showed the basic infrastructure framework for using Linq-based specifications with a flexible repository interface. In this article I dig deeper into the Expression based find functionality and it's implementation.

The Goal

Specification based query support on the repository is a great feature for encapsulation of any query logic. My major problem with this approach was the creation of trivial specifications on a per-domain-object basis. This would litter the code with specifications that had very little functionality contained within them. Generally this is not a bad thing but, in this instance, for the sake of maintainabilty and simplicity I wanted a to be able to perform ad-hoc queries.

The solution was to make my repository able to accept queries like :

            var repository = new Repository<Person>(session);
            
var people repository
                .FindAll(p 
=> p.Name == "steve");

The AdHoc specification

Since I have already made the decision that my MatchingCriteria are of type Expression, the AdHoc specification is trivial - but very cool. The implementation looks like :

    public class AdHoc<T> : Specification<T> where T : IEntity
    {
        
private readonly Expression<Func<T, bool>> expression;

        public 
AdHoc(Expression<Func<T, bool>> expression)
        {
            
this.expression expression;
        
}

        
public override Expression<Func<T, bool>> MatchingCriteria
        {
            
get return expression}
        }
    }

Simplifying the repository using the AdHoc specification

By utilising this simple but powerful specification class we can simplify the api to our IRepository. We are now able to add a FindOne and FindAll overload that accept Linq based queries in an AdHoc fashion. The implementation is as simple as :

        public IQueryable<T> FindAll(Expression<Func<T, bool>> expression)
        {
            
return FindAll(new AdHoc<T>(expression));
        
}

This functionality is able to be consumed in the following fashion (satisfying our goal for this task) :

            var people repository.FindAll(p => p.Name == "steve");

Conclusion

In combination with the flexibility built into the IRepository interface we now have a basis for a data access layer with maximum flexibility. Sql queries are created at execution time to reflect the criteria that we have applied through domain specifications - be they concrete or ad-hoc.

kick it on DotNetKicks.com

August 12, 2008 12:44 by steven.burman
E-mail | Permalink | Comments (2) | Comment RSSRSS comment feed

Linq Expressions, The Specification Pattern and Repositories - Part 2

In Part 1 of this series I expressed my goal of a powerful Linq implementation for the specifications within my domain. In this part of the series I go into further detail and show I have implemented my repositories to support the pattern.

The IRepository definition

In the code below I have restricted my IRepository to be read-only for the purposes of the exercise. Obviously in reality there would be more functionality defined on this interface.

The use of the specification as a parameter to the Find methods is obvious. The use of an Expression is not so obvious at this stage and I will elaborate on this functionality later in the series.

    public interface IRepository<T> where T : IEntity
    {
        T FindOne(Guid id)
;
        
T FindOne(Expression<Func<T, bool>> expression);
        
T FindOne(Specification<T> specification);

        
IQueryable<T> FindAll();
        
IQueryable<T> FindAll(Expression<Func<T, bool>> expression);
        
IQueryable<T> FindAll(Specification<T> specification);
    
}

The Repository

Implementing the repository means tying oneself to a particular Linq provider. In my case I chose Linq to NHibernate but switching it out for another implementation should be trivial.

See in the repository implementation that work is able to be integrated with the specifications by calling either SatisfyElementFrom (FindOne) of SatisfyElementsFrom (FindAll) and providing a candidate parameter provided by the Linq provider - in this case Linq to NHibernate provides a Queryable list proxy when we specify session.Linq().

    public class Repository<T> : IRepository<T> where T : IEntity
    {
        
private readonly ISession session;

        public 
Repository(ISession session)
        {
            
this.session session;
        
}

        
public T FindOne(Guid id)
        {
            
return session.Get<T>(id);
        
}

        
public T FindOne(Expression<Func<T, bool>> expression)
        {
            
return FindOne(new AdHoc<T>(expression));
        
}

        
public T FindOne(Specification<T> specification)
        {
            
return specification.SatisfyingElementFrom(session.Linq<T>());
        
}

        
public IQueryable<T> FindAll()
        {
            
return (from t in session.Linq<T>() select t);
        
}

        
public IQueryable<T> FindAll(Expression<Func<T, bool>> expression)
        {
            
return FindAll(new AdHoc<T>(expression));
        
}

        
public IQueryable<T> FindAll(Specification<T> specification)
        {
            
return specification.SatisfyingElementsFrom(session.Linq<T>());
        
}
    }

Conclusion

In this article I have shown an implementation of my repository facilitated by the use of Linq to NHibernate. The most striking part is the simplicity of the code. We have nicely seperated out our query concerns and the repository provides us with flexibility and also efficiency thanks to the power of Linq.

kick it on DotNetKicks.com

August 12, 2008 12:16 by steven.burman
E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Linq Expressions, The Specification Pattern and Repositories - Part 1


Disclaimer : I am unsure if what I am about to show here is a bridge too far in terms of bastardising the specification pattern ... it very well may be the case. However, Linq has provided a new paradigm that needs to be embraced, and sometimes that requires the tweaking of existing pratices and patterns.

Background Info

For some background on this article I recommend reading the following primers. I would never have to got to where I did without them. Please check out:

Implementing the Specification Pattern via Linq
[http://ubik.com.au/article/named/implementing_the_specification_pattern_with_linq]

Linq, the Specification Pattern and Encapsulation

[http://www.iridescence.no/post/Linq-the-Specification-Pattern-and-Encapsulation.aspx]

Implementing ORM-independent Linq queries
[http://rabdullin.com/implementing-orm-independent-linq-queries/]

The Goal

I wanted a flexible way to leverage the deferred execution power of Linq in my application. The logical place for this to occur was deep in the data access layer at the repository level. Also, as always, I wanted the ability to encapsulate my query logic into specifications and this became the real integration challenge with linq.

Specifications are easy to apply to existing in-memory collections - they fit that paradigm well. But at the lower level I knew linq could provide more power than what was previously possible with the traditional specification pattern. I wanted a way to leverage the deffered execution of Linq to drive my specifications for querying.

The Specification Class

My specification class is not dependent on any particular Linq to SQL provider. I chose to use Linq to NHibernate but that was a personal choice. I am quite sure that a switch to Linq-To-SQL would result in no modifications to any existing specifications. This provider agnostic specification implementation is a nice example of what a common language paradigm like Linq can provide.

Notice that the base abstract specification class handles all of the matching work for the specification. Any inheriting specification simply needs to specify their relevant MatchingCriteria. The SatisfyingElementFrom method (singular) simply enforces that a single result is returned. The bulk of the work is done in SatisfyingElementsFrom, which actually applies the criteria. Note that it is critical that the Matching criteria is of type Expression. This ensures we have access to the expression parsing power of Linq. Simply using a Func or a Predicate will break this implementation.

    public abstract class Specification<T> where T : IEntity
    {
        
public abstract Expression<Func<T, bool>> MatchingCriteria { get; }

        
public T SatisfyingElementFrom(IQueryable<T> candidates)
        {
            
return SatisfyingElementsFrom(candidates).Single();
        
}
        
        
public IQueryable<T> SatisfyingElementsFrom(IQueryable<T> candidates)
        {
            
return candidates.Where(MatchingCriteria).AsQueryable();
        
}
    }

A simple specification

Below is the code for a simple specification implementation. Notice how it has no responsibility apart from specifying the criteria that it represents.

    public class PersonById : Specification<Person>
    {
        
private readonly Guid id;

        public 
PersonById(Guid id)
        {
            
this.id id;
        
}

        
public override Expression<Func<Person, bool>> MatchingCriteria
        {
            
get return => p.Id == id}
        }
    }

Conclusion

So far I have demonstrated how to implement specification classes that have the potential to harness the power of Linq. Please follow the other parts of the series to see further implementation details - specifically the repository.

kick it on DotNetKicks.com

August 12, 2008 11:23 by steven.burman
E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Increasing DateTime storage precision in Nhibernate (and Castle ActiveRecord)

I was a little bit upset when I discovered that persisting a DateTime object with NHibernate in SQL Server 2005 only stored values to second precision. This was unexpected as I thought that I would not lose that much (any?) information from my DateTime instance.

So I went to the internet with problem in hand and tried to find a nice little solution for me. It didn't happen definitively so I though I might write about my solution here. I think that may be what blogs are for.

Implementing NHibernate.UserTypes.IUserType

A custom user type seemed to be the best option so I politely introduced myself to IUserType. Implementing this interface enables NHibernate to perform custom persistence operations at my specification and I'll be damned if it isn't empowering to do so!

The code below has been snipped for brevity but the full implementation is available at the end of this article. Here are the juicy bits ....

public class PreciseDateTimeUserType : IUserType
    {
        
#region IUserType Members

        ......

        
public object NullSafeGet(IDataReader rs, string[] names, object owner)
        {
            
int ordinal rs.GetOrdinal(names[0]);
            if 
(rs.IsDBNull(ordinal))
            {
                
return new NullPreciseDateTime();
            
}
            
else
            
{
                
long value = rs.GetInt64(ordinal);
                return new 
PreciseDateTime(value);
            
}
        }

        
public void NullSafeSet(IDbCommand cmd, object valueint index)
        {
            
long val ((PreciseDateTime) value);
            
((IDbDataParameter) cmd.Parameters[index]).Value val;
        
}

        .....

        
#endregion
    
}

My PreciseDateTime class

The code above introduces PreciseDateTime - a class I have created to support this process. This class represents a DateTime by internally storing it as an Int64 in FileTimeUTC format. This is the key to providing the increased precision (just be aware that the values become unreadable in the database). The PreciseDateTime class looks like this ...

    public class PreciseDateTime
    {
        
protected static long NullValue = long.MinValue;
        private long 
_dateTimeStorage;

        public 
PreciseDateTime(long dateTimeLong)
        {
            _dateTimeStorage 
dateTimeLong;
        
}

        
public bool IsNull
        {
            
get return _dateTimeStorage == NullValue}
        }

        
public PreciseDateTime Clone()
        {
            
return new PreciseDateTime(this);
        
}

        
public static implicit operator long(PreciseDateTime preciseDateTime)
        {
            
if (preciseDateTime.IsNull)
            {
                
return NullValue;
            
}
            
else
            
{
                
return preciseDateTime._dateTimeStorage;
            
}
        }

        
public static implicit operator DateTime?(PreciseDateTime preciseDateTime)
        {
            
if (preciseDateTime.IsNull)
            {
                
return null;
            
}
            
else
            
{
                
return
                    
DateTime.FromFileTimeUtc(preciseDateTime._dateTimeStorage);
            
}
        }

        
public static implicit operator PreciseDateTime(DateTime? dateTime)
        {
            
return
                new 
PreciseDateTime((dateTime.HasValue)
                                        ? dateTime.Value.ToFileTimeUtc()
                                        : NullValue)
;
        
}
    }

Notice how cool implicit operators are in this instance. Basically my code takes any DateTime? representation and implicitly converts it to a PreciseDateTime object without my intervention. This makes for more readable code and prevents errors that could be introduced by manual conversions. Use it like this ...

MyObject.PreciseDateTime DateTime.Now;

Use with Castle ActiveRecord

To start using this implementation in Castle ActiveRecord you can simply do this (inserting your own namespace where appropriate) ...

        private PreciseDateTime _created;
        
        
[Property(ColumnType "Project.Domain.UserTypes.PreciseDateTimeUserType, Project.Domain")]
        
public virtual PreciseDateTime Created
        {
            
get return _created}
            
set { _created = value; }
        }

So I am now assured of not forgetting (again) how to implement custom user types for NHibernate and Castle ActiveRecord. If anything here is blatantly wrong please shout out - for everyone's sake.

If you crave more information about FileTimeUtc and what it represents go to the almighty MSDN

Full code for this article is available here : PreciseDateTimeUserType.cs (3.71 kb)

November 15, 2007 11:59 by steven.burman
E-mail | Permalink | Comments (3) | Comment RSSRSS comment feed