Using Bower and NancyFx together

In .NET land, for package management we’re pretty much all settled on using Nuget. It’s close to ubiquitous, which means, that pretty much any .NET open source (or not) library, can be found there.

There are a few most popular non-.NET packages too. This category contains mostly JavaScript/CSS libraries, which tend to be used in the front-end of projects using .NET on the backend.

While Nuget is great to help you get your foot in the water of the great and broad JavaScript ecosystem, you’ll soon find its suffering from a few drawbacks:

  • The JavaScript packages on Nuget only cover a small subset of the ecosystem
  • The packages on Nuget are usually unofficial, that is maintained by people not affiliated with the projects, and they can lag behind the official releases

Bower is to web (JavaScript/CSS) packages, what Nuget is to .NET.

On a recent project we used NancyFx to build out .NET backend services, and SPA client (based mostly on AngularJs). We used Nuget for our .NET packages and Bower for the client. This post shows how to set Bower up on Windows, and integrate it into a Nancy project.

Getting started

To get Bower you’ll need to have Node and Git installed. Also make sure both of them are in your PATH. Once this is done simply open your command prompt and type

npm i -g bower

After this finishes, you can type bower -v to confirm Bower is installed (and see the version)

Once this is done, let’s open Visual Studio and create a new Nancy Project (I used one of Nancy Visual Studio Templates)
Nancy Visual Studio Template
This will give you a simple starting website.
For static content, like the .css and .js files Bower manages, the convention in Nancy is to stick them in the /Content folder. (see the doco)

Let’s try using Bower to fetch Angular. Open your command prompt and make sure you’re in your solution directory.

Bower 101

There really are very few Bower commands you’ll need

bower seearch angular will find all matching packages (there are quite a few)
Bower serach results for angular
bower install angular will install the package (if you’re getting errors make sure Git is in your PATH)
bower install angular
You’ll notice, however that instead of Content the package is installed into bower_components

the .bowerrc file

We can change the default directory where Bower puts the packages by creating a .bowerrc file in our solution directory, and putting the following in it:

  "directory" : "Web/Content"

Save the file, remove the bower_components folder and let’s install the package again.

bower install angular again
Notice this time the package ended up where we told it to.

Bower is agnostic to Visual Studio, so it will not add the packages to your solution. You’ll need to select Show All Files in Solution Explorer, click on the angular folder and select Include in Project.
angular include in Solution
The reality is, it took you much longer to read this post, than it will take you to do the tasks described.

This is the approach I’ve taken and it seems to be working well for us. Do you have a different workflow? Let me know if the comments.

Strongly typed app settings with Castle DictionaryAdapter

A while ago (almost 4 years ago, to be precise) Ben Hall wrote a blogpost about using Castle DictionaryAdapter to build a simple, strongly typed wrapper aroud application settings.

While extremely simple, and gets the job done, there are a few ways it can be improved. With that, this blogpost can be treated as an introduction to Castle DictionaryAdapter (which sadly has precisely zero documentation).

While the apprpach is really simple, we’re going to take a detailed look and take it slowly, which is why this post is fairly long. Buckle up.

What is DictionaryAdapter

In a nutshell DictionaryAdapter is a simple tool to provide strongly typed wrappers around IDictionary<string , object>

Here’s a simple example:

// we have a dictionary...
var dictionary = new Dictionary<string, object>
	{ "Name", "Stefan" },
	{ "Age", 30 }

// ...and an adapter factory
factory = new DictionaryAdapterFactory();

// we build the adapter for the dictionary
var adapter = factory.GetAdapter<IPerson>(dictionary);

Debug.Assert(adapter.Name == "Stefan");

Wrapping app settings

While the project is called DictionaryAdapter in fact it can do a bit more than just wrap dictionaries (as in IDictionary). It can be used to wrap XmlNodes or NameValueCollections like Configuration.AppSettings and this last scenario, is what we’re going to concentrate on.

The goals

