Using Bower and NancyFx together

In .NET land, for pack­age man­age­ment we're pretty much all set­tled on using Nuget. It's close to ubiq­ui­tous, which means, that pretty much any .NET open source (or not) library, can be found there.

There are a few most pop­u­lar non-.NET pack­ages too. This cat­e­gory con­tains 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 ecosys­tem, you'll soon find its suf­fer­ing from a few drawbacks:

  • The JavaScript pack­ages on Nuget only cover a small sub­set of the ecosystem
  • The pack­ages on Nuget are usu­ally unof­fi­cial, that is main­tained by peo­ple not affil­i­ated with the projects, and they can lag behind the offi­cial releases

Bower is to web (JavaScript/CSS) pack­ages, what Nuget is to .NET.

On a recent project we used Nan­cyFx to build out .NET back­end ser­vices, and SPA client (based mostly on Angu­larJs). We used Nuget for our .NET pack­ages and Bower for the client. This post shows how to set Bower up on Win­dows, and inte­grate it into a Nancy project.

Get­ting 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 sim­ply open your com­mand prompt and type

npm i -g bower

After this fin­ishes, you can type bower -v to con­firm Bower is installed (and see the version)

Once this is done, let's open Visual Stu­dio and cre­ate a new Nancy Project (I used one of Nancy Visual Stu­dio Tem­plates)
Nancy Visual Studio Template
This will give you a sim­ple start­ing web­site.
nancy_solution_structure
For sta­tic con­tent, like the .css and .js files Bower man­ages, the con­ven­tion in Nancy is to stick them in the /Content folder. (see the doco)

Let's try using Bower to fetch Angu­lar. Open your com­mand prompt and make sure you're in your solu­tion directory.

Bower 101

There really are very few Bower com­mands you'll need

bower seearch angular will find all match­ing pack­ages (there are quite a few)
Bower serach results for angular
bower install angular will install the pack­age (if you're get­ting errors make sure Git is in your PATH)
bower install angular
You'll notice, how­ever that instead of Content the pack­age is installed into bower_components

the .bowerrc file

We can change the default direc­tory where Bower puts the pack­ages by cre­at­ing a .bowerrc file in our solu­tion direc­tory, and putting the fol­low­ing in it:

{
  "directory" : "Web/Content"
}

Save the file, remove the bower_components folder and let's install the pack­age again.

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

Bower is agnos­tic to Visual Stu­dio, so it will not add the pack­ages to your solu­tion. You'll need to select Show All Files in Solu­tion Explorer, click on the angular folder and select Include in Project.
angular include in Solution
The real­ity 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 work­ing well for us. Do you have a dif­fer­ent work­flow? Let me know if the comments.

Strongly typed app settings with Castle DictionaryAdapter

A while ago (almost 4 years ago, to be pre­cise) Ben Hall wrote a blog­post about using Cas­tle Dic­tio­naryAdapter to build a sim­ple, strongly typed wrap­per aroud appli­ca­tion settings.

While extremely sim­ple, and gets the job done, there are a few ways it can be improved. With that, this blog­post can be treated as an intro­duc­tion to Cas­tle Dic­tio­naryAdapter (which sadly has pre­cisely zero documentation).

While the apprpach is really sim­ple, 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 nut­shell Dic­tio­naryAdapter is a sim­ple tool to pro­vide strongly typed wrap­pers around IDictionary<string , object>

Here's a sim­ple 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");

Wrap­ping app settings

While the project is called Dic­tio­naryAdapter in fact it can do a bit more than just wrap dic­tio­nar­ies (as in IDictionary). It can be used to wrap XmlNodes or NameValueCollections like Configuration.AppSettings and this last sce­nario, is what we're going to con­cen­trate on.

The goals

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

  • strongly typed — we don't want our set­tings to be all just strings
  • grouped — set­tings that go together, should come together (think user­name and pass­word should be part of a sin­gle object)
  • par­ti­tioned — set­tings that are sep­a­rate should be sep­a­rate (think SQL data­base con­nec­tion string and Azure ser­vice bus url)
  • fail fast — when a required set­ting is miss­ing we want to know ASAP, not much later, deep in the code­base when we first try to use it
  • sim­ple to use — we want the junior devel­oper who joins the team next week to be able to use it properly.

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

Get­ting started

Dic­tio­naryAdapter lives in Castle.Core (just like Dynam­icProxy), so to get started we need to get the pack­age 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 con­fig file

Here's our con­fig file, we'll be deal­ing with. Notice it fol­lows a sim­ple nam­ing con­ven­tion with pre­fixes to make it easy to group com­mon set­tings together. This is based on a real project.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <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="abc123.auth0.com" />
    <add key="auth0-database-connection-name" value="ABC123" />
    <add key="auth0-token-expiration-seconds" value="3600" />
  </appSettings>
</configuration>

As you can see we have two sets of set­tings here. One for gen­eral envi­ron­ment con­fig­u­ra­tion, and another one for inte­gra­tion with Auth0.

Con­fig interfaces

Now let's pro­ceed to cre­at­ing our inter­faces, expos­ing the con­fig­u­ra­tion val­ues to our appli­ca­tion. We fol­low a nam­ing con­ven­tion where the name of con­fig value cor­re­sponds to type/property on the inter­face. This makes it triv­ial to see which con­fig value maps to which prop­erty on which interface.

For clar­ity I'd also rec­om­mend putting the inter­faces in a des­ig­nated name­space, 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; }
}

