Sunday, February 21, 2010

The next Brighton ALT.NET Beers will be held at the co-working venue ‘The Skiff’ at 7.00 pm on Tuesday 2nd of March. I’ll be hosting again, but our great leader, Mr Iain Holder, should be able to join us later.

If, like me, you spend a fair amount of time playing with various security setups, you’ll be quite fed up with using makecert or OpenSSL and the IIS certificate management UI to create and install self-cert x.509 certificates.

But help is at hand. I recently discovered a useful little tool for generating x.509 certificates. It’s called ‘self-cert’ and it’s written by Keith Brown of Pluralsight. It’s pretty basic and doesn’t give you the control over your certificate that OpenSSL provides, but it does automatically install the certificate in the Windows certificate store which is a great benefit.

Keith has included all the source code for self-cert in the zip file including a nicely factored certificate creation library that wraps the Win32 crypto API. This means that you can easily create certificates programmatically:

Here I’m using Keith’s CryptContext class to create an x.509 certificate and then I’m storing the certificate in the local machine’s certificate store.

I’m doing a fair amount of research into federated security and WIF for one of my clients at the moment, so I’m finding more about x.509 than perhaps I wanted to. This tool has been very useful for quickly putting together prototypes. I’ll be posting some more stuff on this soon.

Thursday, February 18, 2010

I’ve covered this before on this blog, but it was a while back and it’s such a neat trick that I don’t feel too bad about repeating myself. The NamingPartsSubsystem allows you to resolve components based on attributes. The attributes themselves are defined as part of the component’s name, so for example, we could have a component with a name like “thing:colour=red,version=2” and then resolve it by asking for a component with id “thing:colour=red”.

The name should match the following syntax:

<name>:<key 1>=<value 1>[,<key n>=<value n>]

Let’s say we define an interface and a number of classes that implement it:

OK, so now we have four different implementations of IThingy some red some blue, some version 1 and some version 2. Now if we just ask for a ‘thing’ we will get Thing1 since that was the first component named ‘thing:…’ that was registered:

Friday, February 12, 2010

Do you have an ASP.NET application? Do you want to record any errors it might throw? Do you want an easy way to view the errors and possibly get them emailed, or even tweeted to you? Look no further ….

ELMAH stands for ‘Error Logging Modules and Handlers’. It’s an incredibly easy to use but full featured set of error logging bolt-on bits for ASP.NET. The committers list on the project page reads like a who’s who of .NET, so you can’t argue that it’s not well supported. The documentation is pretty good so I’m not going to try and give a blow-by-blow account of how to set it up, I just want to show how I’ve used it in Suteki Shop and how easy and simple it is to get up and running.

The first thing to note about ELMAH is that it requires zero change to your application’s code base. The only thing you might want to do is remove any existing error loggin. In fact the best application to use ELMAH with, is one where errors are simply allowed to bubble up to the ‘yellow screen of death’. Don’t forget: The first rule of exception handling: do not do exception handling.

In Suteki Shop I’d previously used the MVC Framework’s default Rescue behaviour, so the only real code change I made was to remove the [Rescue("Default")] attribute from my ControllerBase class. I also had to add the ELMAH assembly to my dependencies folder. But most of the work consists of changes to Web.config.

First I added a new config section, then the ELMAH UI endpoint httpHandler that shows the error log. This is so I can type http://sutekishop.co.uk/elmah/elmah.axd and view any errors that Suteki Shop may throw (no it won’t work for you):

Update: I was contacted by Phil Haselden shortly after I wrote this post, pointing me to this stack overflow answer:
http://stackoverflow.com/questions/1245364/securing-elmah-in-asp-net-websiteYou need to secure the path to ‘elmah.axd’ by making it a child of a ‘virtual’ directory, which in my case I’ve named ‘elmah’, and then only allowing admin users access to that directory. If you don’t do this and simply secure ‘elmah.axd’, it’s possible for a user to view your ELMAH page with a URL like http://sutekishop.co.uk/xxx/elmah.axd. I’ve updated this post now, so if you follow these instructions you should be fine.

Next I added the ELMAH modules I required. I wanted to receive error notifications as tweets so I needed the core error log and the ErrorTweetModule:

You have to specify where you want the log to be stored - you can choose to put the log in a database, but I’m happy to have it written to an xml file in App_Data. I’ve also configured that I want to allow remote access so that I can view the log remotely.

To configure the twitter client I simply created a twitter account named ‘sutekishop’ and specified its user name, password and the format of the error message I want to send. Here I’m sending myself DMs of any error.

Lastly I configured the standard ASP.NET security so that only the admin account on suteki shop is able to view the elmah.axd page:

This means that if you try browsing to http://sutekishop.co.uk/elmah.axd you’ll be thrown back to the login page. If you could login as the administrator you would see this page:

Hmm, looks like a robot’s been doing some fishing and a user who’s session has expired is trying to go back and view their order. I probably shouldn’t throw for that, but return a nice information page instead.