We’ve got a few goals in mind for that project:

  • strongly typed – we don’t want our settings to be all just strings
  • grouped – settings that go together, should come together (think username and password should be part of a single object)
  • partitioned – settings that are separate should be separate (think SQL database connection string and Azure service bus url)
  • fail fast – when a required setting is missing we want to know ASAP, not much later, deep in the codebase when we first try to use it
  • simple to use – we want the junior developer who joins the team next week to be able to use it properly.

With that in mind, let’s get to it.

Getting started

DictionaryAdapter lives in Castle.Core (just like DynamicProxy), so to get started we need to get the package from Nuget:

Install-Package Castle.Core

Once this is done and you’re not using Resharper make sure to add using Castle.Components.DictionaryAdapter; to make the right types available.

The config file

Here’s our config file, we’ll be dealing with. Notice it follows a simple naming convention with prefixes to make it easy to group common settings together. This is based on a real project.

<?xml version="1.0" encoding="utf-8"?>
    <add key="environment-type" value="Local" />
    <add key="environment-log-minimum-level" value="Debug" />
    <add key="auth0-client-id" value="abc123abc" />
    <add key="auth0-client-secret" value="123abc123abc" />
    <add key="auth0-domain" value="" />
    <add key="auth0-database-connection-name" value="ABC123" />
    <add key="auth0-token-expiration-seconds" value="3600" />

As you can see we have two sets of settings here. One for general environment configuration, and another one for integration with Auth0.

Config interfaces

Now let’s proceed to creating our interfaces, exposing the configuration values to our application. We follow a naming convention where the name of config value corresponds to type/property on the interface. This makes it trivial to see which config value maps to which property on which interface.

For clarity I’d also recommend putting the interfaces in a designated namespace, like MyApp.Configuration.

public interface IEnvironment
    EnvironmentType Type { get; }
    LogEventLevel LogMinimumLevel { get; }

public interface IAuth0
    string ClientId { get; }
    string ClientSecret { get; }
    string Domain { get; }
    string DatabaseConnectionName { get; }
    int TokenExpirationSeconds { get; }

Having the interfaces and the config we can start writing the code to put the two together

Bare minimum

Let’s rewrite the code from the beginning of the post to use our config file and interfaces. If you’re not using Resharper you’ll have to manually add a reference to System.Configuration.dll for the following to work.

var factory = new DictionaryAdapterFactory();

var environment = factory.GetAdapter<IEnvironment>(ConfigurationManager.AppSettings);

Debug.Assert(environment.Type == EnvironmentType.Local);

If we run it now, we’ll get a failure. DictionaryAdapter doesn’t know about our naming convention, so we have to teach it how to map the type/property to a config value.

Implementing DictionaryBehaviorAttribute

There are two ways to customise how DictionaryAdapter operates.

  • Transparent, using an overload to GetAdapter and passing a PropertyDescriptor with customisations there.
  • Declarative, using attributes on the adapter interfaces to specify the desired behaviour. If you’ve used Action Filters in ASP.NET MVC, it will feel familiar.

In this example we’re going to use the latter. To begin, we need to create a new attribute, inheriting from DictionaryBehaviorAttribute, and apply it to our two interfaces

public class AppSettingWrapperAttribute : DictionaryBehaviorAttribute, IDictionaryKeyBuilder
    private readonly Regex converter = new Regex("([A-Z])", RegexOptions.Compiled);

    public string GetKey(IDictionaryAdapter dictionaryAdapter, string key, PropertyDescriptor property)
        var name = dictionaryAdapter.Meta.Type.Name.Remove(0, 1) + key;
        var adjustedKey = converter.Replace(name, "-$1").Trim('-');
        return adjustedKey;

We create the attribute and implement IDictionaryKeyBuilder interface, which tells DictionaryAdapter we want to have a say at mapping the property to a proper key in the dictionary. Using a trivial regular expression we map NameLikeThis to Name-Like-This.

Having done that, if we run the application again, the assertion will pass.

Fail Fast

If we remove the environment-log-minimum-level setting from the config file, and run the app again, it will still pass just fine. In fact, since LogEventLevel (which comes from Serilog logging framework) in an enum, therefore a value type, if we read the property everything will seem to have worked just fine. A default value for the enum will be returned.

This is not the behaviour that we want. We want to fail fast, that is if the value is not present or not valid, we want to know. To do it, we need two modifications to our AppSettingWrapperAttribute

