Archive for the ‘ Software development ’ Category

Letting your UnitOfWork & Repositories support multiple frameworks

A little while ago I found myself in a situation where I had to replace Microsoft’s Entity Framework with NHibernate. I had figured this wouldn’t be too much of a problem! I had neatly used a Unit of Work and Repository implementation for all my data access needs, so I felt pretty secure in the knowledge that I should be able to switch quite quickly between the two.

Eventually I did, it wasn’t near as quick as I had initially thought though. I discovered that all these articles on the internet describe how to implement a Unit of Work for a single framework! The one I had written was focused solely on the Entity Framework and was pretty much useless for NHibernate. Dismayed, I decided to scrap what I had and start over with the design. This time specifically keeping in mind that I might want to be able to swap between the two at some point in the future.

Let’s start at the begin. To be able to create a common interface for my repositories, and a common way to interact with my repositories, I decided I would need a common UnitOfWork interface as well. It doesn’t have to do anything, as long as it gives me the ability to cast my objects back and forth.

/// <summary>
/// Doesn't do anything besides providing a common interface.
/// </summary>
/// <remarks>
/// TODO: Distinguish common functionality later and implement it!
/// </remarks>
public interface IUnitOfWork : IDisposable
{
}

Well, that was easy! I now have my interface. I can already picture the frown on your face. After all, what’s the bloody point of an interface without methods?! Admittedly, not much at first sight. Bear with me and you’ll find out why I’ve done this.

The following thing I needed was some sort of interface that allows me to specify the type of context for the Unit of Work. Aha! I smell generics!

/// <summary>
/// Provides a generic interface for a Unit of Work.
/// </summary>
public interface IUnitOfWork<TContext> : IUnitOfWork
{
    TContext Context;
    void SaveChanges<TEntity>(TEntity entity);
    void CancelChanges();
}

Let’s not worry about the specifics yet. The only thing I am worried about here is providing a generic Unit of Work. This way I can simply define a Unit of Work and give the type of the context along with it, for example the ObjectContext for EF4 and ISession for NHibernate! Pretty neat We’re not done yet though. Because the Entity Framework and NHibernate are so different from each other, I decided to implement specific interface for each of those as well. I can imagine different methods might be useful when working with one or the other.

/// <summary>
/// Implement Unit of Work specifically for Entity Framework.
/// Details can be implemented later.
/// </summary>
public interface IEFUnitOfWork : IUnitOfWork<ObjectContext>
{
}

/// <summary>
/// Implement Unit of Work specifically for NHibernate.
/// Details can be implemented later.
/// </summary>
public interface INHUnitOfWork: IUnitOfWork<ISession>
{
}

That’s it! I have now defined the interfaces that will help me with building a common repository interface and a common way of using concrete repositories. Let’s go and have a look at the repositories. Here’s a simple interface for the repositories, it only has three methods for now, but of course you can expand on that to your own liking.

public interface IRepository<T>
{
    T GetFirst(Expression<Func<T, bool>> where,
        Expression<Func<T, object>>[] eagerFetch);

    IEnumerable<T> GetMany(Expression<Func<T, bool>> where,
        Expression<Func<T, object>>[] eagerFetch);

    IEnumerable<T> GetAll(Expression<Func<T, object>>[] eagerFetch);
}

I can now use this interface to implement different base repositories for Entity Framework as well as NHibernate.

I will start by showing the implementation for the Entity Framework. If you pay close attention to it, you will see that the AddIncludesToObjectSet() method uses a generic Include<T> method. This is an extension method on top of the ObjectQuery object. I’ll probably explain this in a follow-up post!

public abstract class Repository<T> : IRepository<T> where T : class
{
    private IEFUnitOfWork unitOfWork;
    private ObjectContext objectContext;
    private ObjectQuery<T> objectSet;

