Introducing μnit

Last week, I teamed up with Bjørn Einar (control-engineer gone js-hipster) and Jonas (bona fide smalltalk hacker) to talk about .NET gadgeteer at the NDC 2012 conference in Oslo. .NET gadgeteer is a rapid prototyping platform for embedded devices running the .NET micro framework – a scaled down version of the .NET framework itself. You can read the abstract of our talk here if you like. The talk itself is available online as well. You can view it here.

The purpose of the talk was to push the envelope a bit, and try out things that embedded .NET micro devices aren’t really suited for. We think it’s important for developers to fool around a bit, without considering mundane things like business value. That allows for immersion and engagement in projects that are pure fun.

I started gently though, with a faux-test driven implementation of Conway’s Game of Life. That is, I wrote the implementation of Life first, and then retro-fitted a couple of unit tests to make it seem like I’d followed the rules of the TDD police. That way I could conjure up the illusion of a true software craftsman, when in fact I’d just written a few tests after the implementation was done, regression tests if you will.

I feel like I had a reasonable excuse for cheating though: at the time, there were no unit testing frameworks available for the .NET micro framework. So you know how TDD opponents find it tedious to write the test before the implementation? Well, in this case I would have to write the unit testing framework before writing the test as well. So the barrier to entry was a wee bit higher.

Now in order to create the illusion of proper craftsmanship in retrospect, I did end up writing tests, and in order to do that, I did have to write my own testing framework. So procrastination didn’t really help all that much. But there you go. Goes to show that the TDD police is on to something, I suppose.

Anyways, the testing framework I wrote is called μnit, pronounced [mju:nit]. Which is a terribly clever name, I’m sure you’ll agree. First off, the μ looks very much like a u. So in terms of glyphs, it basically reads like unit. At the same time, the μ is used as a prefix signifying “micro” in the metric system of measurement – which is perfect since it’s written for the .NET *micro* framework. So yeah, it just reeks of clever, that name.

Implementation-wise it’s pretty run-of-the-mill, though. You’ll find that μnit works just about like any other xUnit framework out there. While the .NET micro framework is obviously scaled down compared to the full .NET framework, it is not a toy framework. Among the capabilities it shares with its bigger sibling is reflection, which is the key ingredient in all the xUnit frameworks I know of. Or at least I suppose it is, I haven’t really looked at the source code of any of them. Guess I should. Bound to learn something.

Anyways, the way I think these frameworks work is that you have some mechanics for identifying test methods hanging off of test classes. For each test method, you create an instance of the test class, run the method, and evaluate the result. Since you don’t want to state explicitly which test methods to run, you typically use reflection to identify and run all the test methods instead. At least that’s how μnit works.

One feature that got axed in the .NET micro framework is custom attributes, and hence there can be no [Test] annotation for labelling test methods. So μnit uses naming conventions for identifying test methods instead, just like in jUnit 3 and earlier. But that’s just cosmetics, it doesn’t really change anything. In μnit we use the arbitrary yet common convention that test methods should start with the prefix “Test”. In addition, they must be public, return void and have no parameters. Test classes must inherit from the Fixture base class, and must have a parameterless constructor. All catering for the tiny bit of reflection voodoo necessary to run the tests.

Here’s the Fixture class that all test classes must inherit from:


namespace Mjunit
{
public abstract class Fixture
{
public virtual void Setup() {}
public virtual void Teardown() {}
}
}

view raw

Fixture.cs

hosted with ❤ by GitHub

As you can see, Fixture defines empty virtual methods for set-up and tear-down, named SetUp and TearDown, respectively. Test classes can override these to make something actually happen before and after a test method is run. Conventional stuff.

The task of identifying test methods to run is handler by the TestFinder class.


namespace Mjunit
{
public class TestFinder
{
public ArrayList FindTests(Assembly assembly)
{
var types = assembly.GetTypes();
var fixtures = GetTestFixtures(types);
var groups = GetTestGroups(fixtures);
return groups;
}
private ArrayList GetTestFixtures(Type[] types)
{
var result = new ArrayList();
for (int i = 0; i < types.Length; i++)
{
var t = types[i];
if (t.IsSubclassOf(typeof(Fixture)))
{
result.Add(t);
}
}
return result;
}
private ArrayList GetTestGroups(ArrayList fixtures)
{
var result = new ArrayList();
foreach (Type t in fixtures)
{
var g = new TestGroup(t);
if (g.NumberOfTests > 0)
{
result.Add(g);
}
}
return result;
}
}
}

view raw

TestFinder.cs

hosted with ❤ by GitHub

You might wonder why I’m using the feeble, untyped ArrayList, giving the code that unmistakeable old-school C# 1.1 tinge? The reason is simple: the .NET micro framework doesn’t have generics. But we managed to get by in 2003, we’ll manage now.

What the code does is pretty much what we outlined above: fetch all the types in the assembly, identify the ones that inherit from Fixture, and proceed to create a TestGroup for each test class we find. A TestGroup is just a thin veneer on top of the test class:


namespace Mjunit
{
class TestGroup : IEnumerable
{
private readonly Type _testClass;
private readonly ArrayList _testMethods = new ArrayList();
public TestGroup(Type testClass)
{
_testClass = testClass;
var methods = _testClass.GetMethods();
for (int i = 0; i < methods.Length; i++)
{
var m = methods[i];
if (m.Name.Substring(0, 4) == "Test" &&
m.ReturnType == typeof(void))
{
_testMethods.Add(m);
}
}
}
public Type TestClass
{
get { return _testClass; }
}
public int NumberOfTests
{
get { return _testMethods.Count; }
}
public IEnumerator GetEnumerator()
{
return _testMethods.GetEnumerator();
}
}
}

view raw

TestGroup.cs

hosted with ❤ by GitHub

The TestFinder is used by the TestRunner, which does the bulk of the work in μnit, really. Here it is:


namespace Mjunit
{
public class TestRunner
{
private Thread _thread;
private Assembly _assembly;
private bool _done;
public event TestRunEventHandler SingleTestComplete;
public event TestRunEventHandler TestRunStart;
public event TestRunEventHandler TestRunComplete;
public TestRunner() {}
public TestRunner(ITestClient client)
{
RegisterClient(client);
}
public TestRunner(ArrayList clients)
{
foreach (ITestClient c in clients)
{
RegisterClient(c);
}
}
public bool Done
{
get { return _done; }
}
public void RegisterClient(ITestClient client)
{
TestRunStart += client.OnTestRunStart;
SingleTestComplete += client.OnSingleTestComplete;
TestRunComplete += client.OnTestRunComplete;
}
public void Run(Type type)
{
Run(Assembly.GetAssembly(type));
}
public void Run(Assembly assembly)
{
_assembly = assembly;
_thread = new Thread(DoRun);
_thread.Start();
}
public void Cancel()
{
_thread.Abort();
}
private void DoRun()
{
FireCompleteEvent(TestRunStart, null);
var gr = new TestGroupResult(_assembly.FullName);
try
{
var finder = new TestFinder();
var groups = finder.FindTests(_assembly);
foreach (TestGroup g in groups)
{
gr.AddResult(Run(g));
}
}
catch (Exception ex)
{
Debug.Print(ex.Message);
Debug.Print(ex.StackTrace);
}
FireCompleteEvent(TestRunComplete, gr);
_done = true;
}
private void FireCompleteEvent(TestRunEventHandler handler,
ITestResult result)
{
if (handler != null)
{
var args = new TestRunEventHandlerArgs
{ Result = result };
handler(this, args);
}
}
private TestClassResult Run(TestGroup group)
{
var result = new TestClassResult(group.TestClass);
foreach (MethodInfo m in group)
{
var r = RunTest(m);
FireCompleteEvent(SingleTestComplete, r);
result.AddResult(r);
}
return result;
}
private SingleTestResult RunTest(MethodInfo m)
{
try
{
DoRunTest(m);
return TestPassed(m);
}
catch (AssertFailedException ex)
{
return TestFailed(m, ex);
}
catch (Exception ex)
{
return TestFailedWithException(m, ex);
}
}
private void DoRunTest(MethodInfo method)
{
Fixture testObj = null;
try
{
testObj = GetInstance(method.DeclaringType);
testObj.Setup();
method.Invoke(testObj, new object[0]);
}
finally
{
if (testObj != null)
{
testObj.Teardown();
}
}
}
private Fixture GetInstance(Type testClass)
{
var ctor = testClass.GetConstructor(new Type[0]);
return (Fixture)ctor.Invoke(new object[0]);
}
private SingleTestResult TestFailedWithException(
MethodInfo m, Exception ex)
{
return new SingleTestResult(m, TestOutcome.Fail)
{ Exception = ex };
}
private SingleTestResult TestFailed(
MethodInfo m, AssertFailedException ex)
{
return new SingleTestResult(m, TestOutcome.Fail)
{ AssertFailedException = ex };
}
private SingleTestResult TestPassed(MethodInfo m)
{
return new SingleTestResult(m, TestOutcome.Pass);
}
}
}

view raw

TestRunner.cs

hosted with ❤ by GitHub

That’s a fair amount of code, and quite a few new concepts that haven’t been introduced yet. At a high level, it’s not that complex though. It works as follows. The user of a test runner will typically be interested in notification during the test run. Hence TestRunner exposes three events that fire when the test run starts, when it completes, and when each test has been run respectively. To receive notifications, the user can either hook up to those events directly or register one or more so-called test clients. We’ll look at some examples of test clients later on. To avoid blocking test clients and support cancellation of the test run, the tests run in their own thread.