Eager fetching

First we want the adapter to eagerly fetch values for every property on the interface. That way if something is wrong, we’ll know, even before we try to access the property in our code.

To do that, we implement one more interface – IPropertyDescriptorInitializer. It comes with a single method, which we implement as follows:

public void Initialize(PropertyDescriptor propertyDescriptor, object[] behaviors)
    propertyDescriptor.Fetch = true;

Validating missing properties

To ensure that each setting has a value, we need to insert some code into the process of reading the values from the dictionary. To do that, there is another interface we need to implement: IDictionaryPropertyGetter. This will allow us to inspect the value that has been read, and throw a helpful exception if there is no value.

public object GetPropertyValue(IDictionaryAdapter dictionaryAdapter, string key, object storedValue, PropertyDescriptor property, bool ifExists)
    if (storedValue != null) return storedValue;
    throw new InvalidOperationException(string.Format("App setting \"{0}\" not found!", key.ToLowerInvariant()));

If we run the app now, we’ll see that it fails, as we expect, telling us that we forgot to set environment-log-minimum-level in our config file.

Wrapping up

That’s it. Single attribute and a minimal amount of bootstrap code is all that’s needed to get nice, simple to use wrappers around application settings.

Additional bonus is, that this is trivial to integrate with your favourite IoC container.

All code is available in this gist.

On C# dynamic and calling base type’s methods

The dynamic keyword has been part of the C# language for quite a while now. I thought I know it well, yet I stumbled upon an interesting case that surprised me.

The code that works

Here’s a piece of code that I started with. This code works like you would expect.

public interface ICanQuack
    void Fly<T>(T map);
    void Quack();

public class Duck : ICanQuack
    public void Fly<T>(T map)
        Console.WriteLine("Flying using a {0} map ({1})", typeof (T).Name, map);

    public void Quack()
        Console.WriteLine("Quack Quack!");

class Program
    private static ICanQuack quack;
    private static void Main(string[] args)

        var map = GetMap();



    private static void SetUpQuack()
        quack = new Duck();

    private static object GetMap()
        return "a map";

Notice the use of dynamic to resolve the generic method type parameter at runtime. This code works and, as you probably guessed, prints:

Flying using a String map (a map)

The innocent change that broke it

Now, even though it’s a completely made up example instead of the real code, flying is something not just ducks do, so let’s extract an interface ICanFly

public interface ICanFly
    void Fly<T>(T map);

public interface ICanQuack : ICanFly
    void Quack();

Rest of the code stays the same.

Looks innocent enough right? Except it just broke out code. It we run it now we’ll get the following error

What happened

Well, to be honest, I’m not quite sure I have a good explanation for the behaviour. Like I said, I was surprised myself that this code stops working now. When you use the dynamic keyword C# compiler tries to use all the information it has at compile time, to optimise the code it generates to support the dynamic invocation, so that it has less work to do at runtime. In this case, by definition, everything that implements ICanQuack also implements ICanFly but the binder seems to not bother checking the base interface. I’m sure Jon Skeet has a perfectly good explanation for it.

How to fix it

The exception message points us pretty clearly towards the problem – the runtime binder uses the static type information about ICanQuack to find the Fly method. Since the method is defined on the ICanFly interface, we need to give the binder a hint that ICanFly is where it should look.

To do that, we need to change the following code


into a bit uglier (but working!):


On strongly typed application settings with Castle DictionaryAdapter

Every non-trivial .NET application ends up using configuration file for its settings. It’s the standard mechanism that’s fairly well adopted across the community. That doesn’t mean however, that it’s simple to deal with.

There have been many various approaches to dealing with the problem, including some from Microsoft. There are a few open source ones, including one from my colleague, Andrew.

Yet another (not even original) approach

This brings us to Castle DictionaryAdapter. Part of the Castle project that never got much traction, partially to poor (read non-existent) documentation. Somewhat similar to DynamicProxy, DictionaryAdapter concentrates on dynamically generating strongly typed wrappers around dictionaries or XML. The idea of using it for wrapping configuration values is not new. Ben blogged about it a few years ago, and I always liked the simplicity and readability of the approach, and how little effort it required.

