NServiceBus for dummies who want to be smarties 5

NServiceBus for dummies who want to be smarties 5… fifth post, this time with an example on how sagas can be used to implement a workflow in ASP.NET MVC.

One of the typical workflows in web applications is when someone signs up for an account, but the web site wants to check if the email address is valid. Let’s look at an example that goes like this:

  1. User enters email address as a signup request
  2. Web application sends email with a “secret” confirmation link
  3. User visits the secret link, thereby activating the account

To keep things simple, I have made a simple page containing two forms: one for the email address, and one that simulates visiting a secret link by letting us enter a “ticket”. The view looks like this:

And then I have made this simple controller to handle the posts from the registration page:

Now, to model this workflow we need some kind of persistence on our backend, which is where sagas come into the picture. Sagas is the built-in mechanism in NServiceBus that helps in building stateful services. Stateful services are, as the word implies, services that preserve some kind of state between receiving messages.

The NServiceBus saga is a nifty way to declare what that state should contain (by letting a class implement ISagaEntity) and – given a message that the saga can handle – how to retrieve that saga (by overriding ConfigureHowToFindSaga and setting up which properties to compare).

Lets start out by specifying that NServiceBus should take care of persisting the saga entity (which will by done through Fluent NHibernate/NHibernate/SQLite under the hood)… that can easily be achieved by changing our backend’s endpoint configuration to this:

This will make NServiceBus persist ongoing sagas in an SQLite db file called “NServiceBus.Sagas.sqlite” inside the backend’s execution directory. If you omit the NHibernateSagaPersisterWithSQLiteAndAutomaticSchemaGeneration() thing, NServiceBus will store ongoing sagas by using its InMemorySagaPersister, which – surprise! – stores sagas in memory.

I had some problems with the in-memory persister however, as I could not make it correlate messages with my saga unless I correlated with interned strings only, by implementing getters on my messages like so:

I imagine this has to do with a deserializer somewhere, somehow generating strings that are not interned, although I have not verified this – I am only guessing! No biggie though, as long as the SQLite saga persister is so easy to use.

In my example the saga is initiated by the RequestRegistration message which contains only an email. When the saga receives that message, the email is stored, and a secret ticket is generated, emailed to the user, and stored in the saga data. The saga is completed when it receives a ConfirmRegistration message with the right ticket.

Let’s specify what will constitute the saga data:

The first three properties come from the ISagaEntity interface – and then come my two properties for storing the email and the ticket.

Please do remember to mark all the properties of your saga data as virtual! Otherwise, Fluent NHibernate will throw some stupid exception, saying that “Database was not configured through Database method” (wtf?) (thanks to this post for sorting that one out!). The exception is fair though, as NHibernate would complain about not being able to create proxies if there were un-interceptable properties on the data class – the error message is just weird…

To create a saga, you let a class inherit from Saga&lt;TSagaEntity&gt; where TSagaEntity would be UserRegistrationSagaData in my example… and then we implement ISagaStartedBy<TMessage> and IMessageHandler<TMessage> where the two TMessage type parameters should be filled out with RequestRegistration and ConfirmRegistration respectively. Like so:

– and then – given the two kind of messages my saga can handle – how to correlate the messages with my saga:

Even though my saga is initiated by RequestRegistration, I set up a mapping that ensures that a new saga will not be created if someone requests registration twice with the same email.

Lastly, the actual logic carried out by the saga – the two message handlers (note that MailSender and NewUserService are application services that are automagically injected becuase they’re public properties of the saga):

Note how I mark the saga as complete by calling MarkAsComplete(), thus allowing the saga data to be deleted. This could also be a nifty place to save the time of when the last registration email was sent to a particular address in order to disallow sending another registration email for the next hour or so, to avoid people spamming each other by using our web site.

Now, if I fire up my backend and request registration with the email [email protected], it looks like this:

Submitting email as a registration request
The result on the backend showing that the message was properly received

Then, if I request registration with [email protected] followed by [email protected], I can verify that a new saga is only created for [email protected]:

Submitting the same email twice results in the same ticket being sent out

And then, when I confirm a registration request, it looks like this:

Submitting one of the 'secret' tickets
The result on the backend after having submitted on of the tickets

Isn’t that great? I cannot imagine a framework with an API more elegant and terse than this.

Conclusion