The great thing is that I also get all these errors as tweets as well:

ELMAH is just so easy to configure and so easy to use that it seems the obvious first choice for error logging in any ASP.NET application.

Tuesday, February 09, 2010

Have you noticed how I keep on putting off the WCF facility? It will come, I’m just waiting until I’ve got the time to do it justice. Instead, today’s trick is a nice easy one: type forwarding. This simply means that you can have a single component satisfy many services. As an example, say we have three interfaces:

Since SrpViolator is registered without specifying a lifestyle, it will have the default lifestyle: singleton. That means that ‘thing’, ‘widget’ and ‘wonder’ from the code snippet above are all the same instance of SrpViolator.

Type forwarding can be very useful, but note that the Single Responsibility Principle means that it’s generally considered bad practice to have a single class play many different roles.

Sunday, February 07, 2010

This trick follows on nicely from trick number 9, ‘Configuring fluently registered components with XML’. Sometimes you might want a configuration value other than a simple string or integer. Windsor provides the ITypeConverter interface that you can implement to supply complex configuration for your components.

As an example, let’s imagine we have a class, HealthMonitor, that pings a series to endpoints and checks that a particular string is returned before a timeout. We want to configure HealthMonitor with an array of HealthEnpoints that specify a URL, an expected string value and a timeout in seconds. Something like this:

Note that we want to use the standard Windsor configuration to say that the ‘healthEndpoints’ constructor parameter is made up of an array and each element of that array is described by ‘item’. We get that without doing anything special.

However, we do need some way of telling Windsor that when a component has a HealthMonitor dependency it should read a ‘url’, ‘expect’ and ‘timeoutSeconds’ value from the configuration and then construct a HealthEndpoint. We do that with a type converter.

We implement AbstractTypeConverter which provides us with some plumbing and implement three methods: ‘CanHandleType’ which tells Windsor which type(s) we are interested in; and two overloads of ‘PerformConversion’, one that takes a string and a target type and one that takes the current configuration section and a target type. Since we want to interpret the current configuration of each ‘item’ we’ll implement the second ‘PerformConversion’ method.

I’ve got a simple internal class ‘Converter’ that keeps track of child nodes of the ‘item’ node and the current context. It simply looks up each required property and converts it to a target type. Once we have our ‘url’, ‘expect’ and ‘timeoutSeconds’ values we construct and return a new HealthEndpoint. Note that we use Windsor’s built-in type converters for the simple target types: ‘context.Composition.PerformConversion’.

Wiring the type converter with Windsor is not obvious. You have to grab Windsor’s ConversionManager sub-system and add the new type converter to that. You could wrap that step with a facility, but there’s also a nice extension point, IWindsorInstaller, that you can also use to wrap up complex setup pieces:

This is pretty simple example, but it’s possible to use type converters for some sophisticated configuration setups. Say you wanted to take some string value and parse it into a configuration class or maybe provide some kind of polymorphic configuration, all this can be done with a type converter.

OK, so that was trick 10, but don’t go away I’ve still got plenty more in the bag. Perhaps I should have used Scott Hanselman’s ‘… of an infinite series’ formula, but I quite like the fact that from now I’ll be over-delivering :)

Thursday, February 04, 2010

Did you know that you can mix fluent and XML configuration for the same component. I’m not the only one who thinks XML component registration is a verbose pit of failure. But there are some things you really do not want to hard code into your application. Things like connection strings, the location of resources on the network and other deployment specific settings. Windsor provides a very nice story for setting property values on your components using an XML file without having to fall back on the awful appSettings or defining your own custom ConfigurationSection. Here’s how it’s done:

Let’s say we have a class ConfigurationThing with some string properties for configuring a database connection:

Notice that we’re also including registration configuration from the file windsor.config. Also note that we give our IConfigurationThing service a name: ‘configuration’. Now in the windsor.config file we can configure the properties of ‘configuration’ by referencing it’s name – except that in the config file it’s confusingly called ‘id’:

This is exactly the same as the standard XML component registration, except that we don’t specify the ‘service’ and ‘type’ attributes of the component. Windsor simply looks for a component registered with the same ‘id’… or rather ‘name’.

Now when we resolve our IConfigurationThing its properties are set to the values we specified in windsor.config:

Because Server, Database, User and Password are properties rather than constructor arguments, the component resolution will not fail if they are not supplied, instead they will all be null. This can be a nice feature if you want to supply default arguments that can be overridden by configuration.

I use this technique a lot. Configuration is one of those unexpected benefits of using Windsor.

Wednesday, February 03, 2010

A frequent complaint people have when they first get to grips with IoC Containers is that they find it hard to tell how their application composes at runtime. What’s needed is a clear description of the tree of dependencies in your application. This dependency ‘graph’ is built at registration time and Windsor exposes its dependency graph via the GraphNodes collection on the Kernel. The following class recursively walks down the GraphNodes tree and outputs the application’s complete component graph: