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.

Nov 112009

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

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

nifty, r# Comments Off
Oct 222009

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!

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:

public class Band : EntityBase
{
	public Band()
	{
		BandMembers = new List<BandMember>();
	}
 
	public virtual string Name { get; set; }
 
	[Cascade]
	public virtual IList<BandMember> BandMembers { get; set; }
 
	public virtual void AddBandMember(User user, BandMemberType bandMemberType)
	{
		var bandMember = FindExistingBandMember(user) ?? new BandMember(user);
		bandMember.BandMemberType = bandMemberType;
	}
 
	public virtual void RemoveBandMember(User user)
	{
		BandMembers.Remove(FindExistingBandMember(user));
	}
 
	BandMember FindExistingBandMember(User user) 
	{
		return BandMembers.ToList().Find(b => b.User == user);
	}
}
 
public enum BandMemberType 
{
	Member, Administrator
}
 
public class BandMember : EntityBase
{
	public BandMember(User user)
	{
		User = user;
	}
 
	public virtual BandMemberType BandMemberType { get; set; }
 
	public virtual User User { get; set; }
}
 
public class User : EntityBase
{
	public virtual string Name { get; set; }
}

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

public class CascadeAttribute : Attribute
{
}

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:

public class CascadeConvention : IHasManyConvention, IReferenceConvention
{
	public void Apply(IManyToOneInstance instance)
	{
		var property = instance.Property;
 
		if (!HasAttribute(property)) return;
 
		Console.WriteLine("CascadeAll on {0}.{1}", property.DeclaringType.Name, property.Name);
 
		instance.Cascade.All();
	}
 
	public void Apply(IOneToManyCollectionInstance instance)
	{
		var property = instance.Member;
 
		if (!HasAttribute(property)) return;
 
		Console.WriteLine("CascadeAllDeleteOrphan on {0}.{1}", property.DeclaringType.Name, property.Name);
 
		instance.Cascade.AllDeleteOrphan();
	}
 
	bool HasAttribute(ICustomAttributeProvider provider)
	{
		return provider.GetCustomAttributes(typeof(CascadeAttribute), false).Length == 1
	}
}

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:

new AutoPersistenceModel()
        // (...)
        .Conventions.Setup(s => s.AddFromAssemblyOf<EntityBase>())
        .Configure(configuration);

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

Got the formatting placeholder indices mixed up a bit… R# to the rescue!

resharper-rocks

Incredible piece of work!

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:

public class Purchase : Transaction
{
	// ...
	public virtual void Record()
	{
		// ...
		//
		// and then:
		foreach(var debtor in MortgageDeed.CurrentDebtors)
		{
			Enlist(debtor.LegalEntity);
		}
	}
 
	void Enlist(LegalEntity entity)
	{
		ServiceLocator.Resolve<ICprEnlistment>().Enlist(entity);
	}
}

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

public class Purchase : Transaction
{
	// ...
	public virtual void Record()
	{
		// ...
		//
		// and then:
		EventBus.Publish(new PurchaseRecorded(Id));
	}
}

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

public static class EventBus
{
	[ThreadStatic]
	static IBus bus;
 
	public static void Publish(object message)
	{
		GetBus().Publish(message);
	}
 
	static IBus GetBus()
	{
		return bus ?? (bus = CreateBus());
	}
 
	static IBus CreateBus()
	{
		return EventBusConfiguration.TestMode
			? new StubBus()
			: ServiceLocator.Resolve<IBus>();
	}
}
 
public static class EventBusConfiguration
{
	public static bool TestMode { set; get; }
}

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

public class EventBus : IEventBus
{
	IKernel kernel;
 
	public EventBus(IKernel kernel)
	{
		this.kernel = kernel;
	}
 
