Archive for the '.net' Category

21
Aug
09

StructureMap and Scanning With Custom Conventions

On my new project we are attempting to use convention over configuration wherever possible to make the developer’s lives easier and our code less error prone.

One way we are doing this is by creating custom type scanners in StructureMap (our selected IoC container).

For example, we have  an interface IEntityMapper<T> that defines the base contract for mapping POCO classes into SharePoint list items (an evolution of SharePoint Guidance).

So given an POCO entity Cheese we also have a entity mapper like:

public class CheeseMapper : IEntityMapper<Cheese>
{
    //... methods implementing the interface (not important)
}

We could easily tell StructureMap to make CheeseMapper the default concrete type of IEntityMapper<Cheese> and repeat for all other entity mappers:

public class ARegistry : StructureMap.Configuration.DSL.Registry
{
     public ModelRegistry()
     {
         ForRequestedType<IEntityMapper<Cheese>>()
                 .TheDefaultIsConcreteType<CheeseMapper>()
     }
}

But this is error prone as I know I will forget to add the registry entry in StructureMap. And because our unit tests create minimal IoC containers for each fixture we aren’t going to pick this up until the integration test.

A better way is to register by convention:

public class ARegistry : StructureMap.Configuration.DSL.Registry
{
     public ModelRegistry()
     {
            Scan(
                    scan =>
                    {
                        scan.AssemblyContainingType(GetType());
                        scan.With<EntityMapperScanner>();
                    });
     }
}

public class EntityMapperScanner : ITypeScanner
{
    public void Process(Type type, PluginGraph graph)
    {
        if(!type.IsClass || type.IsAbstract)
           return;

        var selectedInterface =
               (from candidateInterface in type.GetInterfaces()
                where candidateInterface.IsGenericType
                where typeof(IEntityListMapper<>)
                            .IsAssignableFrom(
                                candidateInterface.GetGenericTypeDefinition()
                            )
                select candidateInterface).SingleOrDefault();

        if(selectedInterface != null)
            graph.Configure(r =>
                   {
                       r.ForRequestedType(selectedInterface)
                        .TheDefaultIsConcreteType(type);
                   });
    }
}

This code inspects each type in the assembly and for each type determines whether it implements the open generic type IEntityMapper<>. If it does, it takes the closed generic interface (i.e. IEntityMapper<Cheese>) as the service to register and the provided type as the implementation.

kick it on DotNetKicks.com

Advertisements
15
May
09

The ‘Always Valid Entity’ is not a fallacy

I had to comment on Jeffrey Palermo’s recent post entitled ‘The fallacy of the always-valid entity’ as I both disagreed with what he was suggesting and wonder if he has missed the point. I thought I’d follow up here with an example that demonstrates how I implement an always valid entity. Many other comments on the post allude to similar approaches also. If you haven’t already, read Jeffrey’s post before reading on.

Jeffrey’s UserProfile class initially throws exceptions in property setters if null values are supplied. These are invariants. I think he’s arguing against this approach. He then evolves the example to present a validation framework that allows a collection of rules to be asserted against an instance of the entity and reports back failed rules.  The rules are intended to be context specific validations, but the context is missing (at least from the example given).

He additionally talks about legacy data and the need to allow for invalid entities for unspecified reasons. He concludes with

“It is futile to attempt to keep entities always-valid.  Let bad things happen to them, and then validate”.

No! I disagree.

If we can’t know an entity is valid anywhere we use it then we can’t afford to trust it. We end up with code where, before we use an entity, we go and check that it is in a suitable state for us. These ‘entities’ are just data structures. They are missing behaviour that enforces internal consistency.

So, how can we build entities in C# that are always valid?

  1. No public property setters. This stops the entity being used as a data structure. It is no longer possible to break the internal state of an entity by abusing setters.
  2. The instance constructor leaves the entity in a valid initial state. It sets sensible defaults for fields, it takes parameters to override defaults and  other parameters to provide values for fields with no sensible default.
  3. Entities are updated by a context-specific ‘command’ method that acts atomically on the instance.

Let’s rework Jeffrey’s UserProfile class to make it an always valid entity, assuming that:

  • The user’s Name must not be empty,
  • The Gender can be one of male, female or unknown.
  • The JoinedDate cannot be null, but can (for now) contain any valid date. You might argue that future dates should be invalid or that the JoinedDate be optional—let’s just ignore this at the moment; is is immaterial for this example.
  • The LastLogin must not be earlier than the JoinedDate.
    public enum Gender
    {
        Unknown = 0,
        Male,
        Female
    }
 
    public class User
    {
        private string name;
 
        public string Name
        {
            get
            {
                return name;
            }
            private set
            {
                if (string.IsNullOrEmpty(value))
                    throw new ArgumentNullException("Name");
 
                name = value;
            }
        }
 
        public Gender Gender { get; private set; }
        public DateTime JoinedDate { get; private set; }
        public DateTime? LastLogin { get; private set; }
 
        public User(string name, Gender gender, DateTime joinedDate)
        {
            Name = name;
            Gender = gender;
            JoinedDate = joinedDate;
        }
 
        public void UpdateProfile(string name, Gender gender)
        {
            Name = name;
            Gender = gender;
        }
 
        public void RecordLogin(DateTime loginTime)
        {
            if (loginTime < JoinedDate)
                throw new InvalidOperationException("loginTime cannot be earlier than JoinedDate");
 
            LastLogin = loginTime;
        }
    }

