Tag Archives: .NET

Fun with Moq: Dynamic mocking

Run time mocking

Sometimes it’s useful to be able to create a Mock object without the type being known at compile time. Normally when using Moq you create a Mock object using this syntax:

var mock = new Mock<IMyInterface>().Object;

But what if IMyInterface is not known at compile time? What you would like would be to do this var mock = new Mock(myType).Object and receive the mocked object back. Turns out this method does not exists, but it’s possible to get around this using the magic of reflection!

public static object DynamicMock(Type type)
   var mock = typeof(Mock<>).MakeGenericType(type).GetConstructor(Type.EmptyTypes).Invoke(new object[] { });
   return mock.GetType().GetProperties().Single(f => f.Name == "Object" && f.PropertyType == type).GetValue(mock, new object[] {});

This piece of code will return to you a mock that implements the interface type you specify and return it as an object. This could then be used for various fun stuff to automate the unit testing of certain things.

Dynamic parameter checking

Seen this code before?

public class MyConcreteClass 
   private readonly IDependency1 _a;
   private readonly IDependency2 _b;
   private readonly IDependency1 _c;
   private readonly IDependency1 _d

   public MyConcreteClass(IDependency1 a, IDependency2 b, IDependency1 c, IDependency1 d)
     if (a == null) throw new ArgumentNullException("a");
     if (b == null) throw new ArgumentNullException("b");
     if (c == null) throw new ArgumentNullException("c");
     if (d == null) throw new ArgumentNullException("d");

     _a = a;
     _b = b;
     _c = c;
     _d = d;

It’s great to cast all those ArgumentNullExceptions to check the value, but testing this is a complete pain, since you’d need four separate test cases for each parameter to verify that the correct exception is being thrown. With dynamic mocking and some reflection this can be totally automated for classes that only take interfaces as parameters – which in a heavily dependency injected application is pretty much all of them.

All you need to test this scenario is a single call to NullParameterCheck<MyConcreteClass>() and this method somewhere in your testing code.

public static void NullParameterCheck<T>()
	var constructor = typeof(T).GetConstructors().Single();

	Assert.IsFalse(constructor.GetParameters().Any(f => !f.ParameterType.IsInterface), "All parameters must be interfaces in order to use this helper");

	for (int i = 0; i< constructor.GetParameters().Length; ++i)
		var paramName = constructor.GetParameters()[i].Name;
		int i1 = i;
		var args = constructor.GetParameters().Select((p, ix) => ix == i1
			? null
			: DynamicMock(p.ParameterType));
			Assert.Fail("No exception for parameter null {0}", paramName);
		catch (TargetInvocationException e)
			Assert.IsTrue(e.InnerException is ArgumentNullException);
			Assert.AreEqual(paramName, ((ArgumentNullException)e.InnerException).ParamName);

This code will loop around each parameter, replacing one of them with null in turn to verify that each interface parameter will generate the corresponding ArgumentNullException

Happy mocking!

Tagged , , , ,

Introducing Piglet

This is an introductory post for my latest creation, Piglet the friendly parsing and lexing tool. As so much software Piglet is written out of both a sense of satisfaction in solving a difficult problem, and seeing a void where my piece of software might be useful to someone. Piglet is open sourced using the MIT license. This post is intended to compliment the readme on github to form a better picture of why I have written this library and how it can be used.

Why another parser generator?!

Because the other parser generators are too big for easy tasks, and harder to integrate into a project. They are also highly technical and hard to understand for someone who isn’t genuinely interested in old-school comp.sci.

The purpose is for you to have a tool at hand for parsing tasks that are smaller than full blown language construction efforts. Piglet tries to bridge the gap between (ab)using regular expressions and going in guns blazing with a large parsing toolset. It is not going to replace ANTLR or any of those tools, though you certainly can parse larger grammars with Piglet. This is the tool to use if you want a low-treshold, easy to use tool for any context free data.

Code based configuration

Piglet is, in sharp contrast to most other generators configurable in code. You create your parser and use it as naturally as you configure any other object. It has about the same functionality as the yacc/bison family of tools and generates similar parsers. This is an important point because if your parser is configured using a separate input file or even a completely separate tool you are always going to have a distance between the running code and the parser. The parser generators also sometimes generate fairly incomprehensible code. If you have a small parsing task, are you really going to use a generator or are you going to roll your own parser?

There are some tradeoffs in this strategy. Obviously the parser generation is going to be done at runtimes. However, the parsers are reentrant to the construction should only need to be done once. It also enables you to be able to use lambdas as actions when rules are followed, which also means that Piglet can construct type-safe parsers!

Ease of use

Unfortunately parsing is a bit complex and it’s usually required to know a bit about context free grammars to be able to construct a parser. Piglet tries to get around this problem by introducing a fluent configuration interface.

It’s easier to show it straight up. This is a full blown JSON parser. The only thing missing here is really only details such as the ability to write 0x notation for hexadecimal and exponent notation for numbers. There rest is all there.

// Create a configuration object. This object generates all the configuration needed for the parser.
var config = ParserFactory.Fluent();

// Create rules. The first rule is the MAIN rule, the rule that everything must be able
// to condense down to. For JSON this is a single object, since a JSON string is always
// just one object.
var jsonObject = config.Rule();

// Used to represent an element of an object
// which is something like "elementname" : some_value
var jsonElement = config.Rule();

// This represents a value of a json element
var jsonValue = config.Rule();

// This represents an array of values
var jsonArray = config.Rule();

// Now we declare what a jsonObject is made up of
// Literals are found in quotes. Interesting parts that we are interested 
// in are named using the As clause, which makes them accessible in the 
// .WhenFound. The result of WhenFound is returned to the caller.
	.WhenFound( o => new JsonObject { Elements = o.ElementList } );

// Declares what an element is made up of. Note that the rule above uses the
// jsonElement before what it is made of is declared. This is a crucial part
// of parsing. This bit has two interesting named pieces "Name" and "Value".
// Since each bit has a value, this gets assigned to the o parameter to the WhenFound lambda.
	.WhenFound( o => new JsonElement { Name = o.Name, Value = o.Value } );

// A jsonValue has several interpretations, separated by Or clauses.
// Predefined parsing is found for simple types. Note the recursive use
// of jsonObject, values can be full objects themselves! There is no need
// for .WhenFound clauses for single part rules, they
// will always return the value of the single part.
	.Or.By("null").WhenFound(o => null); // Need to specify, since the default will return the string "null"

// This rule could have been merged into the jsonValue rule, as its 
// own .Or.By clause. It's separated for readability only.
	   .WhenFound(o => o.Values);

// When the configuratin is completed - create the parser!
// If the parser creation is unsuccessful, this throws the
// friendliest exception possible to help you find the issue.
var parser = config.CreateParser();

// Here is how you use it!
var jObject = (JsonObject)parser.Parse(
		 ""IntegerProperty"" : 1234, 
		 ""another_object"" : {
		 ""empty_object"" : {

There is also a less verbose technical interface, which right now includes more functions than the fluent one does. In the interest of brevity in this post I’m not going to describe it in detail. The features that currently only exists in the tech interface are context dependent precedence, token precedence, panic mode error recovery and type specific parser generation (the fluent parsers will all generate an object as an end result). These should all be upcoming features in further versions for the fluent interface.

The fluent configuration interface is right now in a working state, but can certainly use more functions! Common tasks should be easy to accomplish while harder tasks may require you to fall back on the technical configuration. As an exciting preview of things to come, I’m currently working on an embedded domain specific language generator (made using Piglet) called Snout, which when finished should help the maintainability of the fluent interface.

Piglet is totally dependency free, and written in C# 4. The code is well commented and understandable. If you are looking for code that reasonably explains the parser generation algorithm, Piglet is a sensible choice.

In technical terms, Piglet generates LALR(1) parsers – mainly because it’s an easier way of expressing your grammar since you do not require left factoring which is a pretty difficult concept to explain.

More examples

I’ve written a Demo project that is available in the main github repository which contains a few demos. The unit tests for Piglet are also quite extensive and are suitable for learning. I’m hoping to find more time to write a detailed tutorial on how to go from a given format into a complete parser. Suggestions for tutorials and articles are most welcome.

Getting your hands on it

Piglet lives on GitHub if you want the source code and demos. It also lives on NuGet if you just want the binaries.


You are most welcome, regardless of skill level. There’s lots of stuff to do! Or just fork it and go to town on your own. I would be flattered if you did.

And if you can’t program, Piglet could use a logo. I’m thinking a piglet would make an appropriate one 🙂

Tagged , , ,

How to handle WPF events in native MFC code

I’ve recently had the dubious pleasure of getting to know C++/CLI and revisiting my good old buddy MFC. The task at hand was to integrate a WPF component into an existing MFC application. That task in itself is probably interesting enough to warrant it’s own post but suffice to say that I got this working properly. This means that we’ll end up with a class deriving CDialog that holds a WPF component inside it. Now we want to handle events. In WPF country, this is easy: add this to our WPF class:

public event EventHandler OnMyEvent;

And in our dialog we hold the WPF control in a gcroot<MyWPFControlClassName>. We also have a method we’d like to get called.

void MyDialogClass::OnEvent(System::Object ^sender, System::EventArgs ^args)
   // Do stuff

First off, what prompted this article is what does not work. You cannot from your unmanaged dialog class pass a pointer to your member function to your event like this.

wpfControl->OnMyEvent += gcnew System::EventHandler(

This does not work, and it’s because your class is not a managed class since it’s not declared as ref class. The error message is also less than helpful. So how to solve this? You need a wrapper. Create this class somewhere in your project.

#pragma once

template<class T> ref class ManagedEventWrapper {
   typedef void(T::*MemberFunction)(System::Object^ sender, System::EventArgs^ args);

   ManagedEventWrapper(T& host, MemberFunction function)
      : m_host (host)
      , m_function(function) 
   void OnEvent(System::Object ^sender, System::EventArgs ^args)
      (m_host.*m_function)(sender, args);

   T& m_host;
   MemberFunction m_function;

If you then include this file in your MFC class, then you can subscribe to events like this:

wpfControl->OnMyEvent += gcnew System::EventHandler(
      gcnew ManagedEventWrapper<MyNativeDialogClass>(*this, &MyNativeDialogClass::OnEvent), 

This creates the neccessary layer of extra indirection around the native code to make the event handling work properly. You don’t need to save the reference to ManagedEventWraper since the reference is held by the System::EventHandler which makes sure it does not get garbage collected.

Tagged , , , ,

Exception handling done the right way

I love exceptions, but I get a distinct feeling many people don’t when I see some horrific examples of their use. Especially from people who gets forced into using them by javas wonderful checked exception feature without truly understanding the concept. Or by people so scared of them that they hardly dare catch it, like way too many of the C++ crowd. In these enlightened days, exceptions don’t cause the problems they used to cause, unless you are working with old C++ code which doesn’t use auto_ptr. If you are, abandon all hope and refactor hard.

I’m going to assume you’re writing C# here, but everything I say goes for Java as well. It’s even better there since Java has checked exceptions. But without further ado here’s my handy-dandy guide how to do it right!

Why bother

Because it’s a graceful way of handling exceptional circumstances. Anything that is not considered a normal result of your method that might happen is an exceptional circumstance. Return values are not for exceptional circumstances. I assume you like the .NET framework or Javas similar environment. They’re nice because of exceptions! To see the alternative, take a look at for instance straight up COM in C++. It’s clunky as hell. Without exceptions, the only way to check for any errors is to check return values. Whenever you do something you’ll invariably get the real return value as a pointer-to-a-pointer and the method itself returns a HRESULT which you need to check. But of course, you won’t, since they almost never fail and you will forget. And you can’t read the code like it’s supposed to be read since the return values will be in the parameter list instead of in the actual return.

To compound the problem further C# has an out and a ref specification to parameters. Which is almost in all cases used for this sort of stuff, and almost always totally evil in my book for the reasons stated above. You should never ever do this sort of stuff:

string DoStuff(out BusinessObject bo) {
    // Doing stuff
    // ...
    // Business plan bad, return error
    return ".COM boom failed";

The only way to find out what went wrong it to do string compared on the return value. Evil. Return value checking should be a thing of the past for non-exceptional circumstances.

How do I do it then?

Lets start by how to not do it. Here’s a typical example of doing it wrong

void DoStuff() 
	// stuff goes wrong
	throw new Exception("Shit is hitting fans");

NO! You don’t throw the Exception class, never ever. I wish they made it abstract. This circumvents the catch statements intended use, makes it impossible to tell what’s going wrong and makes babies cry. If you specify an Exception type to catch it will catch every exception. Whatever it was you’ll have to figure out yourself. It might have been shit hitting fans, but it might as well have been a null reference. Maybe it was a division by zero. Who knows?

If shit is hitting fans, you throw a very specific exception relating preferably to that case and no other case.

public class ShitHitFanException : Exception 
    public ShitHitFanException(string message) : base(message 

void DoStuff() 
	// Danger Will Robinson!
	throw new ShitHitFanException("Scotty can’t change laws of physics");

And you catch it by catching the exception you need to handle, permitting the stuff you’re incapable of handling to bubble up to the surface. Maybe even to a crash, if that’s your cup of tea.

catch (ShitHitFanException e) 
    // Alert Will Robinson of danger.

This leads to my next point. You need to use base classes for your exceptions if they have any sort of common ground. Just routinely declaring exceptions as being subclasses to Exception like a big happy community of equals is evil. You need to categorize your exceptions into types of exceptions. For instance, if you have some sort of method which handles files, you might be throwing FileNotFoundException, DirectoryAccessDeniedException and DiskFullException. These have common ground, and should be labeled as such by inheritance. You need a IOException base class. This makes your catching code able to intelligently decide if it wants to handle exceptions specifically or more sweeping without resorting to acts of evil like catching Exception.

More importantly it also enables you to do cool stuff like

void ShuffleImportantDocumentsFromTopDrawer(Document[] topDrawer) 
        foreach (var document in topDrawer) 
            catch (FileNotFoundException e) 
                // Dog probably ate it. Log a warning and continue
    catch (IOException e) 
        // We end up here for BOTH DiskFullException and 
        // DirectoryAccessDeniedException

This is impossible to do gracefully if you have screwed up your inheritance chain or are catching Exception itself. Exceptions have no relation to another, and you can’t catch two similar exceptions handling them the same way without resorting to copy and paste or putting the handling in a separate method, which is weird and ugly. This is oftentimes a problem wih Java file IO. They throw exceptions like there’s no tomorrow and you’re required to catch them all. You probably want to handle some of them the same way. Catch the base class and you’re set.

But, I don’t want to handle it you say. I want someone else to do it for me. First of the bat, lets never ever do this again:

catch (FaultyException e)
   // Whoops. I cant handle this stuff. Do some clean up and signal errors again
   throw new OtherException("There was a problem with faulty method, big surprise");

NO. There’s one huge glaring problem here. You are marshalling away the cause of the exception! The hard and fast rule is: If you are throwing something from inside a catch, you need to supply the exception you throw with it’s underlying cause. Here is the corrected code:

   throw new OtherException("There was a problem with faulty method, big surprise", e);

See how we added the e to the constructor. This makes a world of difference! When you print a stack trace, you’ll be pointed to the correct line, instead of being pointed to the catch block which says absolutely squat about the real nature of the problem.

Another point I’d like to make is that you shouldn’t throw another exception unless you have changed the meaning. But you can still catch stuff and log. As an example, say you have a SOAP service. Since you are diligently applying the principles in this article, you’re using exceptions to handle SOAP errors (they serialize fine, don’t worry about it). But you want a log on the server side as well of any exceptions sent to the client. Enter the second (under)used use of the throw keyword – the parameterless throw.

string MySoapyMethod(string param) 
        // Do cool stuff that fails...
    catch (BrokenException e)
        // Log this stuff so that we know about it
        Log.Error("Broken stuff in Soapy method", e);

This will throw the exception without altering it in any way. This is the other legal way of handling stuff you don’t want to or can’t handle. A final point, when you log using your logging framework, such as log4net, you typically get an option to pass an exception. Use it. If you have an exception logging, never log Log.Error(e.Message). Always log Log.Error("A real description of what went wrong", e). That way, you’ll still preserve the precious stacktrace.

Tagged , ,