As you can see from the RunTest method, each test results in a SingleTestResult, containing a TestOutcome of Pass or Fail. I don’t know how terribly useful it is, but μnit currently distinguishes between failures due to failed assertions and failures due to other exceptions. It made sense at the time.

The SingleTestResult instances are aggregated into TestClassResult instances, which in turn are aggregated into a single TestGroupResult instance representing the entire test run. All of these classes implement ITestResult, which looks like this:


namespace Mjunit
{
public interface ITestResult
{
string Name { get; }
TestOutcome Outcome { get; }
int NumberOfTests { get; }
int NumberOfTestsPassed { get; }
int NumberOfTestsFailed { get; }
}
}

view raw

ITestResult.cs

hosted with ❤ by GitHub

Now for a SingleTestResult, the NumberOfTests will obviously be 1, whereas for a TestClassResult it will match the number of SingleTestResult instances contained by the TestClassResult, and similarly for the TestGroupResult.

So that pretty much wraps it up for the core of μnit. Let’s take a look at how it looks at the client side, for someone who might want to use μnit to write some tests. The most convenient thing to do is probably to register a test client; that is, some object that implements ITestClient. ITestClient looks like this:


namespace Mjunit
{
public interface ITestClient
{
void OnTestRunStart(object sender,
TestRunEventHandlerArgs args);
void OnSingleTestComplete(object sender,
TestRunEventHandlerArgs args);
void OnTestRunComplete(object sender,
TestRunEventHandlerArgs args);
}
}

view raw

ITestClient.cs

hosted with ❤ by GitHub

The registered test client will then receive callbacks as appropriate when the tests are running.

In order to be useful, test clients typically need to translate notifications into something that a human can see and act upon if necessary. In the .NET gadgeteer world, it means you need to interact with some hardware.

For the Game of Life implementation (which can be browsed here if you’re interested) I implemented two test clients interacting with elements of the FEZ Spider kit: a DisplayTestClient that shows test results on a small display, and a LedTestClient that simply uses a multicolored LED light to give feedback to the user. Here’s the code for the latter:


namespace Mjunit.Clients.GHI
{
public class LedTestClient : ITestClient
{
private readonly MulticolorLed _led;
private bool _isBlinking;
private bool _hasFailed;
public LedTestClient(MulticolorLed led)
{
_led = led;
Init();
}
public void Init()
{
_led.TurnOff();
_isBlinking = false;
_hasFailed = false;
}
public void OnTestRunStart(object sender,
TestRunEventHandlerArgs args)
{
Init();
}
public void OnTestRunComplete(object sender,
TestRunEventHandlerArgs args)
{
OnAnyTestComplete(sender, args);
}
private void OnAnyTestComplete(object sender,
TestRunEventHandlerArgs args)
{
if (!_hasFailed)
{
if (args.Result.Outcome == TestOutcome.Fail)
{
_led.BlinkRepeatedly(Colors.Red);
_hasFailed = true;
}
else if (!_isBlinking)
{
_led.BlinkRepeatedly(Colors.Green);
_isBlinking = true;
}
}
}
public void OnSingleTestComplete(object sender,
TestRunEventHandlerArgs args)
{
OnAnyTestComplete(sender, args);
}
}
}

As you can see, it starts the test run by turning the LED light off. Then, as individual test results come in, the LED light starts blinking. On the first passing test, it will start blinking green. It will continue to do so until a failing test result comes in, at which point it will switch to blinking red instead. Once it has started blinking red, it will stay red, regardless of subsequent results. So the LedTestClient doesn’t actually tell you which test failed, it just tells you if some test failed. Useful for a sanity check, but not much else. That’s where the DisplayTestClient comes in, since it actually shows the names of the tests as they pass or fail.

How does it look in practice? Here’s a video of μnit tests for Game of Life running on the FEZ Spider. When the tests all succeed, we proceed to run Game of Life. Whee!


A property with a view

I’ve never been much of an early adopter, so now that Silverlight is dead and cold and has been for a while, it seems appropriate for me to blog about it. More specifically, I’d like to write about the chore that is INotifyPropertyChanged and how to make practically all the grunt work go away.

(Actually, I’m not sure that Silverlight is completely dead yet. It may be that Microsoft won’t be pumping much fresh blood into its veins, but that’s not quite the same thing as being dead. A technology isn’t dead as long as there’s a market for it and all that jazz. Assuming that there are some kinds of applications (such as rich line-of-business applications) that are easier to build with Silverlight than HTML5 given the toolsets that are available, I think we’ll find that Silverlight hangs around to haunt us for quite a while. But that’s sort of a side issue. It doesn’t really matter if Silverlight is dead or not, the issue of tackling INotifyPropertyChanged is interesting in and of itself.)

So INotifyPropertyChanged is the hoop you have to jump through to enable Silverlight views to update themselves as the view models they bind to change. It’s hard to envision not wanting the view to update when the view model changes. So typically you’ll want all the properties you bind to, to automatically cause the view to refresh itself. The problem is that this doesn’t happen out of the box. Instead, there’s this cumbersome and tiresome ritual you have to go through where you implement INotifyPropertyChanged, and have all the setters in your view model holler “hey, I’ve changed” by firing the PropertyChanged event. Brains need not apply to do this kind of work; it’s just mind-numbing, repetitive plumbing code. It would be much nicer if the framework would just be intelligent enough to provide the necessary notifications all by itself. Unfortunately, that’s not the case.

Solution: IL weaving

Silver.Needle is the name I use for some code I wrote to do fix that. The basic idea is to use IL manipulation to automatically turn the plain vanilla .NET properties on your view models into view-update-triggering properties with the boring but necessary plumbing just magically *there*. Look ma, no hands!

If you’re unfamiliar with IL manipulation, you might assume that it’s hard to do because it’s sort of low-level and therefore all voodooy and scary. But you’d be wrong. It might have been, without proper tools. Enter the star of this blog post: Mono.Cecil. Mono.Cecil is a library for IL manipulation written by Jb Evain. It is so powerful, it’s almost indecent: you get the feeling that IL manipulation shouldn’t be that easy. But it is, it really is. It’s a walk in the park. And the power trip you get is unbelievable.

Of course, since I rarely have original thoughts, Silver.Needle isn’t unique. You’ll find that Justin Angel described a very similar approach on his blog, more than two years ago. He uses Mono.Cecil too. So do the Kind of Magic and NotifyPropertyWeaver projects, which might be worth checking out if you actually wanted to use something like this in your project. But as always, it’s much more fun and educational to roll your own!

Disclaimer: it is fairly easy to shoot yourself in the foot when you’re meddling with IL directly. I accept no liability if you try to run any of the code included in this blog post and end up injecting IL into your cat, or causing your boss to fail spectacularly at runtime, or encountering any other unfortunate and grotesque mishap as a result of doing so. You have been warned.

Viewable properties

To do the IL manipulation, we need a way to distinguish between properties to tamper with and properties to leave alone. We’ll refer to the former as viewable properties because, you know, they’re able to work with a view?

Silver.Needle gives you two options for indicating that a property is viewable. The first option is to opt-in for individual properties on a class, by annotating each property with the Viewable attribute. The second option is to annotate the entire class as Viewable, and optionally opt-out for individual properties on that class using the Opaque attribute. In either case, the class is considered to be a “view model”, with one or more viewable properties that notify the view of any changes.


public class ViewableAttribute: Attribute {}

So the task solved by Silver.Needle is to perform the IL voodoo necessary to make sure that the output of the C# compiler of this pretty lean and neato code:


public class PersonViewModel
{
[Viewable]
public string Name { get; set; }
}

…is the same as the output generated directly when compiling this cumbersome and clumsy mess:


public class PersonViewModel : INotifyPropertyChanged
{
private string _name;
public event PropertyChangedEventHandler PropertyChanged;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
NotifyViewableProperty("Name");
}
}
private void NotifyViewableProperty(string propertyName)
{
var propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged.Invoke(this,
new PropertyChangedEventArgs(propertyName));
}
}
}

We start by using Mono.Cecil to look for types that contain such properties. It’s a simple matter of 1) loading the assembly with Mono.Cecil, 2) iterating over the types in the assembly and 3) iterating over the properties defined for each type. Of course, if we find one or more “view model” types with properties that should perform view notification, we must proceed to do the necessary IL manipulation and write the changed assembly to disk afterwards. The meat of the matter is in scanning an individual type and doing the IL manipulation. We’ll come to that shortly. The surrounding bureaucracy is handled by the NotificationTamperer class.


