About stubs, fakes and mocks

Test driven development is not an easy subject. And to be honest, I’ve not been convinced of it’s usefullness when first reading about it, witnessing this post. What I do believe firmelly is the usefulness of unit testing. But I have found that overall resistance to unit testing is rather big mostly because if not done well it turns out to be rather timeconsuming.

Now, let me start by saying I’m not an expert on the subject. I’ve tried applying it to some projects with some success and wanted to use it extensively in the next major release of my Offline Maps project. So I did some research to find where I could improve and my first subject was mock objects.

It turned that mocks are only a part of the complete picture.

Ok mocks, but what about stubs, dummies, fakes, etc…

There is a lot of lingo surrounding unit testing. Before we get any deeper on mock objects lets clearly define what they are and more importandly, what they are not and what differentiates them from stubs, fakes, etc…

Stubs

According to Jeremy Miller, the difference between mocks and stubs is mostly in the sort of testing you’re performing:

The real difference between a mock and a stub is in the style of unit testing, i.e. state-based testing versus interaction testing. A stub is a class that is hard-coded to return data from its methods and properties. You use stubs inside unit tests when you’re testing that a class or method derives the expected output for a known input.

Gerard Meszaros provides a bit more detail:

In many circumstances, the environment or context in which the system under test (SUT) operates very much influences the behavior of the SUT. To get good enough control over the indirect inputs of the SUT, we may have to replace some of the context with something we can control, a Test Stub.

So, you use stubs if you want to provide data to your system under test and the outcome of your system under test is dependend on the content of that data. A good example would be an object which has as input the current date and for example calculates yesterday. If you where to use the effective current date, then you could never write a test because each different day you execute the test would use a different current day, thus calculate a different yesterday and thus the value against which you want to check would change every day. If you however create a stub which provides a current day that you can set fixed, then you can reproduce the result whenever you want:

An example:

The code we want to test is the following:

public ITodayProvider TodayProvider { get; set; }
public DateTime Yesterday 
{
	get { return TodayProvider.Today.AddDays(-1); } 
}

The implementation of ITodayProvider used in the application uses the system date:

public DateTime Today
{
	get { return DateTime.Today; }
}

The implementation of ITodayProvider used in the test however allows to set the date that will be returned:

public DateTime Today
{
	get;
	set;
}

The test with the ITodayProvider using the system date does not produce repeatable results:

[Test]
public void WithoutStubTest()
{
	CalculateYesterday yesterdayCalculator = new CalculateYesterday();
	yesterdayCalculator.TodayProvider = new TodayProvider();

	// Unless you execute this test exactly on 1st september 2009, this test will fail
	Assert.AreEqual(new DateTime(2009, 8, 31), yesterdayCalculator.Yesterday);
}

The test with the ITodayProvider which can be set does allow to produce repeatable results:

[Test]
public void WithStubTest()
{
	CalculateYesterday yesterdayCalculator = new CalculateYesterday();
	TodayProviderStub stub = new TodayProviderStub();
	stub.Today = new DateTime(2009, 9, 1);
	yesterdayCalculator.TodayProvider = stub;

	// This test will always succeed, that is if you implementerd the yesterday calculation correctly.
	// It is however completely independent of the day the test is executed
	Assert.AreEqual(new DateTime(2009, 8, 31), yesterdayCalculator.Yesterday);
}

Fakes

Where a stub actually influences the system undertest, a fake only “fakes” an object in the system under test. Again according to Gerard Meszaros:

The SUT often depend on other components or systems. The interactions with these other components may be necessary but the side-effects of these interactions as implemented by the real depended-on component (DOC), may be unnecessary or even detrimental. A Fake Object is a much simpler and lighter weight implementation of the functionality provided by the DOC without the side effects we choose to do without.

Matin Fowler in his post on different kinds of test doubles states the following:

Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an InMemoryTestDatabase is a good example) So whereas stubs don’t have any working functionality, fakes have. They just take some shortcuts. Stubs are typically hardcoded to return some value.

