NHibernate is very flexible

…but it does impose limitations on your domain model.

Most of these limitations, however, like the need for public/internal/protected members to be virtual, and the requirement for a default constructor to exist with at least protected accessibility, are not that hard to adhere to and usually don’t interfere with what you would do if there were no rules at all.

One of the limitations, however, can be pretty significant – Ayende describes the problem here, using the term “ghost objects”.

But, as I am about to show, this significance only arises if you follow a certain style of coding, which you should usually avoid!

Short explanation of the problem

When NHibernate lazy-loads an entity from the db (i.e. when you call session.Load<TEntity>(id) or when an entity in your session references something through a lazy-loaded association), it does so by providing an instance of a runtime-generated type, which acts as a proxy.

The first time you access something on the proxy, it gets “hydrated”, which is just a fancy way of saying that the data will be loaded from the database.

This would be fine and dandy, if it weren’t for the fact that the proxy is a runtime-generated subclass of your entity, which – in cases where inheritance is involved – will be a sibling to the other derived classes. Consider the simple inheritance hierarchy on the sketch to the right which in code could be something like so:

public abstract class LegalEntity
{
    public virtual Guid Id { get; set; }
}
 
public class Person : LegalEntity
{
    public virtual string FirstNames { get; set; }
    public virtual string LastName { get; set; }
}
 
public class Company : LegalEntity
{
    public virtual string CompanyName { get; set; }
}

- and then NHibernate will generate something along the lines of this (fake :) ) class signature:

public class LegalEntityProxy1234AndSomeMoreStuff : LegalEntity
{
   // ... secret stuff to access db in here
}

See the problem? Here’s the problem:

var legalEntity = session.Load<LegalEntity>(someKnownId);
Assert.IsTrue(legalEntity is Person
              || legalEntity is Company);  //< AssertionException! will never be Person or Company

This means that this kind of runtime type checking will fail in those circumstances where the entity is a lazy-loaded reference of the supertype, and the following will FAIL:

var legalEntity = session.Load<LegalEntity>(someKnownId);
if (legalEntity is Person)
{
    var person = (Person) legalEntity;
    return person.FirstNames + " " + person.LastName;
}
else
{
    // we know it's a company then, right? WRONG!
    var company = (Company) legalEntity;  //< InvalidCastException!
    return company.CompanyName;
}
One possible solution

The other day, Ayende blogged about a recent addition to NHibernate, namely lazy-loaded properties. This allows an entity to be partially hydrated, intercepting calls to certain properties to lazy-load the relevant fields on demand.

This feature is great when storing LOBs alongside the other fields on an entity, but it also laid the ground for his most recent addition, which is the ability to lazy-load an association by setting lazy="no-proxy" on it.

This way, NHibernate will not build a proxy, but instead it will intercept the property getter and load the entity at that point in time, thus being able to return the exact (sub)type of the loaded entity.

Now this seems to solve our problems, but let’s zoom out a bit … why did we have a problem in the first place? Our problem was actually that we failed to write object-oriented code, but instead we wrote a brittle piece of code that would fail at runtime whenever someone added a new subtype, thus violating the Liskov substitution principle. Moreover it just feels wrong to implement business logic that reflects on types!

What to do then?

Well, how about making your code polymorphic? The logic above could be easily rewritten as:

public abstract class LegalEntity
{
    public virtual Guid Id { get; set; }
 
    public abstract string Name { get; }
}
 
public class Person : LegalEntity
{
    public virtual string FirstNames { get; set; }
    public virtual string LastName { get; set; }
 
    public override string Name
    {
        get { return FirstNames + " " + LastName; }
    }
}
 
public class Company : LegalEntity
{
    public virtual string CompanyName { get; set; }
 
    public override string Name
    {
        get { return CompanyName; }
    }
}

- which moves the logic of yielding name as a oneliner into the class hierarchy, allowing us to always get a name from a LegalEntity.

What if I really really need a concrete instance?

Then you should use the nifty visitor pattern to extract what you need. In the example above, I would need to add the following additions:

public interface ILegalEntityVisitor
{
    void Visit(Person person);
    void Visit(Company company);
}
 
public abstract class LegalEntity
{
    // ...
 
