05
Aug
10

This blog has moved

To http://blog.hitchman.net. See you there

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

27
Jul
09

Dependency Injection for NHibernate

Sly has asked about the DependencyInjectionInterceptor class I referred to in a previous post.

Here is the class:

    ///<summary>
    /// An NHibernate interceptor that instantiates objects from a DI container.
    ///</summary>
    public class DependencyInjectionInterceptor : EmptyInterceptor
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(DependencyInjectionInterceptor));
        private readonly IKernel container;
        private readonly Check chk = new Check();
        ///<summary>
        /// Construct the <see cref="DependencyInjectionInterceptor"/>.
        /// Entities found by name in the container will be resolved from there.
        /// All other entities will use default NHibernate instantiation.
        ///</summary>
        ///<param name="container">The IoC container</param>
        public DependencyInjectionInterceptor(IKernel container)
        {
            this.container = container;
        }
        /// <summary>
        ///             Instantiate the entity class. Return <see langword="null" /> to indicate that Hibernate should use the default
        ///             constructor of the class
        /// </summary>
        /// <param name="entityName">the name of the entity </param>
        /// <param name="entityMode">The type of entity instance to be returned. </param>
        /// <param name="id">the identifier of the new instance </param>
        /// <returns>
        /// An instance of the class, or <see langword="null" /> to choose default behaviour
        /// </returns>
        /// <remarks>
        ///             The identifier property of the returned instance
        ///             should be initialized with the given identifier.
        /// </remarks>
        public override object Instantiate(string entityName, EntityMode entityMode, object id)
        {
            try
            {
                return container.Resolve(entityName, new {Id = id});
            }
            catch(ComponentNotFoundException)
            {
                chk.Assert(!container.HasComponent(entityName),
                           string.Format(
                                   "Entity {0}, registered in the container, could not be constructed with an 'Id' " +
                                   "dynamic argument. The DependencyInjectionInterceptor expects to find a component " +
                                   "with a contructor having all dependencies satisfied and with a property named 'Id' to " +
                                   "take the object's id (key).",
                                   entityName));
                log.DebugFormat(
                        "Instantiate: Entity {0} was not registered in the container. Using default NHibernate contruction.",
                        entityName);
                return null;
            }
        }
    }

IKernel is the Castle Micro Kernel (within Windsor). Each entity (mapped class) needs to be registered in the container and must have an Id property.

One important ‘gotcha’ is that Castle will inject into public properties by default, so a class with a many-to-one will be given a default instance of the ‘one’ type by Castle, which you probably don’t want. The simplest way to stop this is to decorate the property with the DoNoWireAttribute in Castle.Core. There are other smarter ways.

As I mentioned in my reply to Sly, alternatives based on the latest NH release are described on NHForge.

04
Jun
09

Aptitude testing software engineers

I sat a three-hour aptitude test yesterday that is designed to test my ability to concentrate, understand complex requirements and accurately implement (follow) instructions.

It was a mentally draining experience. Afterwards I was trying to find a way of explaining the test to my wife (who is a lawyer and mediator, not a techie). She shivered in horror as I explained it to her.

On further reflection I think the following analogies fairly represent the test:

  • The requirements (questions) were written by a psychopathic school principal.
  • The hardware platform was a 1970’s Russian copy of a 1960’s Apollo mission computer.
  • The development was outsourced to a South American software house (at which point the requirements were translated to Spanish). They subcontracted to a developer found on RentACoder who wrote the code in his bedroom.
  • I’ve been asked to debug and prove the programs correctness with only a fan-fold dot-matrix source code listing.

I think I did fairly well. It certainly makes you think hard. The questions are perfectly fair, but are designed to lead you towards false assumptions and dangerous short-cuts.

The things you go through to get a good job!

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

10
May
09

Firefox: Always restore your previous session without the prompt

I often shutdown my machine without closing Firefox. Next time I restart the browser it asks me if I want to resume the previous session.

I always want to restore as the first 5 or 6 tabs are my ‘always open’ apps (GMail, Google Reader, etc,). Clicking ‘Resume Previous Session’ all the time really hacks me off.

Now a bit of Googling turns up innumerable posts about disabling session restore so you always start a new session, but finding information about the opposite behaviour, i.e. always restoring the previous session (without asking) is much harder to find.

In order to raise the profile of this feature, I’m linking to the only other post I know about that talks about this. Ironically I only found this after browsing the source and ‘reverse engineering’ my Google query.

The solution is a bit of a hack as the behaviour I require isn’t directly supported. However Firefox allows extensions to override the default prompt and we can exploit this.

Head to about:config and create a string key ‘browser.sessionstore.restore_prompt_uri‘ and give it a value of ‘javascript:window.close();‘. This tell Firefox that a custom session restore prompt has been provided… which is immediately terminated.

Luckily the session restore code assumes that we want to restore unless the prompt returns otherwise and the net result is no prompt and automatic session restoration.

I hope this takes a little bit of friction out of your day.

07
Apr
09

Australia’s National Broadband Network

Kevin Rudd, the Australian PM has just announced a National Broadband Network providing fibre to the home at speeds of 100Mb/s within the next eight years.

That’s pretty exciting! Except that broadband plans in Oz tend to be capped. I just worked out it would take me 34.1 minutes to use my current monthly quota at this speed.




Follow

Get every new post delivered to your Inbox.