As an example, suppose your object uses a webservice for retrieving some values, you may not be interested in setting up a connection to the webservice, provide a connection string, etc… because the actual webservice used is unimportant to your system under test. You also don’t want everyone executing your tests to be dependend on the availability of that webservice or detrimental behaviour like unavailable connections, timeouts and all that sort of stuff specific to webservices to mess up your test. In this case you could use a fake in webservice which provides the same functionality but is much easier in setup and which doesn’t exhibit the unwanted behaviour of unavailable connections and timeouts.

The code we want to test is the following:

public ITodayProvider TodayProvider { get; set; }
public IDayRangeCalculatorService DayRangeService { get; set; }
public DateTime YesterdayUsingDayRangeService
{
	get 
	{
		IDayRangeCalculator dayRangeCalculator = DayRangeService.ConnectToService();
		int daysBetween = dayRangeCalculator.DaysBetweenTodayAndYesterday();

		return TodayProvider.Today.AddDays(daysBetween); 
	}
}

A fake implementation of the service allows to get away of all problems relating to connecting to and using of webservices:

class DayRangeCalculatorServiceFake : IDayRangeCalculatorService
{
	#region IDayRangeCalculatorService Members

	public IDayRangeCalculator ConnectToService()
	{
		return new DayRangeCalculatorFake();
	}

	#endregion
}

class DayRangeCalculatorFake : IDayRangeCalculator
{
	#region IDayRangeCalculator Members

	public int DaysBetweenTodayAndYesterday()
	{
		return -1;
	}

	#endregion
}

By using the fake in the test we know our test will not fail because of problems related to the webservice. So if our test fails, then we know it’s because our algoritme failed:

[Test]
public void WithDaysBetweenServiceFakeTest()
{
	CalculateYesterday yesterdayCalculator = new CalculateYesterday();
	TodayProviderStub stub = new TodayProviderStub();
	stub.Today = new DateTime(2009, 9, 1);
	yesterdayCalculator.TodayProvider = stub;

	yesterdayCalculator.DayRangeService = new DayRangeCalculatorServiceFake();

	// In this test we are only interested if the method returns the correct yesterday 
	//  and not if the logging was done correctly
	Assert.AreEqual(new DateTime(2009, 8, 31), yesterdayCalculator.YesterdayWithLogging(new LoggingDummy()));
}

Dummies

Dummies have no influence at all on the tests. They are just used to provide values for method parameters, etc…

Fowler:

Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.

Thus, you use a dummy if you test requires an object which thus not have any influence on the outcome of your test. An example could be a method called in your test which has some specific outcome you want to check but for example also take a logging object as a parameter. Remember we are unit testing and each test checks on some aspect of the object. So we want to check the specific outcome of calling the method but in this test we are not at all interested in the logging of the method. Then we provide a dummy logging object which actually thus nothing but allows us to call the method and check the expected outcome.

The code we want to test is the following:

public ITodayProvider TodayProvider { get; set; }

public DateTime YesterdayWithLogging(ILogging logging)
{
	logging.LogMessage("Executing YesterdayWithLogging");
	return TodayProvider.Today.AddDays(-1);
}

In our test we don’t care about logging. So we provide a dummy logging class which does nothing:

class LoggingDummy:  ILogging
{
	#region ILogging Members

	public void LogMessage(string message)
	{
	}

	#endregion
}

In our test we don’t have to worry about the logging

[Test]
public void WithLoggingDummyTest()
{
	CalculateYesterday yesterdayCalculator = new CalculateYesterday();
	TodayProviderStub stub = new TodayProviderStub();
	stub.Today = new DateTime(2009, 9, 1);
	yesterdayCalculator.TodayProvider = stub;

	// In this test we are only interested if the method returns the correct yesterday 
	//  and not if the logging was done correctly
	Assert.AreEqual(new DateTime(2009, 8, 31), yesterdayCalculator.YesterdayWithLogging(new LoggingDummy()));
}

Now, if all this is a bit overwhelming, don’t be concerned. Your test doubles will mostly be a mix of the above, or their focus or purpose will shift as shown by Daniel Cazzulino in his postMocks, Stubs and Fakes: it’s a continuum .

Mock objects, what problems to they solve ?