I started working on a project recently, that has a whole bunch of different sets of config values, which led me to adding some small improvements to the approach.

Not just one big Config God Object

One common mistake (regardless of the approach) is that all the unrelated settings end up in a single massive configuration God Object. There is nothing inherent about the DictionaryAdapter approach forcing you to go down that path. You can split your configuration logically across a few configuration interfaces

public interface SmtpConfiguration
    string Name { get; set; }
    int Port { get; set; }

public interface SomeOtherConfig

// and in the config file:
    <add key="name" value="value" />
    <add key="port" value="25"/>
    <!--  stuff -->

Taking it a bit further, we might explicitly partition the values using prefixes:

    <add key="smtp:name" value="value" />
    <add key="smtp:port" value="25"/>
    <add key="stuff:something" value="bla"/>
    <!--  other stuff -->

DictionaryAdapter knows how to properly resolve prefixed values using KeyPrefixAttribute.

public interface SmtpConfiguration
    string Name { get; set; }
    int Port { get; set; }

Fail fast

One other missing big, is shortening the feedback loop. We don’t want to learn we have an invalid or missing value at some later point in the application’s lifecycle when we try to read it for the first time. We want to know about it as soon as possible. Preferably, when the application starts up (and in a test).

The first problem, we could solve with FetchAttribute Which forces a property to be read when the adapter is constructed, therefore forcing exception in cases where, for example, your property is of type TimeSpan but your config value is not a valid representation of time span.

To solve the other problem we need a little bit of code. In fact, to simplify things, we can merge that with what KeyPrefixAttribute and FetchAttribute provide, to have all the functionality we need in a single type.

public class AppSettingsAttribute : KeyPrefixAttribute, IDictionaryPropertyGetter, IPropertyDescriptorInitializer
    public AppSettingsAttribute(string keyPrefix) : base(keyPrefix)

    public object GetPropertyValue(IDictionaryAdapter dictionaryAdapter, string key, object storedValue,
        PropertyDescriptor property, bool ifExists)
        if (storedValue == null && IsRequired(ifExists))
            throw new ArgumentException("No valid value for '" + key + "' found");
        return storedValue;

    public void Initialize(PropertyDescriptor propertyDescriptor, object[] behaviors)
        propertyDescriptor.Fetch = true;

    private static bool IsRequired(bool ifExists)
        return ifExists == false;

Now our configuration interface changes to:

public interface SmtpConfiguration
    string Name { get; set; }
    int Port { get; set; }

Not only do we get a nice, readable, testable strongly typed access to our settings, that can easily be put in an IoC container. We also are going to get an early exception if we put an invalid value in the config, or we forget about doing it at all.

The full code is on github.

On Castle Windsor and open generic component arity

In the previous post I said there’s one more new feature in Windsor 3.2 related to open generic components.

Take the following class for example:

public class Foo<T, T2> : IFoo<T>

Notice it has arity of 2 (two generic parameters, T and T2) and the interface it implements has arity of 1.
If we have a generic component for this class what should be supplied for T2 when we want to use it as IFoo<Bar>?

By default, if we just register the component and then try to use it we’ll be greeted with an exception like the following:

Requested type GenericsAndWindsor.IFoo`1[GenericsAndWindsor.Bar] has 1 generic parameter(s), whereas component implementation type GenericsAndWindsor.Foo`2[T,T2] requires 2.
This means that Windsor does not have enough information to properly create that component for you.
You can instruct Windsor which types it should use to close this generic component by supplying an implementation of IGenericImplementationMatchingStrategy.
Please consut the documentation for examples of how to do that.

Specifying implementation generic arguments: IGenericImplementationMatchingStrategy

The IGenericImplementationMatchingStrategy interface allows you to plug in your own logic telling Windsor how to close the implementation type for a given requested service. The following trivial implementation simply uses string for the other argument, therefore allowing the component to be successfully constructed.

public class UseStringGenericStrategy : IGenericImplementationMatchingStrategy
	public Type[] GetGenericArguments(ComponentModel model, CreationContext context)
		return new[]
			typeof (string)

