Archives / 2008 / July
  • Clean Separation of Concerns in MVC

    One of the main areas that is cited as a benefit of using the new ASP.NET MVC Framework is that you can obtain a 'clean separation of concerns'. But the question is, what does this really mean, how achievable is it in reality, and should we really be interested in doing it?

    What does it mean?

    Well, from Wikipedia ( - 'the process of breaking a computer program into distinct features that overlap in functionality as little as possible'. The article goes on to say that the MVC design pattern aims to separate content from presentation and data-processing from content. This is all well and good, but where do the lines of separation fall. One is reasonably clear - between the data-processing (Model) and the rest of the application. Almost every attempt at writing an MVC Framework web application illustrates this successfully.

    The slightly harder area to tie down the separation for is when you look at Views and Controllers. Where should the separation occur? What is the division of responsibility? Should the two portions be completely independent, or can they have knowledge of each other? At a certain level, it is reasonably easy to provide some definitions: the view takes responsibility for presentation, and the controller takes responsibility for actions. But there is clearly a grey area in the middle. Clearly most actions can be completed without much dependency on the view that is their 'end point', but the reverse is not necessarily true. In a simple 'display' view there is no problem, but by the time we move to 'editors', we are starting to get into the realms of some trickiness of definition. In fact the way the view is set up may have critical importance to the nature of the controller. This is probably best illustrated with an example. Let us say that I have written a appointment diary application. One of the editors in this is used to change the date of an appointment. I could choose to display this date in one text-box (DD/MM/YYYY format), or I could decide that it will be easier to use if I split it and put the day, month and year components of the date in different text-boxes. Either way, I have introduced a link between the way the data was displayed and my controller. If I change one way of displaying the date into another, I may need to change the controller, unless the view takes care of returning the date to the format from which it 'came'.

    But here lies another problem - 'format from which it came'. It's perfectly legitimate in MVC that the View may have fetched the data it is displaying from the Model directly and that the Controller had no knowledge of the original form of the data at all. Either way, we are getting towards the situation where the Controller needs knowledge of at least one of the Model and the View in order to function. The problem really comes from the nature of HTTP. The View is split between what it was on the server, and what is able to be transmitted 'over the wire'.

    So is full separation achievable?

    Well, we could remove the requirement that the Controller knows things about the View. It would require something of a rethink to the way the MVC Framework is currently designed though. It would require that Views 'submit back to themselves', that the View can then sort out the data before triggering an appropriate Controller action. But there is a problem. We've essentially introduced a dependency that the View now needs to know about the Controller. So we're back to square one! I therefore don't think that the View and Controller having no knowledge of the structure of each other is practical. They are implicitly linked.

    Where does that leave us?

    Well, not all at sea, thankfully! And luckily, I think in considering what we really mean, we come to what really turns out to be a very good way of architecting an MVC web application. I believe that the separation is not a totally strict one of encapsulating all knowledge about the different portions of the code, but rather a clean separation between behaviours and views. Interestingly, this is one of the key points of object oriented design that is often overlooked - designing an application by the behaviours that it must be capable of. The REST-like routing system built into the MVC Framework as it stands takes you even further down this route of considering the application to be much like an object oriented design. Essentially therefore, Controllers can (in some sense) be likened to classes (and indeed this is the language construct they use!), and Action methods are the behaviours of which a Controller is capable. The big advantage of these Action methods being thought of as behaviours is that writing Unit Tests for them becomes a very natural process.

    The conclusion of all of this is that there is going to have to be linking between your Controllers and Views. They can't be written to operate independently. The key point is to see the separation between behaviours and templates. Don't code things that are going to cause a change to the model into your View, and don't code things that are purely a matter of presentation into your Controllers, but expect a certain amount of grey area where the communication between them is concerned.


  • Web Application Usability

    Although this blog is principally about ASP.NET and web application development, I thought I'd drop in a link to an interesting article over on Simple Talk. It's about how to design a software tool. A large portion of what Stephen discusses is to do with user interaction, which is, in my view, absolutely critical to web based applications. The process we use for application design, and for web application design is fundamentally the same here at Red Gate, and this article gives a few insights into the way we do it.

    Linking a couple of different concepts together, we are in the process of reviewing the usability of Simple Talk itself. One of the things we've been highlighting is the fact that there is a lot of content available on the site, and that we need to help people get access to it much more easily, something that they can't necessarily do particularly well at the moment.

    We get a high number of visits to recently published articles such as the Geek of the Week column (for example this week featuring an interview with Linus Torvalds), but people seem to find it hard to access older content. We're going to be looking at this in some depth in the coming weeks, so if you're a Simple Talk reader and have got any particular requests or suggestions, now is the time to get them in, and we will try and do something about them.


  • MVC AJAX Support

    In the latest preview of the Microsoft ASP.NET MVC Framework, one of the newly included features is AJAX helper methods. It's going to be interesting to see where they go with these. At the moment, they've added just a couple of tasters. This blog post discusses how to set them up and make use of them if you want to try them out. Currently, there are two helper methods that have been created, Ajax.ActionLink and Ajax.Form. I will discuss both below. They both generate HTML, much in the manner of pre-existing helpers such as Html.Form.

    The first thing to look at is how to set a page up to be able to make use of these helper methods. Since they are going to call parts of the JavaScript libraries that are part of the Microsoft AJAX Framework, you need to include them in the head section of your page. There are two files that you need to include. Microsoft are currently shipping them in both debug and release configurations. It doesn't matter whether you have debug or release, but you will need to have both files included, and included in the correct order. This will look something like the following:

       1: <head runat="server">
       2:     <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
       3:     <title>AJAX Example</title>
       4:     <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
       5:     <script type="text/javascript" src="../../Content/MicrosoftAjax.js"></script>
       6:     <script type="text/javascript" src="../../Content/MicrosoftMvcAjax.debug.js"></script>
       7: </head>

    Once these have been included, you will be free to use the AJAX tools that have been developed. It is worth a quick aside to briefly discuss the payload size of these Framework helpers. Currently, MicrosoftAjax.js represents about 89KB and MicrosoftMvcAjax.debug.js is about 6KB. These numbers obviously aren't too bad. They're bigger than the equivalent jQuery files, and it will be interesting to see how it matches up as time goes on.

    Having set up the Framework requirements, we can proceed to use the tools supplied. The essence of the helpers that have been created so far is that they allow you to easily make an asynchronous call to a Action Method and to use the response. This essentially makes it possible to create the equivalent of the UpdatePanel from WebForms. This is probably best now illustrated with a simple example, building on top of the standard MVC site that is shipped with the Framework. In the code for the Index view (Index.aspx), we can include something like the following:

       1: <div id="testContainer">
       2:     <%= Ajax.ActionLink("About", "About", new AjaxOptions { UpdateTargetId = "testContainer" })
       3: </div>

    The next stage is to alter the About view (About.aspx) to remove most of the strapping from it. It is not going to need to have a MasterPage for example, or in fact to have anything but some example text.

    So, what is the effect of all this? Well, run it up in a browser and we'll see what happens. As you might expect, running the default page for the site brings up the Home/Index page as normal. Some way down the page, there is a link with the text 'About'. So we click on it. What should happen, all being well, is that the contents of the About view becomes inserted into the page in place of the About link.

    Obviously, there is fairly limited potential in links for passing information back to the controller, so the natural extension is to want to have an 'AJAXified' form. And lo and behold, one exists. Ajax.Form works in a very similar manner to Html.Form (with the exception of needing AjaxOptions just like ActionLink does). And indeed it 'just works' much like you would expect.

    One final aspect of this Framework is worth discussing in this post I believe, and that is controlling what view is selected. Obviously if we have received a request as an AJAX request into the controller it is highly likely that we will want to show a different view to if we had received it as a normal HTTP request. In this case, there is a helper method that is your friend:

       1: if (Request.IsMvcAjaxRequest())
       2: {
       3: }

    This does exactly what it says on the tin and will tell you from where a request originated. The most obvious use of this is, as mentioned above, in switch which view to use. The fact that a view can be an ascx file just as easily as an aspx file gives us therefore a fairly neat way of providing a page with something that will feel a lot like an UpdatePanel in the centre. Instead of the UpdatePanel, we can make the part of the page that will update an ascx file and then include it as a UserControl in our normal view page. We therefore serve the aspx page the first time (when the request is a normal HTTP request) and can then serve just the ascx file for subsequent MVC AJAX requests.

    I do feel at the moment that this framework offers only fairly coarse grained control compared with what is currently available through something like jQuery. The word on the street (or at least ScottGu's blog) is that they're making this a pluggable part of the process just like every other part of MVC. Certainly for ActionLinks at the moment, I think jQuery represents a better solution (lighter, more flexible and just as powerful). For Ajax.Form, I'm not sure one way or the other yet, but it does look like a relatively neat solution. You can certainly achieve the same functionality using jQuery and cause a form to POST, but it does require a certain amount of duplication of code between the jQuery code and the HTML code to set up the form.


  • New versions of Red Gate products

    Well, we've rolled out new versions of several of our products here at Red Gate. In particular, these have been adding SQL Server 2008 support. You can read more about these updates on the website

    As well as SS2008 support, the new versions have picked up lots of bug fixes and a few extra features to boot.

    These are the first wave of the 2008 supporting tools. The remainder are due to be rolled out in the coming weeks. If you want to see some of the forward plan, have a look at - there's some exciting stuff in the pipeline!


  • MVC Preview 4

    It's been announced on ScottGu's blog that MVC Preview 4 is due out later this week. Obviously we'll need to wait and see what it feels like when we get to have a play for real with it, but first impressions from reading down the article is that they seem to have nearly nailed down the core API to create a version that's close to what will go live, and are now busy working on all the bits and pieces that will be necessary for actually using it in a commercial sense. So we're now getting good authorisation, error handling and the like. I'll be getting it as soon as it's released and giving it a good going over to see how the new features play.


  • MVC training day 2

    Back for more! We started the day with a quick look at Dynamic Data (no more than an overview for those that hadn't seen it before), then moved on to look at unit testing the MVC framework, before finishing off with a look at jQuery and how it works with MVC.

    Unit Testing

    We looked at unit testing using NUnit and Moq. It was the first time I'd used Moq and it was interesting seeing just how well the approach fits with MVC. Essentially the idea was to be able to simulate the whole HTTP Context outside of a web server, using mock objects. Steven had written a helper class that mocked up the various parts of things like the request that would be needed to let a web application run successfully. This worked very neatly and allows you to push on in a rather succinct way with your testing and write very nicely structured tests that achieve good coverage of your controllers. Obviously, this does not cover unit testing of the views, but that's a slightly different problem.


    I've used jQuery before on 'Classic' ASP.NET projects, but it's pretty good seeing how easily it fits in with the MVC framework. The tighter control of the HTML output you get with MVC certainly lends itself much more readily to jQuery manipulation. No more worrying about exactly what the ClientID is going to be!

    Steven commented that the word on the street was the Microsoft are saying that they're going to be introducing some sort of AJAX compatibility layer before MVC goes RTM, but it's not yet clear what that's going to be.


  • MVC training day 1

    We've had the first of our two half days with Steven Sanderson this morning. It was split in half, with the first half covering the new C# 3.0 language features and the second tackling MVC.


    We went through some fairly basic examples of LINQ to Objects just to bring everyone up to speed, covering the major language features involved (extension methods, lambdas, generic type inference, automatic properties, anonymous types and the like).


    Moving on to the real meat of the session now! Steven first covered some of the reasons behind MVC. This includes things like the fact that we have fairly limited control over the rendered HTML with WebForms, a false separation of concerns and that it is fundamentally hard to test. He stressed that WebForms fundamentally does quite a good job of what it was designed to do, namely help people coming from a WinForms background in migrating to writing Web Apps. However it doesn't really 'play nicely' with the way the Internet really works.

    We then went through a worked example, building up a sample application. Coming from a Perl/CGI background originally (before I got into ASP.NET) I felt that a lot of what I was seeing was very good and that it stands a chance of removing some of the dirty hacks that start to creep in when you want to do anything more complicated than 'My First WebForm'. It's important to recognise that it isn't for everyone however: you need to understand far more about the way the Internet and HTTP really work in order to get the most out of MVC. That said, if you do understand, you're going to be able to push the tech a lot harder before it starts to fight back!

    I've watch a few presentations on MVC before, but this was the first time I've actually 'got my hands dirty' with it. I am really excited about the direction it's going. There's no doubt that you are forced to think about your web applications in a very different way when using it compared with WebForms, but I don't think that's necessarily a bad thing. It's certainly a technology that we're going to be exploring here in Red Gate's web division (although obviously you're unlikely to see anything written 'for real' in it until it goes to version 1 - probably some time in Q4 2008).

    Tomorrow we've got sessions looking at unit testing and how it fits into MVC, followed by using jQuery and AJAX with it.


  • MVC Training

    Starting tomorrow we've got a couple of training sessions on the new ASP.NET MVC framework lined up here at Red Gate with Steven Sanderson. Steven used to work here, but is currently busy writing one of the books that's going to be an authority on the subject. Check it out here!

    In the web team here we're all looking forward to it and hopefully I'll write up some of the more interesting aspects here! If anyone has any specific questions that you'd like me to put to him, leave a comment below and I'll see what I can do.