public class NotificationTamperer : ITamperer
{
private readonly string _assemblyOutputFileName;
public NotificationTamperer() : this("default_tampered.dll") {}
public NotificationTamperer(string assemblyOutputFileName)
{
_assemblyOutputFileName = assemblyOutputFileName;
}
private static AssemblyDefinition ReadSilverlightAssembly(
string assemblyPath)
{
var resolver = new DefaultAssemblyResolver();
resolver.AddSearchDirectory(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\Silverlight\v4.0");
var assembly = AssemblyDefinition.ReadAssembly(
assemblyPath,
new ReaderParameters { AssemblyResolver = resolver });
return assembly;
}
public bool TamperWith(string assemblyPath)
{
var assembly = ReadSilverlightAssembly(assemblyPath);
bool result = TamperWith(assembly);
if (result)
{
assembly.Write(_assemblyOutputFileName);
}
return result;
}
private bool TamperWith(AssemblyDefinition assembly)
{
bool result = false;
foreach (TypeDefinition type in assembly.MainModule.Types)
{
result = new TypeTamperer(type).MaybeTamperWith() || result;
}
return result;
}
}

There’s not much going on here worth commenting upon, it’s just the stuff outlined above. I guess the only thing worth noting is that we need to add a reference to the Silverlight assemblies, so that Mono.Cecil can resolve type dependencies as necessary later on. (For simplicity, I just hard-coded the path to the assemblies on my system. Did I mention it’s not quite ready for the enterprise yet?)

The interesting stuff happens in the TypeTamperer. You’ll notice that the TypeTamperer works on a single type, which is passed in to the constructor. This is the type that may or may not contain viewable properites, and may or may not end up being tampered with. The type is represented by a Mono.Cecil TypeDefinition, which has collections for interfaces, methods, fields, events and so forth.

The TypeTamperer does two things. First, it looks for any viewable properties. Second, if any viewable properties were found, it ensures that the type in question implements the INotifyPropertyChanged interface, and that the viewable properties participate in the notification mechanism by raising the PropertyChanged event as appropriate.

Let’s see how the identification happens:


public bool MaybeTamperWith()
{
return _typeDef.IsClass
&& HasPropertiesToTamperWith()
&& ReallyTamperWith();
}
private bool HasPropertiesToTamperWith()
{
FindPropertiesToTamperWith();
return _map.Count > 0;
}
private void FindPropertiesToTamperWith()
{
var isViewableType = IsViewable(_typeDef);
foreach (var prop in _typeDef.Properties
.Where(p => IsViewable(p) || (isViewableType && !IsOpaque(p))))
{
HandlePropertyToNotify(prop);
}
}
private static bool IsViewable(ICustomAttributeProvider item)
{
return HasAttribute(item, ViewableAttributeName);
}
private static bool IsOpaque(ICustomAttributeProvider item)
{
return HasAttribute(item, OpaqueAttributeName);
}
private static bool HasAttribute(ICustomAttributeProvider item,
string attributeName)
{
return item.CustomAttributes.Any(
a => a.AttributeType.Name == attributeName);
}

As you can see, the code is very straight-forward. We just make sure that the type we’re inspecting is a class (as opposed to an interface), and look for viewable properties. If we find a viewable property, the HandlePropertyToNotify method is called. We’ll look at that method in detail later on. For now though, we’ll just note that the property will end up in an IDictionary named _map, so that the ReallyTamperWith method is called, tr
iggering the IL manipulation.

For each of the view model types, we need to make sure that the type implements INotifyPropertyChanged. From an IL manipulation point of view, this entails three things:

  • Adding interface declaration as needed.
  • Adding event declaration as needed.
  • Adding event trigger method as needed.

Silver.Needle tries to play nicely with a complete or partial hand-written implementation of INotifyPropertyChanged. It’s not too hard to do, the main complicating matter being that we need to consider inheritance. The type might inherit from another type (say, ViewModelBase) that implements the interface. Obviously, we shouldn’t do anything in that case. We should only inject implementation code for types that do not already implement the interface, either directly or in a base type. To do this, we need to walk the inheritance chain up to System.Object before we can conclude that the interface is indeed missing and proceed to inject code for the implementation.

https://gist.github.com/2340074

This is still pretty self-explanatory. The most interesting method is TypeImplementsInterface, which calls itself recursively to climb up the inheritance ladder until it either finds a type that implements INotifyPropertyChanged or a type whose base type is null (that would be System.Object).

Implementing the interface

Injecting code to implement the interface consists of two parts, just as if you were implementing the interface by writing source code by hand: 1) injecting the declaration of the interface, and 2) injecting the code to fulfil the contract defined by the interface, that is, the declaration of the PropertyChanged event handler.


private void InjectInterfaceDeclaration()
{
_typeDef.Interfaces.Add(_types.INotifyPropertyChanged);
}

The code to add the interface declaration is utterly trivial: you just add the appropriate type to the TypeDefinition‘s Interfaces collection. You get a first indication of the power of Mono.Cecil right there. You do need to obtain the proper TypeReference (another Mono.Cecil type) though. I’ve created a helper class to make this as simple as I could as well. The code looks like this:


public class TypeResolver
{
private readonly TypeDefinition _typeDef;
private readonly IDictionary<Type, TypeReference> _typeRefs =
new Dictionary<Type, TypeReference>();
private readonly TypeSystem _ts;
private readonly ModuleDefinition _systemModule;
private readonly ModuleDefinition _mscorlibModule;
public TypeResolver(TypeDefinition typeDef)
{
_typeDef = typeDef;
_ts = typeDef.Module.TypeSystem;
Func<string, ModuleDefinition> getModule =
m => typeDef.Module.AssemblyResolver.Resolve(m).MainModule;
_systemModule = getModule("system");
_mscorlibModule = getModule("mscorlib");
}
public TypeReference Object
{
get { return _ts.Object; }
}
public TypeReference String
{
get { return _ts.String; }
}
public TypeReference Void
{
get { return _ts.Void; }
}
public TypeReference INotifyPropertyChanged
{
get { return LookupSystem(typeof(INotifyPropertyChanged)); }
}
public TypeReference PropertyChangedEventHandler
{
get { return LookupSystem(typeof(PropertyChangedEventHandler)); }
}
public TypeReference PropertyChangedEventArgs
{
get { return LookupSystem(typeof(PropertyChangedEventArgs)); }
}
public TypeReference Delegate
{
get { return LookupCore(typeof(Delegate)); }
}
public TypeReference Interlocked
{
get { return LookupCore(typeof(Interlocked)); }
}
private TypeReference LookupCore(Type t)
{
return Lookup(t, _mscorlibModule);
}
private TypeReference LookupSystem(Type t)
{
return Lookup(t, _systemModule);
}
private TypeReference Lookup(Type t, ModuleDefinition moduleDef)
{
if (!_typeRefs.ContainsKey(t))
{
var typeRef = moduleDef.Types.FirstOrDefault(
td => td.FullName == t.FullName);
if (typeRef == null)
{
return null;
}
var importedTypeRef = _typeDef.Module.Import(typeRef);
_typeRefs[t] = importedTypeRef;
}
return _typeRefs[t];
}
}

view raw

TypeResolver.cs

hosted with ❤ by GitHub

Mono.Cecil comes with a built-in TypeSystem type that contains TypeReference objects for the most common types, such as Object and String. For other types, though, you need to use Mono.Cecil’s assembly resolver to get the appropriate TypeReference objects. For convenience, TypeResolver defines properties with TypeReference objects for all the types used by TypeTamperer.

With the interface declaration in place, we need to provide an implementation (otherwise, we get nasty runtime exceptions).

Herein lies a potential hickup which might lead to problems in case the implementer is exceedingly stupid, though. Since Silver.Needle is a proof-of-concept rather than a super-robust enterprise tool, I don’t worry too much about such edge cases. Nevertheless, I try to play nice where I can (and if it’s easy to do), so here goes: The issue is that the view model type might already have a member of some sort named PropertyChanged, even though the type itself doesn’t inherit from INotifyPropertyChanged. If it actually is an event handler such as defined by INotifyPropertyChanged, everything is fine (I just need to make sure that I don’t add it.) The real issue if there is some other member named PropertyChanged, say, a property or a method. I can’t imagine why you’d want to do such a thing, but of course there’s no stopping the inventiveness of the sufficiently stupid programmer. To avoid producing a weird assembly that will fail dramatically during runtime, Silver.Needle will discover the presence of a malplaced, ill-typed PropertyChanged and give up, leaving the type untampered (and hence not implementing INotifyPropertyChanged).

Adding the event handler is a bit more work than you might expect. If you inspect the IL, it becomes abundantly clear that C# provides a good spoonful of syntactic sugar for events. At the IL level, you’ll find that the simple event declaration expands to this:

  • A field for the event handler.
  • An event, which hooks up the field with add and remove methods.
  • Implementation for the add and remove methods.

It’s quite a bit of IL:


field private class [System]System.ComponentModel.PropertyChangedEventHandler PropertyChanged
event [System]System.ComponentModel.PropertyChangedEventHandler PropertyChanged
{
.addon instance void Silver.Needle.Tests.Data.Dependencies.Complex.PersonViewModel::add_PropertyChanged(class [System]System.ComponentModel.PropertyChangedEventHandler)
.removeon instance void Silver.Needle.Tests.Data.Dependencies.Complex.PersonViewModel::remove_PropertyChanged(class [System]System.ComponentModel.PropertyChangedEventHandler)
}
.method public final hidebysig specialname newslot virtual
instance void add_PropertyChanged (
class [System]System.ComponentModel.PropertyChangedEventHandler 'value'
) cil managed
{
.maxstack 3
.locals init (
[0] class [System]System.ComponentModel.PropertyChangedEventHandler,
[1] class [System]System.ComponentModel.PropertyChangedEventHandler,
[2] class [System]System.ComponentModel.PropertyChangedEventHandler
)
IL_0000: ldarg.0
IL_0001: ldfld class [System]System.ComponentModel.PropertyChangedEventHandler Silver.Needle.Tests.Data.Dependencies.Complex.PersonViewModel::PropertyChanged
IL_0006: stloc.0
// loop start (head: IL_0007)
IL_0007: ldloc.0
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldarg.1
IL_000b: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate)
IL_0010: castclass [System]System.ComponentModel.PropertyChangedEventHandler
IL_0015: stloc.2
IL_0016: ldarg.0
IL_0017: ldflda class [System]System.ComponentModel.PropertyChangedEventHandler Silver.Needle.Tests.Data.Dependencies.Complex.PersonViewModel::PropertyChanged
IL_001c: ldloc.2
IL_001d: ldloc.1
IL_001e: call !!0 [mscorlib]System.Threading.Interlocked::CompareExchange<class [System]System.ComponentModel.PropertyChangedEventHandler>(!!0&, !!0, !!0)
IL_0023: stloc.0
IL_0024: ldloc.0
IL_0025: ldloc.1
IL_0026: bne.un.s IL_0007
// end loop
IL_0028: ret
} // end of method PersonViewModel::add_PropertyChanged
.method public final hidebysig specialname newslot virtual
instance void remove_PropertyChanged (
class [System]System.ComponentModel.PropertyChangedEventHandler 'value'
) cil managed
{
.maxstack 3
.locals init (
[0] class [System]System.ComponentModel.PropertyChangedEventHandler,
[1] class [System]System.ComponentModel.PropertyChangedEventHandler,
[2] class [System]System.ComponentModel.PropertyChangedEventHandler
)
IL_0000: ldarg.0
IL_0001: ldfld class [System]System.ComponentModel.PropertyChangedEventHandler Silver.Needle.Tests.Data.Dependencies.Complex.PersonViewModel::PropertyChanged
IL_0006: stloc.0
// loop start (head: IL_0007)
IL_0007: ldloc.0
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldarg.1
IL_000b: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate)
IL_0010: castclass [System]System.ComponentModel.PropertyChangedEventHandler
IL_0015: stloc.2
IL_0016: ldarg.0
IL_0017: ldflda class [System]System.ComponentModel.PropertyChangedEventHandler Silver.Needle.Tests.Data.Dependencies.Complex.PersonViewModel::PropertyChanged
IL_001c: ldloc.2
IL_001d: ldloc.1
IL_001e: call !!0 [mscorlib]System.Threading.Interlocked::CompareExchange<class [System]System.ComponentModel.PropertyChangedEventHandler>(!!0&, !!0, !!0)
IL_0023: stloc.0
IL_0024: ldloc.0
IL_0025: ldloc.1
IL_0026: bne.un.s IL_0007
// end loop
IL_0028: ret
} // end of method PersonViewModel::remove_PropertyChanged

view raw

gistfile1.txt

hosted with ❤ by GitHub

The bad news is that it’s up to us to inject all that goo into our type. The good news is that Mono.Cecil makes it fairly easy to do. We’ll get right to it:


private void InjectEventHandler()
{
InjectPropertyChangedField();
InjectEventDeclaration();
}
private void InjectPropertyChangedField()
{
//.field private class [System]System.ComponentModel.PropertyChangedEventHandler PropertyChanged
var field = new FieldDefinition(PropertyChangedFieldName,
FieldAttributes.Private,
_types.PropertyChangedEventHandler);
_typeDef.Fields.Add(field);
}
private void InjectEventDeclaration()
{
// .event [System]System.ComponentModel.PropertyChangedEventHandler PropertyChanged
// {
// .addon instance void Voodoo.ViewModel.GoalViewModel::add_PropertyChanged(class [System]System.ComponentModel.PropertyChangedEventHandler)
// .removeon instance void Voodoo.ViewModel.GoalViewModel::remove_PropertyChanged(class [System]System.ComponentModel.PropertyChangedEventHandler)
// }
var eventDef = new EventDefinition(PropertyChangedFieldName,
EventAttributes.None,
_types.PropertyChangedEventHandler)
{
AddMethod = CreateAddPropertyChangedMethod(),
RemoveMethod = CreateRemovePropertyChangedMethod()
};
_typeDef.Methods.Add(eventDef.AddMethod);
_typeDef.Methods.Add(eventDef.RemoveMethod);
_typeDef.Events.Add(eventDef);
}

Here we add the field for the event handler, and we create an event which hooks up to two methods for adding and removing event handlers, respectively. We’re still not done, though – in fact, the bulk of the nitty gritty work remains.

That bulk is the implementation of the add and remove methods. If you examine the IL, you’ll see that the implementations are virtually identical, except for a single method call in the middle somewhere (add calls a method called Combine, remove calls Remove). We can abstract that out, like so:


private MethodDefinition CreateAddPropertyChangedMethod()
{
return CreatePropertyChangedEventHookupMethod(
"add_PropertyChanged",
"Combine");
}
private MethodDefinition CreateRemovePropertyChangedMethod()
{
return CreatePropertyChangedEventHookupMethod(
"remove_PropertyChanged",
"Remove");
}
private MethodDefinition CreatePropertyChangedEventHookupMethod(
string eventHookupMethodName,
string delegateMethodName)
{
// .method public final hidebysig specialname newslot virtual
// instance void add_PropertyChanged (
// class [System]System.ComponentModel.PropertyChangedEventHandler 'value'
// ) cil managed
var methodDef = new MethodDefinition(eventHookupMethodName,
MethodAttributes.Public |
MethodAttributes.Final |
MethodAttributes.HideBySig |
MethodAttributes.SpecialName |
MethodAttributes.NewSlot |
MethodAttributes.Virtual,
_types.Void);
var paramDef = new ParameterDefinition("value",
ParameterAttributes.None,
_types.PropertyChangedEventHandler);
methodDef.Parameters.Add(paramDef);
methodDef.Body.MaxStackSize = 3;
for (int i = 0; i < 3; i++)
{
var v = new VariableDefinition(_types.PropertyChangedEventHandler);
methodDef.Body.Variables.Add(v);
}
methodDef.Body.InitLocals = true;
var il = methodDef.Body.GetILProcessor();
Action<OpCode> op = x => il.Append(il.Create(x));
// IL_0000: ldarg.0
op(OpCodes.Ldarg_0);
// IL_0001: ldfld class [System]System.ComponentModel.PropertyChangedEventHandler Voodoo.ViewModel.GoalViewModel::PropertyChanged
var eventHandlerFieldDef = _typeDef.Fields
.FirstOrDefault(f => f.Name == PropertyChangedFieldName);
il.Append(il.Create(OpCodes.Ldfld, eventHandlerFieldDef));
// IL_0006: stloc.0
op(OpCodes.Stloc_0);
// // loop start (head: IL_0007)
// IL_0007: ldloc.0
var loopTargetInsn = il.Create(OpCodes.Ldloc_0);
il.Append(loopTargetInsn);
// IL_0008: stloc.1
op(OpCodes.Stloc_1);
// IL_0009: ldloc.1
op(OpCodes.Ldloc_1);
// IL_000a: ldarg.1
op(OpCodes.Ldarg_1);
// IL_000b: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate)
var combineMethodReference = new MethodReference(
delegateMethodName,
_types.Delegate,
_types.Delegate);
var delegateParamDef = new ParameterDefinition(_types.Delegate);
combineMethodReference.Parameters.Add(delegateParamDef);
combineMethodReference.Parameters.Add(delegateParamDef);
il.Append(il.Create(OpCodes.Call, combineMethodReference));
// IL_0010: castclass [System]System.ComponentModel.PropertyChangedEventHandler
il.Append(il.Create(OpCodes.Castclass,
_types.PropertyChangedEventHandler));
// IL_0015: stloc.2
op(OpCodes.Stloc_2);
// IL_0016: ldarg.0
op(OpCodes.Ldarg_0);
// IL_0017: ldflda class [System]System.ComponentModel.PropertyChangedEventHandler Voodoo.ViewModel.GoalViewModel::PropertyChanged
il.Append(il.Create(OpCodes.Ldflda, eventHandlerFieldDef));
// IL_001c: ldloc.2
op(OpCodes.Ldloc_2);
// IL_001d: ldloc.1
op(OpCodes.Ldloc_1);
// IL_001e: call !!0 [mscorlib]System.Threading.Interlocked::CompareExchange<class [System]System.ComponentModel.PropertyChangedEventHandler>(!!0&, !!0, !!0)
// var declaringTypeRef = _typeDef.Module.Import(typeof(Interlocked));
var declaringTypeRef = _types.Interlocked;
var elementMethodRef = new MethodReference(
"CompareExchange",
_types.Void,
declaringTypeRef);
var genParam = new GenericParameter("!!0", elementMethodRef);
elementMethodRef.ReturnType = genParam;
elementMethodRef.GenericParameters.Add(genParam);
var firstParamDef = new ParameterDefinition(
new ByReferenceType(genParam));
var otherParamDef = new ParameterDefinition(genParam);
elementMethodRef.Parameters.Add(firstParamDef);
elementMethodRef.Parameters.Add(otherParamDef);
elementMethodRef.Parameters.Add(otherParamDef);
var genInstanceMethod = new GenericInstanceMethod(elementMethodRef);
genInstanceMethod.GenericArguments.Add(
_types.PropertyChangedEventHandler);
il.Append(il.Create(OpCodes.Call, genInstanceMethod));
// IL_0023: stloc.0
op(OpCodes.Stloc_0);
// IL_0024: ldloc.0
op(OpCodes.Ldloc_0);
// IL_0025: ldloc.1
op(OpCodes.Ldloc_1);
// IL_0026: bne.un.s IL_0007
il.Append(il.Create(OpCodes.Bne_Un_S, loopTargetInsn));
// // end loop
// IL_0028: ret
op(OpCodes.Ret);
return methodDef;
}