Hav­ing the inter­faces and the con­fig we can start writ­ing the code to put the two together

Bare min­i­mum

Let's rewrite the code from the begin­ning of the post to use our con­fig file and inter­faces. If you're not using Resharper you'll have to man­u­ally add a ref­er­ence to System.Configuration.dll for the fol­low­ing 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 fail­ure. Dic­tio­naryAdapter doesn't know about our nam­ing con­ven­tion, so we have to teach it how to map the type/property to a con­fig value.

Imple­ment­ing DictionaryBehaviorAttribute

There are two ways to cus­tomise how Dic­tio­naryAdapter operates.

  • Trans­par­ent, using an over­load to GetAdapter and pass­ing a PropertyDescriptor with cus­tomi­sa­tions there.
  • Declar­a­tive, using attrib­utes on the adapter inter­faces to spec­ify the desired behav­iour. If you've used Action Fil­ters in ASP.NET MVC, it will feel familiar.

In this exam­ple we're going to use the lat­ter. To begin, we need to cre­ate a new attribute, inher­it­ing 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 cre­ate the attribute and imple­ment IDictionaryKeyBuilder inter­face, which tells Dic­tio­naryAdapter we want to have a say at map­ping the prop­erty to a proper key in the dic­tio­nary. Using a triv­ial reg­u­lar expres­sion we map NameLikeThis to Name-Like-This.

Hav­ing done that, if we run the appli­ca­tion again, the asser­tion will pass.

Fail Fast

If we remove the environment-log-minimum-level set­ting from the con­fig file, and run the app again, it will still pass just fine. In fact, since LogEventLevel (which comes from Ser­ilog log­ging frame­work) in an enum, there­fore a value type, if we read the prop­erty every­thing will seem to have worked just fine. A default value for the enum will be returned.

This is not the behav­iour 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 mod­i­fi­ca­tions to our AppSettingWrapperAttribute

Eager fetch­ing

First we want the adapter to eagerly fetch val­ues for every prop­erty on the inter­face. That way if some­thing is wrong, we'll know, even before we try to access the prop­erty in our code.

To do that, we imple­ment one more inter­face — IPropertyDescriptorInitializer. It comes with a sin­gle method, which we imple­ment as follows:

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

Val­i­dat­ing miss­ing properties

To ensure that each set­ting has a value, we need to insert some code into the process of read­ing the val­ues from the dic­tio­nary. To do that, there is another inter­face we need to imple­ment: IDictionaryPropertyGetter. This will allow us to inspect the value that has been read, and throw a help­ful excep­tion 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 for­got to set environment-log-minimum-level in our con­fig file.

Wrap­ping up

That's it. Sin­gle attribute and a min­i­mal amount of boot­strap code is all that's needed to get nice, sim­ple to use wrap­pers around appli­ca­tion settings.