    /// <summary>
    /// Constructs an EntityFramework repository.
    /// </summary>
    /// <param name="unitOfWork">Unit of Work for repository to work with.</param>
    public Repository(IUnitOfWork unitOfWork)
    {
        this.unitOfWork = (IEFUnitOfWork)unitOfWork;
        this.objectContext = this.unitOfWork.Context;
    }

    public virtual T GetFirst(Expression<Func<T, bool>> where,
        Expression<Func<T, object>>[] eagerFetch)
    {
        this.objectSet = this.objectContext.CreateObjectSet<T>();
        AddIncludesToObjectSet(eagerFetch);

        return this.objectSet
            .Where(where)
            .FirstOrDefault();
    }

    public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where,
        Expression<Func<T, object>>[] eagerFetch)
    {
        this.objectSet = this.objectContext.CreateObjectSet<T>();
        AddIncludesToObjectSet(eagerFetch);

        return this.objectSet
            .Where(where)
            .AsEnumerable();
    }

    public virtual IEnumerable<T> GetAll(Expression<Func<T, object>>[] eagerFetch)
    {
        this.objectSet = this.objectContext.CreateObjectSet<T>();
        AddIncludesToObjectSet(eagerFetch);

        return this.objectSet
            .AsEnumerable();
    }

    private void AddIncludesToObjectSet(Expression<Func<T, object>>[] eagerFetch)
    {
        if (eagerFetch != null)
        {
            foreach (Expression<Func<T, object>> fetch in eagerFetch)
            {
                this.objectSet.Include<T>(fetch);
            }
        }
    }
}

For the NHibernate repository I came up with the following code below this paragraph. Keep in mind that I’ve used the alpha version of NHibernate 3.0 and therefor I’m able to use the NHibernate.Linq namespace easily and call the Query<T>() method on the ISession object!

public abstract class Repository<T> : IRepository<T> where T : class
{
    private INHUnitOfWork unitOfWork;
    private ISession session;

    public Repository(IUnitOfWork unitOfWork)
    {
        this.unitOfWork = (INHUnitOfWork)unitOfWork;
        this.session = this.unitOfWork.Context.SessionFactory.GetCurrentSession();
    }

    public virtual T GetFirst(Expression<Func<T, bool>> where,
        Expression<Func<T, object>>[] eagerFetch)
    {
        IQueryable<T> query = this.session
            .Query<T>()
            .Where(where);

        query = AddFetchMode(query, eagerFetch);

        return query.FirstOrDefault();
    }

    public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where,
        Expression<Func<T, object>>[] eagerFetch)
    {
        IQueryable<T> query = this.session
            .Query<T>()
            .Where(where);

        query = AddFetchMode(query, eagerFetch);

        return query.AsEnumerable();
    }

    public virtual IEnumerable<T> GetAll(Expression<Func<T, object>>[] eagerFetch)
    {
        IQueryable<T> query = this.session.Query<T>();
        query = AddFetchMode(query, eagerFetch); 

        return query.AsEnumerable();
    }

    private IQueryable<T> AddFetchMode(IQueryable<T> queryable,
        Expression<Func<T, object>>[] eagerFetch)
    {
        if (eagerFetch != null)
        {
            foreach (Expression<Func<T, object>> fetch in eagerFetch)
            {
                queryable = queryable.Fetch(fetch);
            }
        }

        return queryable;
    }
}

What have I achieved after all this trouble? That I can write our repositories once and never change them, regardless if I’m working with NHibernate or Entity Framework! Also, this is the part where my useless interface without methods comes into play! I know I have an IUnitOfWork object and I can simply pass it along to the constructor of this repository, regardless of the fact if it is an INHUnitOfWork or IEFUnitOfWork. Perhaps this part can still use a bit of work with type safety, so that there are no accidents with passing along a IEFUnitOfWork to a repository that is expecting a INHUnitOfWork!

public class ConcreteRepository : Repository<TEntity>, IConcreteRepository
{
    public ConcreteRepository(IUnitOfWork unitOfWork)
        : base(unitOfWork)
    {
    }
}