It looks a little bit icky at first glance, but it’s actually quite straightforward. You just need to accurately and painstakingly reconstruct the IL statement by statement. As you can see, I’ve left the original IL in the source code as comments, to make it clear what we’re trying to reproduce. It takes patience more than brains.

The final piece of the implementation puzzle is to implement a method for firing the event. Again, Silver.Needle tries to play along with any hand-written code you have. So if you have implemented a method so-and-so to do view notification, it’s quite likely that Silver.Needle will discover it and use it. Basically it will scan all methods in the inheritance chain for your view model, and assume that a method which accepts a single string parameter, returns void and calls PropertyChangedEventHandler.Invoke somewhere in the method body is indeed a notification method.


private static MethodDefinition FindNotificationMethod(
TypeDefinition typeDef,
bool includePrivateMethods = true)
{
foreach (var m in typeDef.Methods.Where(m => includePrivateMethods
|| m.Attributes.HasFlag(MethodAttributes.Public)))
{
if (IsProbableNotificationMethod(m))
{
return m;
}
}
var baseTypeRef = typeDef.BaseType;
if (baseTypeRef.FullName != "System.Object")
{
return FindNotificationMethod(baseTypeRef.Resolve(), false);
}
return null;
}
private static bool IsProbableNotificationMethod(
MethodDefinition methodDef)
{
return methodDef.HasBody
&& IsProbableNotificationMethodWithBody(methodDef);
}
private static bool IsProbableNotificationMethodWithBody(
MethodDefinition methodDef)
{
foreach (var insn in methodDef.Body.Instructions)
{
if (insn.OpCode == OpCodes.Callvirt)
{
var callee = (MethodReference) insn.Operand;
if (callee.Name == "Invoke"
&& callee.DeclaringType.Name == "PropertyChangedEventHandler")
{
return true;
}
}
}
return false;
}

Should Silver.Needle fail to identify an existing notification method, though, there is no problem. After all, it’s perfectly OK to have more than one method that can be used to fire the event. Hence if no notification method is found, one is injected. No sleep lost.

In case no existing notification method was found, we need to provide one. We’re getting used to this kind of code by now:


private MethodDefinition CreateNotificationMethodDefinition()
{
const string MethodName = "NotifyViewableProperty";
var methodDef = new MethodDefinition(MethodName,
MethodAttributes.Private |
MethodAttributes.HideBySig,
this._types.Void);
var paramDef = new ParameterDefinition("propertyName",
ParameterAttributes.None,
_types.String);
methodDef.Parameters.Add(paramDef);
methodDef.Body.MaxStackSize = 4;
var v = new VariableDefinition(_types.PropertyChangedEventHandler);
methodDef.Body.Variables.Add(v);
methodDef.Body.InitLocals = true;
var il = methodDef.Body.GetILProcessor();
Action<OpCode> op = x => il.Append(il.Create(x));
// IL_0000: ldarg.0
op(OpCodes.Ldarg_0);
// IL_0001: ldfld class [System]System.ComponentModel.PropertyChangedEventHandler Voodoo.ViewModel.GoalViewModel::PropertyChanged
var eventHandlerFieldDef = FindEventFieldDeclaration(_typeDef);
il.Append(il.Create(OpCodes.Ldfld, eventHandlerFieldDef));
// IL_0006: stloc.0
op(OpCodes.Stloc_0);
// IL_0007: ldloc.0
op(OpCodes.Ldloc_0);
//IL_0008: brfalse.s IL_0017
var jumpTargetInsn = il.Create(OpCodes.Ret); // See below, IL_0017
il.Append(il.Create(OpCodes.Brfalse_S, jumpTargetInsn));
// IL_000a: ldloc.0
op(OpCodes.Ldloc_0);
// IL_000b: ldarg.0
op(OpCodes.Ldarg_0);
// IL_000c: ldarg.1
op(OpCodes.Ldarg_1);
// IL_000d: newobj instance void [System]System.ComponentModel.PropertyChangedEventArgs::.ctor(string)
var eventArgsTypeRef = _types.PropertyChangedEventArgs;
var ctorRef = new MethodReference(".ctor",
_types.Void,
eventArgsTypeRef);
var ctorParamDef = new ParameterDefinition("propertyName",
ParameterAttributes.None,
_types.String);
ctorRef.Parameters.Add(ctorParamDef);
ctorRef.HasThis = true;
il.Append(il.Create(OpCodes.Newobj, ctorRef));
// IL_0012: callvirt instance void [System]System.ComponentModel.PropertyChangedEventHandler::Invoke(object, class [System]System.ComponentModel.PropertyChangedEventArgs)
var invokeMethodRef = new MethodReference("Invoke",
_types.Void,
_types.PropertyChangedEventHandler);
invokeMethodRef.Parameters.Add(
new ParameterDefinition(_types.Object));
invokeMethodRef.Parameters.Add(
new ParameterDefinition(eventArgsTypeRef));
invokeMethodRef.HasThis = true;
il.Append(il.Create(OpCodes.Callvirt, invokeMethodRef));
// IL_0017: ret
il.Append(jumpTargetInsn);
return methodDef;
}

This produces IL for a NotifyViewableProperty method just like the one we wrote in C# in the “hand-implemented” PersonViewModel above.

Injecting notification

With the interface implementation and notification method in place, we finally come to the fun part – injecting the property notification itself!

Unless you’re the kind of person who use ILSpy or ILDasm regularly, you might wonder if and how it will work with auto-properties – properties where you don’t actually provide any body for the getters and setters. Well, it doesn’t matter. Auto-properties are a C# feature, they don’t exist in IL. So you’ll find there’s a backing field there (albeit with a weird name) that the C# compiler conjured up for you. It’s just syntactic sugar to reduce typing.

What about get-only properties? That is, properties that have getters but no setters? Well, first of all, can they change? Even if they’re get-only? Sure they can. Say you have a property which derives its value from another property. For instance, you might have an Age property which depends upon a BirthDate property, like so:


private DateTime _birthDate;
public DateTime BirthDate
{
get { return _birthDate; }
set { _birthDate = value; }
}
[Viewable]
public int Age
{
get { return DateTime.Now.Years BirthDate.Years; }
}

view raw

BirthDate.cs

hosted with ❤ by GitHub

In the (admittedly unlikely) scenario that the BirthDate changes, the Age will change too. And if Age is a property on a view model that a view will bind to, you’ll want any display of Age to update itself automatically whenever BirthDate changes. How can we do that? Well, if we implemented this by hand, we could add a notification call in BirthDate‘s setter to say that Age changed.


private DateTime _birthDate;
public DateTime BirthDate
{
get { return _birthDate; }
set
{
_birthDate = value;
Notify("Age");
}
}

It feels a little iffy, since it sort of goes the wrong way – the observed knowing about the observer rather than the other way around. But that’s how you’d do it.

Silver.Needle does the same thing for you automatically. That is, for get-only properties, Silver.Needle will inspect the getter to find any calls to getters on other properties on the same object instance. If those properties turn out to have setters, notifications to update the get-only property will be injected there. If those properties are get-only too, the process repeats itself recursively. So you could have chains of properties that depend on properties that depend on properties etc.

To do this correctly, the injection process has two steps. First, we identify which properties depend on which, second, we do the actual IL manipulation to insert the notification calls.

So, first we identify dependencies between properties. In the normal case of a property with a setter of its own, the property will simply depend on itself. (Of course, there might be other properties that depend on it as well.) So for each property with a setter, we build a list of dependent properties – that is, properties that we need to inject notification calls for. Note that while we only do notification for properties tagged as Viewable, we might inject notification calls into the setters of any property on the view model, Viewable or not. (In the example above, you’ll notice that BirthDate is not, in fact, tagged Viewable. When the setter is called, it will announce that Age changed, but not itself!)

The code to register the dependencies between properties is as follows:


private void HandlePropertyToNotify(PropertyDefinition prop)
{
foreach (var affector in FindAffectingProperties(prop, new List<string>()))
{
AddDependency(affector, prop);
}
}
private void AddDependency(PropertyDefinition key,
PropertyDefinition value)
{
if (!_map.ContainsKey(key))
{
_map[key] = new List<PropertyDefinition>();
}
_map[key].Add(value);
}
private List<PropertyDefinition> FindAffectingProperties(
PropertyDefinition prop,
IList<string> seen)
{
if (seen.Any(n => n == prop.Name))
{
return new List<PropertyDefinition>();
}
seen.Add(prop.Name);
if (prop.SetMethod != null)
{
return new List<PropertyDefinition> {prop};
}
if (prop.GetMethod != null)
{
return FindAffectingPropertiesFromGetter(prop.GetMethod, seen);
}
return new List<PropertyDefinition>();
}
private List<PropertyDefinition> FindAffectingPropertiesFromGetter(
MethodDefinition getter,
IList<string> seen)
{
var result = new List<PropertyDefinition>();
foreach (var insn in getter.Body.Instructions)
{
if (insn.OpCode == OpCodes.Call)
{
var methodRef = (MethodReference)insn.Operand;
if (methodRef.Name.StartsWith(PropertyGetterPrefix))
{
// Found an affecting getter inside the current getter!
// Get list of dependencies from this getter.
string affectingPropName = methodRef.Name
.Substring(PropertyGetterPrefix.Length);
var affectingProp = _typeDef.Properties
.FirstOrDefault(p => p.Name == affectingPropName);
if (affectingProp != null)
{
result.AddRange(FindAffectingProperties(affectingProp, seen));
}
}
}
}
return result;
}