In many posts about the type of test doubles there is also the difference between test spies and mocks. From what I could find on them the difference is not that clear to me. So I will treat them as being the same. Of course, if you can explain the difference in a clear way, you’re welcome, or if you know a reference let me know.

About behaviour

We all know it but lets state it once more explicitely:
Objects are instances of classes which exhibit both state and behaviour.

Anyone studying UML will agree that both the class diagram and the sequence diagram are needed to document the interactions of systems. Where the class diagram shows what properties the classes in the system have, the sequence diagram shows what the important method calls made by the objects are. So you could say that the class diagram documents the state of a system (not entirely thru) and the sequence diagram documents the behaviour of the system. And as you need both the class diagram and the sequence diagram you need both state testing and behaviour testing.

When to use mock objects

The main difference with traditional testing is that where traditional testing allows a more state-based approach of testing, mock objects provide a behaviour style of testing. We all know the traditional style of unit testing using frameworks like NUnit, MbUnit and there assert-style testing:

  1. Setup your test
  2. Execute some action
  3. Assert that the properties of the object under test are what you expect

We assert that the state the object under test is in, is what we expect. To check this state, we check the values of the object’s properties.

Behaviour style testing on the other hand verifies the dynamic behaviour of the object under test. Remember that we are using mock objects to represent companion objects “on the edges of the object under test”. That is, objects used by our object under test. Now, sometimes we will want to know if our object under test calls a certain method with certain arguments of the companion object. The post Using Mock Objects Effectively provides a great example:

On closer inspection, it becomes clear that the application is not actually logging anything. Log4J is responsible for doing that. What the application is truly doing is sending a signal (a request) to log4j to log a message. That distinction is *very* important. The appropriate test then is simply to verify that the application is sending the correct signal to the service provider under the right conditions.

We now get following test sequence:

  1. Setup your test
  2. Execute some action
  3. Assert that the required methods have been executed with the correct parameters and in the correct sequence

We assert that the object under test executed the behaviour we expect. To check this behaviour, we check the methods it called and the arguments it provided to those methods.

So, using mock objects for behavioural testing can co-exist with the more traditional style of sate based testing.

Martin Fowler, him again, warns for some caveats when using mock style testing in his article Mocks Aren’t Stubs:

When you write a mockist test, you are testing the outbound calls of the SUT to ensure it talks properly to its suppliers…
Coupling to the implementation also interferes with refactoring, since implementation changes are much more likely to break tests than with classic testing.

An example

The code we want to test is the following:

public ITodayProvider TodayProvider { get; set; }

public DateTime YesterdayWithLogging(ILogging logging)
{
	logging.LogMessage("Executing YesterdayWithLogging");
	return TodayProvider.Today.AddDays(-1);
}

In our test we don’t care about the exact output of the logging but we do care if the logging is called and if it is called with the correct arguments. So we want to record the methodcall and the arguments with which it got called:

class LoggingMock:  ILogging
{
	public int NumberOfMethodCalls { get; private set; }
	public List<String> MethodCallArguments { get; private set; }

	#region ILogging Members

	public void LogMessage(string message)
	{
		NumberOfMethodCalls++;
		if (MethodCallArguments == null)
		{
			MethodCallArguments = new List<string>();
		}

		MethodCallArguments.Add(message);
	}

	#endregion
}

By recording the calls we can check in our test if the method got called and if the provided arguments where correct:

[Test]
public void WithLoggingMockTest()
{
	CalculateYesterday yesterdayCalculator = new CalculateYesterday();
	TodayProviderStub stub = new TodayProviderStub();
	stub.Today = new DateTime(2009, 9, 1);
	yesterdayCalculator.TodayProvider = stub;
	LoggingMock loggingMock = new LoggingMock();

	// In this test we want to see if the logging is called correctly
	DateTime yesterday = yesterdayCalculator.YesterdayWithLogging(loggingMock);

	Assert.AreEqual(1, loggingMock.NumberOfMethodCalls);
	Assert.AreEqual("Executing YesterdayWithLogging", loggingMock.MethodCallArguments[0]);
}

Sample Code

The Code

Links

