Json serialization – RPC style in MVC

In a previous posting, I discussed replacing the stock MVC serializer used for the JsonResult exposed when you use the controller method Json(..) instead of View.

This was all find and dandy. But how – you may wonder – can I call actions that contain complex parameters? Do I need a special binder? Should I write my own?

The answer is mostly “no”. As Phil Hack blogged, the ASP.NET MVC framework already contains value providers that take care of that for you. All you need to do is ensure that your Javascript calls your action using some very specific header and mime types.

Here is a function that may help you

<script type="text/javascript">
var postToAction = function (sender) {
var json = $('textarea#' + sender.data).val();
url: document.location.href,
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
var replyText = JSON.stringify(data);

The special sauce here is the dataType and contentType together with the POST method. The rest is pretty much how jQuery wants to be called.

On line 6 you will note that I’m POSTing to the same URL as the browser is on – you may want to fiddle with that.

We call this function by hooking up a button, something like:

$("button#myButtonId").click('myTextAreaWithJsonContent', postToAction);

In your own implementation you will no doubt compose some object in JavaScript, or create a Json object. In the code above, I’m simply using Json formatted string: Line 3 gets the value from a text area element. If you compose a complex object and want to send it, you will need to convert it into a Json string. jQuery 1.5.1 – which I happen to use – already contains this facility, JSON.stringify(x) would do the trick. You can see it here used on line 12, for the inbound response which I simply stringify and hydrate a response text area. But this is only demo code – you will wire up the success (and failure function- right?) to your own logic.

But back to the core issue: Yes, MVC supports submitting Json and hydrating my controller action, but how do I persuade it to use my custom chosen super duper serializer rather than the stock one?

The answer is: Create a custom ValueProviderFactory and instantiate your favorite serializer in there. A bit of inspection on the MVC source code on CodePlex.com reveals the stock implementation.

Here’s a modified version, which isolates the serialization in a clear way:

public class MyJsonValueProviderFactory : ValueProviderFactory
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
if (controllerContext == null)
throw new ArgumentNullException("controllerContext");
if (!controllerContext.HttpContext.Request.ContentType.StartsWith(
"application/json", StringComparison.OrdinalIgnoreCase))
return null;
object value = Deserialize(controllerContext.RequestContext.HttpContext.Request.InputStream);
if (value == null)
return null;
var bag = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
PopulateBag(bag, string.Empty, value);
return new DictionaryValueProvider<object>(bag, CultureInfo.CurrentCulture);
private static object Deserialize(Stream stream)
string str = new StreamReader(stream).ReadToEnd();
if (string.IsNullOrEmpty(str))
return null;
var serializer = new JavaScriptSerializer(new MySpecialTypeResolver());
return serializer.DeserializeObject(str);
private static void PopulateBag(Dictionary<string, object> bag, string prefix, object source)
var dictionary = source as IDictionary<string, object>;
if (dictionary != null)
foreach (var entry in dictionary)
PopulateBag(bag, CreatePropertyPrefix(prefix, entry.Key), entry.Value);
var list = source as IList;
if (list != null)
for (int i = 0; i < list.Count; i++)
PopulateBag(bag, CreateArrayItemPrefix(prefix, i), list[i]);
bag[prefix] = source;
private static string CreatePropertyPrefix(string prefix, string propertyName)
if (!string.IsNullOrEmpty(prefix))
return (prefix + "." + propertyName);
return propertyName;
private static string CreateArrayItemPrefix(string prefix, int index)
return (prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]");

It all really boils down to the same ceremony as the default implementation, except on the line
var serializer = new JavaScriptSerializer(new MySpecialTypeResolver()); lets to use our own special serializer. Woot!

To use this instead of the built in one, you will modify your global.asax.cs Application_Start() to include something like

var existing = ValueProviderFactories.Factories.FirstOrDefault(f => f is JsonValueProviderFactory);
if (existing != null)
ValueProviderFactories.Factories.Add(new MyJsonValueProviderFactory());

where the built in one gets removed and my custom one gets added. Pretty straightforward.

With this technique and the one described in my previous post, you are ready to use the full power of MVC as an API supporting a nice strongly typed parameter for the back end developer and supporting fully customizable JSON in and out of methods. No real need for other frameworks or technologies for the serving jQuery needs.

Depending on your methods, you may even get away with one set of actions serving both form posts and jQuery invocation.

Happy coding!

Query Oddities – MongoDB style

Oh, I remember it like it was yesterday: Dot-com, no DBA, late nights, a pale developer walking into my office head hung low and mumbling something about restoring backup because he ran an update query with no where clause.. the good old days.

Zoom forward a decade.

A developer is cranking away on some MongoDB query generation in code. Not wanting to make any rookie mistakes, she uses the Query.EQ builder, which would surely create the correct syntax. Better than her own string.Format() at least!

Or so she thought.

The issue is a small peculiarity with the Query methods. The formal signature takes a string and a BsonValue:

public static QueryComplete EQ(
string name,
BsonValue value

So a some call path would get to a method which would create the query. Lets say

public string CreateFooQuery(string value)
var query = Query.EQ("Prop1",value);
return query.ToString();

Did you spot the issue? I didn’t. She didn’t either.

The issue is that the Query.EQ(field, value) method would boil down a value “xyz” to the MongoDB query {“Prop1”:”xyz”} just fine. It would also boil down an empty string “” to the query {"Prop1":""} without flinching. But if you supply null - and yes, strings can be null - then the query becomes {}. Yiekes (!!!): The null query. Yes, the one that matches EVERY document!

Now take that query as a read query - you got all documents returned. Use it for an update - might as well have some good backup strategy!

Note to self: write more unit tests. Ensure that every code path you visit have been visited before and the expected values are returned.


JSON serialization problems and solution in MVC3

For various reasons you may find that the default JsonResult returned by invoking the controller method such as

return Json(data);

Is unsuitable for the consumer. The main issue most often encountered is that this method uses the JsonResult which in turn uses the JavaScriptSerializer with no access to the JavaScriptTypeResolver.

This means that you can provide that serializer a parameter specifying you own custom type resolver.

Other issues, such as maximum recursion depth and maximum length and type resolvers can be simply configured in web.config. See Configuring JSON Serialization section on MSDN.

Back to the core problem though.

To override the JsonResult, we would need to do 2 things:

  1. Create our own custom JsonResult implementation
  2. Tell the controller to use ours rather than the stock one.

A new JsonResult is needed because the base one hard codes the construction of the JavaScriptSerializer.

So here we go. Some CTRL+C, CTRL+V later from the open source MVC on Codeplex gives us

public class TypedJsonResult : JsonResult
public override void ExecuteResult(ControllerContext context)
if (context == null)
throw new ArgumentNullException("context");
if ((JsonRequestBehavior == JsonRequestBehavior.DenyGet)
&& string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("JsonRequest GetNotAllowed");
var response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
if (Data != null)
var serializer = new JavaScriptSerializer(new BiasedTypeResolver());

You will note that we’re still using the JavaScriptSerializer, but this time we’re controlling its construction and decided to give it our own type resolver. More on that type resolver in a bit.

Next, we want to our controller(s) an easy way to choose our TypedJsonResult rather than the stock one. Luckily, the controller boils down the call Json(data) and several other signatures to a call to a virtual signature which we may simply override, like so:

protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
return new TypedJsonResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior };

That’s it! On line 3 you will notice we return our custom Typed JsonResult, whereas the stock implementation would have returned the JsonResult.

If this new behavior is desired everywhere, then you would probably want to place this override in a base controller of your own, and have all your controllers inherit it.

Other powers this bestows on you is of course using some other serializer altogether, such as Json.NET or whatever you fancy.

Now back to my own type resolver. You could, after all, use the SimpleTypeResolver built into the framework, which works quite well. However, it introduces fairly long type names – frowned upon by my clients consuming this Json on other platforms, and also doesn’t enable me to map my own type names to a type of my choice. Enter the BiasedTypeResolver.

private static readonly Dictionary<string, Type> _KnownTypes;
static BiasedTypeResolver()
_KnownTypes = new Dictionary<string, Type> ();
var appDomain = AppDomain.CurrentDomain;
foreach (var assembly in appDomain.GetAssemblies().Where(a => a.GetName().Name.EndsWith(".ValueObjects")))
foreach (var type in assembly.GetTypes().Where(t => !t.IsInterface && !t.IsAbstract))
_KnownTypes[type.Name] = type;
public override Type ResolveType(string id)
var result = Type.GetType(id);
if (result != null || _KnownTypes.TryGetValue(id, out result))
return result;
throw new ArgumentException("Unable to resolve [" + id + "]", "id");
public override string ResolveTypeId(Type type)
if (type == null)
throw new ArgumentNullException("type");
return type.Name;

This resolver spelunks specific assemblies only (those named [whatever].ValueObjects which are my naming convention for POCO public objects) and catalogs them into a dictionary by short type name.

It doesn’t know how to resolve 2 types of the same name if they only differ by namespace, but then again I’d ask “how come you would define 2 classes of the same exact name in your solution?” You can define type names to whatever suites your needs.

The resolver’s responsibility is twofold: Given a string , return the System.Type that corresponds to it. Given a type, return a name for it. The former is used during deserialization, the latter when serializing.

Now you may not need or like this particular type resolver implementation. But now that you can inject your own, possibilities are limitless. These can range to configuration based type resolution, versioning decisions base on some revision upgrades etc.

Note also that upon deserialization, the type resolver is only called when a type discriminator exists in the JSON stream. That is, a complex type that doesn’t contain “__type”:”foo” will be serialized by the JavaScriptSerializer by matching the target member name rather than the resolver. This is nice because the JSON can contain strategically placed type discriminators for polymorphic reasons on some members, but be left terse and bare otherwise.

Hopefully, this helps you, or me-of-the-future when the gray cells got filled with the next great thing..

Happy Coding!

MVC Automatic Menu

An ex-colleague of mine used to call his SQL script generator “Super-Scriptmatic 2000”. It impressed our then boss little, but was fun to say and use. We called every batch job and script “something 2000” from that day on. I’m tempted to call this one Menu-Matic 2000, except it’s waaaay past 2000 :-\ . Oh well.

The problem: I’m developing a bunch of stuff in MVC. There’s no PM to generate mounds of requirements and there’s no Ux Architect to create wireframe. During development, things change. Specifically, actions get renamed, moved from controller x to y etc. Well, as the site grows, it becomes a major pain to keep a static menu up to date, because the links change. The HtmlHelper doesn’t live up to it’s name and provides little help. How do I keep this growing list of pesky little forgotten actions reigned in?

The general plan is:

  1. Decorate every action you want as a menu item with a custom attribute
  2. Reflect out all menu items into a structure at load time
  3. Render the menu using as CSS friendly <UL> <LI> HTML.

The MvcMenuItemAttribute decorates an action, designating it to be included as a menu item:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class MvcMenuItemAttribute : Attribute
public string MenuText { get; set; }
public int Order { get; set; }
public string ParentLink { get; set; }
internal string Controller { get; set; }
internal string Action { get; set; }
#region ctor
public MvcMenuItemAttribute(string menuText) : this(menuText, 0) { }
public MvcMenuItemAttribute(string menuText, int order)
MenuText = menuText;
Order = order;
internal string Link { get { return string.Format("/{0}/{1}", Controller, this.Action); } }
internal MvcMenuItemAttribute ParentItem { get; set; }

The MenuText allows overriding the text displayed on the menu. The Order allows the items to be ordered. The ParentLink allows you to make this item a child of another menu item. An example action could then be decorated thusly: [MvcMenuItem("Tracks", Order = 20, ParentLink = "/Session/Index")] All pretty straightforward methinks.

The challenge with menu hierarchy becomes fairly apparent when you try to render a menu and highlight the “current” item or render a breadcrumb control. Both encounter an ambiguity if you allow a data source to have more than one menu item with the same URL link. The issue is that there is no great way to tell which link a person click. Using referring URL will fail if a user bookmarked the page. Using some extra query string to disambiguate duplicate URLs essentially changes the links, and also ads a chance of collision with other query parameters. Besides, that smells. The stock ASP.Net sitemap provider simply disallows duplicate URLS. I decided not to, and simply pick the first one encountered as the “current”. Although it doesn’t solve the issue completely – one might say they wanted the second of the 2 links to be “current”- it allows one to include a link twice (home->deals and products->deals etc), and the logic of deciding “current” is easy enough to explain to the customer.

Now that we got that out of the way, let’s build the menu data structure:

public static List<MvcMenuItemAttribute> ListMenuItems(Assembly assembly)
var result = new List<MvcMenuItemAttribute>();
foreach (var type in assembly.GetTypes())
if (!type.IsSubclassOf(typeof(Controller)))
foreach (var method in type.GetMethods())
var items = method.GetCustomAttributes(typeof(MvcMenuItemAttribute), false) as MvcMenuItemAttribute[];
if (items == null)
foreach (var item in items)
if (String.IsNullOrEmpty(item.Controller))
item.Controller = type.Name.Substring(0, type.Name.Length - "Controller".Length);
if (String.IsNullOrEmpty(item.Action))
item.Action = method.Name;
return result.OrderBy(i => i.Order).ToList();

Using reflection, the ListMenuItems method takes an assembly (you will hand it your MVC web assembly) and generates a list of menu items. It digs up all the types, and for each one that is an MVC Controller, digs up the methods. Methods decorated with the MvcMenuItemAttribute get plucked and added to the output list. Again, pretty simple. To make the structure hierarchical, a LINQ expression matches up all the items to their parent:

public static void RegisterMenuItems(List<MvcMenuItemAttribute> items)
_MenuItems = items;
_MenuItems.ForEach(i => i.ParentItem =
items.FirstOrDefault(p =>
String.Equals(p.Link, i.ParentLink, StringComparison.InvariantCultureIgnoreCase)));

The _MenuItems is simply an internal list to keep things around for later rendering. Finally, to package the menu building for easy consumption:

public static void RegisterMenuItems(Type mvcApplicationType)

To bring this puppy home, a call in Global.asax.cs Application_Start() registers the menu. Notice the ugliness of reflection is tucked away from the innocent developer. All they have to do is call the RegisterMenuItems() and pass in the type of the application. When you use the new project template, global.asax declares a class _public class MvcApplication : HttpApplication _and that is why the Register call passes in that type.

protected void Application_Start()

What else is left to do? Oh, right, render!

public static void ShowMenu(this TextWriter output)
var writer = new HtmlTextWriter(output);
renderHierarchy(writer, _MenuItems, null);
public static void ShowBreadCrumb(this TextWriter output, Uri currentUri)
var writer = new HtmlTextWriter(output);
string currentLink = "/" + currentUri.GetComponents(UriComponents.Path, UriFormat.Unescaped);
var menuItem = _MenuItems.FirstOrDefault(m => m.Link.Equals(currentLink, StringComparison.CurrentCultureIgnoreCase));
if (menuItem != null)
renderBreadCrumb(writer, _MenuItems, menuItem);
private static void renderBreadCrumb(HtmlTextWriter writer, List<MvcMenuItemAttribute> menuItems, MvcMenuItemAttribute current)
if (current == null)
var parent = current.ParentItem;
renderBreadCrumb(writer, menuItems, parent);
writer.Write(" / ");
static void renderHierarchy(HtmlTextWriter writer, List<MvcMenuItemAttribute> hierarchy, MvcMenuItemAttribute root)
if (!hierarchy.Any(i => i.ParentItem == root)) return;
foreach (var current in hierarchy.Where(element => element.ParentItem == root).OrderBy(i => i.Order))
if (ItemFilter == null || ItemFilter(current))
writer.AddAttribute(HtmlTextWriterAttribute.Href, current.Link);
writer.AddAttribute(HtmlTextWriterAttribute.Alt, current.MenuText);
writer.RenderEndTag(); // link
renderHierarchy(writer, hierarchy, current);
writer.RenderEndTag(); // li
writer.RenderEndTag(); // ul

The ShowMenu method renders the menu out to the provided TextWriter. In previous posts I’ve discussed my partiality to using well debugged, time test HtmlTextWriter to render HTML rather than writing out angled brackets by hand. In addition, writing out using the actual writer on the actual stream rather than generating string and byte intermediaries (yes, StringBuilder being no exception) disturbs me.

To carry out the rendering of an hierarchical menu, the recursive renderHierarchy() is used. You may notice that an ItemFilter is called before rendering each item. I figured that at some point one might want to exclude certain items from the menu based on security role or context or something. That delegate is the hook for such future feature.

To carry out rendering of a breadcrumb recursion is used again, this time simply to unwind the parent hierarchy from the leaf node, then rendering on the return from the recursion rather than as we go along deeper. I guess I was stuck in LISP that day.. recursion is fun though. Now all that is left is some usage! Open your Site.Master or wherever you’d like to place a menu or breadcrumb, and plant one of these calls:

<% MvcMenu.ShowBreadCrumb(this.Writer, Request.Url); %> to show a breadcrumb trail (notice lack of “=” after <% and the semicolon).

<% MvcMenu.ShowMenu(Writer); %> to show the menu.

As mentioned before, the HTML output is nested <UL> <LI> tags, which should make it easy to style using abundant CSS to produce anything from static horizontal or vertical to dynamic drop-downs. This has been quite a fun little implementation and I was pleased that the code size remained low. The main crux was figuring out how to pass parent information from the attribute to the hierarchy builder because attributes have restricted parameter types. Once I settled on that implementation, the rest falls into place quite easily.

Fluent Binder – Simple Magic can happen in 10 lines of C#

Often enough we have frameworks do heavy lifting for us. That’s usually a good thing. But I always found it kind of sedating to let “the man” provide me with too much comfort. Especially when the framework or other SOUP library fails to perform exactly what you want. That usually leads to some grumpiness followed by some code-acrobatics to punch that square peg into a round hole – often negating the elegance and usefulness of the library call altogether.

One task a framework often performs is binding. Binding – as defined here – is taking an object and assigning values to it’s properties from a property bag of sorts. For example, a property bag could be a hash-table or list of name-value pairs and an object would be a POCO (Plain old class object). It’s common in web and ORM contexts, also in web services to receive a dictionary of values and have to attach them to your domain model. The plain straightforward way would be to pluck key value pairs one by one by name and assign to your object. But that’s no fun and error prone. What we would like is to be able to auto-attach values to the target object.

How do we achieve that? Steve Bearman and I actually presented this very briefly as part of a larger talk on advanced C# at SoCal Code Camp last weekend. A bit of reflection, a bit of generics and extensions, and viola:

public static T Populate<T>(this T target, IEnumerable<KeyValuePair<string,object>> values)
Type targetType = target.GetType();
foreach (var kvp in values)
PropertyInfo pi = targetType.GetProperty(kvp.Key);
pi.SetValue(target, kvp.Value, null);
return target;

The extension method Populate() above takes an IEnumerable of KeyValuePair as a parameter. It then iterates a these pairs and for each key finds a property by that name and assigns the value from the dictionary to the target object. Reflection comes in at lines 6 and 7. A property is found based on the name alone, and assigned to. Usage of this extension can look something like this:

Dictionary<string, object> assignments = new Dictionary<string, object>();
assignments.Add("Name", "Paris Hilton");
assignments.Add("ID", 42);
assignments.Add("HomePhone", "(310)-555-1212");
assignments.Add("WorkPhone", "(310)-777-FILM");
Person paris = new Person();
Person result = paris.Populate(assignments);

Simple, granted. Simplistic perhaps. But let’s consider that the average programmer doesn’t write much code like this. There can be many bells and whistles added here: A property getter might only assign if the prperty is writable, attempt to match without case sensitivity, only match if property is public or adorned with an attribute. The main thinks is that you can write this method into your solution in very few lines and shape it as you wish. You do not have to depend on default MVC binders or ORMs being open source or anything like that to have binding performed. Further utilizing this bit (!) of code you might create a simple object factory that returns a new populated type from any object given a property bag of values. In fact, let’s do this right here:

public static class MyFactory<T>
public static T Create(IEnumerable<KeyValuePair<string, object>> values)
T result;
ConstructorInfo ctor = typeof(T).GetConstructor(System.Type.EmptyTypes);
result = (T)ctor.Invoke(null);
return result;

The generic factory MyFactory has a Create() method which takes a property bag as a parameter and returns a populated instance with the values provided. The usage of the factory eliminates the need for creating a new empty instance before populating it. Well, actually , it does it so you don’t have to – code was not eliminated, just consolidated. The usage then becomes:

Dictionary<string, object> values = new Dictionary<string, object>();
values.Add("Name", "Paris Hilton");
values.Add("ID", 42);
values.Add("HomePhone", "(310)-555-1212");
values.Add("WorkPhone", "(310)-777-FILM");
Person actual = MyFactory<Person>.Create(values);

So there we have it folks. Another DIY tidbit that would hopefully help you take control of the common binding task away from framework writers and back into your hands - where it belongs.

In production, you would probably want to also take a look at whether there’s a Populate() or TryPopulate() -exception or return boolean - and handle the whole error pathing in an explicit way that fits your own style of coding. Similarly you should consider whether an unassigned property (missing value in the bag) is cause for error and whether extra unmatched values are cause for error. In this example, an extra value will cause an exception and an unassigned property will not.

Happy Binding!

Between - Extension method to shorten notation

Sometimes I just write code. And sometimes I clean up my code. Most of the times, I focus on the meat of the methods, hacking away at verbose or lengthy flows, re-factoring out common code, trying to untangle overly complex logic etc.

Recently, I noticed that many of the conditional terms I write span very long lines and are a bit cumbersome to read. The reason for that is that many of the variable names are long, or the properties or both and that often the comparison is on a property of an object or member of a collection etc.

So for instance:

if (summerCatalog.Products[0].ProductCategories[0].ParentCategoryID >= 1 && summerCatalog.Products[0].ProductCategories[0].ParentCategoryID <= 4)
  • Can become quite long.
  • Long is not easy to read.
  • Long is not easy to maintain.
  • Long is not easy to think through.

What I really wanted to say is if [value] is between [a] and [b].

Of course, one could say “lets just make the variable names shorter”. But that flies in the face of self explanatory plain naming. So abbreviating for the sake of short-lineliness (New word! You heard it her first!) is out.

Well, this is just screaming “EXTENSION METHODS” doesn’t it?

Here we go then:

/// <summary>
/// Returns whether the value is between the 2 specified boundaries.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value to compare</param>
/// <param name="minValueInclusive">The min value (inclusive).</param>
/// <param name="maxValueInclusive">The max value (inclusive).</param>
/// <returns>True if the value is equal to or between the boundaries; False otherwise.</returns>
public static bool Between<T>(this T value, T minValueInclusive, T maxValueInclusive) where T : IComparable<T>
if (minValueInclusive.CompareTo(maxValueInclusive) > 0)
throw new ArgumentException("minimum value must not be greater than maximum value");
return (value.CompareTo(minValueInclusive) >= 0 && value.CompareTo(maxValueInclusive) <= 0);

The Between function takes any object which supports IComparable and performs syntactic sugar comparison with the inclusive min and max values. What’s more, it adds a basic sanity check for the comparison. How many times do I do that sanity check in my normal code (!)?

Now the conditional is

if (summerCatalog.Products[0].ProductCategories[0].ParentCategoryID.Between(1, 4))

At least I don’t have to refactor this in my brain while reading.

Sure, you might say, but you could have just de-referenced the deep value and then have a shorter conditional, like so:

Category category = summerCatalog.Products[0].ProductCategories[0];
if (category.ParentCategoryID >= 1 && category.ParentCategoryID <= 4)

Yes - of course - but it adds a line of code, places the burden of reading the very common idiom ( x >= a && x <= b) on me, and I constantly stumble on the lest-than-or-equal vs. less-than and it doesn’t check for my boundaries being inadvertently swapped.

So there you have it. A simple extension cuts down your lines of code, makes long text shorter and saves lives. Which begs the question: is this already part of the language - and should it be?

Unit Testing and approval tests

It’s been years now that unit testing frameworks and tools have grabbed our attention, made their way into our favorite IDE and sparked yet another wave of seemingly endless “my framework is better than yours” wars. And then there are the principal wars of whether TDD is better than Test After Development. And most excitingly the automated testing tools etc. Oh, and let’s not forget mocks! So we have all the tools we need – right? Well, kind of, no.

I recently attended a talk by Llewellyn Falco and Woody Zuill the other day, and they used a little library called Approval Tests (http://approvaltests.com/). I immediately fell in love with the concept and the price ($0). Llewellyn is one of the two developers of the product, hosted on http://sourceforge.net/projects/approvaltests/.

What does it do that years of frameworks don’t?

For me, a major nuisance is that you have a piece of code, and that piece of code produces a result (object, state – call it what you will). That result is commonly named “actual” in Visual Studio unit tests. The developer must then assert against that result to ensure that the code ran properly. In theory, unit tests are supposed to be small and only test one thing. In reality, functions which return complex objects rarely can be asserted with one assert. You’d typically find yourself asserting several properties or testing some behavior of the actual value. In corporate scenario, the unit tests might morph into some degree of integration tests and objects become more complex, requiring a slew of assert.this and assert.that().

What if you could just run the code, inspect the value returned, and – if it satisfies the requirements – set “that value” to be the comparison for all future runs? Wouldn’t that be nice? Good news: Approval Tests does just that. So now, instead of writing so many asserts against your returned value, you just call ApprovalTests.Approve() and the captured state is compared against your current runtime. Neat huh?

But wait, there’s more! What if your requirements are regarding a windows form, or a control? how do you write a unit test that asserts against a form? The answer is simple and genius: Capture the form as an image, and compare the image produced by your approved form (after you have carefully compared it to the form given to you by marketing – right?) and compare it to each subsequent run. ApprovalTests simply does a byte by byte comparison of the resultant picture of the form and tells you if it matches what you approved.

Let’s break down the steps for installation:

  1. Add a reference to the ApprovalTests.dll assembly.

Yeah,it’s that simple.

Ok. Let’s break down the steps for adding an approval to your unit test

  1. Write your unit test (arrange, act – no asserts) as usual.

  2. Add a call to Approve().

Yeah, it’s that simple.

How do you tell it that the value received is “the right one”? Upon first run, the Approve() call will always fail. Why? Because it has no stored approved value to compare the actual it received against. When it fails, it will print out a message (console or test report – depends on your unit test runner). That message will contain a path for the file that it received, complaining about a lack of approved file. The value captured from that run (and any subsequent run) is stored in a file named something like “{your unit test file path}{your method}.received.xyz”. If you like the result of the run -the image matches what the form should look like, or the text value is what your object should contain etc – then you can rename it to “{your unit test file path}{your method}.approved.xyz”. You should check the approved file into your source control. After all, it’s content constitutes the basis of the assertion in your unit test!

Consider the very simple unit test code:

public void DateTime_Constructor_YMDSetDate()
DateTime actual;
actual = new DateTime(2038, 4, 1);

The function under test here is the constructor for System.DateTime which takes 3 parameters – month day and year. Upon first run, the test will fail with a message resembling

“_TestCase ‘MyProject.Tests.DateTimeTest.DateTime_Constructor_YMDSetDate’

failed: ApprovalTests.Core.Exceptions.ApprovalMissingException : Failed Approval: Approval File “C:\….\MyProject\DateTimeTest.DateTime_ConstructorYMDSetDate.approved.txt” Not Found.”

That’s because this file was never created – it’s your first run. Using the standard approver, this file will actually now be created but will be empty. In that same directory you will find a file named {…}.received.txt. This is the capture from this run. You can open the received value file, and inspect the text to ensure that the value returned matches your expected value. If it does, simply rename that file to .approved.text or copy it’s content over and run the test again. This time, the Approve() method should succeed. If at any point in the future the method under test returns a different value, the approval will fail. If at any point in the future the specs change, you will need to re-capture a correct behavior and save it.

How do you easily compare the values from the last run and the saved approved value? The approved file is going to be a text file for string approvals, and an image file for WinForm approvals. As it turns out, you can instruct Approval Tests to launch a diff program with the 2 files (received, approved) automatically upon failure, or just open the received file upon failure or silently just fail the unit test. To control that behavior, you use a special attribute

public class ObjectWriterTest

The UserReporterAttribute allows you to specify one of 3 included reporters

  1. DiffReporter – which opens tortoisediff for diffing the received and approved files if the comparison fails.

  2. OpenReceivedFileReporter – which launches the received file using the application registered to it’s extension on your system if the comparison fails.

  3. QuietReporter – which does not launch any program but only fails the unit test if the comparison fails.

When your have a CI server and run unit tests as part of your builds, you probably want to use the quiet reporter. For interactive sessions, one of the first 2 will probably be more suitable.

How are value comparisons performed? Under the standard built in methods, a file is written out and compared to byte by byte. If you wish to modify this or any behavior, you can implement your own approver or file writer or reporter by implementing simple interfaces. I ended up adding a general use object writer so that I can approve arbitrary objects. The effort was fairly painless and straightforward.

I did have to read the code to get the concept. If only my time machine worked: I could have read my own blog and saved myself 20 minutes. Yeah, right.

The project has some bells and whistles – plug ins for a few IDE’s and there’s a version for Java and Ruby. I have not reviewed these versions.

There you have it folks- a shiny new tool under your belt. I can see this saving my hours of mindless typing of Assert.* calls and I can go home early. Yeah, right.

MVC Radio Button List

As predicted, I came around to using some radio buttons. As you might guess by now, I didn’t like the HTML or the implementation in the current MVC release. As you may expect, I wrote my own :-)

The implementation is fairly simple and straightforward. It extends System.Web.MVC.ViewPage, takes a list of objects, allows for selection of one of the radio buttons, supports orientation and supports selection of both the value the radio button submits and the display string for that item independently.

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.UI;
public static partial class HtmlHelpers
public static void ShowRadioButtonList<T>(this ViewPage page, IList<T> list, string name, Expression<Func<T, object>> valueProperty, Expression<Func<T, object>> displayProperty, System.Web.UI.WebControls.Orientation orientation)
page.ShowRadioButtonList(list, name, valueProperty, displayProperty, "3", orientation);
public static void ShowRadioButtonList<T>(this ViewPage page, IList<T> list, string name, Expression<Func<T, object>> valueProperty, Expression<Func<T, object>> displayProperty, string selectedValue, System.Web.UI.WebControls.Orientation orientation)
HtmlTextWriter writer = new HtmlTextWriter(page.Response.Output);
if (writer != null)
Func<T, object> valueGetter = valueProperty.Compile();
Func<T, object> displayStringGetter = displayProperty.Compile();
for (int i = 0; i < list.Count; i++)
T row = list[i];
string value = valueGetter(row).ToString();
writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio");
writer.AddAttribute(HtmlTextWriterAttribute.Id, name + "_" + i);
writer.AddAttribute(HtmlTextWriterAttribute.Name, name, true);
writer.AddAttribute(HtmlTextWriterAttribute.Value, value, true);
if (value == selectedValue)
if (orientation == System.Web.UI.WebControls.Orientation.Vertical)

This implementation uses the type Expression<Func<T,Object>> for the selection of the value and the display string. To invoke the helper, assuming you have a list of Product objects, Product being defined:

public class Product
public int ProductID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }

You can now call the helper from your MVC View Page strongly typed with a model List:

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<List<Product>>"
MasterPageFile="~/Views/Shared/Site.Master" %>

invoked simply

<% this.ShowRadioButtonList<Product>(Model,
a => a.ProductID,
d => d.Title, "4",
Orientation.Horizontal); %>

This call will create a radio button for each product in the list (Model is a List<Product> because we strongly typed the page as such). The radio button will use the ProductID property for the value of the input, and the Title property as the displayed string. If one of the product Id’s happens to be 4, that radio button will be selected in the group. The radio buttons will all be named “productRadioButtonList” but their ID will be appended an ordinal number “productRadioButtonList_1”,”productRadioButtonList_2”,”productRadioButtonList_3” etc.

There you have it: another day, another MVC control, another blog post.