ASP.NET Localization using the Strategy Pattern

Ever wondered how to do pluggable and testable language selection using ASP.NET? Since I’m in a pattern-happy mood I thought I’d implement this using the Strategy design pattern.

My goal with this was to retrieve the culture’s name in which the user would like to see the webpage. This can come from two sources (in my case): the Accept-Language HTTP header and a custom cookie I send to the user when he/she clicks on my  little flags. So the first thing is to define an interface for our strategy:

Let’s see what do we have here. This interface has two methods and a property. I think GetCultureName is obvious, this is why we do this in the first place, it’ll return the culture’s name as a string. IsApplicable is slightly more interesting from a reusability perspective. You see we’ll have to find out if our algorithm is usable at runtime (e.g. the Accept-Language header exists and it isn’t empty, or we have our cookie in the request).  This method will tell us if we could use the current implementation. I’ll give more details right away. Cardinality tells us the order of the algorithms. We can set only one culture to use, and it’s possible that there are more algorithms that can be used on a request, and we need to determine an order in which we’d use them. So if there are more strategies that are applicable, we select the one with the highest cardinality.

So now we need to define the implementations. I’ll provide three: one for cookies, one for the Accept-Language header and a fallback, mostly static strategy if neither of the previous ones are usable. So here they come:

Above is the cookie implementation. As you can see it depends on the ICookieStorage interface, which is just a wrapper around HttpContext’s cookie operations, to help unit testing. I’ll left it as an exercise for you 🙂

Our next implementation is for the Accept-Language header, again there’s a dependency which just uses HttpContext, and again for testing reasons. The concrete algorithm that selects the first language from the list can be improved, but that’s enough for my purposes.

And as I promised, our static fallback strategy. It doesn’t require much explanation, it just covers the case when no other strategy is usable. Of course I could just throw an exception and leave the culture as the default one, but it’s much cleaner this way (as I believe).

OK, the strategies are ready, but they won’t do anything useful without someone to employ them. In a moment you’ll understand why IsApplicable was needed so badly. Here’s the class that does the coordination:

Now a little fact about strategy: it lets you select an implementation of an algorithm at runtime. It ain’t  gonna select itself. A while ago I used to write Factories for this purpose. You could imagine how nice a LocalizationStrategyFactory looks like and what it does. But I read an article somewhere (sorry, I’ve forgotten it and can’t give credit where it belongs), which said that strategies can tell themselves if they’re any good in a case. And that’s exactly what the IsApplicable method does. Basically my DI container (Castle Windsor) resolves all implementations of the ILocalizationStrategy to an array, then with the simplest of LINQ commands I select the first algorithm with the highest cardinality to do the job. And that’s all, simple, clean and last but not least, testable.

Last thing to do is to set the whole thing up in global_asax. Just hook into Application_BeginRequest, and pass the resolved CultureInfo to CultureInfo.DefaultThreadCurrentUICulture (or Thread.CurrentThread.CurrentUICulture, if you are below .NET 4.5).

AD searching and the Template Method design pattern

A while back I had the funny task to obtain users from the AD and do present them in a neatly designed list. Since neatly organized employee lists hold a certain coolness factor, soon other departments grew jealous and wanted peeking their own employees, only with more info available and more neatly organized.

Now nothing holds more fun to the everyday developer than maintaining classes that does the same thing, only in a slightly different way. So I thought the logic can be made reusable, and by employing the magic of generics combined with the template method design pattern, the soon-to-come new departments needing slightly different info for their neatly organized employee lists could be taken care very fast.

So what is a template method and how does it work? Template method is just a fancy name for a method that your base class will call, and you can override its implementation in subclasses. I created a sample project and pushed it to GitHub, so let’s review what’s in there.

The gist of the template method is found in the class ADUserFinderAbstract<T>. Here’s how it’s looks like:

As you see, there’s a method called GetUser which goes into the AD and try to find a user. Then it calls an abstract method in the same class, called convertPrincipal, and passes the found user (or null, to be entirely correct) to this method. You can easily guess what is the point of this whole thing: override the abstract method in a subclass, and provide different implementations depending on various business needs. That’s what is done in the solution.

There are two implementations, one (EmailADUserFinder) simply returns the e-mail address of the user, the other (ComplexADUserFinder) does a lot more work, and tries to load department information, too.

And why go generic? In this particular business case, a generic implementation was more than ideal. I could map to the UserPrincipal object whatever entity I wanted, and do work with that. But template methods doesn’t necessary have to be generic methods of course. It only grants more power in this case.

I hope you’ll find this post useful, don’t forget to check out the GitHub project again!