Mock Objects and Stubs: The Bottle Brush of TDD
Why and When to Use Mock Objects
Best and Worst Practices for Mock Objects
xUnit Patterns
Using Mock Objects Effectively
MF Bliki: TestDouble
Mocks Aren’t Stubs
Mock object

Advertisements

C# 4.0: Optional Method Parameters

In this first post on new C# language features I will write about Optional Parameters and Named Parameters for methods.

Past and Present

In the current and previous versions of C#, if you wanted to give users of your API the ability to use a method with a different number of parameters you had to overload a method:

    public void OldFashionedMethod(string stringParam, int intParam)
    {
      Console.WriteLine("OldFashionedMethod(two parameters) - The parameters are: stringParameter[{0}] intParameter[{1}]",
        stringParam, intParam);
    }

    public void OldFashionedMethod(string stringParam)
    {
      int intParam = 8;
      Console.WriteLine("OldFashionedMethod(one parameter) - The parameters are: stringParameter[{0}] intParameter[{1}]",
        stringParam, intParam);
    }

This allows you to call the method in two ways

SomeClass.OldFashionedMethod("TheParameter", 10);
SomeClass.OldFashionedMethod("TheParameter");

You could of course also use this technique

Future

In th enext version of C# you will be able to provide default values for the parameters of a method, in the declaration of that method

    public void OptionalParameterMethod(string stringParam, int intParam = 8)
    {
      Console.WriteLine("The parameters are: stringParameter[{0}] intParameter[{1}]",
        stringParam, intParam);
    }

This also allows you to write similar as above:
This allows you to call the method in two ways

SomeClass.OptionalParameterMethod("TheParameter", 10);
SomeClass.OptionalParameterMethod("TheParameter");

If it looks like a duck …

If we perform the Duck test on this code we will come to the conclusion that although the code looks the same, the behaviour is different so both probably aren’t ducks.

Using Reflector we can look at how the above is resolved by the compiler:

In the case of overloaded method, the compiler generates the expected method calls, one for each overoaded version:

SomeClass.OldFashionedMethod("TheParameter", 10);
SomeClass.OldFashionedMethod("TheParameter");

However, in the case of default parameter values, the compiler generates calls to the single methods and injects the default parameter value when compiling the call making use of the default parameter:

SomeClass.OptionalParameterMethod("TheParameter", 10);
SomeClass.OptionalParameterMethod("TheParameter", 8);

So the default parameter is not substituted in the method itself, like it is done when using overloaded methods, but it is resolved at the call site.

In practice this means that when the writer of the library changes the value of the default parameter, your code calling this library will not use this new value, unless you recompile your code.

So, what isn’t possible?

Optional parameters are only possible at the end of the parameterlist of a method. So, you can not do the following:

public void OptionalParameterMethod(string stringParam = "DefaultValue", int intParam)

From the above code you might wonder why this isn’t possible, but have a look at the folowing method declaration:

public void OptionalParameterMethod(string stringParam = "DefaultValue", string otherStringParam)

Now, how must the compiler resolve following call?

SomeClass.OptionalParameterMethod("TheParameter");

Is the provided parameter a substitute for the default parameter, or is it a value for the last parameter?

Optional parameters can only be compile time constants. This makes the following impossible:

public void DefaultClassParameter(ParameterClass param = new ParameterClass())

The fact that only compile time constants can be used, limits the use of optional parameters to primitive types, enums, or strings.

Usefull or useless

Optional parameters generally generate some of fuss when discussed because most implemetations use the resolve at call site approach which can produce some unexpected results when the library exposing the method evolves and the default value changes. This article provides some guidance

For once and for all: Delegates, Events, Anonymous Methods and Lambda Expressions

What started as a simple concept, Delegates and Events, has turned into a major subject in the .NET framework with newcommers like Anonymous Methods and Lambda Expressions. In this post I hope to shed some light on what all these are and how they interact. Mind you however that all that is written in this post is not new and has been described in more detail by many other much more smarter people then me. So, allthough I will touch on the various aspects of the subject, for detailed discussions and how certain features work I will forward you to those posts. It is not my goal to repeat what allready has been said, but I wanted investigate what is possible and share my results with you. This way I thought to provide in one post a detailed summary on what is possible and how it’s done.

