Author Archive

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…

Buying a George Clooney machine

At least that’s what my colleague called it when he learned of the fact that I had bought myself a Nespresso machine. Yes, indeed. I guess I should be thankful it makes coffee and doesn’t duplicate George Clooney.

Ever since returning from my holiday in England, I’ve been wanting to invest into a coffee machine. I really missed having cappuccino with my breakfast in the morning and enjoy a proper espresso after dinner in the evening. I tried making my own milk froth once in an attempt to create my own cappuccino and, quite quickly, I came to the conclusion that it takes a bit more than my regular filter coffee with wanna-be milk froth to satisfy my need for a cappuccino.

I started out on a journey to buy a new coffee machine. My demands were easily thought up: automated cappuccino, espresso and lastly, good tasting coffee. To my horror I discovered the wide range of choices to make. Prices varied in ranges from €130 to well over €2000! Right. I set myself to find something priced around €200, maybe €250. That immediately narrowed down the choices quite a lot!

Eventually I settled for a DeLonghi Lattisima. A little more expensive than I originally had in mind, but well worth the money. I can make all sorts of coffee now with just the press of a single button! Awesome! The milk froth is made from fresh milk and the coffee from those expensive, but tasty, little Nespresso cups. My first cappuccino out of that machine was a little miracle to be honest.

Right now I’m at work, staring at my horrible cup of Senseo, which inspired me to write this. I miss my George Clooney machine already! Nespresso. What else?

Against better judgement

So last night I decided to join a pug, they advertised in trade by saying they only had the Lich King left to kill. I joined on the basis of hoping that I might get lucky just once, but I should have known better of course. The general way of a pug is to wait for an hour, go into the raid, wipe once or twice on a boss and then disband the group because everyone is leaving.

Yesterday was a little worse! I joined the group around 8pm. They only needed to fill up five more spots, so I had good hopes of being under way quite shortly. Not so! Two hours later we finally got our first action. Two bloody hours worth of waiting and we managed to wipe in about thirty seconds! The off-tank got kicked immediately and so we had to wait even longer while a new tank was being found.

Another ten minutes later and we went in for our second attempt. It was a little better, but we wiped on the transition phase. The third attempt we actually got to phase two! On the fourth attempt we wiped on phase one and the raid leader decided that the healing was shit and that was the cause of all the wipes, so he kicked us all!

Two and a half hours of my night wasted by some pompous fool who thinks the wipes happened because of bad healing! Let’s not mention the fact that half the people in the group didn’t seem to know what they were doing. You know, the kind of people that are focused on getting the biggest numbers you can imagine and just sit tight, even when they have the disease – and thus should move the fuck out of the group to the add – they just continued to DPS as if nothing was amiss.

So, dearest raid leader of that particular pug. Thank you for wasting my night and my mood!