I am currently looking for a contract in the London area -

If you're hiring a .NET contractor in or around London, look no further!

Dynamic Lambda Expressions - creating functions at run-time


One of my favourite new features in C# 3 are lambda expressions. These nutty little functions are essential to the inner workings of Linq, and open many doors for the adventurous programmer.

It's important to know the difference between Func<> expressions and Expression<> expressions. If you have a lambda of type Func<>, it's simply a function pointer - a strongly typed delegate to a (usually) anonymous method. However, if your expression is of type Expression<>, it's actually a reference to an expression tree - an in-memory tree structure containing nodes that represent the operations that you have defined in your lambda.

This difference is crucial - if it is an Expression<>, it's not actually a function to be executed but rather an abstract description of it - this means we can manipulate and construct them at will, then compile them into executable functions whenever we want to use them.

Consider the following lambda to square an integer:

Expression<Func<int, int>> f = (int x) => x * x;
This gets translated into a statement to build the expression tree that looks like the following:
ParameterExpression x = Expression.Parameter(typeof(int), "x");

Expression<Func<int, int>> f =
    Expression.Lambda<Func<int, int>>
    (
        Expression.Multiply(x, x),
        new ParameterExpression[] { x }
    );
We can then compile it into a "real" delegate and call it using DynamicInvoke().
// Compile it
Func<int, int> func = f.Compile();

// Cast it to a Delegate type
Delegate del = func;

// Call it - prints "4"
Console.Out.WriteLine(del.DynamicInvoke(2).ToString());
So, armed with this technique, we can construct functions at runtime. In the following code sample, I've created a descendent of a DataContext class that prints out the type and primary key value of every updated row when SubmitChanges() is called. It creates a lambda expression tree for each entity type that simply returns the entity's primary key value, and compiles that into a regular delegate.
public class MyNorthwindDataContext : NorthwindDataContext
{
    private Dictionary<Type, Delegate> m_Keys = 
            new Dictionary<Type,Delegate>();

    public override void SubmitChanges(ConflictMode failureMode)
    {
        ChangeSet changes = this.GetChangeSet();
        
        PrintChanges(changes.Updates);
        
        base.SubmitChanges(failureMode);
    }
    
    private void PrintChanges(IList<object> changes)
    {
        foreach (object entity in changes)
        {
            Delegate pk = null;
            if (m_Keys.ContainsKey(entity.GetType()))
            {
                pk = m_Keys[entity.GetType()];
            }
            else
            {
                pk = CreatePrimaryKeyDelegate(entity.GetType());
                m_Keys[entity.GetType()] = pk;
            }
            
            Console.Out.WriteLine(String.Format(
                "An entity of type {0} with primary key {1} was updated.", 
                entity.GetType().Name, 
                pk.DynamicInvoke(entity)));
        }
    }
    
    // This method returns a delegate that returns the primary key
    // value from a DLINQ data entity.
    private Delegate CreatePrimaryKeyDelegate(Type type)
    {
        Type col = typeof(ColumnAttribute);
        ParameterExpression x = Expression.Parameter(typeof(object), "x");
        Expression<Func<object, object>> expression =
            Expression.Lambda<Func<object, object>>
            (
                Expression.TypeAs
                (
                    Expression.Call
                    (
                        Expression.TypeAs(x, type),
                        (
                            // Get the primary key column's get_ method by
                            // examining the attributes.
                            from p in type.GetProperties
                                (BindingFlags.Instance | BindingFlags.Public)
                            where
                                p.IsDefined(col, false)
                                && (p.GetCustomAttributes(col, false)[0]
                                     as ColumnAttribute).IsPrimaryKey == true
                            select p
                        ).First().GetGetMethod()
                    ),
                    typeof(object)
                ),
                new [] { x }
            );

        return expression.Compile();
    }
}
Using the code above:
using (NorthwindDataContext ctx = new MyNorthwindDataContext())
{
    List<Order> orders = (
        from o in ctx.Orders 
        where o.CustomerID == "ALFKI" 
        select o
    ).Take(5).ToList();
    
    orders.ForEach(order => order.Freight = 1);

    ctx.SubmitChanges();        
}
When run, the above code yields the following output:

Review: Koru Instant Energy Strips


Koru is a Maori word that symbolises growth, strength, and peace. It's also the name of a new energy caffinated strip, in the same vein as the Diablo Energy Strips and many other similar products.

They are little strips of what looks like rice paper, designed to disolve on the tongue. The packet claims they work by "trans-mucosal delivery action", working "sublingually" - i.e. "they dissolve on your tongue". The idea behind these is that as the caffeine is absorbed through the mucous membranes in the mouth immediately, the caffeine reaches your bloodstream much faster than anything that you swallow. It's the caffeine equivalent of smoking crack, basically.

Having tried some of these before (and being particularly unable to pass up the opportunity of buying something new and caffinated) I decided to pick up a pack and write a review.

I found them at the checkout of the Whistlestop shop in London Bridge station for the princely sum of £1.99. The packet, a foil bag roughly the size of a playing card, contains 4 of the strips purported to "awaken the mind and the body". No mention is made of the caffeine content of the strips, either on the packet or the web site.

Each strip contains: maltodextrim, hydroxypropylmethyl cellulose, water, triethyl citrate, sorbitol, flavourings (including caffeine), sweeteners (sucralose, aspartame), and titanium dioxide as a colouring. The strips lack the ususal cocktail of ingredients that you often find in new energy products (taurine, ginseng, vitamin-B, and others), so you'll have to be content with the caffeine.

The front of the pack is decorated with slightly disturbing Maori print of what looks a bit like a gorilla, called the "Koru Face Device".

Inside

Inside the pack are 4 strips individually wrapped in foil packets, and a little sticker of the Face Device. The strips are attractively wrapped, with bold lettering on the front, and again the Face Device on the back.

The strips themselves are an off-white, like thick rice paper, with white lettering spelling "Koru" printed diagonally across them.

Consumption

The strips are meant to be placed on the tongue, where they quickly disolve. The pleasant mint flavour, not at all unlike Mentos, quickly gives way to the familiar bitter taste of caffeine, which is enough to give an indication of the caffeine content - very high.

Within a minute I was feeling rather refreshed and alert (with my hangover receding), and without the jitters that often accompany a large dose of caffeine. I could do without my morning coffee after just one of these, and the peak effect lasted for around an hour.

Koru Instant Energy Strips are an expensive but effective way of caffinating yourself. At £1.99 for 4 they are way cheaper than a latte, but still very pricey considering Boots sells a cheaper own-brand version with 28 strips in the pack (although without a scary Maori picture anywhere to be seen). The caffeine content, while not known, does feel very high for this kind of product, and is well worth a try.