It is my hope that after reading this post and reading the referenced articles, one would have an in depth knowledge of delegates, events and the lot.

Delegates

The basic construct for all the above is the delegate. For those familiar with C++: a delegate can be seen as similar to a function pointer in that it allows you to pas a reference to a method around and then later call that method. There are however some differences between them resulting in people trying to emulate delegates in C++

For those unfamiliar with C++, this Stack Overflow article has a nice explanation:

The best analogy that I’ve found to explain delegates it’s a testament or your last will.

It’s a set of instructions that of course you write before you die, and you leave it in a safe place. Then after your death, your attorney will execute those instructions…

Delegates are used mostly when the code that wants to execute the actions doesn’t knows the enough details of what that action should be, you can view it as a sequence of actions to be executed at the appropriate time.

Declaring a delegate

Declaration of a delegate is done in C# using the delegate keyword:

// A delegate is a type of itself, so you
// can declare it outside the scope of a class
delegate int SomeMethodDelegate(string arg);

This declaration declares a delegate which can call methods that return an integer and have a string as their single argument. A delegate is a type of it’s own, so a delegate can be declared outside the scope of a class unlike methods and properties. But just as a type (class, struct, …) can not be declared inside a method, neither can a delegate. If you declare a delegate using the above syntax, you are actually declaring a type derived from the Delegate type. Actually, it’s derived from the System.MulticastDelegate type.

Using the delegate

Instantiating the delegate and binding a method to it is as simple as:

// Provided you have an object delegateDemo of a class which implements 
// a method called MethodCall which takes a string and returns an integer
SomeMethodDelegate delegateReference = new SomeMethodDelegate(delegateDemo.MethodToCall);

Using the delegate is similar to invoking the method

int i = delegateReference("String argument");

There is a more longwinded way of instantiating delegates and invoking them directly involving the Delegate class. I will not illustrate it here but you can find more information about it in the Stackoverflow question “Possible to instantiate and invoke a delegate by name?”

Delegates are “Multicast”

In the .Net framework, delegates are multicast. What this means is that you can bind more then one method to a delegate:

SomeMethodDelegate delegateReference = new SomeMethodDelegate(delegateDemo.MethodToCall);
delegateReference += new SomeMethodDelegate(delegateDemo.SomeOtherMethodToCall);

If you now invoke the delegate, the two methods bound to the delegate will be called. If a method in the chain throws an exception, latter methods will no longer be called. You can avoid this by iterating the multicast delegate invocation list yourself.

Life made easy

Delegates are practical beasts and you can use them in lot’s of places. To help you and to prevent you’d have to declare new delegate types all over the place, Microsoft declared some delegate types in the .Net Framework which you can use out of the box:

Action Delegate 
Action<T> Generic Delegate 
...
Action<T1, T2, T3, T4> Generic Delegate

These encapsulate methods with no return value and zero to 4 arguments.

So, whenever you find the need to write code like

delegate void YourDelegate(int, double, string);
YourDelegate yourDelegateInstance;

you can instead write:

Action<int, double, string> yourDelegateInstance;
Func<TResult> Generic Delegate 
Func<T, TResult> Generic Delegate 
...
Func<T1, T2, T3, T4, TResult> Generic Delegate 

These encapsulate methods with a return type and zero to 4 arguments.

You can find more about predefined delegates here.

Deep dive

There is also another, more powerfull, way of instantiating delegates. If you take a look at the MSDN documentation of the Delegate type, then you will see it has a method CreateDelegate which has a number of overriden signatures of which Delegate.CreateDelegate Method (Type, Object, MethodInfo, Boolean) is the most generic one. Where in the above samples the assignment of the delegate also specifies the object to call the method from, with this method it is possible to postpone this decision untill you actually call the instantiated delegate, by providing the object as an argument to the delegate.

delegate void OpenMethodDelegate(DelegateDemo target);

class DelegateDemo
{
  public DelegateDemo(string arg)
  {
    m_arg = arg;
  }

  public void MethodToCall()
  {
    Console.Write("This method got called on object DelegateDemo[" + m_arg + "] using a delegate.\n");
  }
}
	
