Tomatoday

tomatoday logoAs mentioned in my previous post, my colleague Troels Richter is working on a Pomodoro application. What I did not say was that it is actually already available for people to try out – it’s called Tomatoday, it’s based on Silverlight 3 (SL4 version on the way), and it can be found at www.tomatoday.dk.

It consists of an online activity inventory and a simple timer application that is pretty nifty when run out-of-browser. It will of course be even niftier when it gets fully ported to Silverlight 4 when the timer gets to run in chrome-less out-of-browser mode.

If you try out the application, and you have suggestions or ideas, we will be very grateful if you submit them to Tomatoday’s forum at Uservoice.

Hot tomato sauce

pomodoro-techniqueAt Trifork where I work, one of the hot new things is The Pomodoro Technique, as it seems more and more of my colleagues are experimenting with it. If you don’t know anything about it, I can tell you (in my own words) that it’s a personal mini-process to make you more productive, thus more happy and fulfilled.

It goes like this (from www.pomodorotechnique.com):

  1. Choose a task to be accomplished
  2. Set the Pomodoro to 25 minutes (the Pomodoro is the timer)
  3. Work on the task until the Pomodoro rings, then put a check on your sheet of paper
  4. Take a short break (5 minutes is OK)
  5. Every 4 Pomodoros take a longer break

– where tasks are chosen from your “todo today”, which you assemble in the morning by picking tasks from your “activity inventory”. There’s a few more tricks in it, e.g. a form of notation that fits the process well and how to track disturbances.

Having done this for little more than one month, I think I can safely say that it is almost guaranteed to either

  • make you more productive
  • make you very conscious about why you’re not that productive

focus-boosterPractitioners of the technique usually prefer to use a real egg timer (in the shape of a tomato of course), because of the tactile feedback you get from actually manipulating a physical object – but as I am sitting in an open office with 6 other developers, and some of them are doing pomodoros as well, we are using the next best thing: a Pomodoro timer app.

Right now I am using the Focus Booster app, because it’s pretty and doesn’t take up that much space on the screen. One of my colleagues, Troels Richter, is currently working on a more complete Pomodoro app (in Silverlight) that will help in all the aspects of the Pomodoro Technique.

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

ReSharper 5 and ASP.NET MVC goodies

I have probably only scratched the surface of the goodies that JetBrains have added to the new ReSharper 5, but here’s two nifties I discovered today: F12 jumps from the redirect string to the corresponding action method in my controller (the light arrow), and F12 on a view result method gives me the ability to jump to the corresponding view (the gray arrow). That’ s just neat!

resharper_aspnet_mvc

Note to future self about R# and keyboard shortcuts

Did you ever sit with Visual Studio and R# writing tests, wondering if you could run tests without touching your mouse? I did that all the time, until I found out that you could go to Tools => Options => Environment => Keyboard and filter the list by “Resharper.Resharper_Unit”, giving access to keyboard shortcuts to run the current test context, debug the current test context + more.

resharper_keyboard_shorts

I have assigned Ctrl + Alt + Enter to run my current test context and Shift + Ctrl + Alt + Enter to run my current test session.

R# FTW

Recently I made a post because I was experiencing a moment of silent awe with R#.

R# 5 is on its way, and the feature list is impressive! I am excited about the call and value tracking features, because that’s basically all I do in one particular huge legacy system I am working on.

I am going to wait a few days, and then I will download one of the nightly builds and go check it out – I almost cannot wait!

Fluent NHibernate automapping and cascading

One of the things you usually end up wanting to configure on a case-to-case basis when using NHibernate is cascading – i.e. which relations should NHibernate take responsiblity for saving.

An example could be in DDD terms where you have an aggregate root, that contains some stuff. Let’s take an example with a Band which is the subject of the BandMember role, which in turn references another aggregate root, User, that is the object of the band member role.

It is OK for us that we need to save a User and a Band in a repository, that’s the idea when dealing with aggregate roots. But everything beneath an aggregate root should be automatically persisted, and the root should be capable of creating/deleting stuff beneath itself without any references to repositories and stuff like that.

