.net and other musings

Ben Lovell, an agile developer living in the UK.

Incremental development with Monorail: Part Three

Part One
Part Two

In the last instalment we finished up with a suite of passing tests. However, we’ve yet to produce anything remotely usable so lets continue by reaching down further and driving out our services/persistence. We’ll start by writing the following test:

23

We’ve meddled with our test setup a little to introduce the MockRepository for mocking out our PostController’s new dependency on the IBlogPostService. Our test now calls the AddPost method on our service interface and sets up the resulting AddPostResponseDto. Running the test produces a bunch of compiler whinging so we best implement the newly introduced bits:

24

25 

26

These are the only changes and additions we’ve made in order for the tests to compile and run. Running our test now produces the following result:

27

As we’ve yet to modify the PostController.Save(…) call to include a call the newly introduced IBlogPostService dependency. Lets go ahead and do this now:

28

We’ve now included the call to our newly introduced service and we set the responseMessage if the response is signaled as successful. Lets run our test now:

29

It works, ship it! Actually no, again we’re pretty low on actual functionality right now. Remember we’ve yet to actually drive out any implementation of the IBlogPostService interface as yet and I expect that the acceptance test will fail horribly since we didn’t wire up the necessary container configuration either. Lets go ahead and run the whole test suite and see what gives:

30

In the brief moments the browser appears during the test we can see the following:

31

Hmm, as I predicted earlier our application fails to run due to the lack of proper container configuration. Before we can do this we need to implement the IBlogPostService interface somewhere. We need to write a failing test to begin our foray into the implementation of a BlogPostService:

32

Lets create the BlogPostService only performing the steps necessary to pass the test above:

33

Run the test:

34

Now we have a working BlogPostService we can now wire up our container configuration to pass the acceptance test:

35

Now running the full suite of tests produces the following:

36

Our tests pass!

That’s it for this post. I’ve checked in the latest changes to the repository. In the next post we’ll continue our efforts and begin to implement validation on our screen-bound DTO’s.

Google code hosted project: http://code.google.com/p/mr-blogengine/

Incremental development with Monorail: Part Two

Part one can be found here.

So in part one we had finished up at a failing test. Lets recap what this was:

14

And our failing test:

9

Our add view assumes that a Save action exists on our PostController. In attempting to make the test above pass, we will introduce this new action. However, this will be driven out from the PostController’s test fixture like so:

15

We’re faced with a bunch of unimplemented types and members shown in red thanks to Resharper’s error highlighting. As you can see from the test we’ve introduced the AddPostRequestDto and the three properties it exposes. Secondly we’ve introduced the Save action to the PostController that accepts our AddPostRequestDto. Our test then simply asserts that the correct response was set and that the postcreated view is displayed.

Our first step is the implementation of the AddPostRequestDto. Thankfully Resharper will perform this for us:

16 

We’ve added this new type to the Core project under a new Messages namespace and folder for organisation.

Lets now go ahead and implement the new Save action on the PostController:

17

As you can no doubt see, we’ve done only the simplest thing possible to pass the test. Lets run our tests and see the results:

18

Well our controller fixtures pass nicely. I’ve got a sneaky suspicion that our acceptance test might fail however:

19

The expected confirmation was not displayed! We can assume this is as we’ve yet to create the postcreated view and spat back the responseMessage from this. Lets go ahead and create the view now:

 20

If I run the test again, in the very short time the browser is visible I can see that we’re failing with an exception occurring during the Monorail binding. To fix this we need to derive the PostController  from Monorail’s SmartDispatcherController and add the DataBind attribute to the Save action’s only parameter:

21

So lets go ahead and run our whole test suite:

22

Sweet! How functional our application is at this stage is still pretty debatable but we’re getting there :)

Our next task is to actually step down a layer and introduce a service to handle our persistence. I’ve checked in the latest changes. Stay tuned for the next post.

The google code hosted project: http://code.google.com/p/mr-blogengine/

Incremental development with Monorail