The contract is quite simple, given a ComponentModel and CreationContext (which will tell you what the requested closed type is) you return the right types to use for generic arguments when closing the implementation type of the model.

You hook it up in exactly the same way as IGenericServiceStrategy (and yes, there’s an overload that allows you to specify both).

container.Register(Component.For(typeof (IFoo<>))
	.ImplementedBy(typeof (Foo<,>), new UseStringGenericStrategy())

Now the service will resolve successfully.
Generic component resolved

On Castle Windsor and open generic components

While Windsor supported open generics components since pretty much forever, there’s been some improvements in version 3.2 that I haven’t blogged about yet, but which can be pretty useful in some advanced scenarios. I’ll cover them in this and future blogpost.

Just so we’re clear – what are open generic components?

So what are open generic components? Components based on a generic type where we don’t specify the generic arguments. Like the following:

// register
container.Register(Component.For(typeof (IFoo<>))
	.ImplementedBy(typeof (Foo<>))

// will provide IFoo<Bar>, IFoo<Baz>, IFoo<any_valid_type>

In this case we say that the component provides IFoo<> closed over Bar, Baz etc

Being picky about what we’re closing over: IGenericServiceStrategy

Sometimes we want to restrict the types we want our components to support. C# language allows us to use generic constraints to specify that, and Windsor will obviously respect that, but sometimes we need to go beyond what language provides.

One realistic example might be restricting to specific types from a given assembly, like in this StackOverflow question.

Windsor 3.2 has a new hook point for just that – IGenericServiceStrategy, which allows you to plug custom logic to specify whether you want a component to support a given closed version of it’s open generic service.

Here’s a sample implementation limiting to types from a single assembly:

public class OnlyFromAssemblyStrategy : IGenericServiceStrategy
	private readonly Assembly assembly;

	public OnlyFromAssemblyStrategy(Assembly assembly)
		this.assembly = assembly;

	public bool Supports(Type service, ComponentModel component)
		return service.GetGenericArguments().Single().Assembly == assembly;

To hook the strategy:

container.Register(Component.For(typeof (IFoo<>))
	.ImplementedBy(typeof (Foo<>), new OnlyFromAssemblyStrategy(someAsembly))

Now when you need IFoo<SomeTypeFromWrongAssembly> either another component will need to supply it, or the dependency will not be satisfied (which, if the dependency is not optional, will result in exception).
Component Not Found exception

On Nuget, Git and unignoring packages

Git has a helpful ability to ignore certain files. When working on .net projects, you normally want to ignore your .suo file, bin and obj folders etc.

If you’re using the excellent GitExtensions it will even provide a default, reasonable .gitignore file for you.

Problem is, that while you want to ignore certain patterns in most of your project, generally you want none of those rules to apply to your nuget packages.

Everything in packages folder should be committed. Always. No exceptions.

To do that, you need to leverage a child .gitignore file.

Create a .gitignore file inside your packages folder and add the following line to it:


This tells Git to disregard any ignore rules of the parent file. Now all your packages will be committed completely, without missing any of their functionality.

On Windsor 3.2 release

Windsor 3.2 release is now live on nuget and sourceforge.

This release is mostly about bugfixes and incremental improvements and while some breaking changes were made, for vast majority of users this will be a drop-in update.

The highlights of the release are in the documentation, so I won’t repeat them here.

End of an era

It is the last release to support .NET 3.5 and Silverlight.

Also, I’m thinking of sunsetting (such a nice word) Remoting facility, Factory Support facility (the one that allows you to specify factory method via XML, not to be confused with Typed Factory facility), Event Wiring facility and Synchronize facility.

Obviously, Windsor being a community driven project, if someone wants to step in and take over any of these facilities we’ll keep updating them. Otherwise this will likely be their last release.

On Testing: Why write tests?

This post is secod part of my Back to basics: on testing series.

Developers writing tests

People new to software, or coming from organizations where all testing is done by dedicated people often find the idea of developers doing testing bizarre.


After all, we’re the highly trained, educated professionals. We get payed to do the hard bits. Clicking around the UI to see if a label is misaligned or an app crashed surely should be delegated to somebody else, outsourced even.

Truth is, there are various kinds of tests, and while there is value in UI tasting (automated or not) we’ll concetrate at somethig else first.

You write the tests for your future self

The idea of developers writing tests came not from academia but from the field. From people who spent years developing successful software. And as you get out there, and start working with teams of people, on real life big systems that solve real problems, you realise that some things you belived (or in fact were taught) to be true, are not.

We’ll get into the details as we progress with this series, but let’s start with the biggest one:

The code is written, and read, and read, and read and read some more and modified, and read, and modified again, and read some more again and then few months later read yet again and again

You may notice there’s much more reading than writing there. That is true for most code – you don’t just write and forget it, like is the case with coding assignments at unversity. Real-life code is long lived, often expanded and modified and commonly the person doing the expanding is not the person who originally wrote the code. In fact the original author may have already moved on to work elsewhere.

  • How do you know what the code does?
  • How do you know where to make the change?
  • How do you know your change didn’t break any of the assumptions that code interacting with the bit you changed makse about it?
  • How do you know the change you made works the way you wanted it to?
  • How do you know the API you created (in other words the public methods) are easy to use and will make sense to the other developers using it (that may also be you few weeks from now!).

These are the reasons for writing tests. Tests are the most economical way of ensuring the change you will make two months from now fit in the design constrants you designed today. Tests are the fastest way for other developers (or again, future you) to get a feel of how a piece of code works; what it does, and how you’re supposed to use it.

Don’t just take my word for it

In the next part of the series we’ll start looking at actual code, writing some tests, and explaining the concepts around them.

Until then, if you have any questions, or suggestions as to what to cover in future posts of the series, feel free to leave a comment.

Using Resharper to ease mocking with NSubstitute

The problem

While C# compiler provides a decent level of generic parameter type inference there’s a bunch of scenarios where it does not work, and you have to specify the generic parameters explicitly.

One such case is when you invoke a generic method inline, and the return type is the generic type parameter.

In other words, the following scenario:


In this case the compiler won’t infer the generic parameter of GenericMethod and you have to specify it explicitly.

As helpful as Resharper often is, it also doesn’t currently provide any help (other than placing the cursor at the appropriate location) and you have to specify the type parameter yourself.

Oh the typing!

I’m quite sensitive to friction in my development work, and I found this limitation quite annoying. Especially that the pattern is used quite often.

Specifically the excellent NSubstitute mocking framework is using it for creation of mocks via



If I wanted to use NSubstitute to provide the argument for my GenericMethod I’d have to do quite a lot of typing:


type Su or few more characters to position completion on the Substitute class.

Press Enter.


Type . and assuming the right overload of For is selected press Enter again (or press arrow to pick the right overload before that).

Finally, type enough of the expected type’s name for completion to select it, and press Enter to finish the statement.


It may not look like much but if you’re writing a lot of tests those things add up. It ends up being just enough repetitive typing to break the flow of thoughts and make you concentrate on the irrelevant mechanics (how to create a mock for IFoo) rather than what your test is supposed to be doing (verifying behavior of UsesIFoo method when a non-null arg is passed).

Resharper to the rescue

While there’s no easy way to solve the general problem, we can use Resharper to help us solve it in this specific case with NSubstitute (or any other API, I’m using NSubstitute as an example here).

For that, we’ll write a Smart Template.

How to: writing a Smart Template

Go to Resharper menu, and pick Templates Explorer…

Make sure you’re on the Live Templates tab, and click New Template.


For Shortcut select whatever you want to appear in your code completion for the template, for example NSub.

Select the template should be allowed in C# where expression is allowed.

Check Reformat and Shorten qualified references checkboxes and proceed to specifying the template itself, as follows:


The $type$ is a template variable, and the grid on the right hand side allows us to associate a macro with it. That’s where the magic happens.

Pick Change macro… and select Guess type expected at this point.

After you’ve done all of that, make sure you save the template.



Now your template will be available in the code completion.



All it takes to get to the end result now is to type ns, Enter, Enter.

The main benefit though is not the keystrokes you save, but the fact there’s almost no friction to the process, so you don’t get distracted from thinking about logic of your test.