So you can see that it’s a recursive process to walk the dependency graph for a get-only property. You’ll notice that there is some code there to recognize that we’ve seen a certain property before, to avoid infinite loops when walking the graph. Of course, it might happen that we don’t find any setters to inject notification into. For instance, it may turn out that a viewable property actually depends on constant values only. In that case, Silver.Needle will simply give up, since there is no place to inject the notification.

When we have the complete list of properties and dependant properties, we can do the actual IL manipulation. That is, for each affecting property, we can inject notifications for all affected properties.

There are two possible strategies for the injection itself: simple and sophisticated. The simple strategy employed by Silver.Needle is to do notification regardless of whether any state change occurs as a result of calling the property setter. For instance, you might have some guard clause deciding whether or not to actually update the field backing the property – a conditional setter if you will. Perhaps you want to write to the backing field only when the value has actually changed. Silver.Needle doesn’t care about that. If the setter is called the view is notified. I believe this makes sense, since the setter is the abstraction boundary for the operation you’re performing, not whatever backing field you may or may not write to. Also, I reckon that it doesn’t *hurt* much to do a couple of superfluous view refreshes.

It would be entirely possible to do something a little bit more sophisticated, though – I just don’t think it’s worth the effort (plus it violates encapsulation, doesn’t it?). If we wanted to, we could use a simple program analysis to distinguish between paths that may or may not result in the view model altering state. Technically, we could take the presence of a stfld IL instruction (which stores a value to a field) as evidence for state change. We could even throw in a little bit of data flow analysis to see if the value passed to the setter was actually on the stack when to the stfld was executed. In that case, we’d interpret “property change” to mean “some field acquires the value passed to the setter”, which may or may not seem right to you. So it could be done, within reason.

Notice, though, the appeal to reason. It’s easy to come up with a setter which results in an observable state change without ever calling stfld. For instance, you could push the value onto a stack instead of storing it in a field, and have the getter return the top element of the stack. Sort of contrived, but it could be done. Or you could pass the value to some method, which may or may not store it somewhere. So you see, it’s hard to do properly in the general case. Hence Silver.Needle keeps things simple, and says that the view should be notified of property change whenever the setter is called. That way, we might do a couple of superfluous notifications, but at least we don’t miss any.

Now we just need to figure out where to inject the notification calls. Obviously it needs to be the last thing you do in the setter, to ensure that any state change has actually occurred before we do the notification (otherwise we’d refresh the view to show a stale property value!). That’s easy if you have a single return point from your setter, somewhat harder if there are are several.

You could of course inject notification calls before each return point. That would give the correct semantics but is a bit brutish and not particularly elegant. Instead, Silver.Needle will essentially perform an extract method refactoring if there is more than one return point. The original body of the property setter is moved to a new method with a name derived from the property name. The property setter is then given a new body, consisting of a call to the new method, followed by necessary notification calls. Nice and tidy.

A third alternative would be to wrap the body of the setter in a try block and perform notification in a finally block. Yes, that would mean that notifications would be given even if an exception is thrown during the execution of the setter. Would that be a problem? No. Why not? Because you shouldn’t throw exceptions in your setters. Again, if you have complex logic in the setters of your view models, I have a meme for you: “View models, you’re doing it wrong”.

So, implementation-wise, we need to support two scenarios: with or without refactoring. In either case, we end up with a setter that has a single return point preceeded by notification calls. As usual, it’s pretty straight-forward to do the necessary alternations to the body of the setter using Mono.Cecil. Here’s
the code:


private void InjectNotification(MethodDefinition methodDef,
IEnumerable<string> propNames)
{
if (_notifyMethodDef == null || methodDef == null)
{
return;
}
if (HasMultipleReturnPoints(methodDef))
{
RefactorSetterAndInjectNotification(methodDef, propNames);
}
else
{
InjectNotificationDirectly(methodDef, propNames);
}
}
private bool HasMultipleReturnPoints(MethodDefinition methodDef)
{
return methodDef.Body.Instructions.Count(
insn => insn.OpCode == OpCodes.Ret) > 1;
}
private void RefactorSetterAndInjectNotification(
MethodDefinition oldMethodDef,
IEnumerable<string> propNames)
{
var methodName = "Refactored" + oldMethodDef.Name
.Substring(PropertySetterPrefix.Length) + "Setter";
var methodDef = new MethodDefinition(methodName,
oldMethodDef.Attributes,
oldMethodDef.ReturnType);
foreach (var oldParamDef in oldMethodDef.Parameters)
{
var paramDef = new ParameterDefinition(
oldParamDef.Name,
oldParamDef.Attributes,
oldParamDef.ParameterType);
methodDef.Parameters.Add(paramDef);
}
methodDef.Body = oldMethodDef.Body;
_typeDef.Methods.Add(methodDef);
oldMethodDef.Body = new MethodBody(oldMethodDef);
var il = oldMethodDef.Body.GetILProcessor();
Action<OpCode> op = x => il.Append(il.Create(x));
op(OpCodes.Ldarg_0);
op(OpCodes.Ldarg_1);
il.Append(il.Create(OpCodes.Call, methodDef));
op(OpCodes.Ret);
InjectNotificationDirectly(oldMethodDef, propNames);
}
private void InjectNotificationDirectly(MethodDefinition methodDef,
IEnumerable<string> propNames)
{
var il = methodDef.Body.GetILProcessor();
var returnInsn = il.Body.Instructions.Last();
foreach (var s in propNames)
{
var loadThis = il.Create(OpCodes.Ldarg_0);
var loadString = il.Create(OpCodes.Ldstr, s);
var callMethod = il.Create(OpCodes.Call, _notifyMethodDef);
il.InsertBefore(returnInsn, loadThis);
il.InsertBefore(returnInsn, loadString);
il.InsertBefore(returnInsn, callMethod);
}
}

The code isn’t too complicated. The MethodDefinition passed to InjectionNotification is the setter method for the property, and propNames contains the names of properties to notify change for when the setter is called. In case of multiple return points from the setter, we perform a bit of crude surgery to separate the method body from the method declaration. We provide a new method definition for the body, with a name derived from the name of the property. While in Dr Frankenstein mode, we proceed to assemble a new method body for the setter. That body consists of three instructions: push the this reference onto the stack, push the value passed to the setter onto the stack, and invoke the new method we just created out of the original method body.

Now we know that the setter has a single return point, and we can inject the notification calls. We just need to loop over the properties to notify, and inject a trio of 1) push this, 2) push property name and 3) invoke notification method for each.

And that’s it, really. We’re done. Mission accomplished, view model complete.

Of course, to make things practical, you’re gonna need a build task and a Visual Studio template as well. I’ll get to that some day.


Patching polymorphic pain at runtime

In the last post, we saw that data binding in ASP.NET doesn’t support polymorphism. We also saw that we could mitigate the problem by using simple wrapper types. Writing such wrappers by hand won’t kill you, but it is fairly brain-dead. I mentioned that an alternative would be to generate the wrappers at runtime, using reflection. That actually sounds like a bit of fun, so let’s see how it can be done. If nothing else, it’s a nice introductory lesson in using Reflection.Emit.

Comeback of the canines

As an example, let’s revisit our two four-legged friends and one enemy from the previous post: the Dog, the Chihuahua and the Wolf. They all implement ICanine.

The canines have gained a skill since last time, though – they can now indicate whether or not they’ll enjoy a particular kind of food. The code looks like this:


public enum Food { Biscuit, Meatballs, You }
public interface ICanine
{
string Bark { get; }
bool Eats(Food f);
}
public class Wolf : ICanine
{
public virtual string Bark { get { return "Aooo!"; } }
public bool Eats(Food f) { return f != Food.Biscuit; }
}
public class Dog : ICanine
{
public virtual string Bark { get { return "Woof!"; } }
public virtual bool Eats(Food f) { return f != Food.You; }
}
public class Chihuahua : Dog
{
public override string Bark { get { return "Arff!"; } }
public override bool Eats(Food f) { return f == Food.Biscuit; }
}

view raw

Canines.cs

hosted with ❤ by GitHub

What we want to do in our web application is display a grid that shows the canine’s eating preferences as well as its bark. This calls for a combination of auto-generated and custom columns: an automatic one for the Bark property, and a custom one for each kind of food.

The DataGrid is declared in the .aspx page:


<asp:DataGrid
ID="_grid"
runat="server"
AutogenerateColumns="true"
FontSize="X-Large"
FontNames="Consolas"
HeaderStyleBackColor="LightBlue" />

view raw

DataGrid.cs

hosted with ❤ by GitHub

This gives us a column for the Bark out of the box.

In the code-behind, we add a column for each kind of food. We also get a list of canines, which we wrap in something called an BoxEnumerable<ICanine> before binding to it.


protected void Page_Load(object sender, EventArgs e)
{
GetGridColumns().ForEach(f => _grid.Columns.Add(f));
_grid.DataSource = new BoxEnumerable<ICanine>(GetCanines());
_grid.DataBind();
}
private static List<DataGridColumn> GetGridColumns()
{
return new List<DataGridColumn>
{
new TemplateColumn
{
HeaderText = "Biscuits?",
ItemTemplate = new FoodColumnTemplate(Food.Biscuit)
},
new TemplateColumn
{
HeaderText = "Meatballs?",
ItemTemplate = new FoodColumnTemplate(Food.Meatballs)
},
new TemplateColumn
{
HeaderText = "You?",
ItemTemplate = new FoodColumnTemplate(Food.You)
}
};
}
private static IEnumerable<ICanine> GetCanines()
{
return new List<ICanine> {new Dog(), new Wolf(), new Chihuahua() };
}

