.net and other musings

Ben Lovell, an agile developer living in the UK.

Category: ASP.NET

Incremental development with Monorail: Part Seven

Since our last installment I slipped in a ninja-edit to one of the configuration files. This was to ensure that our sole service was marked as transient rather than the default Windsor lifestyle of singleton. This was pointed out to me by an eagle-eyed commenter and was an oversight on my part. So we’re now at rev10 and ready to roll once again!

In our last post we tidied up a few bits and improved our code-base rather than actually adding features as such. This time we’re going to move down into the persistence and start to drive out this notional layer.

We’re going to handle data access using the repository pattern. The repositories will work on our ActiveRecord entities ensuring they’re persisted to our database. We will introduce a new interaction between our service BlogPostService and the newly introduced repository interface IBlogPostRepository. Let’s get on and write a test:

71

The test above is fairly self-explanatory. We’ve introduced the IBlogPostRepository and we’re passing it into our BlogPostService which should then call the Save method passing our mapped post. We need to get rid of the red code and get the test passing, so first we must create our new interface, and then modify the service constructor:

72

73

We need to modify our other tests that construct the BlogPostService as they’re still assuming only a single argument constructor exists. As we have some duplication going on we’ll push this construction up into our setup code:

74

We should be able to run our tests in this fixture now:

75

As expected, since our BlogPostService doesn’t actually do much with our repository yet, we need to do some pretty minor tweaking to pass this test:

76

Let’s try again now:

77  Cool, let us try and run the whole suite including our integration type tests:

78

The integration tests are failing as we’ve yet to map the new dependency in our Windsor configuration. We can specify this now:

79

We still have failing integration tests though, so we need to add the BlogPostRepository specified in our configuration:

80

As you can see it doesn’t do much, but we just want our tests passing at this stage. Let’s run the whole suite of tests now:

81

Great, we have a working product once more. I’m going to finish here, as ever, the latest changes have been committed:

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

Next time we’ll make our new repository more useful and finally hit the database!

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 Five

Welcome back. In this post I’ll be getting our tests passing again and cleaning things up a little. We left off with a failing integration test:

42

I suspect this is due to the IBlogPostMapper dependency we introduced to our BlogPostService not being handled by the container. If we run in the browser we can confirm this is in fact true:

As we’ve yet to implement our IBlogPostMapper we must go ahead and do this before we can add the container configuration to pass our integration test. Lets bust out a test and get things rolling:

43

We have a few blanks to fill in in order to get this to compile and run:

  1. Make the DTO’s properties virtual so we can mock them. This is in preference to extracting an interface.
  2. Implement IBlogPostMapper.
  3. Add the necessary properties to the IBlogPost interface.

Lets go ahead and do this now:

44

IBlogPostMapper minimal implementation:

45 

The necessary modifications to IBlogPost:

46

Now we can compile and run our test:

47

Our BlogPostMapper implementation is throwing an exception so lets go back and take another step to try and pass our test:

48

BlogPost:

49

I’m pretty certain we’ve done enough to pass our test now. Lets have a go:

50

OK now lets focus on the full suite:

51

Our integration test is still bombing but as we’ve got a mapper now, we can go ahead and wire up our Windsor configuration and get things moving again:

52

We’ve added another configuration file: mapper.config and referenced this from the web.config. We shouldn’t need to do any more than this so lets run our full test suite:

53

Our full suite is passing now. Not bad for 5 minutes work! As usual the latest changes are checked in to the Google code project hosted here.

Now we have a full passing suite, in our next edition I’ll be moving down into the persistence and also incorporating a few modifications from Hammett. Stay tuned!

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/

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.

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…

Windows Vista and IIS Features (or lack of)

Damn. I’m late to the party and I’ve only just recently started using Vista for development. One thing I’ve just stumbled across is that you can’t debug ASP.NET applications with IIS7 on Vista Home Premium, as Windows Authentication is disabled and cannot be enabled in this SKU. Hmmm, upgrade here I come.

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)
{
    //...
}

BackgroundMotion sample application

I found BackgroundMotion via Andrew Peter’s blog – created in partnership with Microsoft as a “best practice” example application. I’ve had a look at the source code and at first glance it’s quite a nicely architected solution… Certainly better than some of the starter kits coming out of Microsoft (anyone remember Petshop!?). Anyway it features all of the following:

  • Use of a domain-driven design techniques. Repository and Unit of Work abstractions over LINQ to SQL
  • Model-level validation using the Validation Block
  • Dependency injection using Composite Web Block
  • Using Lucene.NET to index a domain model
  • Using MVP with declarative data-binding in the presentation layer

