Lambda cheat sheet

A while ago I wrote about all the new language features of C# 3.0 and it occurred to me that I’d left out a chunk about Lambdas. With LINQ being such an important part of C#3.0 that seems like a terrible omission, so I’m going to make up for it now.

The easiest way to think about a lambda is that it is a short form of anonymous methods that were introduced in C#2. However, you can also use lambdas to create expression trees (I’ll come to those in more detail in another post, for the moment, I’ll be concentrate on using lambdas for creating anonymous methods).

Basic Structure

A lambda that looks like this

(i) => 123 + i
^^^ ^^ ^^^^^^^
(1) (2)  (3)

is compiled to an anonymous method

delegate (int i) { return 123+i; }
         ^^^^^^^   ^^^^^^^^^^^^^
           (1)          (3)

The first part of the lambda (1), in the brackets, declares the parameters. The brackets are, incidentally, optional if there is only one parameter. The type is inferred so you don’t have to explicitly declare it as you would have to do with an anonymous method. However, if the compiler cannot infer the parameter type then you will have to declare it explicitly:

(int i) => 123 + i

The second part (2) is pronounced “goes to” and does not really have an equivalent with an anonymous method, although you could argue that it is the equivalent of the delegate keyword.

The third part (3) is the expression or statement. In a lambda expression the return is implicit so it does not need to be declared. It can also contain a number of statements enclosed in separated by semi-colon, but in that case it cannot be used to create expression trees and you must explicitly have a return statement if there is something being returned.

delegate void DisplayAdditionDelegate(int i, int j);

DisplayAdditionDelegate add = (i, j) =>
    { Console.WriteLine("{0} + {1} = {2}", i, j, i+j); };
add(2, 5);
// Output is: 2 + 5 = 7

Framework assistance

The .NET Framework provides a number of predefined generic delegate types that can be used with lambdas in order that is is easy to refer to them and pass them around.

Each of these contains a generic list of parameter types and finally the return type, or if there are no parameters just the return type.

The delegates with a return type are defined as:

public delegate TResult Func<TResult>()
public delegate TResult Func<T, TResult>(T arg)
public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2)
public delegate TResult Func<T1, T2, T3, TResult>(T1 arg1, T2 arg2, T3 arg3)
public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4)

The delegates without a return type are defined as:

public delegate void Action<T>(T obj)
public delegate void Action<T1, T2>(T arg1, T2 arg2)
public delegate void Action<T1, T2, T3>(T arg1, T2 arg2, T3 arg3)
public delegate void Action<T1, T2, T3, T4>(T arg1, T2 arg2, T3 arg3, T4 arg4)

You can then uses these delegates to represent an appropriate method without having to create a custom delegate type – for most purposes they are quite sufficient.

Outer variables

Outer variables are variables that the lambda can use that are defined in the method that defines the lambda.

int j = 25;
Func<int, int> function = i => 100 + i + j;
j = 75;
int result = function(50);
// result == 225

As you can see in the above example the value of j is not evaluated at the point the lambda is declared, but at the point it is invoked. The lambda is able to keep a reference to j even although it was declared in a different scope. The same is true if the lambda is eventually invoked from a different scope block altogether. For example, if it has been passed out of the method in which it is declared.

The lambda can also change the value of the outer variable. For example:

int j = 6;
Func<int, int> function = i => { j = j * j; return 100 + i + j; };
int result = function(50);
// result == 186
// j == 36

Updated chart of .NET version numbers

Way back when, I published a table detailing the version numbers of the various parts that make up a .NET application: The Tools, the C# language, the Framework itself and the Engine (CLR) that it all runs on. With the latest version about to be released I thought it was time to update that table.

 