MethodInfo method = typeof(DelegateDemo).GetMethod("MethodToCall", BindingFlags.Public | BindingFlags.Instance);
OpenMethodDelegate nonBoundDelegate = (OpenMethodDelegate)Delegate.CreateDelegate(typeof(OpenMethodDelegate), null, method);
DelegateDemo delegateDemo1 = new DelegateDemo("delegateDemo1");
nonBoundDelegate(delegateDemo1);
DelegateDemo delegateDemo2 = new DelegateDemo("delegateDemo2");
nonBoundDelegate(delegateDemo2);

With the above delegate declaration, you can create 4 different delegate instantiations, all documented here. In the sample code with this post you can see an implementation of the 4 possibilities.

Events

Events are technically essentialy the same as delegates, only they have been declared with the modifier “event”. Thus, they are a special kind of delegate: a “modified” delegate. However they serve a different semantic purpose.

Declaring an event

Because an event is a special kind of instance of a or is a modified delegate, you declare events as a special type of instance of the delegate.

delegate int SomeMethodHandler(string arg);
public event SomeMethodHandler SomeMethodEvent;

You could compare it with declaring a const:

int i;		   // The normal type (in the above this is the delegate)
const int j;	// The modified type (in the above this is the event)

The type of modification it does is however completely different. (and then again, it’s not, but you will read about this further).

Using the delegate as an event

Instantiating the event and binding it to a method is done like:

eventDemo.SomethingHappenedEvent += new EventDelegate(eventDemo_SomethingHappenedEvent);

Notice how we used the “+=” operator instead of the simple assignment operator as done with regular delegates. This is one of the effects of using the event modifier on the delegate. What actually happens when you use the event modifier on a delegate is the following:

  1. A field is created on your class with the type of the delegate.
  2. “Add” and “Remove” accessor methods are created to access that field. These two methods are generaly called “Event Accessors”

This is much in the same way as when you declare a property to access a field. This is also why the above descibes the implementation of what is called “Field like events”. The above syntax is a C# shortcut for accessing those add and remove handlers.

Using the event-delegate is similar to invoking a method.

SomethingHappenedEvent();

What is not visible in this code is the fact that this call can only be made inside a method of the class declaring the event. The event field can not even be accessed in a class deriving from the class declaring the event. This also is an effect of using the event modifier on the delegate instance.

If you want to provide access to derived classes, Microsoft suggests declaring so called “On” handler methods:

event MyCorrectEventHandler MyCorrectEvent;
event EventHandler<MyCorrectEventArgs> TheSameButWithoutTheDelegate;

protected virtual void OnMyCorrectEvent(MyCorrectEventArgs e)
{
  EventHandler<MyCorrectEventArgs> handler = TheSameButWithoutTheDelegate;
  if (handler != null)
  {
    e.SomeValue = 1;
    handler(this, e);
  } 
}

In the derived class, you then raise the event by calling this On… method.

The “event” modifier: what does it do?

The event keyword in C# is actually a modifier on the delegate type. What it modifies is the visibility of certain members of the delegate so that effectively you can only access the Combine and Remove methods of the Delegate type, that being the reason why you can only add or remove delegate handlers.

Some conventions

The above code, allthough correct, is not the common way of using events. Microsoft provides some guidelines on how to declare and use event in the .NET Framework:

  • The delegate for the event has no return value.
  • The delegate for the event always has two parameters, the first of type object and referencing the object that fires the event, and the second an EventArgs derived class which identifies details of the event.

In the above you will probably recognize the typical eventhandler signature from windows forms:

void button_ClickHandler(object sender, System.EventArgs e)

Life made easy

When make heavy use of events in your code, you will find yourself declaring lots of events. That would require you to also write lots of delegates for those events, all with this same basic structure of a method taking an object and a EventArgs derived class.

To make life easier Microsoft provides two delegate for you to prevent this clutter:

EventHandler Delegate 
EventHandler<TEventArgs> Generic Delegate 

So instead of having to write

delegate void MyPersonalEventHandler(object sender, EventArgs e);
event MyPersonalEventHandler MyPersonalEvent;

You can now write

event EventHandler MyPersonalEvent;

Or if you have your own event arguments:

class YourEventArgs : EventArgs {... }
event EventHandler<YourEventArgs> YourEventWithSpecialArguments;

Deep dive
The above illustrates the most common way of using the event modifier on delegates. If you look at the documentation for the event modifier you will notice that there is also the possibility of declaring events as virtual, abstract, etc… Whereas the event modifier changes the visibility of certain members of the delegate, declaring an event as virtual or abstract actually changes the the implementation of the event much in the same way as declaring a property as virtual or abstract.

Just as a abstract or virtual properties provide just the signature for the property getter and setter methods, an abstract or virtual event provides just the signature for the event “add-er” and “remove-er” methods.

You can then provide your own implementations for the event accessor methods. Being able to provide your own accessor methods implementations is however not a privilege for abstract and virtual events, but can be done for every event.

Again, in the sample code you can see an implementation of this.

Anonymous methods

Since C# 2.0 there is a new syntax for attaching methods to delegates named Anonymous methods. Well, this is actally an over-simplification of anonymous methods. But let’s stick with this simplification for a minute.

Declaring an anonymous method

In the Delegate section you learned that attaching a method to a delegate is done by creating the method in a class first and then assigning that method to the delegate:

delegate int SomeMethodDelegate(string arg);

class ClassWithMethod
{
   int MethodToCall(string arg) { ... }
}

SomeMethodDelegate delegateReference = new SomeMethodDelegate(delegateDemo.MethodToCall);

This can be cumbersome because it obligates you to create a method in a class which you will not always want to do. So C# 2.0 provides you the possibility to declare that method inline with the assignment to the delegate:

SomeMethodDelegate d = delegate(string param) { Console.WriteLine("Param: " + param.ToString()); };
d("A Parameter");

This can be very handy in certain situations like sorting of items in a list.

Deep dive

Now why is this an oversimplification? Because with the syntax of Anonymous Methods comes a programming construct more generaly known as Closures to C#.

What closures allow you to do is use the variables known in the scope declaring the anonymous method, inside the anonymous method. As an example:

public static void UsingLocal()
{
  int i;
  i = 1; 
  Action d = delegate(int param) { Console.WriteLine("With Parameters[" + param.ToString() + "] and Local[" + i.ToString() + "]"); };
  d(2);
}

This even extends to the fields of the class in which the declaring scope resides:

class AnonymousMethodDeepDive
{
  private int m_field;

  public AnonymousMethodDeepDive(int field)
  {
    m_field = field;
  }

  public int Property { get; set; }

  public void UsingField()
  {
    Action d = delegate(int param) { Console.WriteLine("With Parameters[" + param.ToString() + "] and Field[" + m_field.ToString() + "]"); };
    d(1);
  }

  public void UsingProperty()
  {
    Action d = delegate(int param) { Console.WriteLine("With Parameters[" + param.ToString() + "] and Property[" + Property.ToString() + "]"); };
    d(1);
  }
}

What essentialy happens is:

  1. The compiler generates a class, capturing all the local variables as proeprties of that class.
  2. The compiler generated class has as a method the anonymous method, thus making it’s properties (and thus tha variables in the decalring scope) available to the anonymous method.

There are a few optimizations in some special cases, but the above is the most generic way to look at these.

Now, if you think you understand all this, then read these two posts.

Lambda Expressions

Lambda Expressons are in their most basic form a more convenient syntax for anonymous methods. Again, their is a lot more to lambda expressions then this, but those features have nothing to do with delegates so I will not discuss them in this post.

Syntax

The most generic way for writing lambda expressions is:

Func f1 = (int x, string y) =&gt; { Console.WriteLine("A Return Value And Two Parameters: " + x.ToString()); return x + 1; };

In this assignment statement the form

() => { }

is the lambda expression.

Now, there are a few simplifications possible:

Because C# supports parameter type inference, you can drop the type specifiers for the arguments:

Func f1 = (x, y) => { Console.WriteLine("A Return Value And Two Parameters: " + x.ToString()); return x + 1; };