	public void Publish(object message)
	{
		// get type of published message
		var messageType = message.GetType();
 
		// close the handler type to be subscribers
		// of this exact type of message
		var handlerType = typeof(ISubscribesTo<>)
			.MakeGenericType(messageType);
 
		// make MicroKernel do its thing
		var handlers = kernel.ResolveAll(handlerType);
 
		// invoke handlers
		foreach(object handler in handlers)
		{
			var method = handler.GetType().GetMethod("Handle");
			method.Invoke(object, new [] {message});
 
			kernel.ReleaseComponent(handler);
		}
	}
}

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

public interface ISubscribesTo<T>
{
	void Handle(T message);
}

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

public class EnlistLegalEntitiesWithCpr : ISubscribesTo<PurchaseRecorded>
{
	ICprEnlistment cprEnlistment;
	ITransactionRepository transactionRepository;
 
	public EnlistLegalEntitiesWithCpr(ICprEnlistment cprEnlistment, ITransactionRepository transactionRepository)
	{
		this.cprEnlistment = cprEnlistment;
		this.transactionRepository = transactionRepository;
	}
 
	public void Handle(PurchaseRecorded message)
	{
		var purchase = transactionRepository.FindById(message.Id);
		var debtors = purchase.MortgageDeed.CurrentDebtors;
 
		foreach(var debtor in debtors)
		{
			cprEnlistment.Enlist(entity);
		}
	}
}

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.

Another simple place to hook your stuff into 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:

void OnActionExecuting(ActionExecutingContext context);
void OnActionExecuted(ActionExecutedContext context);
void OnResultExecuting(ResultExecutingContext context);
void OnResultExecuted(ResultExecutedContext context);

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

Just wanted to share my experiences regarding the super cool mini framework, Topshelf – a bi-product from the development of MassTransit. When Dru and the other guys were working on MassTransit, they needed to create Windows services a lot, which led to the separation of the Windows service stuff from the other stuff – and now they call it Topshelf.

You use Topshelf by creating a console application. In the Main method, you create a configuration, which you hand over to Topshelf. Then, everything just works as expected.

Topshelf requires that you to use an IoC container hidden behind the common service locator interface, which is neat because then it’s up to you to decide which container to use. In this example, I am using Windsor.

Creating a service is as simple as this:

namespace SomeService
{
  public class Program
  {
    [STAThread]
    public static void Main(string[] args)
    {
      const string serviceName = "some_service";
 
      var cfg = RunnerConfigurator.New(
        x =>
        {
          x.BeforeStart(
            s =>
              {
                Console.WriteLine("Starting {0}...", serviceName);
                ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(CreateWindsorContainer()));
              });
 
          x.AfterStop(
            s =>
              {
                Console.WriteLine("Stopping {0}...", serviceName);
                ((WindsorServiceLocator) ServiceLocator.Current).Dispose();
              });
 
          x.ConfigureService<SomeService>(
            c =>
            {
              c.WithName(serviceName);
 
              c.WhenStarted(s => s.Start());
              c.WhenStopped(s => s.Stop());
              c.WhenPaused(s => { });
              c.WhenContinued(s => { });
            });
 
          x.SetDisplayName("My funky service");
          x.SetDescription("This is a funky service that depends on MSMQ");
          x.SetServiceName(serviceName);
 
          x.DependencyOnMsmq();
        });
 
      Runner.Host(cfg, args);
    }
}

Everything in the snippet above works as expected. Note how I create my Windsor container and store it behind WindsorServiceLocator, which is my trivial implementation of the IServiceLocator interface. This way, Topshelf will pull the specified service type(s) (SomeService in the sample) from the container, and call the specified methods to start/stop (and possibly pause/resume) the service.

Note also how I specify that my service has a dependency on message queueing – neat!

Running and debugging the service is as easy as executing the .exe.

Installing/uninstalling can be done with

SomeService.exe /install
SomeService.exe /uninstall

Nifty!

Apr 152009

Usually, when writing code, you adhere to some conventions on how your stuff should work. At least I hope you do – otherwise your code is probably a mess!

Sometimes, these conventions can be enforced by using some patterns to allow for compile-time checking – one example, that I can think of right now, is using the visitor pattern to implement multiple dispatch, which is explored a little bit in another post.