Nice to see Lucene.NET being employed. As is NUnit. I’ll have a closer look when I get a chance. Expect some comments shortly.

RoR vs. Web Forms vs. MonoRail Pt2

Ok so in the last post I talked about some of the more obvious issues I have with ASP.NET and web forms development. Thankfully, the Castle Project’s MonoRail framework goes some way to alleviating that pain.

The Positives

MVC, MVP, ABC easy as 123…

Under the covers, MonoRail is a full MVC compliant framework essentially comprising a front controller sitting over the ASP.NET infrastructure intercepting specially formed URI’s. The HTML ends up in the browser via your choice of view engine, with NVelocity (a fork of the Jakarta Velocity port) the default and most accessible, Brail being the Boo dynamic language and most performant option and of course a cruddy web forms engine too which nobody should use. 🙂 I’ve been comfortably using NVelocity for a while now, and provide testament that its not difficult to pick up.

The controller code orchestrates the flow of logic through the application and rails URI’s map nicely to actions on the controller which are ultimately public methods on the controller class itself. All nice and easy. Actions exposed on controllers derived from the magical SmartDispatcherController can translate posted form values into domain model objects for you by simply adding the DataBind attribute to your action’s argument list:

public void Save([DataBind("publisher")] Publisher publisher)

In the above example the publisher argument is passed into the Save action fully constructed via the form or query string values posted! This saves on the usual binding and scraping stuff you normally do in web forms and which almost always ends up sitting in the code behind untested. Note: the databinding stuff is of course very flexible and my example above just touches on the possibilities.

ActiveRecord

The model can be supplied with an ActiveRecord enabled domain model. This of course abstracts away NHibernate behind the scenes. Unfortunately generic collections support doesn’t work right now but I believe that work is firmly underway.

Edit: Generic collections are supported, as long as you’re running from the trunk.

Domain entities are adorned with the necessary attributes defining how their properties are mapped to your data source. This is a departure from the usual hbm XML mapping files but just as expressive.

ActiveRecord also supplies simple validation in the form of special attributes including email validation, regular expression validation and the like.

UI Components

Reusability of UI components is achieved via ViewComponent. These can support nested sections, parameters etc.

AJAX and client scripting support

Built into MonoRail are a number of helpers which allow you to perform the usual AJAX stuff such as calling remote server side methods and callback support, Scriptaculous and Effects2 client side goodness. In fact the helper extensibility is a nice way of adding extensions and wrapping commonly performed functionality in the view.

Convention over configuration

Like RoR, MonoRail prefers convention over configuration. The project structure skeleton is the same throughout all MonoRail enabled solutions. The MonoRail installer also includes a handy templated solution provider for both VS.NET 2003 and 2005 to create the project skeleton and testing is included. Accustomed MonoRail developers can open any solution and just know where things are going to be.

Testability

One of the sore points of ASP.NET development was the unit testing difficulty. MonoRail overcomes this by enforcing the MVC pattern. Controllers are testable classes sitting outside of the usual ASP.NET cruft. There are a number of framework features within MonoRail which specifically aid testing.

Scaffolding

Like RoR, controllers adorned with the necessary scaffolding attributes can automatically produce the basic markup and logic for CRUD operations on your domain model. Handy for prototyping or creating rough-and-ready data entry capabilities in your applications.

Container support

MonoRail supports IoC via the Windsor container. Controllers and their dependencies/parameters can be injected by the container if necessary.

The negatives

MonoRail does have some negatives, which I will mull over:

No 3rd party or ASP.NET web forms controls support

I don’t really see this as an issue but can see that some ASP.NET developers will. Fans of the big UI library packages will complain, but there is this old concept of HTML and it is surprising how flexible it can be 😉 Most use of control libraries I have seen has been misguided, by this I mean they’re usually added to a screen just because they can.

The web forms control library isn’t such an issue as things like calendars, grids and the like are not to difficult to duplicate the MonoRail way.

Learning a whole bunch of new concepts/patterns/practices

Most ASP.NET developers are what can only be described as morts. They’re not familiar with design patterns and good practices such as clean separation since they came from either ASP or VB (procedural backgrounds) so this stuff doesn’t come naturally. If you’ve used NHibernate you’ll pick up the ActiveRecord stuff in no time. Learning the template syntax for your chosen view engine is of course another consideration.