That was the fifth post in my “NServiceBus for dummies who want to be smarties” series. Sixth and last post will be about our backend publishing messages whenever interesting stuff happens. This will provide a message based interface for interested parties to subscribe to.

NServiceBus for dummies who want to be smarties 4

NServiceBus for dummies who want to be smarties 4… fourth post, this time on how to incorporate NServiceBus as a backend in an ASP.NET MVC application.

How to create the projects

First, create a new ASP.NET MVC project. I assume you know how to use an IoC container to instantiate controllers, and that you know how to configure your container (otherwise, there are plenty of information available – e.g. here and here), so I will just show this simple snippet on how to build the bus and put it in the container:

In Application_Start:

– and then the container can be created like this:

Notice the call to the extension method CastleWindsorBuilder? It comes from the assembly NServiceBus.ObjectBuilder.CastleWindsor.dll which is included with NServiceBus – it provides the adapters necessary for NServiceBus to a) register everything it discovers (like e.g. all your implementations of IHandleMessages&lt;&gt;), and b) pull instances when needed thus supplying dependencies during object activation. This way of supporting multiple IoC containers just plain ROCKS!

At this point NServiceBus has registered itself and registered all message handlers found in the current web application’s bin directory ( Configure.WithWeb() as opposed to Configure.With()) in the supplied IoC container, and since I am pulling all my controllers from Windsor, I can jump directly to implementing my HomeController:

As you can see, I implemented two actions responding to a HTTP post, both sending a message to the backend, but DoSomethingBad throws an exception, in which case i do not want the message to actually be sent.

My view is just a trivial (Spark) view with two forms:

And then I made a simple backend with one message handler:

Now, to check if things work, I navigate to /home/index, which on my computer looks like this:

dosomething

– and then I enter the text “WHEE!” into the first text field and press “Send”, yielding the following in my backend’s console window:

fantastic

Which is great! My backend receives messages from my web application, so now I can put all kinds of heavy calculations and processesing and whatnot in there, to be computed outside of web requests.

Now, what if something bad happens during the web request, and we do not want any messages to actually be sent? Well, if I enter a text into the other text field and submit it (to the DoSomethingBad action of my HomeController), nothing happens on the backend! Why is that?

Simply because I have started a TransactionScope in my controller layer supertype, TxBaseController, ensuring that all controller actions are run inside a (possibly distributed) transaction! It looks like this:

– and since message queueing plays along nicely with the currently ongoing ambient transaction (which e.g. the incredible NHibernate ALSO does), this transaction scope will make sure that everything just works!

Conclusion

That concludes today’s “NServiceBus for dummies who want to be smarties”. This one was on how to actually put NServiceBus to use as a simple backend for an ASP.NET MVC web application. Freaking easy, right?! Next time I will show how to put sagas to use by implementing one of the workflows of a typical web application.

Book review: ASP.NET MVC 1.0 Quickly

This book is exactly what its title says: a quick introduction to ASP.NET MVC. A natural implication is that it cannot cover that much material, and it seems Maarten went for breadth instead of depth.

In my opinion, when a book chooses to be a “quick guide”, it should focus more on showing the preferred ways to do stuff. Instead, this book seems to have too much ViewData["stuff"] = fluff going on. Why bother wasting pages showing all the tedious, error-prone, hard-to-maintain ways to do stuff when there is so little space?

asp.net.mvc.quickly.quickly

If I were to author a book on ASP.NET MVC, I would focus on explaining ASP.NET MVC from the extensibility points and out. For example, System.Web.Mvc.Controller is just one way to implement the IController interface, and so on. I think that would provide a much more wholistic image of the framework, and the extensibility points is where ASP.NET MVC shines. I don’t think Maarten’s book really shows where the framework shines.

I enjoyed the chapter on using existing ASP.NET features though, and, not being an ASP.NET guy at all, I think I learned some stuff there.

My conclusion is that this book is absolutely for beginners, and that the code samples in the book should not be taken literally, because almost none of them are examples on what the community considers best practice.

Title: ASP.NET MVC 1.0 Quickly
Author: Maarten Balliauw
ISBN 10/13: 184719754X / 978-1847197542
Publisher: Packt Publishing

My favorite ASP.NET MVC hooks #2: Action filter attributes

Another simple place to hook your stuff in to the framework is action filters. An action filter is an attribute that derives from ActionFilterAttribute which is a convenience class containing the following methods for you to override:

A lot of the examples around the internet show how to use action filters to restrict access to controller actions or how to apply caching. I won’t do that here, because those concerns are boring. No, we care about how to make life easy for ourselves and how to write testable, non-breakable, maintenance-and-wrist-friendly code. That is, we reserve the right to be lazy.

A fine example on how to be lazy is by letting action filters fetch data for you to avoid repetitive repository gymnastics in every controller action – and I am actually going to be very lazy right now, because I wrote two posts on this topic earlier:

  1. How to avoid duplicate data fecthing with ASP.NET MVC
  2. Another way to avoid duplicate data fetching with ASP.NET MVC

My favorite ASP.NET MVC hooks #1: Controller factory

My favorite hook in the ASP.NET MVC framework is the controller factory. I like it so much because it serves as a very simple entry point to the application, thus providing the perfect place to insert an IoC container. My container of choice is Castle Windsor – not because I have tried any other container – I really can’t say that I have – but because I just happened to be introduced by a colleague to Windsor, and I have yet to experience anything it can’t do for me!

An ASP.NET MVC controller factory is an implementation of the IControllerFactory interface – a simple interface with two methods: one that provides an IController given a string and some more stuff, and one that allows the controller to clean up any resources it might have allocated. The interface looks like this:

As you can see, it provides a means to return a controller, given all sorts of information about the current request and what could be resolved as the controllerName from the request URL.

ASP.NET MVC accesses the controller factory via the ControllerBuilder class – so if we want to provide our own controller factory, we must install the factory before any requests get served. An obvious place to do this, is the Application_Start method inside the global.asax.cs file. This way our controller factory will be installed every time the web application starts up.

The controller factory can be set in two ways: 1) By providing the type of the factory, and 2) By providing an instance of the factory. Then it’s up to you if you want to let ASP. NET MVC instantiate the factory. I usually do it like this:

– and let ASP.NET MVC instantiate and store a singleton instance of my factory.

My controller factory implementation looks like this:

Very simple. It takes the string, that was resolved as the controller name – e.g. “home”, “hOme”, “HOME” or whatever – and converts it to lower case, and then it uses that to look up a controller in my container. This means that all my controllers are registered in the container, and they will have all their dependencies automatically resolved when the container creates each instance.

A controller registration might look like this:

Simple – yet incredibly effective!

Respect your test code #2: Create base classes for your test fixtures

When writing code, I often end up introducing a layer supertype – i.e. a base class with functionality shared by all implementations in that particular layer in my application.

This also holds for my test code – and why shouldn’t it? Test code is as real as real code, so the same rules apply and it should benefit from the same pain killers as we implement in our application code.

For example when testing repositories and services that need to query the database, I can save myself a lot of writing by stuffing all the boring NHibernate push-ups in a DbTestFixture supertype – this includes building a configuration that connects to a test database, building a session factory, storing that session factory somewhere, re-creating the entire database schema in the test fixture setup, and running each test in a transaction that is automatically rolled back at the end of each test + a few convenience methods that allow me to flush the current session etc.

The DbTestFixture might look something like this (note that all my repositories take an instance of ISessionProvider in their ctor – that’s how they obtain the currently ongoing session, which is why I have a TestSessionProvider to inject into repositories under test):

Then a fictional repository test might look as simple as this:

Note how DbTestFixture flushes in all the right places so I don’t need to worry about that.

This test fixture supertype can be used for all my database access tests, as well as integration testing. But what about unit tests? I am using Rhino Mocks, so my unit test fixture base looks like this:

Real simple – it just stores my MockRepository and gives me a few shortcuts to the mocks I care for. Then I inherit this further to ease testing e.g. my ASP.NET MVC controllers like this:

As you can see, I make it a real “fixture” – the controllers I am about to test will fit into this fixture like a glove, and I will certainly never forget to instantiate my controller only once, because I start out by implemeting that part in the implementation of the CreateController method.

A controller test might look like this:

Another way to avoid duplicate data fetching with ASP.NET MVC

If you read my previous post and you thought to yourself: “but that’s a violation of DRY!”, then please stop whining right away!

If you – like me – like to make your dependencies explicit, you will probably think that it is perfectly fine to have to do the following things every time you want to have a piece of data automatically supplied for you:

  1. Apply the attribute to the action method (can be omitted if it has already been applied at the controller level)
  2. Change the signature of the action method
  3. Make sure the data makes its way into the view model handed to your view