    public abstract void Accept(ILegalEntityVisitor visitor);
}
 
public class Person : LegalEntity
{
    // ...
 
    public override void Accept(ILegalEntityVisitor visitor)
    {
        visitor.Visit(this);
    }
}
 
public class Company : LegalEntity
{
    // ...
 
    public override void Accept(ILegalEntityVisitor visitor)
    {
        visitor.Visit(this);
    }
}

This way, we’re taking advantage of the fact the each subclass knows its own concrete instance, thus allowing it to pass itself to the visitor we passed in.

This is the preferred solution when the logic you’re writing doesn’t belong inside the actual entitiy class, like e.g. when you want to convert the entity to an editable view object, because this will make your code break at compile time if someone adds a new specialization, thus requiring each piece of logic to handle that specialization as well.

Oh, and if you’re a Java guy, you might be missing the ability to create an inline anonymous visitor withing the scope of the current method, but that can be easily emulated by a generic visitor, like so:

public class LegalEntityVisitor : ILegalEntityVisitor
{
    Action<Person> handlePerson;
    Action<Company> handleCompany;
 
    public LegalEntityVisitor(Action<Person> handlePerson, Action<Company> handleCompany)
    {
        this.handlePerson = handlePerson;
        this.handleCompany = handleCompany;
    }
 
    public void Visit(Person person)
    {
        handlePerson(person);
    }
 
    public void Visit(Company company)
    {
        handleCompany(company);
    }
}

- which would allow you to write inline typesafe code like this:

double risk = CalculateInitialRisk();
 
// multiply some number depending on type of legal entity
legalEntity.Visit(new LegalEntityVisitor(person => risk *= GetRiskExperienceForPeople(),
                                         company => risk *= GetRiskExperienceForCompany(company));

Only thing missing now is the ability to return a value in one line depending on the subclass. Well, the generic visitor can be used for that as well by adding the following:

 
public class LegalEntityVisitor : ILegalEntityVisitor
{
    // ...
 
    public static TResult Func<TResult>(LegalEntity legalEntity, 
                                        Func<Person, TResult> handlePerson, 
                                        Func<Company, TResult> handleCompany)
    {
        TResult result = default(TResult);
 
        legalEntity.Visit(new LegalEntityVisitor(p => result = handlePerson(p),
                                                 c => result = handleCompany(c)));
 
        return result;
    }
}

- allowing you to write code like this:

 
public string GetReportTypeCodeFor(LegalEntity legalEntity)
{
    return LegalEntityVisitor.Func(legalEntity, p => "P00000", c => "C" + GetReportingCode(c));
}

- and still have the benefit of compile-time safety that all specializations have been handled.

When to reflect on types?

IMO you should only reflect on types in business login when it’s a shortcut that doesn’t break the semantics of your code. What do I mean by that? Well, e.g. the implementation of the extension method System.Linq.Enumerable.Count() looks something like this:

public int Count<T>(this IEnumerale<T> items)
{
    if (items is ICollection<T>)
    {
        return ((ICollection<T>)items).Count;
    }
 
    var count = 0;
    // iterate and count manually
 
    return count;
}

This way, providing the number of items is accelerated for certain implementations of IEnumerable<T> because the information is already there, and for other types there’s no way to avoid manually counting.

Conclusion

I don’t think I will be using the new lazy="no-proxy" feature, because if I need it, I think it is a sign that my design has a bad smell to it, and I should either go for polymorphism or using a visitor.

Leave the first comment

When jQuery was released…

…web development changed forever! (to me at least :) )

It’s amazing how the CSS-selector-based approach has proven its effectiveness and durability, and combined with the incredible wealth of extensions, choosing jQuery is simply a no-brainer.

By the way, jQuery 1.4 has been released. Check out this post for a walkthrough of some of the new features.

Leave the first comment

C# vs. Clojure vs. Ruby & Scala

Short preface: at a job interview, Zach Cox was told to aggregate words and word counts from a bunch of files into two files, sorted alphabetically and by word count respectively, which he did in Ruby and Scala. This led Lau Bjørn Jensen to do the same thing in Clojure, which apparantly sparked other people to do it in Java, Python etc.

