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 🙂

It’s just annoying that Joel Spolsky is such is great writer…

…because I almost never agree with him!

For instance, in this post – inspired by the book, Coders At Work – he describes the character he calls “the duct tape programmer”, who is the archetype of that annoyingly great programmer, who just seems to be able to solve any kind of problem with only a few tools.

One of the attributes of “the duct tape programmer” is that he seldomly wastes time writing tests, because “(…) the customer isn’t going to complain about that”. Another is that he does not succumb to hype and trends in software development, he is confident that what he knows is enough.

And so Joel goes, on and on about this fantastic programmer, who’s capable of delivering what the customer wants without all the fancy hypes brand-spanking-new technologies and methodologies that all the other programmers seem to waste their time with.

The problems, as I see it, are: a) Very few programmers are like that (you know, that Linus Torvals/Bjarne Stroustrup kind of guy), and b) I will NEVER be the guy who maintains his code!

The thing is – to continue Joel’s analogy – that “the duct tape programmer” might be able to win a go-cart race with a go-cart made of duct tape and WD-40, but I would NOT trust him to make a car for me to drive on the highways! – because I would not expect that car to be safe at high speed, and I would not expect it to last for years, and I would not expect it to withstand rain, snow, sand, etc.

In my opinion, automated unit tests and integration tests serve many purposes. One (obvious) one is to continually verify the behavior of a system, given that implementations may change and bugs be fixed and so on. Another is to DOCUMENT the behavior of the system, like in “we agreed with the customer that it should work like this”. Yet another is to aid the programmer while writing his code into separating concerns, because doing that just causes less pain when writing tests. Joel should stop bashing TDD.

And when it comes to new technologies and methodologies, I think it is SO IMPORTANT to keep an eye open for new AND old better ways to do stuff. My opinion is that I get smarter all the time by keeping an open eye on what other people are thinking and doing, and I get smarter all the time by putting some of it to use. Joel is just annoying here, because his statements lack nuance – keeping up with new stuff is NOT the same as bringing in new stuff unconsciously, but Joel does not seem to be capable of drawing this distinction.

In my opinion, there is no place for “the duct tape programmer” on a team. At least not on my team.

So if you care about your teammates, about the quality AS WELL AS THE MAINTAINABILITY AND EXPLAINABILITY of your code, please DO write tests!

And please DO separate concerns and take the time to factor out stuff into easy-to-understand narrow and focused classes!

And please, please DO use new as well as old technologies and practices where it makes sense – don’t put stuff off because it’s new, and you are used to hand-rolling your own linked lists and string structs in C and the C++ STL is just another fancy new hype to you.

Microsoft Office Web Apps usability fail

It’s weird, but it seems Microsoft are often very bad at designing UIs.

One major FAIL in my opinion is their new Office Web Apps. Take a look at the following screenshots:

fail-1

fail-2

They show clearly how wrong their new “ribbon” tool bar is – why waste 50 % of the vertical screen real estate on a few clunky buttons? And why oh why would anyone throw in the Windows Live logo + Office Web Apps navigations menus ON TOP OF THE RIBBON?

Take a look at the second screenshot above – tt’s just plain stupid that a single PowerPoint slide cannot fit on a widescreen monitor at a decent zoom level.

That’s just weird.

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.

Book review: ASP.NET 3.5 CMS Development

asp-net-35-cms-developmentAnother book from Packt, that I got a chance to review, is ASP.NET 3.5 CMS Development.

First I thought that this would be the book that showed me a genuine reference implementation of a CMS in ASP.NET, giving me the introduction to the concepts of CMSs that I think I need. I have never used CMSs before (besides WordPress :)), so I have only a vague notion of the concepts.

But the book turns out to be more like a beginner’s introduction to the .NET stack, which just happens to be in a CMS context.

The book starts out by explaining how to set up an ASP.NET website with a single page based on a text file that can be edited “online”. Then it moves on and expands the website in all directions by putting the pages inside a SQL Server – and then it walks the reader through the details of setting up the site in IIS.

The book is actually pretty good at explaining all these things in a precise to-the-point manner, but I think it should be noted that the stuff in this book is not production ready. But then again, lots of books contain code samples and stuff that is not production ready.

If you are new to the .NET platform, you could definitely benefit from reading this book. If you are looking for instructions on how to develop CMSs, I don’t think this is the right book.

Conclusion: A nice introduction to the .NET platform.

Title: ASP.NET 3.5 CMS Development
Authors: Curt Christianson, Jeff Cochran
ISBN 10/13: 1847193617 / 978-1-847193-61-2
Publisher: Packt Publishing