But what about conventions, that can only be checked at runtime? Well, how do we usually check stuff that can only be checked at runtime? – by writing tests, of course!

One project I am currently involved in, is written in ASP.NET MVC. All form posts are done using the automatic binding features of the framework, and I am following the convention that the names of my view models should end in “Form” – so as to enabling me to easily distinguish my form posting DTOs from my other view models. What is more natural, then, than performing the following test:

[Test]
public void ActionParametersAreEitherPrimitiveTypesOrTruePocos()
{
	var assembly = Assembly.GetAssembly(typeof (HomeController));
	var types = assembly.GetTypes().ToList();
 
	types
		.FindAll(ThatIsConcreteController)
		.SelectMany(t => t.GetMethods().ToList().FindAll(ControllerActions))
		.ToList()
		.ForEach(CheckMethodInfo);
}
 
bool ControllerActions(MethodInfo info)
{
	return info.IsPublic && typeof(ActionResult).IsAssignableFrom(info.ReturnType);
}
 
void CheckMethodInfo(MethodInfo info)
{
	var parameters = info.GetParameters().ToList();
 
	parameters.ForEach(p => CheckParameterType(info, p));
}
 
void CheckParameterType(MethodInfo methodInfo, ParameterInfo parameterInfo)
{
	Assert.IsTrue(IsPrimitiveType(parameterInfo) || IsFormType(parameterInfo),
	              string.Format(
	              	"Action {0} of {1} has parameter of type {2} which is invalid. Use only true pocos from the view models assembly.",
	              	methodInfo.Name,
	              	methodInfo.DeclaringType.Name,
	              	parameterInfo.ParameterType.Name));
}
 
bool IsFormType(ParameterInfo info)
{
	var type = info.ParameterType;
 
	return
		type.Assembly == Assembly.GetAssembly(typeof (LogInForm))
		&& type.Name.EndsWith("Form");
}
 
bool IsPrimitiveType(ParameterInfo info)
{
	// add mores types here if they should be allowed as well
	return
		new List<Type>
			{
				typeof (int),
				typeof (string),
				typeof(int?),
				typeof(Guid)
			}.Contains(info.ParameterType);
}
 
bool ThatIsConcreteController(Type type)
{
	return typeof(Controller).IsAssignableFrom(type) && !type.IsAbstract;
}

That is, I am running through all controller types, getting all actions, and checking the the parameter types are either in the array of accepted types (IsPrimitiveType) or a “true poco” (which in this application is a simple view model whose name ends with “Form” and comes from the right assembly).

This way, I will always know which types are used to deserialize forms. Great! But what about that pesky MissingMethodException whenever I forget to provide a public default contructor in my form models? Easy as cake! That part is checked by the following test:

[Test]
public void AllFormModelsHavePublicDefaultConstructor()
{
	var assembly = Assembly.GetAssembly(typeof (LogInForm));
	var types = assembly.GetTypes().ToList();
 
	types
		.FindAll(ThatCouldBePoco)
		.FindAll(ThatSatisfiesPocoNamingConvention)
		.ForEach(AssertHasPublicDefaultConstructor);
}
 
bool ThatCouldBePoco(Type type)
{
	return type.IsClass
	       && !type.IsAbstract;
}
 
bool ThatSatisfiesPocoNamingConvention(Type type)
{
	var name = type.Name;
 
	return name.EndsWith("Form");
}
 
void AssertHasPublicDefaultConstructor(Type type)
{
	var constructors = type.GetConstructors().ToList();
 
	Assert.IsTrue(constructors.Exists(IsPublicDefaultConstructor),
	              string.Format("Poco type {0} does not provide a public default constructor.",
	                            type.Name));
}
 
bool IsPublicDefaultConstructor(ConstructorInfo info)
{
	var parameters = info.GetParameters();
 
	return parameters.Length == 0;
}

These two tests combined, will assert that nothing will go wrong when submitting forms in my ASP.NET MVC project. That’s just nifty! And I really like the notion that I am helping future me.

© 2010 mookid on code Suffusion WordPress theme by Sayontan Sinha