Summary

In summary, the benefits of using MonoRail over web forms are clear. Clean separation of concerns, testability, reduced complexity and none of the web form cruft and artifacts. MonoRail won’t suit everybody, but even if you’re happy with web forms it’s definitely worth a look. Personally I think its the only way worth programming in the enterprise with ASP.NET today.

RoR vs. Web Forms vs. MonoRail

As you know, I’ve been lucky enough to do a fair bit of Ruby on Rails development lately and well, what can I say? I’ve been spoiled! The development experience leaves me running out of expletives. I adore Rails… Especially in contrast to ASP.NET or more specifically – web forms. I have always had mixed feelings with regards to ASP.NET but now more than ever – given my aforementioned experience of the graceful RoR framework. Allow me to elaborate on some of the issues I have with ASP.NET:

The cruft to allow stateful paradigms on a stateless protocol…

… Of which there are several: post-backs, view-state and complex page life-cycle immediately spring to mind. In trying to do anything slightly dynamic with the control tree you run into view-state problems difficult to debug and frankly just not worth the bother. Web Forms and control development in general is a black art thanks to the huge and unwieldy collection of events kicking off during the page life-cycle – which nobody really understands save for perhaps God and Scott Guthrie. In trying to create an abstraction over the inherent statelessness of HTTP, which by definition should reduce complexity, ASP.NET has only served to add more. Yes, ASP.NET utterly bastardises HTTP. Make no mistake.

Code behind, beside, back-to-front etc

Code behind is a decent concept. Providing a means to remove application logic from the view – you know, seperation of concerns and all that. However, the common use for the code-behind is more often like an application logic purgatory if you will – between the final dispatch to heaven (the middle tier) or hell (the view). OK so ASP.NET doesn’t force you to put logic in the code behind but it doesn’t exactly encourage you not to? The path of least resistence is always the path most followed, which in this case means piles of code which should sit in a lower tier being present in the code behind.

Testability

It is extremely hard to write testable code in ASP.NET. Mainly due to the previous point regarding code behind. Logic creeps into the code behind where it is impossible to get to by conventional testing. Sure you can write acceptance or end-to-end tests using Selenium or some other automated UI testing tool, but i’m talking closer to the metal tests… as-in unit tests.

The built-in ASP.NET controls

Most of them are overly complex and rely on piles of viewstate to get things done. ASP.NET 2 helps reduce the payload a little via control state but this is just another quirk if you ask me. Controls produce dodgy markup (ok I’m aware of the whole control adapter thing, but why should I fix MS broken HTML?) and bizarre ID tags making cross browser and standards-based web development a real bane. Some of the other weirdness such as handling OnDataBinding and OnItemCreated etc and reaching into the control tree just to highlight a particular row or cell is a real pain. Some of the big-boy controls have this kitchen sink approach i.e. datagrid, gridview etc. The validators, while a nice concept, don’t really cut it in the enterprise world. Where you’d almost certainly be performing proper validation in your DomainModel someplace.

IDE and designer integration

ASP.NET and the .NET framework in general were created to sell tools and server licences, which is clearly evident given the tight coupling with VS.NET. Take VS.NET out of the picture and ASP.NET development is a hugely different and less pleasurable experience. Show me someone who can create an ASP.NET web application using Notepad? Of course thats not what we should be using in the enterprise but its a good benchmark for both a language, or framework simplicity.

There are things I do like about ASP.NET. I like the extensibility of the provider model, the hosting aspect, the HTTP pipeline and extensibility points such as modules and handlers are nice – especially in IIS7. It scales too, but a lot of that is due to IIS from 6 and on really.

So is there a light at the end of the tunnel? Well, yes… In the form of the fantastic MonoRail framework. Stay tuned for part 2 🙂

Ode to VS.NET 2003 webform designer

The VS.NET webform designer,
Was engineered by a bunch of part-timers,
I clicked ‘design-mode’ and it ate all my code,
I can’t wait til the day I retire

🙂

Orcas Designer: The New Hope

With reference to my last webform designer woes post, someone has pointed me to the upcoming webforms designer in Visual Studio codename Orcas. Apparently Orcas takes the design surface from Expression Web, which is an altogether nicer experience than that of the current Visual Studio products.

Good news as well is that Orcas supports multiple build targets… So .NET 2.0 compatibility is guaranteed too! I’m downloading as I post this and I’ll post a mini-review of sorts as soon as I’ve had a thrash around.