In my opinion this is a fair compromise between avoiding writing code and still being explicit about what is going on.

If you, however, feel that there are too many steps above, and you want stuff to happen more automagically, you can do it in another way, that I find almost as attractive… first, create an interface to apply to all view models, that are capable of holding this piece of data – e.g. like this:

Then, make your page level view model implement this interface – from my previous example:

And then modify the action filter to fetch the data in OnActionExecuting and insert the view model for you in OnActionExecuted – like so:

This way, at most two things need to be done to automatically provide a piece of view data:

  1. Make the page level view model implement an appropriate interface (can be omitted if it already implements it)
  2. Apply the attribute to the action method (can be omitted if it has already been applied at the controller level)

It is definitely more DRY, but its lack of verbosity makes it harder to understand. And here, I don’t mean “understand” as in “haha, Mogens is too stupid to understand what is going on” – my point is that I will be wasting a few more brain cycles the next time I look at this action method while trying to figure out how it worked.

How to avoid duplicate data fecthing with ASP.NET MVC

One of the things I like about ASP.NET MVC is that there are so many ways to do everything. I.e. the framework is pretty un-opinionate. This, of course, can also be a serious drawback, because there will more bad snippets on the ‘net where people do ugly stuff in non-preferred ways. And sometimes it is hard to figure out if the way you’re doing something is actually the best for you.

In this post I would like to show a simple trick on how to avoid duplicate data fetching with ASP.NET MVC. That is, how can you avoid typing the same data fecthing logic in every controller action when a piece of data must be available to more than one action method.

In ASP.NET MVC it is actually very easy: use an action filter attribute, and have the filter load the data in the OnActionExecuting method. For example something like this (assuming that you have an ISessionContext that provides information about the currently logged-in user):

This way, if you apply this attribute at either the controller or the controller action level, a new action parameter will automatically be available for you to use. A simple example could be something like this:

By providing the data through the ActionParameters dictionary of the filter context, you can be explicit about which pieces of data will be available inside every controller action.

Working with Windsor and ASP.NET MVC

In the previous post I showed how easy it is to install an IoC container at the system boundary of your ASP.NET MVC application and have it resolve everything from there.

But what I did not show, was where the container came from – in the example, the container just pops out of nowhere on this line:

So how can we implement GetContainerInstanceFromSomewhere()?

Well, I like to do it like this:

Isn’t that easy? And then I have a folder structure in my ASP.NET MVC project that looks like this:

config-folder

It can be seen that I have a folder for each configuration of the system (development, test, prod) and one containing configuration files that are common for all configurations. For each configuration I have a hibernate.cfg.xml to configure NHibernate and a windsor.config which is loaded by the Windsor container in each particular configuration.

My development/windsor.config looks like this:

It can be seen that my development configuration is used to Cassini running on port 1766 🙂 moreover, it can be seen that my development configuration is using a fake, logging email sender, which – much as you would expect – only logs the content from emails that would otherwise have been sent.

Of course, the configuration files will not automatically be available to the web application the way they are organized now – therefore, my web project has a post-build task with the following two lines:

– thus copying the common configuration files along with the development configuration files to the base directory of the web application.

This also means that my build script must overwrite the development configuration files when building the system in a deployment configuration. It can be achieved as simple as this (using MSBuild):

Here I have define tasks for compiling the web site (“build”), deploying the binaries + views + content files (“deploy”), deploying common configuration files (“deploy_common_configuration_files”), and then one task for each deployable configuration: “deploy_test” and “deploy_prod”. This makes deploying the web site on my test web server as easy as running the following command:

What is left now, is to make sure that the different sets of configuration files are valid in the sense that Windsor can resolve everything right. That is easily accomplished in the following NUnit test:

This way, if I introduce a service in my development configuration that should have been implemented by a production version of the service in my production configuration, I will immediately know about it.

I think this post covers an easy and pragmatic way to control multiple configurations with Windsor and ASP.NET MVC. Of course you might want to split out the configuration-specific parts into multiple files instead of having only a windsor.config for each configuration. What I mean is something like this:

The great thing is that we can refactor our configuration with confidence because of our test. And if we want to be extra-certain that everything works as expect, we might begin to add assertions like this: