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).

Advertisements

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!

The Specification pattern using LinqSpecs

In my previous post about the Specification pattern I showed how the pattern works and how to implement it. I’ve also uploaded a sample project on Specification to GitHub. But my implementation suffers from a serious fallback: you cannot generate database queries using it, instead you have to pull everything into memory and iterate over that. Luckily you haven’t have to write and parse your own expression trees (although it could be a nice experience). There’s a nice library on CodePlex called LinqSpecs which does just that. Disclaimer: I have nothing to do with LinqSpecs and didn’t take part of its development. I just found it extremely useful so I thought I’d share it in my blog.

The LinqSpecs implementation is a little bit different than what I wrote. First it uses an abstract base class instead of an interface. Then it doesn’t use methods to concatenate the various specifications, instead it relies on overloading the logical operators. But the most important thing is that it doesn’t return a simple Boolean value whether or not your candidate satisfies the specification. It returns an expression instead. The method looks like as follows:

For me it was a bit unclear how to work with this, but here’s a concrete implementation:

And here’s how to use it in an arbitrary repository:

Since the specification returns an expression you don’t have to provide one in the Where extension method on the datacontext, so the syntax feels more right. One issue arises with unit testing, since testing the previous version was much more intuitive. I wouldn’t like to copy a discussion here, instead here’s a link from the project page on unit testing specifications.

The Specification Pattern

A recurring problem in my job is designing composite search forms. I guess it’s a fairly common scenario to receive a specification of a massive form with tons of checkboxes, textboxes and other UI controls for filtering your model. I knew there has to be a good way to do this, and I found the specification pattern which does just that.

Imagine your average repository :

It’s a barely testable, tightly coupled something which behaviour you cannot easily modify. It’s our starting point. We’ll have something like this when we finish:

The main concept of the pattern is to abstract away each search criteria into its dedicated class. The resulting classes then can be unit-testable, easily modifiable and even reusable. Reusability came very handy in my last project where I built a class for each search criteria then I just composed them in various ways to satisfy the business need.

The core of the specification pattern is an interface or an abstract class, depending on your personal taste, which looks like this:

This does nothing particular, just a generic interface with a single bool method taking a parameter of the type you want to filter. This is the absolute minimum you need to start working.

But the power of the pattern is that you can combine your classes with bool logic. A common choice is to have a base CompostieSpecification class, but if you have an abstract Specification class you can combine the two. CompositeSpecification looks like this in my example project:

Notice that it has three methods, And, Or and Not which returns concrete specification subclasses. Here’s how the AndSpecification class looks like, I’m pretty sure you’ll get the idea of the other two after this:

This was the abstract part of our implementation. You can find all of the above in my accompanying GitHub Specification sample project. They come fully covered with unit tests, too.

Now let’s look at our concrete person example. The sample project loads a bunch of randomly created person objects and lets you filter them by name, age and job title. Here’s the PersonNameSpecification implementation which is responsible for filtering by name:

The significant gain is that now you can unit test this search filter. I included a bunch of tests (the specifications themselves fully covered) so you can check out them.

In my sample project the creation of the specifications is the job of the SpecificationBuilder class, and it does a less than stellar job, and complicate things unnecessarily so I wouldn’t recommend that as a valuable example. This code fragment focuses on the pattern much better:

Specification is suited for otherwise complicated filtering, and typically a database is involved. In this case you’d prefer to use the IQueryable interface instead of IEnumerable and let your ORM build an optimal query instead of pulling everything into memory and filtering there. My sample isn’t suited for that, you’ll need additional work. You’ll need to build an expression tree from your specifications. Fortunately there’s a nice project on CodePlex called LinqSpecs which just does that. In my next post I’ll show you how to modify this example to work with it.

Sample project on Specification pattern

Today I spent the afternoon building a sample project to demonstrate the power of the Specification pattern. I’m not done yet, but I uploaded sample project on github. This pattern comes particularly handy if you have a lot of search conditions and you’d like to isolate them and make them testable.

About the implementation: ASP.NET MVC 3 running dependency injection on Castle Windsor. I didn’t take the time to include a database so I just created a fake Repository. I used a Façade for abstracting data access away, and there’s a Builder to create the appropriate specification objects based on user input. And user input is aggregated into a query object to enhance loose coupling.

And of course there’s a home-brew implementation of the Specification pattern and the project comes with pretty good test coverage, too. Note that I’d never recommend writing your own implementation, this project is for educational purposes only. In a following post I’ll describe the Good Way™ which I use in work.

The one thing that bothers me with this project is that I had the thought that having interfaces for every class is a nice example of YAGNI, so I only added one when it was absolutely needed. This lead to difficulties in testing and an awkward feeling working with these concrete classes. I guess that I’m yet to find the balance in this question.

So next week I’ll post how the Specification pattern is usable and how to implement it.

The Model-View-Presenter pattern

My job is to develop custom SharePoint solutions (mostly web parts with various business functionality). Since SharePoint doesn’t support ASP.NET MVC I need to work with WebForms. It’s a decent technology, but after working with MVC for years it’s a serious fallback. Fortunately there’s a pattern which helps you maintain clear separation of concerns and loose coupling which lends itself well for ASP.NET WebForms, the Model-View-Presenter pattern.

The main concept behind the pattern is that you have a model you need to work with in your UI, a view which is the UI and a presenter which glues these two together. It’s pretty similar to MVC. I’ve created a sample project and hosted it on GitHub, all the code in this post can be found there. Continue reading “The Model-View-Presenter pattern”

Decorator

“Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.”

Design Patterns: Elements of Reusable Object-Oriented Software

Imagine the time before fancy and automatic GUIs, and the case of a simple textview. Sometimes, we enter more information in it than it can show. The behavior which we are accustomed to in these cases is that suddenly a scrollbar will appear out of nowhere, and magic! we can scroll down to see the rest of the text entered. But do we always need that scrollbar? If we’d create a subclass for textview with the name TextViewWithScrollBar, and use it anyway, would it make sense?

No it wouldn’t, we’d only need those bars whenever we exceed the space given us within the textview. And we cannot see that fore. So what is the solution?

From the title, you can guess easily that it’s nothing else but the Decorator pattern. Notice the following: “Attach additional responsibilities to an object dynamically.”. Not a class, but an instance of a given class, the object. This is the key phrase here. But how can we achieve such behavior. The answer is simple, we need four players here:

  • Component: a very brief and lightweight interface for your objects that can have dynamic responsibilities (such as render a scrollbar).
  • ConcreteComponent: the object itself which implements Component.
  • Decorator: implements Component, and maintains a reference to a ConcreteComponent.
  • ConcreteDecotator: adds the dynamic responsibilities to ConcreteComponent, implements Decorator.

Now a code example for the above:

Continue reading “Decorator”