Spark codec for OpenRasta

May 29th, 2009

It all started after I went to Sebastian Lambla’s talk on OpenRasta at a VBUG event. I really got into the framework – it felt to me as a cleaner and lighter way to think about MVC when compared to ASP.NET MVC. At the same time, I really wanted to have look at the Spark View Engine as I think the syntax is a breath of fresh air and welcome relief from all the tagsoup we seem to get into when writing MVC views.

When I asked ‘Is there a Spark codec for OpenRasta?’ I had the reply ‘No, but why don’t you write one’. Never one to back down from a challenge I did. And you can download it from GoogleCode (though I would prefer you grab the trunk cos the latest version is probably already out of date!).

OpenRasta meet Spark, Spark meet OpenRasta
If you are not familiar with either of these projects, then this project probably means nothing to you. If you get one and not the other then read on.

OpenRasta ‘is a Resource-Oriented framework to build MVC-style applications on asp.net 2 and above.’ (I copied this from here). Easiest way to get into it I think is to either hear a talk on it, or use this tutorial.

The Spark View Engine is written for ASP.NET MVC and provides a slightly alternative syntax for specifying views. Basically it uses an extended set of attributes and tags on top of plain old HTML to let you do crazy things like:

<viewdata products="IEnumerable[[Product]]"/>
  <ul if="products.Any()">
    <li each="var p in products">${p.Name}</li>
  </ul>
  <else>
    <p>No products available</p>
  </else>

Simple, readable and pretty cool I think, when your alternative is a big old mess of tagsoup. Out of all the alternatives, it is definitely the clearest and most logical I have seen so far. Any web-designers/front-end devs out there want to tell me if they agree?

Using the Codec from OpenRasta
In a later post I might choose to talk about my design approach, but when it came to OpenRasta, this approach was very much ‘Copy what the webforms codec does’. So to use the spark view engine, you start by adding this to the top of your configuration block:

    ResourceSpace.Uses.SparkCodec();

This does some behind the scenes magic to register all the stuff you need to use the SparkCodec.

Next, for the resources you want to render using spark, you configure along the lines of:

ResourceSpace.Has.ResourcesOfType<ShoppingList>()
					.AtUri("/shoppinglist")
					.HandledBy<ShoppingListHandler>()
					.AndRenderedBySpark("shoppingList.spark");

… note the ‘AndRenderedBySpark’ extension method there which passes in the name of the spark template you are going to use. The Spark lookup procedure takes in a root folder as part of its configuration and I have defaulted this to ‘Views’. So ShoppingList.spark must exist in the folder views/.

There you are – you are all ready to start getting Sparky with your OpenRasta. Note that OpenRasta allows you to mix and match your codecs – so you can just have one or two views rendered using Spark if that is what you want.

Extensions to the Spark syntax

One of the things I liked about OpenRasta was some of the markup extensions that it contains. I.e. you can do something like:

   Xhtml.TextBox(()=>MyResource.Name)

And through the magic of expressions, the output html is something like:

   <input type="text" name="MyResourceTypeName.Name" value="Whatever the current value of the name is"/>

The base view class from which all spark views inherit (SparkResourceView) exposes the Xhtml interface so you can just use the extension method as is. However, I thought that seeing as the point of the Spark syntax is to hook tidily into html, I wanted to provide an alternative. So I have used the extensions facility in the Spark View Engine (which was simple once I got the hang of it), to add some custom attributes. Now if your view contains the following:

<viewdata resource="Customer"/>
<input for="resource.Name" type="text" anotherattribute="somethingelse"/>

The output becomes:

<viewdata resource="Customer"/>
<input name="Customer.Name" value="Fred" type="text" anotherattribute="somethingelse"/>

Similarly to hook into the URI-resolving stuff in OpenRasta you can have something like:

<viewdata resource="Customer">
<a to="resource">Click here to view the customer</a>
<a totype="IEnumerable<Customer>">Click here to view all customers</a>