The only thing I would need to do when I switch between NHibernate or Entity Framework now is to change the using statement and the project references to point to the proper assembly containing the specific classes and interfaces!

using Storminajar.Framework.Data.NHibernate;

or

using Storminajar.Framework.Data.EntityFramework;

Of course I would still need to make my application aware of which Unit of Work to use and I would have to implement that logic somewhere, but at least I won’t have to change my code of my repositories!

Loading embedded UserControls from assemblies

I needed a way to share custom UserControls between different projects. There are a lot of articles about this already on the web, but it did take me a little while to pick a suitable approach and work it out. I eventually settled for creating a VirtualPathProvider and embedding my UserControls in the assembly of a separate web application. The inspiration came from this article on codeproject.

It really works like a charm, but I didn’t like the way how the LoadControl() gets called. From my point of view it felt a little unnatural to remember the specific way to build the virtual path to load the assembly. I wrapped this in a little extension method on the Page class. It’s just a little wrapper to provide a clearer call to LoadControl().

public static class PageExtensions
{
    public static Control LoadControl(this Page page, string assemblyName,
        string namespaceName, string userControlName)
    {
        try
        {
            string virtualPath = String.Format("~/App_Resource/{0}/{1}.{2}",
                assemblyName, namespaceName, userControlName);

            return page.LoadControl(virtualPath);
        }
        catch (Exception ex)
        {
            throw new Exception("Loading embedded user control failed! "
                + "See InnerException for more details.", ex);
        }
    }
}

This way, whenever I need to load a UserControl that has been embedded in an assembly, I can simply call the overloaded LoadControl() method without having to remember the precise syntax of the URL. For example:

protected void Page_Load(object sender, EventArgs e)
{
    Control myCustomCtrl = LoadControl(
        "Storminajar.MyWeb.UserControls.dll",
        "Storminajar.MyWeb.UserControls",
        "CustomControl.ascx");

    // Add control to the page.
    this.PlaceHolder1.Controls.Add(myCustomCtrl);
}

The good part about this is that I can still cast the Control to a real CustomControl object and set additional properties if I want to. Remember when doing this, a reference needs to be made to the Storminajar.MyWeb.UserControls.dll assembly! The reference isn’t strictly necessary when just loading a UserControl without the need to access specific properties.

Also, an interesting  thing I found out is that I can only seem to load this control through the code-behind. When I declare the control in my aspx file, it doesn’t seem to want to instantiate the controls (such as combo boxes, grids, etc). So, for example, the following code does not work:

<%@ Page Language="C#" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="Storminajar.MyWeb.Default"
    MasterPageFile="~/Shared/Templates/Site.Master"
    Title="Default page illustrating my example." %>

<%@ Register Assembly="Storminajar.MyWeb.UserControls"
    Namespace="Storminajar.MyWeb.UserControls" tagPrefix="Library" %>


    

Nor does the following work:

<%@ Page Language="C#" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="Storminajar.MyWeb.Default"
    MasterPageFile="~/Shared/Templates/Site.Master"
    Title="Default page illustrating my example." %>

<%@ Register tagPrefix="Library" tagName="CustomControl"
    Src="~/App_Resource/Storminajar.MyWeb.UserControls.dll/
           Storminajar.MyWeb.UserControls.CustomControl.ascx"
%>


    

I can’t for the life of me imagine why this wouldn’t instantiate all the different components in the UserControl; especially Telerik components, such as: RadComboBox, RadGrid, etc. If anyone spots the errors (ignore the capitalisation issues in my sample, for some reason I can’t get the text formatted properly), I would appreciate it if you let me know!

Replacing Entity Framework with NHibernate

A few weeks ago, we came to the conclusion that there are a few vital issues with Microsoft’s latest Entity Framework.

I had already discovered the limitations of the designer when working with large models. To my surprise this has been a known issue for a very long time, but there no improvements have been made with the release of Entity Framework 4.0. A guideline I’ve seen on MSDN says that models from about 125 entities and upwards should be split up. Ironically enough, there’s hardly any support for splitting a model in different parts and I would end up with editing my mapping files manually, because there’s no designer support once you go down this road.

However, there’s an even bigger issue that we ran into, while performing the most basic operations in our real world application. We had chosen to work with Self Tracking Entities, as it looked to be a perfect and simple solution for all our problems. Yeah, I know… we should have known better! I’ll give you a simple example, that has nothing to do with our real world application, but will give you a clear insight in the problems.

Consider the following scenario: we have a web page that shows a list of cats. Every cat has an owner (well that’s what the owner likes to think anyway). Let’s say we want to change the owner for a cat.

I would consider this just a very basic chore, easily be solved in a way like this:

public void UpdateTheCat(int catId, Owner newOwner)
{
    Cat myCat = this.Cats.Where(c => c.CatId == catId).Single();
    myCat.StartTracking();

    // Update cat properties and eventually the owner.
    myCat.Owner = newOwner;

    using (IUnitOfWork uof = ObjectFactory.Create<IUnitOfWork<())
    {
        ICatRepository icr = ObjectFactory.Create<ICatRepository<(uof);
        icr.Update(myCat);
    }
}

Where the CatRepository Update method would do something like this:

public void UpdateCat(Cat myCat)
{
    this.objectContext.ApplyChanges<Cat>(myCat);
    this.objectContext.SaveChanges();
}

Well, this is simply not possible. No matter what I did, whenever I tried to update a Navigation Property in a detached object, I would get an exception telling me that there were duplicate key values in the ObjectStateManager. Apparently someone in Microsoft’s Entity Framework team has made this by design. You’re not allowed to simply update your object this way because it could be that both objects would have changed and the Entity Framework wouldn’t be able to resolve the conflict.

That’s an understandable design decision. What’s not so understandable is that they check if it’s the same object based on it’s reference (aka. memory pointer). So, if I fetch a cat object from the database and, at a later stage in my code, create a complete new cat with the exact same values then, apparently, it’s not the same cat! Purely from a technical point of view this is 100% correct, because my new cat is in a different part of the server memory. However, from a functional point of view it’s still the exact same cat.

So, simply updating objects or adding and removing objects from a collection becomes a huge pain in the backside. Of course Microsoft presents workarounds. But, that’s exactly what they are, workarounds. In our case the workarounds weren’t very useful either, so we were stuck.

Feeling very disappointed I set out to learn more about NHibernate. It didn’t take long before we discovered we could simply cross out a lot of the limitations from the Entity Framework. To our delight we discovered that the NHibernate session is light-weight enough to store in the HttpSession! This looks to be a major advantage for us! This means the session can keep tracking its own changes over multiple requests to the server!

More to come later…

Creating a custom ConfigurationSection

Yesterday afternoon and the early bits of this morning I spent my time breaking my head on creating a custom ConfigurationSection. I kept getting an exception with the message unrecognized element ‘add’. I thought it would all be so simple!

Here’s the background of why I ended up tinkering with this stuff. I wanted to define a few custom tags in my web.config to specify which modules should be loaded when the application would start. A quick google search learned me that creating my own custom ConfigurationSection was the way to go. It didn’t look too difficult, so I got right down to business and started coding away!

Web.config:

<configSections>
    <sectionGroup name="moduleSettings">
        <section
            name="modules"
            type="Storminajar.Modules.Framework.Configuration
                  .ModuleSection,
                  Storminajar.Modules.Framework"
            allowDefinition="Everywhere"
            allowLocation="true"/>
    </sectionGroup>
</configSections>
<moduleSettings>
    <modules>
        <module name="Module 1"
                description="My first module!"
                type="Storminajar.Modules.Module1.MyModule,
                      Storminajar.Modules.Module1" />
        <module name="Module 2"
                description="My second module!"
                type="Storminajar.Modules.Module2.MyModule,
                      Storminajar.Modules.Module2" />
    </modules>
</moduleSettings>

Let’s have a look at the working code.

ConfigurationSection:

public class ModuleSection : ConfigurationSection
{
    [ConfigurationProperty("", IsDefaultCollection = true)]
    [ConfigurationCollection(typeof(ModuleCollection),
        AddItemName="module")]
    public ModuleCollection Modules
    {
        get { return (ModuleCollection)this[""]; }
        set { this[""] = value; }
    }
}

ConfigurationElementCollection:

public class ModuleCollection : ConfigurationElementCollection
{
    public ModuleCollection()
    {
    }

    #region ConfigurationElementCollection Specific Memebers
    protected override ConfigurationElement CreateNewElement()
    {
        return new ModuleElement();
    }

    protected override object GetElementKey(
        ConfigurationElement element)
    {
        return ((ModuleElement)element).Name;
    }

    public override ConfigurationElementCollectionType
        CollectionType
    {
        get
        {
            return ConfigurationElementCollectionType
                .AddRemoveClearMap;
        }
    }
    #endregion

    #region Collection Related Members
    public ModuleElement this[int index]
    {
        get { return (ModuleElement)BaseGet(index); }
        set
        {
            if (BaseGet(index) != null)
            {
                BaseRemoveAt(index);
            }
            BaseAdd(value);
        }
    }

    public new ModuleElement this[string cultureKey]
    {
        get { return (ModuleElement)BaseGet(cultureKey); }
        set
        {
            if (BaseGet(cultureKey) != null)
            {
                BaseRemove(cultureKey);
            }
            BaseAdd(value);
        }
    }

    public bool Contains(string name)
    {
        foreach (ModuleElement element in this)
        {
            if (element.Name == name)
            {
                return true;
            }
        }
        return false;
    }

    public void Add(ModuleElement element)
    {
        BaseAdd(element, true);
    }

    public int IndexOf(ModuleElement element)
    {
        return BaseIndexOf(element);
    }

    public void RemoveAt(int index)
    {
        if (this.Count > index)
        {
            BaseRemoveAt(index);
        }
    }

    public void Remove(ModuleElement element)
    {
        if (BaseIndexOf(element) >= 0)
        {
            RemoveAt(BaseIndexOf(element));
        }
    }

    public void Clear()
    {
        BaseClear();
    }
    #endregion
}

ConfigurationElement:

public class ModuleElement : ConfigurationElement
{
    [ConfigurationProperty("name", IsRequired = true)]
    public string Name
    {
        get
        {
            return this["name"] as string;
        }
    }

    [ConfigurationProperty("description", IsRequired = false)]
    public string Description
    {
        get
        {
            return this["description"] as string;
        }
    }

    [ConfigurationProperty("type", IsRequired = false)]
    public string Type
    {
        get
        {
            return this["type"] as string;
        }
    }
}

If you ever get to the point of banging your head on your desk, because of the aforementioned unrecognized element ‘add’, make sure to double check the implementation of the ConfigurationSection! It’s extremely important to have defined the ConfigurationProperty with an empty string! It only seems to occur when a value is specified at this point!

[ConfigurationProperty("", IsDefaultCollection = true)]
[ConfigurationCollection(typeof(ModuleCollection),
        AddItemName="module")]
    public ModuleCollection Modules { ... }

Let me repeat that:

It’s extremely important to have defined the ConfigurationProperty of the ConfigurationElementCollection in the ConfigurationSection with an empty string!

I spent a couple of hours trying to figure this out… A bit of a waste of time!

Generic factory and repositories: Part 2 revisited

This post is part of a series:
- Generic factory and repositories: Part 2 revisited
- Generic factory and repositories: Part 2
- Generic factory and repositories: Part 1
- WCSF, Repositories and Unit of Work?

In Part 2 I discussed my implementation for a SimpleRepositoryFactory. I said that I wasn’t quite happy with the implementation of the factory class, as I would have to adjust my Create() method every time I would add a new repository to the project. At first I was looking for a solution that would let me pass a typeof() into the generic parameter of the InternalRepositoryFactory. For example, I wanted to do something like:

InternalRepositoryFactory<typeof(I), typeof(C)>.Create();

Of course this doesn’t work. Generics need to be resolved at compile time and therefore it’s impossible to create the code I wanted. Or is it?

There is one way of dynamically inserting types into a generic class and/ or method during runtime: reflection! I might be a bit of a nerd, but I love working with reflection. It can do everything! This doesn’t mean I use it inappropriately, I just happen to like the challenge of diving into completely unreadable code and making stuff work! :)

I managed to adjust my SimpleRepositoryFactory in such a way that I would never need to touch the Create() method again. Even if I add new repositories to the project at a later stage!

public static class SimpleRepositoryFactory
{
    private static Dictionary<Type, Type> repositoryTypes =
        new Dictionary<Type,Type>()

    /// <summary>
    /// Creates repository object based on its interface
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="args"></param>
    /// <returns></returns>
    public static T Create<T>(params object[] args)
    {
        if (repositoryTypes.ContainsKey(typeof(T)))
        {
            // Create InternalRepositoryFactory<I, C>.
            Type internalFactory =
                typeof(InternalRepositoryFactory<,>);
            internalFactory = internalFactory.MakeGenericType(
                typeof(T), repositoryTypes[typeof(T)]);

            // Get the Create() method from the
            // InternalRepositoryFactory.
            MethodInfo method = internalFactory.GetMethod(
                "Create", BindingFlags.Static |
                BindingFlags.NonPublic);

            // Invoke the Create() method and return the result.
            // For some reason I need to wrap 'args' into a new
            // object[]?
            return (T)method.Invoke(
                internalFactory, new object[] {args});
        }
        else
        {
            throw new Exception("Type: " + typeof(T)
                + " does not exist in dictionary. Register"
                + " the type mappings first by using the"
                + " RegisterTypeMapping method.");
        }
    }

    /// <summary>
    /// Registers the repository types, marking them as
    /// available to use with the RepositoryFactory.
    /// </summary>
    /// <typeparam name="I">Interface type of object.</typeparam>
    /// <typeparam name="C">Concrete type of object.</typeparam>
    public static void RegisterTypeMapping<I, C>()
    {
        // Only add the type mapping if it doesn't exist.
        if (!typeMapping.ContainsKey(typeof(I)))
        {                
            typeMapping.Add(typeof(I), typeof(C));
        }
    }
}

There are multiple downsides to this code.

Even though I don’t have to touch the Create() method any more, I have to maintain the internal dictionary with definitions. I have moved the problem to a different area in my code. However, the positive side of this is that I can’t break the implementation by accident. If I need to be able to instantiate a new repository, I will add a new definition to the dictionary, using the RegisterTypeMapping() method.

Another downside is that I’ve made the code a lot more complex! This does not improve readability or maintainability at all! Imagine a colleague, unschooled in the ways of reflection, needs to make changes to this code while I am on holidays… the poor bastard would have a very hard time trying to figure it all out!

I can imagine the performance takes a hit as well. I have no clue how much, as I haven’t bothered to measure. However, I think we can all agree that using reflection to resolve types and invoke methods is a bit more costly than simply invoking a method with generics.

I have no idea whether I should use this code or not. I’ve wrote it, I’ve seen it works and I enjoyed the challenge of figuring it out, but all the potential downsides make me scratch my head whether or not I should revert the code back to the way it was. I did write this post in case you, as reader, might really need to do something similar. Therefore I will let you make up your own mind and I won’t tell you what’s right or wrong. Just remember to sit down and think it over again when you suspect you need to resolve generics dynamically at runtime!

Lastly, I’d like to point out that I’ve moved far away from my original intent of developing a factory to create repositories, instead it has become a very generic class that can instantiate any sort of object as long as it implements an interface that can be returned. I’m not even sure if it can actually be classified as a factory pattern any more. SimpleRepositoryFactory seems a very inadequate name as it does not describe the actual implementation!