So how do we do that with NHibernate? Well, it just so happens that NHibernate can be configured to cascade calls to save, delete, etc. through relations, thus allowing the aggregate root to logically “contain” its entities.

This is all fine and dandy, but when Fluent NHibernate is doing its automapping, we need to be able to give some hints when we want cascading to happen. I usually want to be pretty persistence ignorant, BUT sometimes I just want to be able to do stuff quickly and just get stuff done, so I usually end up “polluting” my domain model with a few attributes that give hints to a convention I use.

Consider this:

Notice that little [Cascade]-thingie in there? It’s implemented like this:

Trivial – but I want that to be spotted by Fluent NHibernate to make the BandMembers collection into a cascade="all-delete-orphan", which in turn will cause the methods AddBandMember and RemoveBandMember to be able to update the DB.

I do this with a CascadeConvention, which is my implementation of the IHasManyConvention and IReferenceConvention interfaces. It looks like this:

What is left now is to make sure Fluent NHibernate picks up my convention and uses it. I usually do this by throwing them into the same assembly as my entities and do something like this when configuring FNH:

– which will cause all conventions residing in the same assembly as EntityBase to be used.

This works really good for me, because it makes it really easy and quick to configure cascading where it’s needed – I don’t have to look deep into an .hbm.xml file somewhere or try to figure out how cascading might be configured somewhere else – the configuration is right where it’s relevant and needed.

Extremist PI-kinds-of-guys might not want to pollute their domain models with attributes, so they might want to use another way of specifying where cascading should be applied. Another approach I have tinkered with, is to let all my entities be subclasses of an appropariate base class – like e.g. AggregateRoot (implies no cascading), Aggregate (implies cascading), and Component (implies that the class is embedded in the entity).

The great thing about Fluent NHibernate is that it’s entirely up to you to decide what kind of intrusion offends you the least 🙂

Simple and pragmatic event bus with Castle Windsor

Almost always, when writing even the simplest of systems, the need arises for some kind of event publishing/subscription mechanism. There are of course many ways to achieve this, but I have found that Castle Windsor can provide everything that I need to build a simple, yet incredibly powerful event bus.

Consider this example from the real world: mortgage deeds follow many paths through our mortgage deed administration system, and one of them is purchase for the administrator’s own portfolio. Upon recording the purchase, it is crucial that the debtors are enlisted in our subscription at the Central Office Of Civil Registration (CPR in Danish), allowing us to receive updates whenever people change names or move without telling us.

A naive implementation of the Record method on the Purchase could look like this:

– but this is ugly! Enlisting the debtors has no direct relation to the logic of how to record a purchase, and when this requirement came, this implementation caused numerous tests to break. You could of course argue that our tests should not rely on the record method, but that was however the case, and it was a real P.I.T.A. to implement this.

Moreover, this approach forces us to grab our service locator inside a domain entity, which is really bad for too many reasons to mention here.

What we SHOULD have done, and what I have been doing ever since, is to create a simple event bus that resolves handlers to messages through Windsor (actually directly through the kernel because it is automatically injected). This way, I could have implemented the record method like this:

– and then this method would never change again (at least not for the wrong reasons)…

Then I have my simple event bus mediator (just an ounce of indirection, allowing my entities to be unaware of the service locator):

– which, depending on the bool inside the static EventBusConfiguration class, will be either a fake bus that swallows all its messages, or the real deal:

This means that subscribing to a message is as simple as registering implementations of this:

in my Windsor Container, e.g. the handler that enlists people in our subscription at the Central Office Of Civil Registration:

This is really cool, because it allows one to build systems where logic is deliciously decoupled, and you can add stuff, and then some more stuff, and the new stuff will not break the old stuff, because it doesn’t interfere with it.

Moreover, if you feel like extending it a little bit, it shouldn’t take that much of an effort to publish the events into a message queue for other systems to handle. If, for example, it took a while to process something, then I would definitely benefit from letting another process take care of that while my web request continues. Or if I wanted to update my data warehouse, I would build an aggregator in another process that did batch updates of the warehouse.

Oh, and this is one of the reasons that I would not hesitate to choose Castle Windsor if I were allowed to bring only one thing to a deserted island… you can build almost anything with a cool IoC container.

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