Addi­tional bonus is, that this is triv­ial to inte­grate with your favourite IoC container.

All code is avail­able in this gist.

On C# dynamic and calling base type's methods

The dynamic key­word has been part of the C# lan­guage for quite a while now. I thought I know it well, yet I stum­bled upon an inter­est­ing case that sur­prised 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)
    {
        SetUpQuack();

        var map = GetMap();

        quack.Fly((dynamic)map);

        Console.ReadKey(true);
    }

    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 para­me­ter at run­time. This code works and, as you prob­a­bly guessed, prints:

Fly­ing using a String map (a map)

The inno­cent change that broke it

Now, even though it's a com­pletely made up exam­ple instead of the real code, fly­ing is some­thing not just ducks do, so let's extract an inter­face ICanFly

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

public interface ICanQuack : ICanFly
{
    void Quack();
}

Rest of the code stays the same.

Looks inno­cent enough right? Except it just broke out code. It we run it now we'll get the fol­low­ing error
Error

What hap­pened

Well, to be hon­est, I'm not quite sure I have a good expla­na­tion for the behav­iour. Like I said, I was sur­prised myself that this code stops work­ing now. When you use the dynamic key­word C# com­piler tries to use all the infor­ma­tion it has at com­pile time, to opti­mise the code it gen­er­ates to sup­port the dynamic invo­ca­tion, so that it has less work to do at run­time. In this case, by def­i­n­i­tion, every­thing that imple­ments ICanQuack also imple­ments ICanFly but the binder seems to not bother check­ing the base inter­face. I'm sure Jon Skeet has a per­fectly good expla­na­tion for it.

How to fix it

The excep­tion mes­sage points us pretty clearly towards the prob­lem — the run­time binder uses the sta­tic type infor­ma­tion about ICanQuack to find the Fly method. Since the method is defined on the ICanFly inter­face, we need to give the binder a hint that ICanFly is where it should look.

To do that, we need to change the fol­low­ing code

quack.Fly((dynamic)map);

into a bit uglier (but working!):

((ICanFly)quack).Fly((dynamic)map);

On strongly typed application settings with Castle DictionaryAdapter

Every non-trivial .NET appli­ca­tion ends up using con­fig­u­ra­tion file for its set­tings. It's the stan­dard mech­a­nism that's fairly well adopted across the com­mu­nity. That doesn't mean how­ever, that it's sim­ple to deal with.

There have been many var­i­ous approaches to deal­ing with the prob­lem, includ­ing some from Microsoft. There are a few open source ones, includ­ing one from my col­league, Andrew.

Yet another (not even orig­i­nal) approach

This brings us to Cas­tle Dic­tio­naryAdapter. Part of the Cas­tle project that never got much trac­tion, par­tially to poor (read non-existent) doc­u­men­ta­tion. Some­what sim­i­lar to Dynam­icProxy, Dic­tio­naryAdapter con­cen­trates on dynam­i­cally gen­er­at­ing strongly typed wrap­pers around dic­tio­nar­ies or XML. The idea of using it for wrap­ping con­fig­u­ra­tion val­ues is not new. Ben blogged about it a few years ago, and I always liked the sim­plic­ity and read­abil­ity of the approach, and how lit­tle effort it required.

I started work­ing on a project recently, that has a whole bunch of dif­fer­ent sets of con­fig val­ues, which led me to adding some small improve­ments to the approach.

Not just one big Con­fig God Object

One com­mon mis­take (regard­less of the approach) is that all the unre­lated set­tings end up in a sin­gle mas­sive con­fig­u­ra­tion God Object. There is noth­ing inher­ent about the Dic­tio­naryAdapter approach forc­ing you to go down that path. You can split your con­fig­u­ra­tion log­i­cally across a few con­fig­u­ra­tion interfaces

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

public interface SomeOtherConfig
{
    //stuff
}

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

Tak­ing it a bit fur­ther, we might explic­itly par­ti­tion the val­ues using prefixes:

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

Dic­tio­naryAdapter knows how to prop­erly resolve pre­fixed val­ues using KeyPrefixAttribute.