Inspired by the aforementioned problem, and an extended train ride home (thank you, Danish National Railways!!), I decided to see what a C# (v. 3) version could look like:

namespace NewsReader
{
  using System;
  using System.IO;
  using System.Linq;
  using System.Text.RegularExpressions;
 
  class Program
  {
    static void Main()
    {
      const string dir = @"c:\temp\20_newsgroups";
      var stopwatch = System.Diagnostics.Stopwatch.StartNew();
      var regex = new Regex(@"\w+", RegexOptions.Compiled);
 
      var list = (from filename in Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
                  from match in regex.Matches(File.ReadAllText(filename).ToLower()).Cast<Match>()
                  let word = match.Value
                  group word by word
                  into aggregate
                    select new
                             {
                               Word = aggregate.Key,
                               Count = aggregate.Count()  ,
                               Text = string.Format("{0}\t{1}", aggregate.Key, aggregate.Count())
                             })
        .ToList();
 
      File.WriteAllLines(@"c:\temp\words-ordered-by-count.txt", list.OrderBy(c => c.Count).Select(c => c.Text).ToArray());
      File.WriteAllLines(@"c:\temp\words-ordered-by-word.txt", list.OrderBy(c => c.Word).Select(c => c.Text).ToArray());
 
      Console.WriteLine("Elapsed: {0:0.0} seconds", stopwatch.Elapsed.TotalSeconds);
    }
  }
}

Weighing in at 35 lines and executing in 10.2 seconds (on my Intel Core 2 laptop with 4 GB RAM), I think this is a pretty clear and performant alternative to the other languages mentioned.

2 comments so far, add yours

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.

One comment so far, add another

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.

One comment so far, add another

NServiceBus for dummies who want to be smarties 6

NServiceBus for dummies who want to be smarties 6… sixth and last post in the series will show an example using the publish/subscribe functionality provided by NServiceBus.

One could image all kinds of cool integration scenarios where interested parties somehow receive events from our system regarding stuff that may be interesting to them. Let’s imagine that our user registration from the fifth post is an extremely interesting event to the sales department and the Über Boss of our enterprise.

To accomodate this, I create a separate assembly meant for holding messages that are not private to our application. This way, I can easily distinguish between messages that I can change whenever I feel like it, and messages that I must put more care and effort into crafting, because they will most likely live forever when a dozen applications in our enterprise are suddenly depending on them.

This means that my saga from the fifth post will handle an email confirmation like this:

    public void Handle(ConfirmRegistration message)
    {
      Console.WriteLine("Confirming email {0}", Data.Email);
 
      NewUserService.CreateNewUserAccount(Data.Email);
 
      MailSender.Send(Data.Email,
                      "Your registration request",
                      "Your email has been confirmed, and your user account has been created");
 
      Bus.Publish(new SomeoneActuallyRegistered {Email = Data.Email});
 
      MarkAsComplete();
    }

As you can see, I Bus.Publish(...) a message saying that someone with a particular email has registered.

To be able to publish stuff, some kind of subscription storage must be configure for the endpoint. Therefore, I change my backend’s EndpointConfig to be configured with this:

      Configure.With()
        .CastleWindsorBuilder(container)
        .Sagas()
        .NHibernateSagaPersisterWithSQLiteAndAutomaticSchemaGeneration()
        .MsmqSubscriptionStorage()
        .XmlSerializer();

- which means my backend will be storing subscriptions in a message queue.

If you are somehow unclear on the difference between sending and publishing, I can tell you that the conceptual difference is this: sending is like saying “do this stuff”, whereas publishing is like saying “this stuff happened” – see the difference in tense?

Functionally, the difference is that sending will put a message in the queue specified as recipient for that particular message whereafter one recipient will consume that message off its input queue (possibly competing with others), whereas publishing will put a message in the input queue of each one of whoever subscribed to that particular message (possibly many – possibly zero).

Now, to simulate the sales department and the über boss, I create two new projects containing an app.config that looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core" />
    <section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core" />
  </configSections>
 
  <MsmqTransportConfig InputQueue="salesDept"
                       ErrorQueue="error"
                       NumberOfWorkerThreads="1"
                       MaxRetries="5" />
 
  <UnicastBusConfig>
    <MessageEndpointMappings>
      <add Messages="PublicMessages" Endpoint="backend" />
    </MessageEndpointMappings>
  </UnicastBusConfig>
</configuration>

- and similarly for the über boss.

Note how a subscriber must have a message endpoint mapping telling where messages will be published – in the example above, my mapping specifies that all messages from my PublicMessages assembly can be subscribe to on the endpoint named “backend”. And obviously, a subscriber must have an input queue, through which subscribed messages will be received.

The EndpointConfig can look like this:

namespace SalesDept
{
  public class EndpointConfig : 
    IConfigureThisEndpoint, 
    AsA_Server, 
    IWantCustomLogging, 
    IWantToRunAtStartup
  {
    public IBus Bus { get; set; }
 
    public void Init()
    {
    }
 
    public void Run()
    {
      Bus.Subscribe<SomeoneActuallyRegistered>();
 
      Console.WriteLine("Sales department running...");
    }
 
    public void Stop()
    {
    }
  }
}

- and similarly for the über boss as well.

Note how the service subscribes to the messages that it wants to receive by calling Bus.Subscribe<...> in the Run() method. What happens, is that NServiceBus somehow communicates to whoever is configured as the publisher of messages of type SomeoneActuallyRegistered, that messages should be sent to this service’s input queue.

And then, I implement a message hander in each service… first, the sales department:

namespace SalesDept
{
  public class SendInformationAboutProducts : IMessageHandler<SomeoneActuallyRegistered>
  {
    public void Handle(SomeoneActuallyRegistered message)
    {
      Console.WriteLine("Sending stupid emails to {0}", message.Email);
    }
  }
}

and then, the über boss:

namespace ÜberBoss
{
  public class NoteEmailInLittleBlackBookOfEvilSchemes : IMessageHandler<SomeoneActuallyRegistered>
  {
    public void Handle(SomeoneActuallyRegistered message)
    {
      Console.WriteLine("Noting email {0}", message.Email);
    }
  }
}

To make this run, I go to “Set StartUp projects…” of my solution and make all my services start up when I press F5.

Picture showing how to configure multiple startup projects

Now, we can check things out by pressing F5, thus running the backend, the sales department, and the über boss at once. On my machine, it looks like this:

Running three services at once

Now it doesn’t take too much imagination to come up with all kinds of cool solutions to integration scenarios.

Conclusion

That concludes the sixth and last post in my “NServiceBus for dummies who want to be smarties” series. I hope the series can provide some information on how to get started using NServiceBus, and perhaps fill out some of the gaps that comes from documentation in the form of sparsely available blog posts from different sources.

Comments Off

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:

<p>
  Enter your email address to begin registration
</p>
 
<form method="post" action="!{Url.Action("BeginRegistration")}">
  Email: <input name="email" type="text" />
  <input type="submit" value="Begin registration" />
</form>
 
<p>
  - or enter your ticket to confirm your email
</p>
 
<form method="post" action="!{Url.Action("ConfirmRegistration")}">
  Ticket: <input name="ticket" type="text" />
  <input type="submit" value="Confirm registration" />
</form>

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

  public class RegistrationController : TxBaseController
  {
    readonly IBus bus;
 
    public RegistrationController(IBus bus)
    {
      this.bus = bus;
    }
 
    public ViewResult Index()
    {
      return View();
    }
 
    public RedirectToRouteResult BeginRegistration(string email)
    {
      bus.Send(new RequestRegistration {Email = email});
 
      return RedirectToAction("Index");
    }
 
    public RedirectToRouteResult ConfirmRegistration(int ticket)
    {
      bus.Send(new ConfirmRegistration {Ticket = ticket});
 
      return RedirectToAction("Index");
    }
  }

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:

      Configure.With()
        .CastleWindsorBuilder(container)
        .Sagas()
        .NHibernateSagaPersisterWithSQLiteAndAutomaticSchemaGeneration()
        .XmlSerializer();

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:

public string Email
{ 
    get { return string.Intern(email); }
    set { email = value; }
}

I image 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:

  public class UserRegistrationSagaData : ISagaEntity
  {
    public virtual Guid Id { get; set; }
    public virtual string Originator { get; set; }
    public virtual string OriginalMessageId { get; set; }
 
    public virtual string Email { get; set; }
    public virtual int Ticket { get; set; }
  }

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<TSagaEntity> where TSagaEntity would be UserRegistrationSagaData in my example… and then we implement ISagaStartedBy and IMessageHandler where the two TMessage type parameters should be filled out with RequestRegistration and ConfirmRegistration respectively. Like so:

  public class UserRegistrationSaga : Saga<UserRegistrationSagaData>,
    ISagaStartedBy<RequestRegistration>,
    IMessageHandler<ConfirmRegistration>
  {
     //...
  }

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

    public override void ConfigureHowToFindSaga()
    {
      ConfigureMapping<RequestRegistration>(saga => saga.Email, message => message.Email);
      ConfigureMapping<ConfirmRegistration>(saga => saga.Ticket, message => message.Ticket);
    }

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

    public void Handle(RequestRegistration message)
    {
      // generate new ticket if it has not been generated
      if (Data.Ticket == 0)
      {
        Data.Ticket = NewUserService.CreateTicket();
      }
 
      Data.Email = message.Email;
 
      MailSender.Send(message.Email,
                      "Your registration request",
                      "Please go to /registration/confirm and enter the following ticket: " + Data.Ticket);
 
      Console.WriteLine("New registration request for email {0} - ticket is {1}", Data.Email, Data.Ticket);
    }
 
    public void Handle(ConfirmRegistration message)
    {
      Console.WriteLine("Confirming email {0}", Data.Email);
 
      NewUserService.CreateNewUserAccount(Data.Email);
 
      MailSender.Send(Data.Email,
                      "Your registration request",
                      "Your email has been confirmed, and your user account has been created");
 
      // tell NServiceBus that this saga can be cleaned up afterwards
      MarkAsComplete();
    }

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 omg@wtf.com, 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 laterz@hax0rz.com followed by omg@wtf.com, I can verify that a new saga is only created for laterz@hax0rz.com:

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.

One comment so far, add another

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:

ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(CreateWindsorContainer()));

- and then the container can be created like this:

    IWindsorContainer CreateWindsorContainer()
    {
      var container = new WindsorContainer();
 
      // register controllers and other stuff here
 
      Configure.WithWeb()
        .CastleWindsorBuilder(container)
        .XmlSerializer()
        .MsmqTransport()
          .IsTransactional(true)
          .PurgeOnStartup(true)
        .MsmqSubscriptionStorage()
        .UnicastBus()
        .CreateBus()
        .Start();
 
      return container;
    }

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 IMessageHandler<>), 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 resolved 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:

  public class HomeController : TxBaseController
  {
    readonly IBus bus;
 
    public HomeController(IBus bus)
    {
      this.bus = bus;
    }
 
    [AcceptVerbs(HttpVerbs.Post)]
    public RedirectToRouteResult DoSomething(string text)
    {
      bus.Send(new SomethingHappened {Message = text});
 
      return RedirectToAction("Index");
    }
 
    [AcceptVerbs(HttpVerbs.Post)]
    public RedirectToRouteResult DoSomethingBad(string text)
    {
      bus.Send(new SomethingHappened { Message = text });
 
      throw new ApplicationException("oh noes!");
    }
 
    public ViewResult Index()
    {
      return View();
    }
  }

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:

<use master="Site"/>
 
<h1>DoSomething</h1>
<form method="post" action="!{Url.Action("DoSomething")}">
  Enter text: <input type="text" name="text" />
  <input type="submit" value="Send" />
</form>
 
<h1>DoSomethingBad</h1>
<form method="post" action="!{Url.Action("DoSomethingBad")}">
  Enter text: <input type="text" name="text" />
  <input type="submit" value="Send" />
