I’m on Mastodon – https://mastodon.au/@kko

Yes, I’ve hardly posted here in the last several years. I’ve been on Twitter since 2008, and in the early years it was complimentary to this blog, but over time more and more discussions migrated over there, from blog comments. It was more engaging, faster flowing and had a lower barrier of entry. It also allowed me to reach and interact with people who never read this blog.

With time, I got less and less active, but still used it daily (with some exceptions and detox periods) in a more passive form, relying heavily on its Lists feature (and TweetDeck client) and DMs.

It was (still is) a tool I value, and more precisely, I value the thoughts and information people who use it choose to share.

Lately, more and more of those people have been either abandoning it, getting kicked out, or at the very least creating a backup on another network, usually Mastodon.

So have I, at https://mastodon.au/@kko. My use remains largely unchanged and passive, but there is some of that vibe that early Twitter had

Writing better code reviews

In a distributed team, like ours, Pull Request reviews are one of the main ways we communicate about code. That makes it crucial they are clear, helpful, respectful, concise and actionable.

This tweet pointed me to https://conventionalcomments.org/ which is an interesting compendium of tips for how to make them so.

I’m not 100% sold of the rigidity it implies (I might have to use the approach for a while to form a stronger opinion), but even ignoring that part, it’s a good resource, so this post is really little more than a bookmark for me. However, as it might be useful to others, I decided to post it here.

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.
nancy_solution_structure
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"?>
<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 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)
    {
        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 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
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

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 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
{
    //stuff
}

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

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

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

DictionaryAdapter knows how to properly resolve prefixed values using KeyPrefixAttribute.

[KeyPrefix("smtp:")]
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:

[AppSettings("smtp:")]
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[]
		{
			context.RequestedType.GetGenericArguments().Single(),
			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())
	.LifestyleTransient());

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<>))
	.LifestyleTransient());

// 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 its 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))
	.LifestyleTransient());

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.