Year 2002 2003 2005 2006 2007 2010
Tool VS.NET 2002 VS.NET 2003 VS 2005 VS 2005
+ Extension
VS 2008 VS 2010
Language (C#) v1.0 v1.1 v2.0 v2.0 v3.0 v4.0
Framework v1.0 v1.1 v2.0 v3.0 v3.5 v4.0
Engine (CLR) v1.0 v1.1 v2.0 v2.0 v2.0 v4.0

 

The main new thing is that finally someone has had the good sense to re-sync the version numbers. It all got a bit silly with the release of Visual Studio 2008.

O2, please train your store employees

Last week I changed the tariff on my phone to better suit my usage. However, it turns out that by changing the tariff I also needed to change some settings on my phone. So, when the old tariff cut out, so did my 3G connectivity and I lost internet on my phone for a couple of days until a friend of a friend who happens to work for O2 explained what I needed to do to get it to work. Up until then, since I had made no modifications to my phone, I had be blaming O2’s network infrastructure.

Here is a summary of the tweets I made about it:

  • 4/March:
    • Don’t have a data network available. Most irritating @o2. Where’s my 3G network?
    • Still no data network. @o2 what are you doing. All the way from Glasgow to Edinburgh an no data network.
    • Made it all the way back to glasgow. Still no data network. @o2 get your shit together!
    • Woohoo! I have data back on my iPhone. But then I’m now at home connected to my wifi network. @o2 thanks for nothing!
  • 5/March:
    • Still no data network. @o2 you #FAIL big time! I’m moving to orange when I get a chance.
    • @kstenson No data network in Glasgow, in Edinburgh or points in between. Phone signal only. @o2 #FAIL
    • Got a data network back! One of @chriscanal‘s friends works for @o2 and fixed it for me
    • Turns out because I changed my tariff my connections settings also changed. But no one told me that!

O2 could have saved themselves a lot of frustration from me if their store employee had been told that the tariff also required a change in phone settings.

My reading list #1

I’ve decided that I need a quick and easy way to remind myself of the useful articles that I’ve read recently or are on my stack to read. Since I use my blog as an aide memoire anyway, I thought why not just put up a blog post once in a while after reading something useful. So here’s the first one…

Web

  • The Kayak Framework: An easy way to speak HTTP with .NET
    Kayak is a lightweight HTTP server for the CLR, and the Kayak Framework is a utility for mapping HTTP requests to C# method invocations. With Kayak, you can skip the bulk, hassle, and overhead of IIS and ASP.NET.
  • REST APIs must be hypertext-driven
    What needs to be done to make the REST architectural style clear on the notion that hypertext is a constraint? In other words, if the engine of application state (and hence the API) is not being driven by hypertext, then it cannot be RESTful and cannot be a REST API. Period.
  • REST – The Short Version
    Getting a clear handle on the definition of the REST architectural style can be daunting. While there is no shortage of descriptions available, I did not find many of them helpful at first. Also, as I began talking about REST to colleagues, I often had a difficult time producing clear descriptions for the key points. Over time, however, I sharpened my summary into a version that seemed to make sense to most of my listeners. I offer here my rendition of the REST model.
  • Applying the Web to Enterprise IT
    This is a blog that contains a number of useful article on ReST.
  • Building a website for the iPhone
    This tutorial will cover the basic setup and creation of a web page for the iPhone that will detect and change the content based on the phones orientation.

Professional Development

  • Unskilled and unaware of it
    People tend to hold overly favourable views of their abilities in many social and intellectual domains. The authors suggest that this overestimation occurs, in part, because people who are unskilled in these domains suffer a dual burden: Not only do these people reach erroneous conclusions and make unfortunate choices, but their incompetence robs them of the metacognitive ability to realize it.
  • Did your boss thank you for coding yourself to death?
    Here is some perspective, you’re not doing this for yourself, you’re doing it for “the man”. Admittedly he might be a nice man, but you don’t owe him slavish commitment. Here is even more perspective, how often are you actually playing with interesting problems and cool tech and how many times are you churning out code desperately trying to get something delivered and meet some arbitrary deadline that someone has assigned to you?

Agenda for DDD Scotland 2010

We have finally got all the speakers confirmed and the agenda sorted out for DDD Scotland 2010. Subject to any last minute changes this is is:

Time

Room A (80)

Room B (40)

Room C (40)

Room D (40)

08:45-09:20

Registration

09:20-09:30

Housekeeping

09:30-10:30

HTML 5: The Language of the Cloud (Craig Nicol)

Contractual Obligations: Getting Up and Running with Code Contracts (Barry Carr)

WCF Data Services (Iain Angus)

Team Foundation Server 2010 for Successful Project Management (Martin Hinshelwood)

10:30-10:40

Break

10:40-11:40

Exception Driven Development (Phil Winstanley)

Real World Application Development with Castle Windsor and ASP.NET MVC 2 (Chris Canal)

Get Going with jQuery (George Adamson)

T4 and How it Can Be Used for Code Generation in Visual Studio 2008/2010 (Rob Blackmore)

11:40-12:00

Break

12:00-13:00

Web Standards are Broken, and it’s Getting Worse (Sebastien Lambla)

A Guided Tour of Silverlight 4 (Mike Taulty)

Commercial Software Development Is Easy, Not Going Bust Is the Hard Bit (Liam Westley)

Defensive Programming 101 (Niall Merrigan)

13:00-14:30

Lunch time: Grok Talks

Lunch time:
Local Open Source Incubator

Lunch time: Sponsor talk

Lunch time: Sponsor talk

14:30-15:30

Getting Started with Behaviour-Driven Development Using Cucumber (Steve Sanderson)

Silverlight – Real World Gotchas (Ray Booysen)

What ASP.NET (MVC) Developers Can Learn from Rails (Paul Cowan)

Developments in MultiCode and Concurrent Programming with .NET 4 (Barry Wimlett)

15:30-15:40

Break

15:40-16:40

Real World MVC Architectures (Ian Cooper)

Cloud Coffee – A Year Developing on Windows Azure (Dominic Green)

C# on the iPhone with Monotouch (Chris Hardy)

Domain Specific Languages – What Are They and Why Should You Care? (Mark Dalgarno)

16:40-17:00

Closing

Integrating Exceptioneer with OpenRasta

[NOTE: This post was created using OpenRasta 2.0 RC (rev 429)]

One service I’ve found to be increasingly useful is Exceptioneer by Pixel Programming. As I’m about to start a new project using OpenRasta I wanted to be able to use Exceptioneer with it in order that I can log any exceptions effectively.

For a basic 404 error it was very easy. Just following the instructions on the Exceptioneer site for the ASP.NET integration worked a treat.

However, a little more work was required for when something like a Handler in OpenRasta threw an exception that didn’t get caught. In this case I had to set up an OperationInterceptor in order to catch the exception and send it to Exceptioneer.

Here is the ExceptionInterceptor class:

class ExceptionInterceptor : OperationInterceptor
{
    readonly IDependencyResolver resolver;

    public ExceptionInterceptor(IDependencyResolver resolver)
    {
        this.resolver = resolver;
    }

    public override Func<IEnumerable<OutputMember>> RewriteOperation
        (Func<IEnumerable<OutputMember>> operationBuilder)
    {
        return () =>
        {
            IEnumerable<OutputMember> result = null;
            try
            {
                result = operationBuilder();
            }
            catch (Exception ex)
            {
                Client exceptioneerClient = new Client();
                exceptioneerClient.CurrentException = ex;
                exceptioneerClient.Submit();
                throw;
            }
            return result;
        };
    }
}

Note that you have to include using Exceptioneer.WebClient; at the top of the file.

What this gives us is the ability to log any exception that is left uncaught from the Handler, log it then allow OpenRasta to continue on as it would have normally.

All that remains is to wire this up. In the Configuration class (if you’ve used the Visual Studio 2008 project template, or what ever your IConfigurationSource class is called otherwise) the following is added to the Configure method:

ResourceSpace.Uses.CustomDependency<IOperationInterceptor,
    ExceptionInterceptor>(DependencyLifetime.Transient);

 

Now any time a handler has an uncaught exception, it will be logged and sent off to Exceptioneer.

Further reading:

Tip of the Day #17: Duplicate input fields

Don’t allow duplicate input fields into your form.

The other day I was trying to debug a bug in an application that I maintain. The code created a set of pagination buttons at the top of the page with previous and next buttons. At some point a request had come in that the buttons needed to be replicated at the bottom of the page. Since the HTML was being built up in a string and dumped in a literal control in the first place the developer that was tasked with making the change just dumped the string into two literal controls, the original at the top of the page, and the new one at the bottom of the page. The previous and next buttons use hidden input field to tell the application which actual page number the buttons correspond to. And these were now duplicated and as a result the previous and next buttons ceased to work.

Here is an example of something similar:

<input id="first-hidden-field" value="123" type="hidden" name="some-name" />
<input id="submit-button" value="Submit" type="submit" />
<input id="second-hidden-field" value="456" type="hidden" name="some-name" />

When the form fields are returned to the application and the field “some-name” is queried the result back is a combination of the two fields with the duplicate name. In this case:

string someName = Request.Form["some-name"];

will result in the value of “123,456” being stored in the string. Basically, it is the comma separated form of all the input fields with the given name.

Exploding out of the Closet

Ben Nunney - Jan 2010I don’t usually put personal stuff on my blog, but I have a feeling that this year there are going to be a few posts like this. My blog has always been mostly an aide memoire for me but at the same time I realise that if it helps anyone then all the better. While writing this has been a useful exercise for me, I hope more than anything that it helps others.

Yesterday a good friend of mine, Ben Nunney, posted on his blog and article entitled “Luck, Love and Dinner”. While I did post a brief reply to the blog post at the time I felt that a longer response was in order.

Ben ended his post with “I’ve talked to a lot of people … who have only recently begun to accept themselves for who they are, or who have only just started to realize that the days aren’t looking as dark as they did for Britten, Wilde and Turing.”

As someone who hid in the closet until the age of 35 I am guessing I’m one of the people he was talking about in that final paragraph. So, let me tell you my coming out story and how I got to being 35 and only just coming out.

Coming Out

Sebastien Lambla - May 2009

In March 2009 I was in London for a conference and a friend invited me along to the pub one evening and brought a couple of other friends with him. It was there that I met Seb for the first time. He was just very open about himself and his sexuality. I’d never met anyone like that before. It was Seb’s openness that allowed me to start breaking down the mental barriers in my head and I began the acceptance process.

It was mid-May that I realised I’d finally begun to accept myself. Then sometime around late late July I realised that I had stopped snacking and as a result I had begun to lose weight. I’ve always eaten comfort foods when stressed and it became obvious that hiding from myself had been causing a lot of stress.

In August I was once again in London for a conference and I met Phil (another gay friend) and Seb again. It was at that point that I decided that I should tell them and ask for advice. Unfortunately, I didn’t really find an opportune moment that weekend.

In September I was down in Manchester for a mini-conference. In the pub after the conference I asked Seb if he could spare some time to talk to me in private that evening. So, it was at about 2AM after returning to the hotel that I finally took my first steps out of the closet.

From my point of view I felt incredibly stupid. All that I had read on the internet prior to that talked about people coming out in their teens or early twenties. So it seemed to me that I was very slow. Seb was able to put me at my ease by letting me know of people he knew that had come out much later in their life than I had.

I also sought advice on what to do next. I had taken the first steps but I didn’t really know what to do next. I didn’t want to hide any more, that much I knew.

I put together a list of the people I was closest to, the people I wanted to tell personally rather than have them find out second hand. Over the following two weeks I contacted all of them. Each conversation started with me kind of stumbling around trying to find the right set of words to use. I was anxious in case I found out any of my friends were less than tolerant and this might be the conversation that could end that friendship.

I have to say that as I got through the list and I received positive reactions from my friends it gave me a new confidence that I’d never felt before. It wasn’t just tolerance, it was acceptance. I now feel closer to all those friends. At the same time, it also made me feel silly that I hadn’t done this long before.

Within about 10 days I’d personally told all my closest friends. All that was left was my parents.

I had in fact made one attempt to tell them but bottled it at the last minute. The following weekend I made a second attempt, but as I stumbled around trying to get the conversation going I bottled it again so I simply went home again. However, on the way out of my parents house I asked if I could speak to my mum sometime in the next few days.

So one evening after work I drove round to my parents house and spoke with just my mum. I figured it would be easier with just one person. Naturally, I was extremely anxious. As usual, I stumbled around a little before simply blurting out “I’m gay!”

At that point there was a pause as I looked at my mum’s blank expression for any signs of which way the conversation was about to turn. For me it seemed like an eternity. In fact I can’t have been any more than about a second or so. She then cheered up and responded “Oh, thank goodness for that. I thought something was wrong!”

How did I get here?

So, now you know the details of my coming out let me go back and tell you how I got to being 34 by the time I finally accepted my sexuality and 35 by the time I finally exited the closet.

Back when I was at school and I had the first inclining that I was attracted to men I obviously wasn’t sure what to do. I felt that there was no one to speak to. While I was trying to figure out if this was a permanent feeling or just a phase another kid in my class was outed.

Stonewall - FITIt wasn’t pleasant. And quite frankly I didn’t want to go through that so I hid. I buried my feelings as deeply as I could. Effectively I hid from myself. From that point, every time I heard a homophobic comment it just got piled in on top burying those feelings even deeper.

Perhaps if there was something like Stonewall’s FIT campaign that might not have happened. Perhaps if many things were different I would have come to acceptance sooner. It is now all water under the bridge and there is little point dwelling on it because what is done is done and cannot be undone.

Phil Winstanley - Dec 2009

Moving On

Now, this post is entitled “Exploding out of the Closet”. And you might be forgiven for wondering why at this stage.

When I spoke to Seb on the day of my coming out, he told me that he thought I was a bit of a closed person. He always had the impression that I wasn’t very open about myself. After that conversation I dec
ided that this was something that had to change. Since I’d realised that it was something that had caused me to build up a whole heap of stress I decided that I needed to be more open, not just with others but with myself too. As I mentioned above, I already knew I didn’t want to hide any more so being more open definitely be something that would compliment that.

While I never made any grand announcement on twitter (at least, that was my intention) I just just joked with the friends that already knew. My sense of humour has always included a fair bit of innuendo [^] so I expected that people would pick up soon enough.

I also attended my first Gay Geek Dinner in November followed by a tour of some of Soho’s gay bars and clubs. While there I tweeted my experience and uploaded some photos onto Facebook and Flickr. After that, I had assumed that everyone must have realised given this volume of information. Phil even commented later that I had “exploded out of the closet” (Hence the title of the post)

Incidentally, I did eventually make that grand announcement because the innuendo confused a number of people so I had to clear that up [^]. And of course, I guess this blog post acts as a grand announcement too. So, I guess I’m now well and truly out!

If you have Spotify: I’m Coming Out – Diana Ross.

Update

I received some comments also on Twitter about this blog post in addition to the comments below. Here are the twitter comments:

Upcoming talks

My SQL Injection Attack prevention talk is on the road. I’ve already given the talk in Dundee, Newport and Nuneaton. And in the coming months I’ll be delivering it in Glasgow, London and Newcastle.

If you want to come and learn about securing your database from a developer perspective you can come along.