view raw

GridColumns.cs

hosted with ❤ by GitHub

The food preference columns use an ItemTemplate called FoodColumnTemplate. It’s a simple example of data binding which goes beyond mere properties, since we’re invoking a method on the data item:


class FoodColumnTemplate : ITemplate
{
private readonly Food _food;
public FoodColumnTemplate(Food food)
{
_food = food;
}
public void InstantiateIn(Control container)
{
var label = new Label();
label.DataBinding += OnDataBinding;
container.Controls.Add(label);
}
private void OnDataBinding(object sender, EventArgs e)
{
var label = (Label) sender;
var row = (DataGridItem) label.NamingContainer;
var canine = (ICanine) row.DataItem;
label.Text = canine.Eats(_food) ? "Yes" : "No";
}
}

If we run the application, we get the result we wanted:

Foods-result

Without the presence of the BoxEnumerable<ICanine> above, though, we’d have a runtime exception at our hands. Under the covers, BoxEnumerable<ICanine> is producing the necessary wrappers around the actual canines to keep the DataGrid happy.

How it works

Let’s see how we can do this. Here’s an overview of the different moving parts:

Box-overview

That’s a fair amount of types, but most of them have trivial implementations. Consider BoxEnumerable<T> first:


public class BoxEnumerable<T> : IEnumerable<Box<T>>
{
private readonly IEnumerable<T> _;
public BoxEnumerable(IEnumerable<T> e)
{
_ = e;
}
public IEnumerator<Box<T>> GetEnumerator()
{
return new BoxEnumerator<T>(_.GetEnumerator());
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}

As you can see, it’s really the simplest possible wrapper around the original IEnumerable<T>, turning it into an IEnumerable<Box<T>>. It relies on another wrapper type, BoxEnumerator<T>:


public class BoxEnumerator<T> : IEnumerator<Box<T>>
{
private readonly IEnumerator<T> _;
private readonly BoxFactory<T> _factory = new BoxFactory<T>();
public BoxEnumerator(IEnumerator<T> e)
{
_ = e;
}
public void Dispose()
{
_.Dispose();
}
public bool MoveNext()
{
return _.MoveNext();
}
public void Reset()
{
_.Reset();
}
public Box<T> Current
{
get { return _factory.Get(_.Current); }
}
object IEnumerator.Current
{
get { return Current; }
}
}

That too is just a minimal wrapper. The only remotely interesting code is in the Current property, where a BoxFactory<T> is responsible for turning the T instance into a Box<T> instance. BoxFactory<T> looks like this:


public class BoxFactory<T>
{
private readonly Box<T> _ = EmptyBoxFactory.Instance.CreateEmptyBox<T>();
public Box<T> Get(T t)
{
return _.Create(t);
}
}

view raw

BoxFactory.cs

hosted with ❤ by GitHub

This is short but a little weird, perhaps. For fun, we’re adding a dash of premature optimization here. We’re using EmptyBoxFactory to create an “empty” instance of Box<T> (that is, without an instance of T inside). The BoxFactory<T> holds on to that empty instance for the rest of its lifetime, and uses it to create “populated” boxes. In other words, the initial empty box acts as a prototype for all subsequent boxes. That way, we avoid using reflection more than once to create the boxes. This should make people who fear the performance penalty of reflection a little happier. Let’s see how the prototype creates populated boxes for the factory:


public Box<T> Create(T t)
{
var box = (Box<T>) MemberwiseClone();
box._ = t;
return box;
}

view raw

CreateBox.cs

hosted with ❤ by GitHub

Easy as pie, we’re just cloning and setting the protected T field. Doesn’t get much simpler than that.

It’s time to start worrying about the box itself, though. Of course, this is where things get both non-trivial and interesting.

So the goal is to create a type at runtime. The type should be used to wrap each item in an IEnumerable<T>, so that the control’s DataSource is set to a perfectly homogenous IEnumerable. That is, it will only contain instances of the same concrete type. The wrapper type won’t have any intelligence of its own, it will merely delegate to the wrapped instance of T.

To support auto-generation of columns, the wrapper type must have the same public properties as T. (We won’t consider the option of masking or renaming properties – that’s a use case that goes beyond just fixing what is broken.) In the case of T being an interface, a viable option would be for the wrapper type to implement T. However, we need the wrapper to work for all kinds of T, including when T is a base class with one or more non-virtual members. In the general case, therefore, the wrapper must simply mimic the same properties, duck typing-style.

Auto-generation of columns is pretty nifty, and a property-mimicking wrapper is sufficient for that scenario. For more sophisticated data binding scenarios, though, you need to be able to call arbitrary methods on the item we’re binding to. To do so in the general case (where T might be a class), we need some way of shedding the wrapper. We can’t simply call the methods on the wrapper itself, since we don’t have access to the name of the dynamically generated wrapper type at compile time. The C# compiler wouldn’t let us (well, we could use dynamic, but then we’re giving up static typing). So we’ll be using an Unwrap method, giving us access to the bare T. (Note that we can’t use a property, since that would show up when auto-generating columns!)

Now how can we call Unwrap if the type doesn’t even exist at compile time? Well, we know that there’s a small set of core capabilities that all wrapper types are going to need: the wrapped instance of T, and a way of wrapping and unwrapping T. So let’s create an abstract base class containing just that:


abstract class Box<T>
{
protected T _;
public T Unwrap() { return _; }
public Box<T> Create(T t)
{
var box = MemberwiseClone();
box._ = t;
return box;
}
}

view raw

Box.cs

hosted with ❤ by GitHub

That way, we can always cast to Box<T>, call Unwrap, and we’re good.

Why are we calling it a “box”, by the way? It’s sort of a tip of the hat to academia, of all things. According to this paper on micro patterns, a “box” is “a class which has exactly one, mutable, instance field”. That suits our implementation to a T (hah!) so “box” it is.

The concrete box for our example should conceptually look like this:


public class BoxedICanine : Box<ICanine>, ICanine
{
public string Bark
{
get { return _.Bark; }
}
public bool Eats(Food f)
{
return _.Eats(f);
}
}

view raw

BoxedICanine.cs

hosted with ❤ by GitHub

Of course, the boxes we generate at runtime will never actually have a C# manifestation – they will be bytecode only. At this point though, the hand-written example will prove useful as target for our dynamically generated type.

Note that we’re going to try to be a little clever in our implementation. In the case where T is an interface (like ICanine), we’re going to let the dynamically generated box implement the original interface T, in addition to extending Box<T>. This will allow us to pretend that the box isn’t even there during data binding. You might recall that we’re casting to ICanine rather than calling Unwrap in the FoodColumnTemplate, even though the data item is our dynamically generated type rather than the original canine. Obviously we won’t be able to pull off that trick when T is a class, since C# has single inheritance.

Looking at the bytecode for BoxedICanine in ILDASM, ILSpy or Reflector, you should see something like this (assuming you’re doing a release compilation):


.class public auto ansi beforefieldinit BoxedICanine
extends PolyFix.Lib.Box`1<class PolyFix.Lib.ICanine>
implements PolyFix.Lib.ICanine
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
.maxstack 8
L_0000: ldarg.0
L_0001: call instance void PolyFix.Lib.Box`1<class PolyFix.Lib.ICanine>::.ctor()
L_0006: ret
}
.method public hidebysig newslot virtual final instance bool Eats(valuetype PolyFix.Lib.Food f) cil managed
{
.maxstack 8
L_0000: ldarg.0
L_0001: ldfld !0 PolyFix.Lib.Box`1<class PolyFix.Lib.ICanine>::_
L_0006: ldarg.1
L_0007: callvirt instance bool PolyFix.Lib.ICanine::Eats(valuetype PolyFix.Lib.Food)
L_000c: ret
}
.method public hidebysig specialname newslot virtual final instance string get_Bark() cil managed
{
.maxstack 8
L_0000: ldarg.0
L_0001: ldfld !0 PolyFix.Lib.Box`1<class PolyFix.Lib.ICanine>::_
L_0006: callvirt instance string PolyFix.Lib.ICanine::get_Bark()
L_000b: ret
}
.property instance string Bark
{
.get instance string PolyFix.Lib.BoxedICanine::get_Bark()
}
}

view raw

BoxedICanine.il

hosted with ❤ by GitHub

This, then, is what we’re aiming for. If we can generate this type at runtime, using ICanine as input, we’re good.

IL for beginners

If you’re new to IL, here’s a simple walk-through of the get_Bark method. IL is a stack-based language, meaning it uses a stack to transfer state between operations. In addition, state can be written to and read from local variables.

The .maxstack 8 instruction tells the runtime that a stack containing a eight elements will be sufficient for this method (in reality, the stack will never be more than a single element deep, so eight is strictly overkill). That’s sort of a preamble to the actual instructions, which come next. The ldarg.0 instruction loads argument 0 onto the stack, that is, the first parameter of the method. Now that’s confusing, since get_Bark seems to have no parameters, right? However, all instance methods receive a reference to this as an implicit 0th argument. So ldarg.0 loads the this reference onto the stack. This is necessary to read the _ instance field, which happens in the ldfld !0 instruction that follows. The ldfld !0 pops the this reference from the stack, and pushes the reference held by the 0th field (_) back on. So now we got an reference to an ICanine on there. The following callvirt instruction pops the ICanine reference from the stack and invokes get_Bark on it (passing the reference as the implicit 0th argument, of course). When the method returns, it will have pushed its return value onto the stack. So there will be a reference to a string there. Finally, ret returns from the method, leaving the string reference on the stack as the return value from the method.

If you take a look at the Eats method next, you’ll notice it’s practically identical to get_Bark. That’s because we’re essentially doing the same thing: delegating directly to the underlying T instance referenced by the _ field.

Now, how can we generate stuff like this on the fly?

Creating a type at runtime

As you can see below, a .NET type lives inside a module that lives inside an assembly that lives inside an appdomain.

Appdomain-blue

So before we can start generating the actual type, we need to provide the right environment for the type to live in. We only want to create this environment once, so we’ll do it inside the constructor of our singleton EmptyBoxFactory:


private readonly ModuleBuilder _moduleBuilder;
private EmptyBoxFactory()
{
const string ns = "PolyFix.Boxes";
_moduleBuilder = Thread.GetDomain()
.DefineDynamicAssembly(new AssemblyName(ns), AssemblyBuilderAccess.Run)
.DefineDynamicModule(ns);
}

AssemblyBuilderAccess.Run indicates that we’re creating a transient assembly – it won’t be persisted to disk. We’re holding on to the module builder, which we’ll use when creating types later on. Assuming that we’ll be using the BoxEnumerable<T> in multiple data binding scenarios (for various Ts), the module will be accumulating types over time.

The public API of EmptyBoxFactory is limited to a single method, CreateEmptyBox. It uses reflection to create an instance of the appropriate type.


public Box<T> CreateEmptyBox<T>()
{
return (Box<T>)Activator.CreateInstance(GetBoxType<T>());
}

Creating the instance is simple enough (albeit slower than newing up objects the conventional way). The real work lies in coming up with the type to instantiate, so we need to move on! GetBoxType<T> looks like this:


private Type GetBoxType<T>()
{
var t = typeof(T);
string typeName = t.FullName + "Box";
foreach (var existingType in _moduleBuilder.GetTypes())
{
if (existingType.FullName == typeName)
{
return existingType;
}
}
return CreateBoxType(t, typeof (Box<T>), typeName);
}

view raw

GetBoxType.cs

hosted with ❤ by GitHub

We’re still treading the waters, though. Specifically, we’re just checking if the module already contains the suitable box type – meaning that we’ve been down this road before. Assuming we haven’t (and we haven’t, have we?), we’ll go on to CreateBoxType. Hopefully we’ll see something interesting there.


public Type CreateBoxType(Type t, Type boxType, string typeName)
{
var boxBuilder = _moduleBuilder.DefineType(
typeName, TypeAttributes.Public, boxType, t.IsInterface ? new[] {t} : new Type[0]);
var f = boxType.GetField("_", BindingFlags.Instance | BindingFlags.NonPublic);
return new BoxTypeFactory(t, boxBuilder, f).Create();
}

Oh man, it seems we’re still procrastinating! We haven’t reached the bottom of the rabbit hole just yet. Now we’re preparing for the BoxTypeFactory to create the actual type.

Two things worth noting, though. One thing is that if t is an interface, then we’ll let our new type implement it as mentioned earlier. This will let us pretend that the box isn’t even there during data binding. The other thing is that we’re obtaining a FieldInfo instance to represent the _ field of BoxType<T>, which as you’ll recall holds the instance of T that we’ll be delegating all our method calls and property accesses to. Once we have the FieldInfo, we can actually forget all about BoxType<T>. It’s sort of baked into the TypeBuilder as the superclass of the type we’re creating, but apart from that, BoxTypeFactory is oblivious to it.

But now! Now there’s nowhere left to hide. Let’s take a deep breath, dive in and reflect:


class BoxTypeFactory
{
private readonly Type _type;
private readonly TypeBuilder _boxBuilder;
private readonly FieldInfo _field;
private readonly Dictionary<string, MethodBuilder> _specials = new Dictionary<string, MethodBuilder>();
public BoxTypeFactory(Type type, TypeBuilder boxBuilder, FieldInfo field)
{
_type = type;
_boxBuilder = boxBuilder;
_field = field;
}
public Type Create()
{
foreach (MethodInfo m in _type.GetMethods())
{
if (!IsGetType(m)) CreateProxyMethod(m);
}
foreach (PropertyInfo p in _type.GetProperties())
{
ConnectPropertyToAccessors(p);
}
return _boxBuilder.CreateType();
}
private static bool IsGetType(MethodInfo m)
{
return m.Name == "GetType" && m.GetParameters().Length == 0;
}
private void CreateProxyMethod(MethodInfo m)
{
var parameters = m.GetParameters();
// Create a builder for the current method.
var methodBuilder = _boxBuilder.DefineMethod(m.Name,
MethodAttributes.Public | MethodAttributes.Virtual,
m.ReturnType,
parameters.Select(p => p.ParameterType).ToArray());
var gen = methodBuilder.GetILGenerator();
// Emit opcodes for the method implementation.
// The method should just delegate to the T instance held by the _ field.
gen.Emit(OpCodes.Ldarg_0); // Load 'this' reference onto the stack.
gen.Emit(OpCodes.Ldfld, _field); // Load 'T' reference onto the stack (popping 'this').
for (int i = 1; i < parameters.Length + 1; i++)
{
gen.Emit(OpCodes.Ldarg, i); // Load any method parameters onto the stack.
}
gen.Emit(m.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, m); // Call the method.
gen.Emit(OpCodes.Ret); // Return from method.
// Keep reference to "special" methods (for wiring up properties later).
if (m.IsSpecialName)
{
_specials[m.Name] = methodBuilder;
}
}
private void ConnectPropertyToAccessors(PropertyInfo p)
{
var paramTypes = p.GetIndexParameters().Select(ip => ip.ParameterType).ToArray();
var pb = _boxBuilder.DefineProperty(p.Name, p.Attributes, p.PropertyType, paramTypes);
WireUpIfExists("get_" + p.Name, pb.SetGetMethod);
WireUpIfExists("set_" + p.Name, pb.SetSetMethod);
}
private void WireUpIfExists(string accessor, Action<MethodBuilder> wireUp)
{
if (_specials.ContainsKey(accessor))
{
wireUp(_specials[accessor]);
}
}
}

Oh. That’s almost anti-climatic – it’s not really hard at all. The Create method is super-simple: create proxy methods for any public methods in the type we’re wrapping, wire up any properties to the corresponding getter and/or setter methods, and we’re done! CreateProxyMethod seems like it might warrant some explanation; however, all we’re really doing is copying verbatim the IL we looked at in our walkthrough of get_Bark earlier. The wiring up of properties is necessary because a property consists of two parts at the IL level, a .property thing and a .method thing for each accessor. That, too, we saw in the IL of the hand-written class. So there’s really not much to it.

You might note that we’re explicitly not creating a proxy for the GetType method, defined on System.Object. This applies to the case where the type we’re boxing is a class, not an interface. In general, we shouldn’t proxy any non-virtual methods inherited from System.Object, but in practice that’s just GetType. So we’re taking the easy way out. (Note that the .NET runtime wouldn’t actually be fooled if we did inject a lying GetType implementation – it would still reveal the actual type of the object. Still, it’s better to play by the book.)

We will be providing proxies for virtual methods, though (e.g. Equals, GetHashCode and ToString). This makes the box as invisible as possible.

Afterthought: Anonymous types

There’s actually an alternative way of getting around the problem with broken polymorphism in simple scenarios. Rather than hand-writing your own wrapper or generating one at runtime, you can have the C# compiler generate one for you at compile time, using anonymous types. In fact, you can approximate a working solution for our example just by doing this in the code-behind:


protected void Page_Load(object sender, EventArgs e)
{
_grid.DataSource = GetCanines().Select(
c => new {
Biscuit = c.Eats(Food.Biscuit),
Meatballs = c.Eats(Food.Meatballs),
You = c.Eats(Food.You),
c.Bark
});
_grid.DataBind();
}

view raw

Canines.Anon.cs

hosted with ❤ by GitHub

Note that you don’t add any custom columns in this case, it’s all auto-generated. Running the application, you get this:

Food-result-anon

It’s not exactly the same as before, but it’s pretty close. Unfortunately, the approach isn’t very flexible – it breaks down as soon as you want to display something that’s not just text in the grid. For instance, say you want something like this:

Food-dropdown

Anonymous types won’t help you, but the runtime wrapper will (as will a hand-written one, of course). You just need a suitable ITemplate:


public class FoodListColumnTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var list = new DropDownList();
list.DataBinding += OnDataBinding;
container.Controls.Add(list);
}
private void OnDataBinding(object sender, EventArgs e)
{
var list = (DropDownList) sender;
var row = (DataGridItem) list.NamingContainer;
var canine = (ICanine) row.DataItem;
Action<Food> add = food => { if (canine.Eats(food)) { list.Items.Add(food.ToString()); } };
add(Food.Biscuit);
add(Food.Meatballs);
add(Food.You);
}
}

So…

Turns out that generating types at runtime is no big deal. It provides a flexible solution to the data binding problem, without the need for mindless hand-written wrappers.

As usual, let me know if you think there’s something wrong with the approach or the implementation. Also, I’d love to hear it if you have a different solution to the problem.