[KeyPrefix("smtp:")]
public interface SmtpConfiguration
{
    string Name { get; set; }
    int Port { get; set; }
}

Fail fast

One other miss­ing big, is short­en­ing the feed­back loop. We don't want to learn we have an invalid or miss­ing value at some later point in the application's life­cy­cle when we try to read it for the first time. We want to know about it as soon as pos­si­ble. Prefer­ably, when the appli­ca­tion starts up (and in a test).

The first prob­lem, we could solve with FetchAttribute Which forces a prop­erty to be read when the adapter is con­structed, there­fore forc­ing excep­tion in cases where, for exam­ple, your prop­erty is of type TimeSpan but your con­fig value is not a valid rep­re­sen­ta­tion of time span.

To solve the other prob­lem we need a lit­tle bit of code. In fact, to sim­plify things, we can merge that with what KeyPrefixAttribute and FetchAttribute pro­vide, to have all the func­tion­al­ity we need in a sin­gle 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 con­fig­u­ra­tion inter­face changes to:

[AppSettings("smtp:")]
public interface SmtpConfiguration
{
    string Name { get; set; }
    int Port { get; set; }
}

Not only do we get a nice, read­able, testable strongly typed access to our set­tings, that can eas­ily be put in an IoC con­tainer. We also are going to get an early excep­tion if we put an invalid value in the con­fig, or we for­get about doing it at all.

The full code is on github.

On Castle Windsor and open generic component arity

In the pre­vi­ous post I said there's one more new fea­ture in Wind­sor 3.2 related to open generic components.

Take the fol­low­ing class for example:

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

Notice it has arity of 2 (two generic para­me­ters, T and T2) and the inter­face it imple­ments has arity of 1.
If we have a generic com­po­nent for this class what should be sup­plied for T2 when we want to use it as IFoo<Bar>?

By default, if we just reg­is­ter the com­po­nent and then try to use it we'll be greeted with an excep­tion like the following:

Requested type GenericsAndWindsor.IFoo`1[GenericsAndWindsor.Bar] has 1 generic parameter(s), whereas com­po­nent imple­men­ta­tion type GenericsAndWindsor.Foo`2[T,T2] requires 2.
This means that Wind­sor does not have enough infor­ma­tion to prop­erly cre­ate that com­po­nent for you.
You can instruct Wind­sor which types it should use to close this generic com­po­nent by sup­ply­ing an imple­men­ta­tion of IGener­icIm­ple­men­ta­tion­Match­ingStrat­egy.
Please con­sut the doc­u­men­ta­tion for exam­ples of how to do that.

Spec­i­fy­ing imple­men­ta­tion generic argu­ments: IGenericImplementationMatchingStrategy

The IGenericImplementationMatchingStrategy inter­face allows you to plug in your own logic telling Wind­sor how to close the imple­men­ta­tion type for a given requested ser­vice. The fol­low­ing triv­ial imple­men­ta­tion sim­ply uses string for the other argu­ment, there­fore allow­ing the com­po­nent to be suc­cess­fully constructed.

public class UseStringGenericStrategy : IGenericImplementationMatchingStrategy
{
	public Type[] GetGenericArguments(ComponentModel model, CreationContext context)
	{
		return new[]
		{
			context.RequestedType.GetGenericArguments().Single(),
			typeof (string)
		};
	}
}

The con­tract is quite sim­ple, given a ComponentModel and CreationContext (which will tell you what the requested closed type is) you return the right types to use for generic argu­ments when clos­ing the imple­men­ta­tion type of the model.

You hook it up in exactly the same way as IGenericServiceStrategy (and yes, there's an over­load that allows you to spec­ify both).

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

Now the ser­vice will resolve suc­cess­fully.
Generic component resolved

On Castle Windsor and open generic components

While Wind­sor sup­ported open gener­ics com­po­nents since pretty much for­ever, there's been some improve­ments in ver­sion 3.2 that I haven't blogged about yet, but which can be pretty use­ful in some advanced sce­nar­ios. I'll cover them in this and future blogpost.

Just so we're clear — what are open generic components?

So what are open generic com­po­nents? Com­po­nents based on a generic type where we don't spec­ify the generic argu­ments. Like the following:

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

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

In this case we say that the com­po­nent pro­vides IFoo<> closed over Bar, Baz etc

Being picky about what we're clos­ing over: IGenericServiceStrategy

Some­times we want to restrict the types we want our com­po­nents to sup­port. C# lan­guage allows us to use generic con­straints to spec­ify that, and Wind­sor will obvi­ously respect that, but some­times we need to go beyond what lan­guage provides.

One real­is­tic exam­ple might be restrict­ing to spe­cific types from a given assem­bly, like in this Stack­Over­flow ques­tion.

Wind­sor 3.2 has a new hook point for just that — IGenericServiceStrategy, which allows you to plug cus­tom logic to spec­ify whether you want a com­po­nent to sup­port a given closed ver­sion of it's open generic service.

Here's a sam­ple imple­men­ta­tion lim­it­ing to types from a sin­gle 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))
	.LifestyleTransient());

Now when you need IFoo<SomeTypeFromWrongAssembly> either another com­po­nent will need to sup­ply it, or the depen­dency will not be sat­is­fied (which, if the depen­dency is not optional, will result in excep­tion).
Component Not Found exception

On Nuget, Git and unignoring packages

Git has a help­ful abil­ity to ignore cer­tain files. When work­ing on .net projects, you nor­mally want to ignore your .suo file, bin and obj fold­ers etc.

If you're using the excel­lent GitEx­ten­sions it will even pro­vide a default, rea­son­able .git­ig­nore file for you.

Prob­lem is, that while you want to ignore cer­tain pat­terns in most of your project, gen­er­ally you want none of those rules to apply to your nuget packages.

Every­thing in pack­ages folder should be com­mit­ted. Always. No exceptions.

To do that, you need to lever­age a child .git­ig­nore file.

Cre­ate a .git­ig­nore file inside your pack­ages folder and add the fol­low­ing line to it:

!*

This tells Git to dis­re­gard any ignore rules of the par­ent file. Now all your pack­ages will be com­mit­ted com­pletely, with­out miss­ing any of their functionality.

On Windsor 3.2 release

Wind­sor 3.2 release is now live on nuget and source­forge.

This release is mostly about bug­fixes and incre­men­tal improve­ments and while some break­ing changes were made, for vast major­ity of users this will be a drop-in update.

The high­lights of the release are in the doc­u­men­ta­tion, so I won't repeat them here.

End of an era

It is the last release to sup­port .NET 3.5 and Silverlight.

Also, I'm think­ing of sun­set­ting (such a nice word) Remot­ing facil­ity, Fac­tory Sup­port facil­ity (the one that allows you to spec­ify fac­tory method via XML, not to be con­fused with Typed Fac­tory facil­ity), Event Wiring facil­ity and Syn­chro­nize facility.

Obvi­ously, Wind­sor being a com­mu­nity dri­ven project, if some­one wants to step in and take over any of these facil­i­ties we'll keep updat­ing them. Oth­er­wise this will likely be their last release.

On Testing: Why write tests?

This post is secod part of my Back to basics: on test­ing series.

Devel­op­ers writ­ing tests

Peo­ple new to soft­ware, or com­ing from orga­ni­za­tions where all test­ing is done by ded­i­cated peo­ple often find the idea of devel­op­ers doing test­ing bizarre.

testing

After all, we're the highly trained, edu­cated pro­fes­sion­als. We get payed to do the hard bits. Click­ing around the UI to see if a label is mis­aligned or an app crashed surely should be del­e­gated to some­body else, out­sourced even.

Truth is, there are var­i­ous kinds of tests, and while there is value in UI tast­ing (auto­mated or not) we'll con­ce­trate at some­thig else first.

You write the tests for your future self

The idea of devel­op­ers writ­ing tests came not from acad­e­mia but from the field. From peo­ple who spent years devel­op­ing suc­cess­ful soft­ware. And as you get out there, and start work­ing with teams of peo­ple, on real life big sys­tems that solve real prob­lems, 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 writ­ten, and read, and read, and read and read some more and mod­i­fied, and read, and mod­i­fied again, and read some more again and then few months later read yet again and again