Whilst I personally wouldn’t want this code in production, lets look at what it has achieved.

  • Gender is an enumeration. This restricts us to valid values at compile time. However, we explicitly recognise a business requirement that the gender may not be known, rather than allow an indeterminate null state.
  • I prefer the entity name User rather then UserProfile. We are modeling a domain with Users. A user’s profile is the properties of the User entity. UserProfile screams data structure.
  • I’ve opted for automatic properties with private setters for most properties. This means the presentation layer can read my entity to create a View Model or for direct binding, but updates through properties are not possible.
  • Where I have an invariant I wish to enforce, I’ve opted to use the private property setter to enforce this. This is a compromise and we must trust our developers not to short-circuit the setter, either by malice or ignorance. This is a pretty weak form of validation (but good enough for this example). Bear with me, I’ll blog on this shortly.
  • ‘Command’ methods update the entity in a controlled manner. They return void. They have atomic behaviour, by which I mean a logical update is made in one call to the instance.
    • The business has asked that the user can update their profile. The name must not be empty.
    • The business also wants to record the last login time for users. Note that we aren’t using DateTime.Now here, as this has two shortcomings: it hurts testability and explicitly ties the time of the execution of the RecordLogin method to the time of the executing server. RecordLogin might be at the end of an message queue that processed the message minutes after the login actually occurs.
  • The constructor and the UpdateProfile method both use the Name setter and therefore the non-empty name invariant is enforced.
  • Note that users of NHibernate or other ORM frameworks might require a default constructor. If so make the accessability as restrictive as possible (that’s ‘protected’ for NH).
  • We can use a validation framework that implements a notify pattern (as in Jeffrey’s example) if we wish. I kept it simple for this example.

Given the rules above, it is not possible to get this entity into an invalid state. As for bulk loads and legacy data, this entity will insist that the external data is correct. Use a data cleansing tool to make sure the data meets your domain models requirements.

In my next post I’ll look at how to improve this code further through the use of value objects.
kick it on DotNetKicks.com

16
Mar
09

Composing Specifications

In my previous post, I suggested that composing specifications using my implementation may prove difficult. It turns out not to be so hard.

  public readonly Func<long, Predicate> IdEqualWithARunningSheet;
  public HasSpecifications()
  {
      IdEqualWithARunningSheet = (id => IdEqual(id).And(ARunningSheet()));
  }

Because the specifications are defined as instance members, we need to use the constructor to reference them, which is a shame. We could make the specification members static, but then the LINQ queries start to look odd.

The And method looks like this:

public static Expression<Func<T, bool>> And<T>(
        this Expression<Func<T, bool>> source,
        Expression<Func<T, bool>> other)
{
    return (Expression<Func<T, bool>>) Expression.Lambda(
                                               Expression.AndAlso(source.Body, other.Body),
                                               source.Parameters.ToArray());
}
13
Mar
09

Specification Pattern and LINQ to NHibernate

We love Specifications!

Oh no, not another post about the Specification pattern! Oh yes, to add to the existing body of knowledge found here, here, here, here, here, here, and in many other places, I’d like to present my own take on the pattern.

My particular focus is on smooth integration with LINQ, and the approach described below manages this but does have some limitations.

Consider this a proof-of-concept if you will. It certainly hasn’t been exercised in production code with real world queries yet.

Wouldn’t it be nice…

…If we could write something like this and have NHibernate.Linq interpret the method call to SQL:

Specifications in Linq
var withId100 = 
     from shift in repository.Query<Shift>()
     where shift.Has.IdEqual(100)
     select shift;
         
var withRunningSheets = 
     from shift in repository.Query<Shift>()
     where shift.Has.ARunningSheet()
     select shift;

var involvingUser = 
     from shift in repository.Query<Shift>()
     where shift.Has.InvolvementOf(loggedOnUser)
     select shift;

It is possible!

If we rewrite the embedded LINQ as a method chain we can see that IQueryable<T>.Where takes an Expression<Func<T,bool>> parameter, so our specification (e.g. IdEqual, HasInvolvementOf) needs to return this type.

Exploiting partial function application we can make the signature of our specification would look like:

Specification signature
   public readonly Func<long, Expression<Func<Shift,bool>>> IdEqual =
           id => shift => shift.Id == id;

This does look a little daunting, but we can ease the eyestrain by judicious use of a using alias:

Easier on the eye
namespace VicPol.ERS.Model.RunningSheets
{
    using Predicate = Expression<Func<Shift, bool>>;
    public class Specifications
    {
        public readonly Func<long, Predicate> IdEqual =
                id => shift => shift.Id == id;
    }
}

What we have here is a field member (IdEqual) that returns a function that takes a long and returns an expression tree representing a function that takes a Shift and returns a boolean. (Did you get that?)

Linq is interested in the expression tree. In the examples above (Specifications in Linq) ‘shift.Has.IdEqual(100)’ is calling the function returned by IdEquals with the value 100. The Where extension method takes the return value.

This compiles fine but, as you’d expect, NHibernate.Linq doesn’t know what IdEqual means.

This leaves us with the challenge of transforming the method call into the expression returned by the method. Ideally NHibernate.Linq could do this for us, but given the current rework going on around Linq providers for NHibernate I’ve not even attempted this.

Instead we cheat and overload the Where method again to provide an implementation that does this translation.

The method translator
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace VicPol.ERS.Model.Persistence
{
    public static class SpecificationExtensions
    {
        public static IQueryable<T> Where<T>(this IQueryable<T> source, Expression<Func<T, Expression<Func<T, bool>>>> spec)
        {
            return source.Where(getPartiallyAppliedSpecification(spec));
        }
         
        public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Expression<Func<T, Expression<Func<T, bool>>>> spec)
        {
            return source.Where(getPartiallyAppliedSpecification(spec).Compile());
        }
         
        public static bool Satisfies<T>(this T source, Func<T, Expression<Func<T, bool>>> spec)
        {
            return IsSatisfiedBy(spec(source), source);
        }
         
        public static bool IsSatisfiedBy<T>(this Expression<Func<T, bool>> source, T candidate)
        {
            return source.Compile()(candidate);
        }
         
        private static Expression<Func<T, bool>> getPartiallyAppliedSpecification<T>(
                Expression<Func<T, Expression<Func<T, bool>>>> specificationExpression)
        {
            //We're expecting a call to a function provided by some field member.
            var invocationExpression = specificationExpression.Body as InvocationExpression;
            if(invocationExpression == null) throw new ArgumentException("Expected invocation expression");
            var memberExpression = invocationExpression.Expression as MemberExpression;
            if(memberExpression == null) throw new ArgumentException("Expected invocation expression to reference member");
         
            //The members return value is itself a function. 
            //This is what gets evaluated by the LINQ QueryProvider. 
            //We cache this to avoid repeated reflection and instance creation.
            MulticastDelegate openSpec;
            if(!cache.TryGetValue(memberExpression.Member, out openSpec))
            {
                //If the function is not cached, we create an instance of the member's declaring 
                //type and invoke the member to get the function.
                var member = memberExpression.Member as FieldInfo;
                if(member == null) throw new ArgumentException("Expected member expression to reference field");
                if(!member.FieldType.IsSubclassOf(typeof(MulticastDelegate)))
                    throw new ArgumentException("Expected member to be a subclass of MulticastDelegate (e.g. Func<>)");
         
                var instance = Activator.CreateInstance(member.DeclaringType);
                openSpec = (MulticastDelegate) member.GetValue(instance);
         
                lock(cacheLock)
                    if(!cache.ContainsKey(memberExpression.Member))
                        cache.Add(memberExpression.Member, openSpec);
            }
         
            //Now we take the arguments provided to the specification expression and invoke the function with them.
            //This results in the partially applied expression function that is passed to the QueryProvider.
            var args = invocationExpression.Arguments.Select(
                    arg => Expression.Lambda(arg, null).Compile().DynamicInvoke())
                    .ToArray();
            return (Expression<Func<T, bool>>) openSpec.DynamicInvoke(args);
        }
         
        public static int CacheSize
        {
            get { return cache.Count; }
        }
         
        public static void ClearCache()
        {
            cache.Clear();
        }
         
        private static readonly object cacheLock = new object();
        private static readonly IDictionary<MemberInfo, MulticastDelegate> cache =
                new Dictionary<MemberInfo, MulticastDelegate>();
    }
}

There’s quite a bit going on here. Firstly we have the extension methods IQueryable<T>.Where and IEnumerable<T>.Where; these overload the existing extension methods in System.Core. The signature for the specification parameter causes the compiler to convert the specification field (e.g. IdEqual) to an expression tree. Satisfies and SatisfiedBy allow the specification to be used by assertions (for example validation of business rules).

Hopefully the comments in the method getPartiallyAppliedSpecification explain what is going on sufficiently clearly. This method is the heart of making specifications work ‘nicely’ with Linq. I’ve make a cursory attempt to make the caching of the reflection, instance activation and method call thread safe. Please correct and improve this code!

The methods CacheSize and ClearCache are there only for testing.

Putting it all together

Declaring specifications
using System;
using System.Linq;
using System.Linq.Expressions;
using VicPol.ERS.Model.Support;

namespace VicPol.ERS.Model.RunningSheets
{
    using Predicate = Expression<Func<Shift, bool>>;
    public partial class Shift
    {
        private HasSpecifications has;
        public virtual HasSpecifications Has
        {
            get
            {
                if(has == null) has = new HasSpecifications();
                return has;
            }
        }
         
        public class HasSpecifications
        {
            public readonly Func<long, Predicate> IdEqual =
                    id => shift => shift.Id == id;
         
            public readonly Func<Predicate> ARunningSheet =
                    () => shift => shift.RunningSheet != null;
         
            public readonly Func<User, Predicate> InvolvementOf =
                    user => shift =>
                            shift.Sessions.Any(
                                    session =>
                                    session.LogOn.UserId == user.UserName ||
                                    session.LogOn.User2 == user.UserName ||
                                    session.LogOn.User3 == user.UserName ||
                                    session.LogOn.User4 == user.UserName);
        }
    }
}

The specification ‘InvolvementOf’ begins to reveal the power of the specification pattern in Linq. The following snippet show the specifications in use:

Using specifications in NHibernate.Linq queries
  var shiftWithId100 =
      from shift in repos.Query<Shift>()
      where shift.Has.IdEqual(100)
      select shift;
         
  var shiftWithARunningSheet =
      from shift in repos.Query<Shift>()
      where shift.Has.ARunningSheet()
      select shift;
         
  var shiftWithIdEquals100AndWithARunningSheet =
      from shift in repos.Query<Shift>()
      where shift.Has.IdEqual(100)
      where shift.Has.ARunningSheet()
      select shift;
         
  var shiftInvolvingUser =
      from shift in repos.Query<Shift>()
      where shift.Has.InvolvementOf(loggedOnUser)
      select shift;

As can be seen in the third example, specifications can be combined in queries, however the somewhat more natural syntax of using ‘&’ between the constraints is not possible as the & operator is not defined on the Expression class (normally the & would be part of the expression tree). Other operators, like ‘!’ (not) also suffer a similar fate. Also using this style of specification as an assertion (the Satisfies method) is a little clunky. I haven’t yet tried to see how composable these specifications are, but I suspect this may be a further limitation.

Finally, I hope NHibernate.Linq will formally support specifications in the near future.

24
Feb
09

Fluent NHibernate with Burrow

I like Burrow for web application development. I’ve used it on two projects now and it basically just disappears into the background.

The new kid on the block is Fluent NHibernate. This is very cool. Bye bye angle bracket tax!

So for my latest project I decided to use them both. Getting them to work together took a little bit of digging around in the source of Burrow, as it likes to be configured by XML from your web.config.

Here how I have it set up.

    <NHibernate.Burrow customConfigurator="VicPol.ERS.Model.Persistence.NHibernateMapping, VicPol.ERS.Model" >
        <persistenceUnits>
            <add name="MDN" nh-config-file="~\nhibernate.config" />
        </persistenceUnits>
    </NHibernate.Burrow>


The interesting part of this is the attribute ‘customConfiguration’ which tells Burrow to instantiate an instance of the type given as the attribute value and use this to customise Burrow and/or NHibernate at run time.

This type must implement NHibernate.Burrow.IConfigurator:

using FluentNHibernate;
using log4net;
using NHibernate.Burrow;
using NHibernate.Cfg;
using VicPol.ERS.Model.Support;
 
 
namespace VicPol.ERS.Model.Persistence
{
    public class NHibernateMapping : IConfigurator
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(NHibernateMapping));
 
 
 
        public virtual void Config(IBurrowConfig val)
        {
        }
 
 
 
        public virtual void Config(IPersistenceUnitCfg puCfg, Configuration nhCfg)
        {
            log.DebugFormat("Config: Setting up NHibernate DependencyInjectionInterceptor and Mappings");
 
            nhCfg.SetInterceptor(new DependencyInjectionInterceptor(Container.EntitySubkernel));
            nhCfg.AddMappingsFromAssembly(typeof(NHibernateMapping).Assembly);
        }
    }
}


The second overload of Config is run for each persistence unit. It takes an instance of NHibernate.Configuration which lets us play around as we see fit with the NH configuration.

I’m using the extension method AddMappingsFromAssembly provided by FluentNHibernate to set up my entity mapping fluently.

As an aside, the other code in here tells NHibernate to use a dependency injection container to construct the entities it loads.