On render, this figures out the URIs based on what you set up for the resources in question as part of the configuration.

Anyway, this syntax is far from complete – it works enough to just about power the demo application that I packaged with the codec source so I suggest you take a look at this for more pointers.

Futures
This started as a small pet project but if you want to give me a hand please please do catch up with me on twitter. The same goes for any other feedback (apart from ‘it’s crap’ – that would not be very nice). I have a small idea for an application that I wanted to have a go at with OpenRasta and as I get into implementing this I am sure I will come up with a few more extensions to the syntax.

Now it is far too hot and I am going out to get an ice lolly.

Adventures in BDD style testing – too many scenarios!

April 29th, 2009

I have been attempting to write a big article on my experiences of BDD/ BDD style testing or what ever you want to call it. However, I have learnt that big über articles generally are never finished (by reader or writer) so I have cut it down a bit…

So I have been using a style of BDD for my current project for a couple of months now. As this was intended to be a ’smart UI’ application (no smirks at the back please…), I have only picked a few isolated areas that could be separated out and done properly. What I now have is a big mishmash of different styles, tests etc. but overall I am happy with the approach I have taken. As the part of the app I am dealing with has lots of rules, exceptions, caveats etc., expressing these in BDD-style sentences has had a big payoff. Only the other day I was asked how we handle a particular piece of data/conditions and all I had to do was read the names of my tests and I had the answer for them without having to remember anything ( I don’t remember code I have written 2 days ago, let alone 2 weeks ago!).

Anyway, there are some things I have got wrong. I haven’t really stuck to a Given->When->Then structure. I seem to have cobbled together the Given/When bits with a few ands. i.e.:

When the user requests money from his account and the pin is correct and he has enough money and he requests 10 pounds and he is wearing a brown that then return 10 pounds from the cash machine and debit his account by 10 quid

Whereas a better structure may be:

Given that the user is wearing a brown hat and he has enough money and he has entered the correct pin number, When he requests ten pounds then a £10 note should be returned from the cash machine and user’s account should be debited by ten pounds

It’s bit more wordy, but it scans better and more importantly can be converted into some sort of code:

    public class When_user_requests_ten_pounds : 
                              User_wearing_brown_hat_and_has_enough_money_and_entered_correct_pin
    {
         public void Debit_his_account_with_10_pounds()
         {
         }
 
         public void Return_10_pounds_from_the_cash_machine()
         {
         }
    }

Anyway this is all well and good until I start getting into counter examples. For example, if I had the following scenario and expected behaviour:

Given that the moon is in the seventh house and jupiter aligns with mars, when a new age dawns then this should be the dawning of the age of aquarius.

(the original sort of scans better)

I could fulfill the conditions of this slightly bizarre requirement with the following (equally bizarre) code:

       public class NewAgeDawner
       {
             public NewAge DawnNewAge()
             {
                  return NewAge() {OwnedBy=Zodiac.Aquarius};
             }
       }

That would essentially cause the tests to pass but is obviously wrong as it happens whether the scenario is set up as described or not (i.e. it always dawns the age of aquarius regardless of position of moon and jupiter/mars alignment). At this point I find it useful to go back to my early electronics lessons and write a bit of a truth table to describe the behaviour I need to see:

Moon in 7th Jupiter aligned with mars Age of aquarius?
0 0 0
0 1 0
1 0 0
1 1 1

So even though I only care about the last item in this list (where both conditions are met) I have to write 4 tests. Not that I am complaining at all (not me…) – the more test code the better, but given that three of the four outcomes should have the same result, it’s a lot of duplication. For example, I have some behaviour in my system that sets a couple of fields based on arguments passed in and then persists the object to the database. However, there are a number of states in which the operation cannot succeed and I want to make sure the fields are not changed, and the operation returns a suitable result message explaining why it couldn’t work. For each of these invalid states, I must write three tests:

		[Test]
		public void Result_is_failure()
		{
			Result.Success.ShouldBeFalse();
		}
		[Test]
		public void Error_message_explains_failure_reason()
		{
			Result.Message.ShouldEqual("Moon is not in the seventh house...");
		}
		[Test]
		public void Save_not_called()
		{
			MyRepository.SaveWasNotCalled();
		}

With the exception of the message (which will change each time), I have to copy paste all these tests for each invalid state. Is this really the right thing to do?

I know we should be free and easy with our test code and write as much as is necessary – generally ending up with more test code than production code, but by copy pasting?? Is there a better way?

Extension method assertions versus standard assertions

April 24th, 2009

I have been playing around lately with assertions in my  tests and figuring out the best (funnest?) way to work with them. Within the context of BDD style testing there seems to have emerged a style for using extension methods for asserts. As I found out at the SkillsMatter NBehave talk, NBehave comes with a set of extension method wrapped assertion methods so I guess that is where the link comes from perhaps.

What do I mean by extension method assertions?

OK so a normal vanilla unit test might check that the conditions of the test are met as follows:

      Assert.IsEqual(foo, bar);
      Assert.IsNotNull(foobar123);

Or if you have been bitten by the fluent bug:

      Assert.That(foo, Is.EqualTo(bar));
      Assert.That(foobar123, Is.NotNull());

Anyway, if you use the extension methods approach you will typically have defined somewhere something like:

        public static class AssertionExtensions
	{
		public static T ShouldBe&lt;T&gt;(this object val)
		{
			Assert.That(val, Is.InstanceOf(typeof (T)));
			return (T) val;
		}
 
		public static void ShouldBeNull(this Object val)
		{
			Assert.That(val, Is.Null);
		}
    }

Leaving your asserts looking something like:

   foo.ShouldEqual(bar);
   foobar123.IsNotNull();

You could even read that back and it might make some sort of sense: “Foo shoud equal bar”. “Foobar123 should not be null”. As far as C# goes, that is pretty damn readable (I see you Ruby-heads smirking at the back!).

Taking it a bit further

I have started to get into BDD style testing for project number one (well, the parts that aint smart-ui anyway), and I have got slightly carried away with my extension method asserts. As each test is testing a different outcome of the behaviour under test, I think the best tests only have one line of code in them. Something like:

[TestFixture]
public When_user_sends_article_to_a_friend 
{
       ....
       [Test]
       public void Email_is_sent_to_the_friends_address_via_email_service()
       {
               EmailService
                    .EmailWasSent()
                    .To("Fred@flintstone.com");
       }
}

(For the record my assertions have never got to more than one method, but it would be possible right!).

Arguably you could just say this is a bit of syntactic sugar, but I think it hides the complexity of what it means to satisfy these requirements… which I believe is A Good Thing. At first glance, I should be able to read this code out loud and have half a chance at figuring out the intentions of what was supposed to be tested. I don’t need to worry whether EmailService is a stub/mock/stubbed-mock(!) – and indeed if it starts life as a mock then progresses to a concrete, this test doesn’t need to change.

It’s not for BAs
One argument I have heard for extension-method assertions is that it ‘makes it readable for business analysts’. Now, if your business analyst happens to be a former programmer, you might be on to something. However, that is not usually the case, our BAs can’t understand it and such a claim rather detracts from the usefulness of these methods.
Really what we should be thinking about is the how readable extension method assertions are for us! If someone asks me ‘what does this function do’ and I wrote it about 10 days ago (this is about the maximum time I can remember anything about something I have created), I can find out easily and quickly. Similarly, the poor dev who comes after me could probably have a go at comprehending it too.

My morning’s work

April 17th, 2009

If only I could afford a real artist…

thesleepydevlogo

A basic problem of mapping

April 13th, 2009

So I have a very basic problem with no doubt a very basic solution which at the present time is eluding me.

For some reason on this project 90% of the objects I work with are already in existence (in the database as well as conceptually in space-time !). Therefore most creation code for my entities is just for the purposes of reconstituting an object from a DTO. This is where I am having the problem. In a piece of functionality I haven’t even fully implemented yet I have the following:

public class MyEntityDTO
{
	public int OneField { get; set; }
	public string AnotherField { get; set; }
}
 
public class MyEntity
{
	private readonly int oneField;
	private readonly string anotherField;
	public MyEntity(MyEntityDTO dto)
	{
		oneField = dto.OneField;
		anotherField = dto.AnotherField;
	}
 
	public MyEntityDTO CreateDTO()
	{
		return new MyEntityDTO(...;
	}
 
	... insert domain logic here...
}

And a test akin to:

[TestFixture]
public class When_MyEntity_Is_Reconstituted_From_DTO
{
 
	private MyEntityDTO DTO {get; set;}
	public override When()
	{
		DTO = Builder.CreateWithAllFieldsFilledIn();
		Result = new MyEntity(DTO);
	}
	[Test]
	public void AnotherField_Is_Copied_In()
	{
		Result.AnotherField.ShouldEqual(DTO.AnotherField);
	}
}

… and a similar test to test persistence to a DTO.

OK for starters, but I know that somewhere down the line, ‘MyEntity’ is going to get quite a few more properties and value objects. So when I add a new property I have to do the following:

  • Write a new test to test that the DTO property is copied to the MyEntity instance (thanking goodness for BDD style testing which makes this very simple)
  • Write a new test to test that the MyEntity property is copied to the DTO
  • Implement the property in the DTO
  • Implement the property in MyEntity

Already this is getting my lazy-senses tingling. It’s only one property! What happens if I refactor three properties into a value object or add a dozen more. I can’t guarentee that future me is going to want to go through all those steps. Problem is I can’t see any way to simplify this in just code alone.

In an ideal world, I would use NHibernate, do away with the DTO and let my mapping do the work. However, this would contravene the NIH rule of the current project I am working on. My data access layer is all hand-coded SQL so I try and keep it’s work to the absolute bare minimum (still seems to be where 99% of the bugs lie but that’s another story…).

Another idea would be to use automapper (which I have been meaning to try for a while now) but I am stuck in 2.0 so no go there I presume.

I guess at the end of the day most coding problems are social – maybe I should be using NHibernate here and screw NIH syndrome!

QCon 2009

March 8th, 2009

QCon London 2009

I am attending QCon London 2009 next week and I am in the process of deciding which bits I will attend. Although this is the first proper conference I have been able to get to (benefits of controlling your own training budget!), I am aware that sometimes you can end up going to less than you thought, but it’s good to have a plan. Aside from keynotes, my plan is currently:

Wednesday

Particularly keen on the Agile Track on this day, particularly the Michael Feather’s TDD retrospective but some of the Emerging Languages stuff : particularly Iron Python and Martin Fowler’s Ruby talk. Might check out some of the Web as a Platform stuff too.

Thursday

Mainly dominated by the DDD track today. I must try and finish ‘the book’ before I go (it’s really good and I can’t believe it is so long before I read it). Sadly this means I will miss the Guardian Architecture talk, but maybe ‘Rebuilding guardian.co.uk with DDD’ will be more interesting/relevant. I also hope I can make some of the Agile organisational patterns stuff too. Everything else looks quite interesting but the DDD stuff will probably be the biggest draw!

Friday

If I haven’t dropped from exhaustion, I like the look of the DSLs track and Historically Bad Ideas (at the least I think it would make me feel better about some of mine…). Obviously, Tony Hoare’s null reference talk is an absolute must and Traditional Programming Modules… will make me feel better about some of my more recent [enforced] working practices (I say no more than that). Might check out Groovy too…

Sadly, I can’t attend bullseye as after this, as we are off to walk a chunk of the South Downs way so I have to get my skates on to Brighton!

I think there is going to be some interesting stuff here. I picked QCon mainly for the interesting subjects and people that are talking. I prefer to attend the general software development talks rather than those relating to a specific technology as I find them more interesting, but I will try and make a bit of a mix of general/technology specific topics where I can.