You may notice there's much more read­ing than writ­ing there. That is true for most code — you don't just write and for­get it, like is the case with cod­ing assign­ments at unver­sity. Real-life code is long lived, often expanded and mod­i­fied and com­monly the per­son doing the expand­ing is not the per­son who orig­i­nally wrote the code. In fact the orig­i­nal 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 assump­tions that code inter­act­ing 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 cre­ated (in other words the pub­lic meth­ods) are easy to use and will make sense to the other devel­op­ers using it (that may also be you few weeks from now!).

These are the rea­sons for writ­ing tests. Tests are the most eco­nom­i­cal way of ensur­ing the change you will make two months from now fit in the design con­strants you designed today. Tests are the fastest way for other devel­op­ers (or again, future you) to get a feel of how a piece of code works; what it does, and how you're sup­posed to use it.

Don't just take my word for it

In the next part of the series we'll start look­ing at actual code, writ­ing some tests, and explain­ing the con­cepts around them.

Until then, if you have any ques­tions, or sug­ges­tions 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 prob­lem

While C# com­piler pro­vides a decent level of generic para­me­ter type infer­ence there's a bunch of sce­nar­ios where it does not work, and you have to spec­ify the generic para­me­ters 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 fol­low­ing scenario:

resharper_generic_call

In this case the com­piler won't infer the generic para­me­ter of GenericMethod and you have to spec­ify it explicitly.

As help­ful as Resharper often is, it also doesn't cur­rently pro­vide any help (other than plac­ing the cur­sor at the appro­pri­ate loca­tion) and you have to spec­ify the type para­me­ter yourself.

Oh the typing!

I'm quite sen­si­tive to fric­tion in my devel­op­ment work, and I found this lim­i­ta­tion quite annoy­ing. Espe­cially that the pat­tern is used quite often.

Specif­i­cally the excel­lent NSub­sti­tute mock­ing frame­work is using it for cre­ation of mocks via

Substitute.For<IMyTypeToMock>();

method.

If I wanted to use NSub­sti­tute to pro­vide the argu­ment for my GenericMethod I'd have to do quite a lot of typing:

resharper_step1

type Su or few more char­ac­ters to posi­tion com­ple­tion on the Substitute class.

Press Enter.

resharper_step2

Type . and assum­ing the right over­load of For is selected press Enter again (or press arrow to pick the right over­load before that).

Finally, type enough of the expected type's name for com­ple­tion to select it, and press Enter to fin­ish the statement.

resharper_step3

It may not look like much but if you're writ­ing a lot of tests those things add up. It ends up being just enough repet­i­tive typ­ing to break the flow of thoughts and make you con­cen­trate on the irrel­e­vant mechan­ics (how to cre­ate a mock for IFoo) rather than what your test is sup­posed to be doing (ver­i­fy­ing behav­ior of UsesIFoo method when a non-null arg is passed).

Resharper to the rescue

While there's no easy way to solve the gen­eral prob­lem, we can use Resharper to help us solve it in this spe­cific case with NSub­sti­tute (or any other API, I'm using NSub­sti­tute as an exam­ple here).

For that, we'll write a Smart Tem­plate.

How to: writ­ing a Smart Template

Go to Resharper menu, and pick Tem­plates Explorer…

Make sure you're on the Live Tem­plates tab, and click New Tem­plate.

creating_template_1

For Short­cut select what­ever you want to appear in your code com­ple­tion for the tem­plate, for exam­ple NSub.

Select the tem­plate should be allowed in C# where expres­sion is allowed.

Check Refor­mat and Shorten qual­i­fied ref­er­ences check­boxes and pro­ceed to spec­i­fy­ing the tem­plate itself, as follows:

NSubstitute.Substitute.For<$type$>()

The $type$ is a tem­plate vari­able, and the grid on the right hand side allows us to asso­ciate 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.

creating_template_2

Result

Now your tem­plate will be avail­able in the code completion.

resharper_step1a

resharper_step2a

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

The main ben­e­fit though is not the key­strokes you save, but the fact there's almost no fric­tion to the process, so you don't get dis­tracted from think­ing about logic of your test.