If you have a single statement, you can drop the curly braces and the semicolon:

Action d4 = (x, y, z) => Console.WriteLine("Three Parameters: [{0}][{1}][{2}]", x, y, z);

If you have a single parameter, you can drop the parameter braces:

Action d2 = x => { Console.WriteLine("One Parameter: " + x.ToString()); };

If you have a single statement, which is the return value, you can drop the “return” keyword:

Func f2 = x => x + 1;

Code

You can download the code here

Put an “N” in front of it, or add “.NET” to the back. Part I

Thats been a long time:

For other projects, see:

Offline Maps: Version 1.4.2.0 and update of the base URL’s

I finally got to posting my code on the codeplex website. You can find it here.

The project page on this blog will remain the main source of information about features of the application and how to use it. The codeplex site will however become the reference for the binaries and soucecode. No updates will be posted anymore on Box.net

So, without any further ado: go to the codeplex projectpage and download the application on the Releases page. People wanting to investigate the sourcecode can find it on the Source code page.

First thing to do is to update the base-url. For information on how to do this, visit this page.

Enjoy!

Exploring Workflow Foundation Intermezzo 1: Apply what we learned so far – Early post of the Image Processing Activity Library

Just a quick posting of an application of Windows Workflow Foundation in the area of image processing.

When I started the Exploring Workflow Foundation series of posts this is the reason I started them: I wanted to make a library in the area of image processing based on workflow activities. Well, to be honest, it’s more the other way around: I wanted to learn Workflow Foundation and ended up with image processing as a candidate subject. Anyway, this library is not complete, let alone production ready code. It’s what I have so far but it still needs a lof of tweaking. For example, I did not make use of any validation code when compiling th eworkflow, which is something I will definitely add in the future. There is also no real exception handling code. In other words: this version is just a quick post of what I have so far but still needs a lot of work.

So keep watching for updates.

Just go to the ImageProcessing WF page for a download of the available code.

NHibernate and ASP.Net: what’s the problem?

I’ve been looking at NHibernate again lately and wanted to start using it in an ASP.NET application. “So what?” you say, well that’s also what I was thinking. But googling for ASP.NET and NHibernate turned out to be very interesting:

Using NHibernate with ASP.NET

Of course, I could have gone with some of the existing frameworks but then what would I have learned?

What is the problem
The above link on using NHibernate with ASP.NET gives a very good introduction to what the problem is:

The stateless nature of HTTP creates a few challenges with regard to using NHibernate compared to Winforms. One challenge is where to store the SessionFactory, and another one is how to handle each user’s NHibernate Session.

What are the possible solutions?
As the post NHibernate, Part 3 of xxx: NHibernate Session Management proves, your options are infinite. The same above link on using NHibernate with ASP.NET also provides some introductary notes on possible solutions. Another interesting post is on Codeproject: NHibernate Best Practices with ASP.NET, 1.2nd Ed..

The main stream of thought is to make a NHibernate session for every request made to the ASP.Net application. The problem is however how to tap into that request. Most solutions use the IHttpModule interface.

What is this IHttpModule? Wel, it is an interface you can implement which allows you to tap into ASP.Net applications, session and requests. You can read more about it in the article The ASP Column: HTTP Modules

Enterprise Implementations
There will most certainly be more then the ones I provide here, but these are thye ones I’ve found (but not yet used):
Rhino tools
S#arp Architecture

Hope this all sheds some light on what to do. I was originally planning to have an attempt at an implementation but found in the above and below cited articles enough examples and impelmentations that I could hardly provide any more insight. So, check the articles for sample code.

Links

The ASP.Net Application Model:
Understanding the HttpApplication Class
ASP.NET Applications
Application and Session Objects in ASP.NET
The ASP Column: HTTP Modules

NHibernate Session Management
NHibernate Session Management in Domain Driven App’s
Simple NHibernate Example, Part 4 : Session Management

Existing implementations:
Rhino tools
S#arp Architecture

More questions and trouble:
NHibernate in an ASP.NET MVC application
NHibernate Session Module opens unecessary transactions for CSS and images
NHibernate Sessions with ASP.NET