.net and other musings

Ben Lovell, an agile developer living in the UK.

Category: Castle

Incremental development with Monorail: Part Six

We finished up in part five with a full suite of passing tests and our BlogPostService is slowly taking shape now. The next few posts will introduce persistence and validation but before we get started on these features, we have a little housekeeping to perform on our existing code.

First step is to build the Castle trunk and update our references to the latest versions. Secondly, we’ll incorporate a few changes suggested by Hammett.

After building and replacing our references with the latest Castle build I’ll run the tests as a sanity check before we proceed:

62

With that out of the way our first code change will ensure we play nicely with HTTP. It is considered good practice to ensure requests which update or create resources is carried out via POST – so we can modify our only PostController.Save action to ensure this is so but before we do this we’ll write a test:

60

Running our test produces the following:

61

We’ll modify our Save action now to ensure we only accept the POST verb:

63

We have added the AccessibleThrough attribute and explicitly specified that our action must only allow the POST verb. We’ll run our test again and make sure everything is working as expected:

64

The next step is to modify our add.vm view to use the helper methods to generate our form tags. We’ve done that and once again we’ll run our tests:

65

I’m noticing a little duplication creeping in to our integration tests that should be removed. Also, until now we’ve had to assume that a web server is running on a specific port on our development machine in order to run the integration tests. Through a little tweaking we can spin-up a temporary server in our test fixture setup code and host our test code there instead.

First we add the WebDev.WebHost.dll to our lib project directory and ensure we’re referencing this from the testing project. The next step is to create an app.config file in the testing project so we can configure where and from which port our testing server should be hosting from:

66  Now we add some setup code for the fixture:

67

We’ll also make sure we bring the server down when we’re finished:

68

Now ensure the VS web server is not running on the same port, then we can run our tests and make sure our latest changes work out:

69

Now, since we specify the web root and port through configuration, we should also use these configurable values to determine the URLs in our tests:

70

You can see our tests now call BuildTestUrl to determine the full URL where we’re hosting the development server. Neat. I’m sure when we add further integration fixtures we’ll extract class this, but for now we have a nice working set of tests and should remember the principle of YAGNI!

I’m going to cut this installment short here. In the next post we’ll get back into the swing of it and continue implementing features.

As ever, the latest code has been checked in and is available here:

http://code.google.com/p/mr-blogengine/

MVC Storefront

Rob Conery has been posting a series of screencasts featuring the development of an ASP.NET MVC based product catalogue. This is being carried out in a “TDD” like fashion. The interesting difference between his posts and mine (apart from the obvious fact that I’m lazy and haven’t screencasted… yet) is that he starts from the bottom of the stack and works upwards towards the UI where as I do the opposite.

Its interesting contrasting the two approaches not to mention the differences between the ASP.NET MVC framework and Castle Monorail way of getting things done.

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!

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…

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?

Microsoft MVC Framework

Some of you may be aware of the ALT.net conference going on this weekend. I wasn’t particularly interested in a gathering of egos in mutual back-slapping, but I was interested in the announcement of the System.Web.MVC framework from Microsoft.

This has been on the cards for a while and had kinda been announced a while back by Scott Guthrie. Since then not much detail has been uncovered other than a one or two hires for the dev team (from what I’ve heard from my sources ;))

Jeffrey Palermo announced some of the technical details in this blog post, although light in actual substance, yet giving us more idea than anything released previously.

Some of the key things of note:

  • Testability: the key concern. Overcome by making everything virtual/behind interfaces and extension points abound.
  • Ability to plug-in to framework via aforementioned extension points. Gives us the ability to add extra view-engines a la Monorail.
  • Default view-engine implementation using ASPX without postback and viewstate pain.
  • Controllers can be resolved from a container i.e. Windsor, Spring.net etc.

A CTP is due towards the end of the year (Monorail will suffice just fine until, and probably far after then) and the framework is slated for release with VS2008 as an add-on to the general release.

Some of the things I’ll be interested in seeing are whether the following are supported:

  • Handling devices, i.e. sniffing user agent and providing different views. Something just recently provided in patch form to Monorail.
  • The MSMVC equivalent of Monorail’s ViewComponent concept.
  • Routing and URL rewriting support.
  • Monorail Helper equivalent.
  • AJAX support.

It has been mentioned that some of the plumbing may be used to reduce the Monorail codebase. Now that could be interesting…

Agile project management with StoryVerse

If you’re practicing agile project management take a look at StoryVerse – an open source agile project management application built on Monorail and ActiveRecord.

StoryDetail

In particular I like the no-fuss UI. Very reminiscent of Google UI. Anyway take a look.

Quick SmartDispatcherController tip

If you’re using the SmartDispatcherController in your Monorail application, consider restricting the parameter store using the From property defined on the DataBindAttribute. You’ll get a small performance boost (as Monorail doesn’t have to go looking for whether the data is coming from querystring or form post) and you get the added benefit of preventing submits through querystring or form when it is not the intended behaviour.

Example:

public void Create([DataBind("contact", From=ParamStore.Form)] Contact contact)
{
    //...
}

Dependency injection with Monorail and Windsor

Dependency Injection (or IoC) is a practice I apply when designing software. It enables enforcement of the Single Responsibility Principle and also has the added side effect of producing more testable code.

Scott Bellware has posted an excellent write-up on dependency patterns and it got me thinking about my favoured approach with dependency injection and how the Castle Windsor container provides that for us. I favour constructor based DI as it enforces the fact that your class must be wired up during initialisation. It makes your dependencies highly visible and as Scott mentions – goes some way to producing a self-documenting API.

Some of the common alternatives, or perhaps complimentary approaches include resolving dependencies from the container or service locator hidden in the constructor (dirty), or the provision of property setters for your dependent interfaces. Of course providing getters (or at least public getters) is a no-no as you would be exposing your dependencies to consumers thus violating encapsulation. But I guess this goes without saying?

Thankfully, Monorail controllers and their dependencies can be wired up using constructor based DI via RailsFacility and Windsor integration. Take the following example:

dependencies

ContactController in the diagram above is a simple Monorail controller that depends on the IContactService to carry out most of its work. Stemming from there the IContactService implementation has dependencies on IContactRepository and an external library (from NSpectre) interface IValidatorFactory which is created using the Windsor factory facility and some custom factory code, but more on that later… As you can see from the model, the dependencies are injected via constructor arguments.

Using the RailsFacility is fairly simple, rather than me explaining it I’ll point you to the docs here. Once you’ve got the facility and container set up, you simple declare your controllers and their dependent components via configuration:

<component id="contact.controller" type="Campaigns.Controllers.ContactController, Campaigns.Controllers">
      <parameters>
        <mailTo>benjamin.lovell@gmail.com</mailTo>
        <subject>Contact message from Website</subject>
      </parameters>
    </component>

I’ve explicitly declared some of the required values for the ContactController constructor above. Just as reminder the signature for ContactController  constructor:

public ContactController(IContactService contactService, string mailTo, string subject)

When the ContactController is wired up by windsor the IContactService contactService argument is resolved to the following service configured in my components.config file:

<component id="contact-service"
               service="Campaigns.Core.IContactService, Campaigns.Core"
               type="Campaigns.Services.ContactService, Campaigns.Services">
    </component>

Of course, ContactService also joins in the fun and has its dependencies injected via the same means:

<component id="contact-repository"
               service="Campaigns.Core.IContactRepository, Campaigns.Core"
               type="Campaigns.Repository.ContactRepository, Campaigns.Repository" />

Windsor detects that the ContactService constructor takes a IContactRepository argument and resolves this automatically.

Now for the keen-eyed among you, and going back to my point earlier regarding the IValidatorFactory dependency… This is resolved using the natty Windsor factory facility, the best explanation of which is here. In my configuration I state that IValidatorFactory dependencies should be resolved via my custom factory code:

using NSpectre.Core;
using NSpectre.Core.Configuration;
using NSpectre.Core.Implementation;

namespace Campaigns.Core
{
    /// <summary>
    /// Factory for NSpectre validators
    /// </summary>
    public class NSpectreFactory : INSpectreFactory
    {
        #region Fields

        private readonly string xmlEmbeddedResourcePath;
        private readonly bool saveGeneratedCode = false;
        private readonly string path;

        #endregion

        #region Constructors

        /// <summary>
        /// Initialises the factory with the embedded resource path.
        /// </summary>
        /// <param name="xmlEmbeddedResourcePath">The path to the embedded resource.</param>
        /// <param name="saveGeneratedCode">Save the generated code</param>
        /// <param name="path">The path to save the code to</param>
        public NSpectreFactory(string xmlEmbeddedResourcePath, bool saveGeneratedCode, string path) : this(xmlEmbeddedResourcePath)
        {
            this.saveGeneratedCode = saveGeneratedCode;
            this.path = path;
        }

        /// <summary>
        /// Initialises the factory with the path to the NSpectre configuration embedded resource.
        /// </summary>
        /// <param name="xmlEmbeddedResourcePath"></param>
        public NSpectreFactory(string xmlEmbeddedResourcePath)
        {
            this.xmlEmbeddedResourcePath = xmlEmbeddedResourcePath;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the path to the configuration embedded resource.
        /// </summary>
        public string XmlEmbeddedResourcePath
        {
            get { return xmlEmbeddedResourcePath; }
        }

        /// <summary>
        /// Gets a flag indicating whether NSpectre should save the generated code.
        /// </summary>
        public bool SaveGeneratedCode
        {
            get { return saveGeneratedCode; }
        }

        /// <summary>
        /// Gets the path to save the generated code to.
        /// </summary>
        public string Path
        {
            get { return path; }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Creates the validator factory
        /// </summary>
        /// <returns>The validator factory, initialised</returns>
        public IValidatorFactory CreateFactory()
        {
            IConfigurationReader reader = new EmbbeddedXmlResourceConfigurationReader(xmlEmbeddedResourcePath, new NullLogger());
            Initialiser initialiser = new Initialiser();

            if (SaveGeneratedCode)
                return initialiser.CreateValidatorFactory(reader, saveGeneratedCode, path);
            else
                return initialiser.CreateValidatorFactory(reader);
        }

        #endregion
    }
}

The custom factory is hooked up using the following configuration:

<component id="nspectre.factory" 
               service="Campaigns.Core.INSpectreFactory, Campaigns.Core" 
               type="Campaigns.Core.NSpectreFactory, Campaigns.Core">
      <parameters>
        <xmlEmbeddedResourcePath>Campaigns.Core.Model.NSpectreValidations.xml, Campaigns.Core</xmlEmbeddedResourcePath>
      </parameters>
    </component>

    <component id="nspectre.default" 
               type="NSpectre.Core.IValidatorFactory, NSpectre.Core"
               factoryId="nspectre.factory"
               factoryCreate="CreateFactory" />

You really notice the effectiveness of this approach when adding new controllers to your project. You simply add the controller code, define its dependencies in the constructor and add the configuration for the controller to your controllers.config file and everything is resolved and injected for you at runtime. Very nice indeed, I’m sure you will agree!

Testing is made easy by providing dynamic mocks. To make this an even nicer experience take a look at the AutoMockingContainer from the nice folks at Eleutian!

To wrap up I have to say: Castle really does kick the llama’s ass.