</form>

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

  public class HandleSomethingHappened : IMessageHandler<SomethingHappened>
  {
    public void Handle(SomethingHappened message)
    {
      Console.WriteLine("Something happened: {0}", message.Message);
    }
  }

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:

  public abstract class TxBaseController : Controller
  {
    TransactionScope currentTx;
 
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
      currentTx = new TransactionScope();
 
      base.OnActionExecuting(filterContext);
    }
 
    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
      base.OnActionExecuted(filterContext);
 
      var exceptionHappened = filterContext.Exception != null;
      var exceptionWasHandled = filterContext.ExceptionHandled;
 
      if (!exceptionHappened || exceptionWasHandled)
      {
        currentTx.Complete();
      }
 
      currentTx.Dispose();
    }
  }

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

Comments Off

NServiceBus for dummies who want to be smarties 3

NServiceBus for dummies who want to be smarties 3… third post on how to do some more stuff with NServiceBus.

But where do the messages go?

Well, where did you tell the framework to send them?

The answer to this question is deferred until the last meaningful moment, i.e. the moment when the generic host starts up and reads its app.config.

How do I receive messages?

The answer is simple: use the MsmqTransportConfig section to tell NServiceBus where this service can be reached. If the specified queue does not exist, it will be created. E.g. like so:

  <MsmqTransportConfig InputQueue="client"
                       ErrorQueue="error"
                       NumberOfWorkerThreads="1"
                       MaxRetries="5" />

How do I send messages?

This question is a bit harder to answer. First, it can be specified in the UnicastBusConfig/MessageEndpointMappings element, for each message type, or for an entire assembly at a time. E.g. like so:

  <UnicastBusConfig>
    <MessageEndpointMappings>
      <add Messages="Messages" Endpoint="someService" />
      <add Messages="MessagesRootNamespace.SomeSpecificMessage, Messages" Endpoint="anotherService" />
    </MessageEndpointMappings>
  </UnicastBusConfig>

In the example above, I have configured that all messages from the assembly Messages except SomeSpecificMessage will be routed to someService, whereas SomeSpecificMessage has its own destination in the queue anotherService.

Note that this section is not required if the service is a publisher, because then it will know where to send messages because other services have subscribed, and in the process they leave the name of the queue where they can be found.

Conclusion

That concludes today’s “NServiceBus for dummies who want to be smarties”. This was about where messages go. Next post will be an example with a simple infrastructure for an ASP.NET MVC backend running on NServiceBus, accepting subscriptions from other services. It’s going to be hot!

Comments Off

NServiceBus for dummies who want to be smarties 2

NServiceBus for dummies who want to be smarties 2… second post, this time on how to do some more stuff with NServiceBus.

How to do stuff when the service starts

Make a class implement IWantToRunAtStartup, e.g. like so:

public class BuildPoolOfExpensiveObjects : IWantToRunAtStartup
{
    public void Run()
    {
        // build that pool
    }
 
    public void Stop()
    {
        // dispose it properly
    }
}

How to speed up delivery of messages that are transient in nature

If your message contents get stale after a short period of time, it makes no sense to use reliable messaging where messages are written to disk before the message queueing service attempts to deliver the messages to their destination. Therefore, to be true to the transient nature of the messages and speed up delivery, you can decorate some of your messages with the [Express] attribute. E.g. like so:

[Express]
public class SomeFrequentlyChangingValueJustChanged : IMessage
{
    public double Value { get; set; }
}

How to make messages expire after some amount of time

If you know your message content does not make sense after some period of time, say one hour, just decorate your message with the [TimeToBeReceived] attribute – e.g. like so:

[TimeToBeReceived]("01:00:00")]
public class AnotherPeriodicallyChangingValueJustChanged : IMessage
{
    public double Value { get; set; }
}

Note that the argument to the attribute must be Parseable – unfortunately C# does not allow for calling e.g. TimeSpan.FromHours(1) in the attribute initializer.

How to stop logging all kinds of noise to the console

Logging is good, but not all the time. To disable all of NServiceBus’ logging, just make your endpoint config implement the interface IWantCustomLogging and do nothing in the Init method – e.g. like so:

public class EndpointConfig : IConfigureThisEndpoint, AsA_Server, IWantCustomLogging
{
    public void Init()
    {
        // ... do nothing here =)
    }
}

Conclusion

That concludes today’s “NServiceBus for dummies who want to be smarties”. This was about how to add some more life to your service. Next post will be about the question: where do the messages go?

2 comments so far, add yours