EDIT: This is hosted in a google code project accessible from here: http://code.google.com/p/mr-blogengine/

 

This is the first of a series of posts I’m penning where I’ll be incrementally developing a basic blog engine running on the Castle trunk and developed wholly test first.

Each new feature or addition will be described by simple narrative, followed by some testing/coding from the UI (or controller in this case) down to the database.

I’ll be using much of the Castle stack goodness including Monorail, Windsor and ActiveRecord. Unit testing with Mbunit and acceptance testing with Watin.

My aim with this series of posts is to demonstrate the power of the Castle stack, combined with TDD and the slow, incremental addition of features. After each post I’ll check in my latest changes which will after a clean build will result in a fully working system.

project-structure

I’ve completed a small amount of scaffolding up-front for brevity:

  • Castle built from trunk
  • Solution and project structure
  • Basic configuration of Monorail and Windsor

As you can see from the right, our solution consists of three projects. The core project will hold our domain model, interfaces, services and application code. There is a test project for both our unit tests and acceptance tests, and finally we have the web application project holding our controllers, views and static content. I’ve put together a basic layout and stylesheet that serve our needs for now. This will be added to as our blog engine matures.

Although we have no concrete examples as yet, the controllers, services, facilities and configuration properties are configured through Windsor XML configuration files in the web project. We’re running on a Castle build I ran locally after checking out the trunk some point over the last couple of days.

It will be interesting to see how our initial design adapts as required when features are piled on during the later stages of development. I’ve not got any specific plans on how long this series will go on for although I am considering moving my blog away from WordPress and will most likely host under the very blog engine I’ll be creating. Good times! Anyway enough of this, lets move on to the first iteration.

 

 

Iteration 1: Create a Post

For this iteration we will build our first cut at the blog post authoring screen. This comprises a very basic form allowing the author to specify the title, short description and full content of the post. I think you’ll agree that what we’re building in this iteration won’t serve as a fully powered blog engine any time soon, but lets restate our initial aim here: to incrementally build and adapt our system as new requirements and features emerge. With that said, lets get on to building our first feature!

Our first test:

1

From our basic requirement we’re now driving out the PostController. This test simply gets our controller into a good state for testing, handily provided by Monorail’s BaseControllerTest and our first test method asserts that when the Add action is called on our controller the correct view is rendered. As you can see from the grab above there is a lot of red code. Resharper is highlighting the members we’ve yet to implement. I attempted to run this test but the compiler chokes. Time to do what we need to pass this test:

2

Well that was simple enough. Lets run our test and see the result:

Test Results

As expected, the test now passes. However, there are some serious issues with our controller and the related Monorail configuration:

  1. The controller has no associated layout.
  2. We’ve yet to create the requisite view: Add.vm.
  3. We’ve not added the Windsor XML configuration for our controller.

Before we can do anything to remedy the issues above we’ll need to write a failing test. I’m going to use Watin to create a test which flexes Monorail a little more. Currently our only test relies heavily on most of the controller dependencies being stubbed/mocked out by the BaseControllerTest class. We’ll need to test through the browser to ensure our controller and view/layout are wired up correctly:

 4

As you can see above we’ve crafted a very simplistic test which asserts that the text “Ben Lovell’s Blog” is found in the browser at the specified URL. Note also that our test assumes the application is running at localhost on port 16489. I’ve configured this in the web application properties so we just need to ensure that the VSNET web development server is running on this port for our application. Lets run the test:

5

As expected it fails. To pass this test we need to perform the three steps mentioned earlier. To do this we first add the Layout attribute to the controller and specify the default layout, the contents of which are shown here:

7

Next we create an empty view: Add.vm in the views/post folder, and finally we wire up the XML configuration for our controller in the controllers.config file as shown below:

6

Lets try and run the test now:

8

Now we’re making progress! Lets extend our test a little more now. This time we will find the title, description and content fields, enter some values and submit the form. Asserting that the confirmation message was displayed telling the user their post was saved:

 9

A few things have changed here: we’ve altered the naming of the test to clarify intent, and as mentioned previously our test will enter some values into our form fields and submit the form. Our last assertion is checking that the correct confirmation message is displayed. Now we could argue that the setting of the description and content is superfluous in this test as the outcomes aren’t asserted. But, the effort required to implement those fields is minimal and highly unlikely to impact on any existing code/tests (i.e. none!).

Lets run the test and see the outcome:

10

Our test complains that the “Add Post” text was not found. Lets go and fiddle with our view:

12

Good to go, lets run the test:

11

Hmm, the first two asserts are passing but now we’re failing on unfound input: post.Title. Time to add the form and fields to the view, we’re going to make a slight jump and include the description and content inputs in our view also:

13

Re run the test:

14

It fails as we have yet to create the save action on the controller, and also the nonexistent action doesn’t display the required confirmation… For obvious reasons.

At this stage I’m going to wrap this up for now. Part two will follow over the next couple of days. Stay tuned!

Front-end DTO’s

An interesting discussion was brought up in one of the ALT.NET groups regarding the use of DTO’s in the presentation layer that I had to chime in on.

I’m a strong advocate of message passing from the UI to your services for several reasons:

  1. Test driving from the top-down is my favoured approach when developing web applications. I’ll start by writing a failing test for my controller (you should know by now I use Monorail ;)). Then I’ll stub out any dependencies, these usually being service interfaces which accept and return simple DTO’s with absolutely no behaviour. Stubbing out the services allows you to return dummy data very early on in your development. The nice thing about this approach is you can get a working UI together very quickly and then drive out the development of each layer until you hit your domain model. From which point you can then wire-up your real service and repository implementations and satisfy your acceptance tests end-to-end. Now I’m not suggesting that this approach isn’t possible without DTO’s but it makes it a heck lot easier in my experience.
  2. DDD aggregates by their very nature are composed of behaviours you don’t want to pass into your UI. Using DTO’s for binding into your UI keeps things nice and lightweight. Cohesion is high as the DTO’s are created for a very specific purpose, usually to satisfy a particular screen or UI workflow.
  3. I had made the rather nebulous statement that the use of DTO’s insulates your UI against changes in your domain model. Quite rightly somebody replied saying that this was all relative and there are many means to insulate against change. Of course, I wholeheartedly agree but in my defence I was replying to the OP from my iPhone. Now for me to explain this a little… Unless you’re using query projections (a la NHibernate) you’ll be mapping from your domain entities to specific DTO’s using some kind of mapper class. Your mapper probably depends on the interfaces of your particular domain entities and the implementation of your DTO’s. I say implementation as I drive out the mapping using state-based testing, which of course makes perfect sense when mapping from one state to another! Using DTO’s means our controller has a nice seam between itself and the services through their interfaces thus the controller (read: UI) has no knowledge of the domain model at all. Any changes to the domain model are catered for by changing the mapper specific to the affected messages. I won’t get into versioning messages, mainly because I haven’t got the time or inclination :)
  4. I’ve always thought (and I read this somewhere I think, but can’t remember where) that a sign of a well designed architecture, among other things of course, is the ability to replace the UI and have everything function correctly. Now it was probably more poetic than that but essentially what this means is your UI should have absolutely zero dependencies on anything below your service interfaces. Using DTO’s and message passing means the only work your controllers are doing is scraping the request, passing your message to a service and binding the response. I’ve demonstrated this in systems I’ve developed by providing an API (which can be considered another UI if you squint a little and look sideways) which is comprised of exactly the same service calls and DTO’s my web UI is using.
  5. My last point isn’t specifically tied to the use of DTO’s but more based around messaging architecture in general… What this gives me from the very beginning (i.e. the first test) is a nice basis for distributing my architecture. Our services can be hosted on an application server separately from our web application  or preferably located transparently via a message bus which brings in a whole heap of nice side-effects…

So in summary you can see I’m a big fan of the domain model in my services, mapping to and from DTO’s in my UI. What is your favoured approach?

Screen casts coming soon

My plan is to build a basic blogging engine using Castle Monorail, Windsor, ActiveRecord and developed with DDD & TDD. I’ll screencast the whole procedure from start to finish, outlining the basic story or stories for each screencast episode and then go ahead and implement those stories.

Due to the (potential) size of this I’ll no doubt split this up over many screencasts – probably weighing in at around an hour or so per piece. Production values will be conspicuously low of course and the screencasts are not necessarily meant to serve as an educational tool, more a window into my usage of tools & techniques.

I’ll spike out the solution bootstrapping and structure before the first screencast rather than bore you with the requisite stuff. Anyway, expect the first bunch of stories to appear some point early next week…

In the Darkroom

darkroom I’ve no doubt that I’m one of the most easily distracted people in the world, especially when writing documents on the PC. If I’m not answering IM’s or emails then I’m checking Google Reader or messing with Word formatting or some other vacuous waste of time.

One tool I’ve found that helps massively with this is Darkroom, in fact, I’m blogging this post using it right now. Darkroom is a full screen distraction free notepad type application with a black background and green text. Think old school terminal or command line style and you’re there.

I find I’m amazingly more productive this way, maybe you will be too? Download Darkroom here.

iPhone not appearing in iTunes (error 18)

I’ve had a few issues with the phone today: namely the thing isn’t being recognised by iTunes, plus my music and videos have mysteriously disappeared from the iPhone itself.

Upon trying to restore the iPhone from a backup in iTunes I got the dreaded message:

The iPhone “iPhone” could not be restored. An unknown error occurred (-18)

Luckily after a bit of jiggery-pokery I managed to get it functioning as normal with all data and settings restored following these steps:

  • On the iPhone, go into Settings > General and do a full delete of settings and data
  • Hard-reset the iPhone by holding the power key and the home key until the Apple logo appears
  • Plug back into iTunes
  • iTunes recognises the iPhone and offers to set it up fresh or perform a restore. Pick restore
  • Bingo!

Phew got a bit worried there for a moment. Hopefully this might help someone in the future!

Apple iPhone

I was lucky enough to receive an iPhone for Christmas and have been using it pretty solidly now for the last few days. You’ve no doubt read the huge reviews of the device a million times by now so I won’t go on about it, except perhaps  to say  it must be the single coolest device I’ve ever owned and used.

There a couple of things the iPhone is lacking of course, again these have been well publicised but the ones affecting me the most are the SMS functionality, more specifically the inability to address an SMS message to more than one recipient at once. The camera isn’t superb, being only 2MP and lacking a flash. I have a digital camera for taking proper pictures so again this doesn’t irk me too much. A native application for uploading pics to Flickr would have been a nice addition. I’m sure this will surface shortly after the iPhone SDK drops.

EDGE coverage is great in the Reading area, as is London of course. I tend to stick to the iPhone optimised sites and email on the move so the lack of bandwidth doesn’t affect me so much. As part of the o2 contract I can hop on to the Cloud’s wifi hotspots at most train stations, pubs etc as well which is nice when EDGE doesn’t cut it.

I’ve so far resisted the urge to jailbreak the phone to install the 3rd party native applications as I did with my iPod Touch which incidentally has been deprecated by the iPhone :) Time will tell however if I can stick to the Apple endorsed software.

MVC.NET

Unless you’ve been living under a rock for the last few days you will have noticed that the first CTP of the ASP.NET 3.5 extensions has now shipped. ScottGu has the lowdown as usual.

Given the extensibility of the framework, its not surprise that several interesting modifications/add-ins are cropping up. Hammett has dropped a pile of samples:

MvcExtensions: a class library project with all extensions developed including parameter binder support, Windsor integration and a NVelocity View Engine. I remember complaining about relying exclusively on inheritance to change behavior/add specializations. Looks like I’m not alone on this… To some things, a vertical approach is good enough, but not usually to frameworks. The inheritance scheme eventually will turn into hell in a complex project. I know as I been there.

RestSupport: Uri formats and a nice Respond To syntax inspired on the work from Chris Ortman/MonoRail.RestSupport.

UsingAR: self explanatory

UsingNVelocity: ditto.

Take a look at his blog post for more details and to download the samples here.

However the most traction award has to go to the open source MvcContrib project on Codeplex which will serve as a repository for all things MVC. MvcContrib has already taken contributions in the form of controller factories for the main container frameworks out there: Windsor, Spring.net and StructureMap.net and a Monorail style binder to aid conversion of a NameValueCollection (i.e. form or querystring) to an object graph.

I’ve been toying with MVC for a few hours in between real work and the one benefit which initially strikes me is nicer VS.net integration using the webform view engine. Full intellisense and type safety in the views is something sorely missing from Monorail (given that I use the NVelocity view engine there, not sure about the other view engines and what they provide).

A side-effect of using the MVC framework is that I’m finally getting to use all the cool 3.5 language features too.

The Day of Reckoning?

… OK perhaps not. Anyway, today is the supposed release date of the first CTP of the new Microsoft System.Web.MVC framework. As you’ve no doubt seen in previous posts this is a pretty big deal to me.

I’m putting the final touches on a fairly big project right now and have a smaller (internal) one lined up which would be a perfect candidate for testing out System.Web.MVC. Lets see how it stacks up against Monorail…

Google Reader

I’ve just noticed that Google Reader now offers recommendations to supplement your usual subscriptions:

googlereader

Interesting… The one feature I really miss though is comment viewing capabilities. Sometimes the best discussion is in the comments, especially among the more popular feeds.

Microsoft MVC next week?

Some news if you haven’t read it elsewhere: the ASP.NET 3.5 extensions CTP is due for release at some point next week. My primary interest being MVC by far, then Astoria I guess.

I can’t wait to start fiddling with the MVC framework. Good work Microsoft!

Check out ScottGu’s post here for more information.

Rolling with the 2008’s

I’ve finally got round to installing the RTM edition of VS2008. Apart from taking the best part of 5 hours, including removing the beta version I had installed (and had been using for the last few months solid), everything has gone pretty much without incident.

I say “pretty much without incident” as I did have one pant-wetting moment when the installer rolled back due to some nondescript assembly failing to install correctly. However, the time honoured fix: i.e. reboot seemed to have done the trick.

The project I’m working on at the mo has already been upgraded to the new VS2008 format way-back when I had installed the beta so no troubles there either.

ReSharper and VisualSVN are all fine and dandy. My settings have also crossed the chasm, so all-in-all not a bad install experience pour moi.

Speaking of ReSharper, we need a new edition taking care of the 3.5 language features post haste!

ASP.NET Development Landscape

With all the System.Web.Mvc goodness flying around at the moment, the Microsoft or nothing shops (you know, the ones that flat-out can’t adopt a technology unless it comes from the borg) might finally get a taste of how web development should be done. Unfortunately for the aforementioned reason, Monorail has never be an option for those developers.

The one thing that really excites me about MSMVC is the periphery of concepts that will be introduced by way of association: deep testability, SRP, DIP and SoC. Traditionally these practices aren’t promoted (or I might go so far as say easily achieved) heavily in the .NET technologies and frameworks coming out of Microsoft. As we’re focusing on ASP.NET at the moment, sure, they’re possible to adhere to whether you’re using ASP.NET in the presentation layer or not, but ASP.NET doesn’t promote them the same way the MVC framework will.

I can’t help but wonder how different the landscape might be now if MSMVC was released with .NET 1.0 instead of webforms?

iPod Touch Hackage

Those clever hackers have finally jailbreaked the iPod Touch. After a little wrangling I’ve managed to unlock mine and have gone install crazy.

I’m loving the Mail and NES applications in particular. Checkout the springboard now:

S5000938

EDIT: I followed these instructions for unlocking the touch with Windows.

Follow

Get every new post delivered to your Inbox.