Thoughts on Software by Andrew Davey
 Monday, March 24, 2008
Testing Controller RenderView

I've seen people testing that RenderView is called by a controller by inheriting into a "testable" controller. Madness!

RenderView is just a convenience method that calls to IViewEngine, so why not just test expectations on that with a mock? We basically want to test that the correct ViewContext is sent to the RenderView method of the view engine.

This is my test:

[TestFixture]
public class HomeControllerTests : ControllerTestsBase<HomeController>
{
    public override HomeController CreateController()
    {
        return new HomeController();
    }

    [Test]
    public void Renders_Index()
    {
        var render = ExpectRenderView();

        Controller.Index();

        Assert.That(render.Data.ViewName, Is.EqualTo("Index"));
    }
}

I don't think we can get more straight forward than that!

This is my test base class:
(I'm using Moq as the mock framework.)

public abstract class ControllerTestsBase<T>
    where T : Controller
{
    public T Controller;
    public Mock<IViewEngine> ViewEngine;

    [SetUp]
    public virtual void SetUp()
    {
        Controller = CreateController();
        ViewEngine = new Mock<IViewEngine>();
        Controller.ViewEngine = ViewEngine.Object;

        Controller.ControllerContext = new Mock<ControllerContext>(new Mock<HttpContextBase>().Object, new RouteData(), Controller).Object;
    }

    public abstract T CreateController();

    public RenderCall<ViewContext> ExpectRenderView()
    {
        var render = new RenderCall<ViewContext>();
        ViewEngine.Expect(v => v.RenderView(It.IsAny<ViewContext>()))
            .Callback(new Action<ViewContext>(render.Set));
        return render;
    }
}

The RenderCall class provides a place to receive the view context that is passed.

public class RenderCall<T>
{
    bool _called;
    T _data;

    public T Data
    {
        get
        {
            if (!_called) throw new InvalidOperationException("View was not rendered.");
            return _data;
        }
    }

    public void Set(T data)
    {
        _data = data;
        _called = true;
    }
}
Monday, March 24, 2008 4:08:16 PM (GMT Standard Time, UTC+00:00)  #    Comments [0]   |  |  | 

 Tuesday, February 19, 2008
VB.NET 9 as an HTML View Engine

VB.NET 9 introduces a clean syntax for expressing XML data. XHTML is XML so why not use VB.NET to generate it, instead of ASPX pages? People are creating view engines for the new ASP.NET MVC framework. How about a view engine that uses VB.NET XML literals?

The benefits to this approach include full intellisense and access to a the full VB.NET language when creating HTML.

I see a view as a function from some data to an XML element (the <html> element):

Function CustomersPage(ByVal title As String, ByVal customers As IEnumerable(Of Customer)) As XElement
    Return _
        <html>
            <head>
                <title><%= title %></title>
            </head>
            <body>
            <%= From customer In customers Select _
                <div id=<%= customer.LastName %>>
                    <h1><%= customer.FirstName %></h1>
                </div> %>
            </body>
        </html>
End Function

The important change from ASPX is that this is HTML in Code, rather than Code in HTML. As a result less "automagical" behaviour is required; It's just a function! This means AJAX features like "partial rendering", where a section of page needs to be updated, can be expressed by just calling a function that returns a <div> element. That same function can be used by the full HTML page function too.

ASPX "usercontrols" become simply functions as well. ASPX Master Pages are functions that have arguments for "placeholders" that get inserted into an template HTML page. Instead of having to reinvent a bunch of programming language concepts inside ASPX, we can just use a programming language that now support XML!

The only down side to this approach is we lose the IDE visual designer support. However, I find viewing an ASPX page that contains even simple conditional data rendering next to useless. I'd rather keep IE open and just refresh the page to see changes.

I am yet to embrace the MVC framework. I am waiting to see if the next release can better support Snooze framework ideas. However, there's no reason I can't use this VB XML magic in Snooze as it current is.


Tuesday, February 19, 2008 12:12:17 PM (GMT Standard Time, UTC+00:00)  #    Comments [0]   |  |  |  |  | 

 Monday, December 24, 2007
Nouns-Verbs, OOP-Functional, REST-Web Services

This is just a quick thought that came to me whilst making coffee this morning...

REST places focus on nouns (resources) in a system. Whereas it seems web services are more concerned with verbs. A service is a collection of operations. The data is passed to and from operations as messages.

Now both approaches have their merits. What strikes me as strange is our choice of programming languages when attempting to implement the aforementioned architectural styles. Object orientated programming is all about nouns (classes). Functional programming is all about verbs (functions).

I know that there is way more to web services than just a bunch of operations (because that would be simply RPC right?). However, my point is that surely OOP is ideally suited to describing a set of resources as required by a RESTful design.


Monday, December 24, 2007 9:44:48 AM (GMT Standard Time, UTC+00:00)  #    Comments [2]   |  |  | 

 Sunday, December 23, 2007
REST Verbs in ASP.NET MVC

I am yet to play with the new ASP.NET MVC framework. However, I am spending time reading around the area to see if it will benefit me to get more involved.

A concern that came to mind when researching is the claims of it enabling a RESTful approach to web programming. Whilst this may be true, all the examples so far seem contrary to REST. My limited understanding of REST says that URLs represent a Resource. How is http://www.mysite.com/customers/delete/42 a resource?!

Yet that is indeed the format of URL we are being shown by Scott Guthrie and others. It makes ASP.NET MVC look more like another RPC system, just with parameters encoded into the address instead of message body.

So is it possible to specify a resource URL and then a number of HTTP verbs that can execute against it? It probably is, given the extensibility of ASP.NET MVC's architecture. However, one may ask, should I be hacking this into the framework? Would the end result look anything like the original MVC code at all? Probably not!

Is it time for a real REST framework built on top of ASP.NET? I think it is!

It needs to be Resource centered. It needs to fully leverage the rich feature set of HTTP, not just GET and POST! And just to be awesome, it needs to have a client-side story too. Real REST relies on the client-side to store state. Could this be Silverlight, or do we still want JavaScript? (I'm up for cross compiling to JS from C# or MSIL!)


Sunday, December 23, 2007 4:02:00 PM (GMT Standard Time, UTC+00:00)  #    Comments [5]   |  |  |  |  | 

 Sunday, November 04, 2007
C# Code Transformation Tool

I've made a custom Visual Studio tool that uses a C# parser
(http://www.codeplex.com/csparser/) to convert C# code into an XML
representation. So far only the declaration stuff, classes, method
signatures etc.
I then have a XSLT template engine that takes the XML and a template
file to generate content.
Templates look like:
<% for-each /namespace/class[attribute/@type='ServerModel'] %>
public class <%@name%>
{
}
<%/for-each%>
Easy stuff if you are happy with XSLT.
Currently I use it to generate proxies to classes in my Mobile MVP
library. There are lots of uses I imagine.
Are there any other similar tools out there? If not what are the
prefered places to release this? I took a look at CodePlex but the
TFS source control made me shudder. I'm much more at home with SVN...


Sunday, November 04, 2007 11:02:13 PM (GMT Standard Time, UTC+00:00)  #    Comments [1]   |  |  | 

 Friday, November 02, 2007
Separating design and code with HTML and JavaScript

There is a lot of hype around Silverlight and WPF enabling true separation of developer and designer. This is certainly a great way to work. However, I don't think this is enabled only now by XAML. There is no reason the same cannot be achieved with HTML.

It seems like developers went so far down the server-side HTML generation route we left designers floundering with only CSS left in their toolkit. Whilst you can do some amazing things with CSS, sometimes you just need to change the HTML. If the HTML is riddled with <% %>, server controls or other template commands how is out poor designer going to work with the file?

My current attention is around using pure HTML and putting all dynamic content generation into JavaScript. The only thing to enforce on the HTML is that certain elements have known "id" attribute values.


Friday, November 02, 2007 4:42:04 PM (GMT Standard Time, UTC+00:00)  #    Comments [3]   |  |  |  | 

 Tuesday, October 02, 2007
ToJavaScript Extension Method

Has anyone looked into an extension method on the .NET 3.5 Expression class that returns a JavaScript method? This could then be sent to the client web browser.

So you could then write validation logic in C# and run it in the browser as JavaScript!


Tuesday, October 02, 2007 8:39:56 AM (GMT Standard Time, UTC+00:00)  #    Comments [1]   |  |  | 

 Sunday, September 30, 2007
Thoughts on client-server communication for the Model in MVP

I am thinking about my client-side MVP pattern and how best to communicate with the server. The current issue is how explicit to make the client/server divide. There are ways to make it feel like the Model is one consistent class, with tools doing all the marshalling to the server, invocation and return. This papering over of the "cracks" may however bite me in the ass at a later date. I reckon that adding the required flexibility to enable tweaking will just end up making the divide explicit again - rendering the exercise pointless.

So the alternative is to write the model with only client-side code. The server-side logic will then be in a service class somewhere. A benefit here is that the developer is free to choose the service style (SOAP, REST, etc).

I still want to avoid writing the client-side model proxy class that calls to the server. A tool is needed to take a service description and create a proxy class. In the context of a JavaScript model object, we need the proxy to be making XML HTTP requests.

I would like to use WCF to create the service. This is a good overview of getting WCF to talk JSON. If I enable meta-data transfer on the service, writing a tool to read this and create a proxy class should be simple.


Sunday, September 30, 2007 9:02:14 AM (GMT Standard Time, UTC+00:00)  #    Comments [0]   |  |  | 

 Monday, September 24, 2007
Trial mode Facebook applications?

Why do most Facebook applications require me to add the application before being able to do anything with them? I would prefer to see a trial version first, or at least some screenshots! I rarely download an application for Windows without first looking at some screenshots.

Having to add a Facebook application just to evaluate effectively puts bad data into my news feed. I didn't add "Cool app 1.0" because I plan on using it. I'm only trying it out! I'd like to see Facebook applications have a demo/trial mode. Perhaps allow me to use it with reduced functionality, or implement a "demo user".


Monday, September 24, 2007 12:42:14 PM (GMT Standard Time, UTC+00:00)  #    Comments [1]   | 

 Monday, September 17, 2007
Client-side MVP with Script#

Have you seen Script#? It is very impressive cross-compiler from C# to JavaScript. The libraries make it simple to program against the HTML DOM and Silverlight among other technologies. I have been using them recently to program Silverlight 1.0 without having to actually touch JavaScript. Using high-level OOP concepts makes creating complex user interactions much easier.

The Model-View-Presenter pattern has been very popular on the server-side when creating HTML applications. However, it seems that not many people have considered using it within the browser. With AJAX techniques becoming the way to make interactive web applications, it seems a little odd that people are not using more high-level concepts client-side. Of course, this mostly applies to the .NET space. I am aware there are Java toolkits that generate JavaScript.

I am therefore going to look into using Script# to implement a client-side, MVP-style, web application. The Model will contain local data and communicate with the server (via XML HTTP requests). The View will be a simple object that can get and set values from HTML/Silverlight elements and raise events when the user clicks on buttons, etc. The Presenter object will then orchestrate the user interaction logic. All this will be done within JavaScript by using Script# to convert C# classes, etc, into JavaScript concepts.

By writing all the code C#, it should be possible to tier split the Model class into server-side and client-side pieces. Whilst the JavaScript on the client-side is drastically different from the C# server-side model, they will share a common set of data fields. So it should be possible to serialize between the two worlds.


Monday, September 17, 2007 4:24:00 PM (GMT Standard Time, UTC+00:00)  #    Comments [0]   |  |  |  | 

 Sunday, July 08, 2007
The Right Amount of Code Generation

David Hayen talks about the problem of using code generation at a large scale within software projects. The first use gives a lovely RAD hit, but over time you get more constrained and limited by the generated code. I always found this problem using any kind of data-n-drop data binding (although .NET 2.0 windows forms data binding seems almost flexible enough).

It is hard to get large scale code generation perfect - almost impossible in reality. I find using code generation at a smaller scale to actually raise the level of abstraction in code more useful. Languages such as Boo and Ruby have great syntax for defining mini domain specific languages to raise abstraction levels. Syntactic macros in Nemerle and Lisp are true compile-time code generators. The key to these methods is that the programmer has not lost the expressivity his language gives him. If a certain macro is not really fitting, you can always write out the code long-hand and refactor later if necessary.

Large scale code generation assumes software is smooth and regular. In the real-world we have to deal with special cases and, worse, changing requirements. Trying to make a code generation tool fit all of these requires it to be as expressive as a real programming language! Only now we are buried in stacks of XML config files and templates.

One area I do see a benefit for these quick-n-dirty code generators is in prototyping. You want to get something half-real in front of customers quickly to gather feedback. However, never be precious about your code. The best writing is re-writing! A lot of software hangs around for a lot longer than we expect, or even hope. It is probably best to make it as maintainable as humanly possible.

The fact that a magic tool generated thousands of lines of code for you doesn't stop them for existing. The more code that exists, more chance there is for something to be wrong. If your chosen programming language requires you to write reams of code to express something that you can conceptualise more simply, then I'm sorry you need a better language.


Sunday, July 08, 2007 12:03:08 AM (GMT Standard Time, UTC+00:00)  #    Comments [0]   | 

 Sunday, June 10, 2007
Where now?

With exams completed, I am effectively done with university. I still have to wait for my results and attend graduation, but I am now free to do what ever I like!

It seems like everyone in my year is either staying on for more academia or seeking regular employment. Neither of these particularly appeals to me. The way I see it, I can innovate and invent out in the real world. I have really had enough of formal education. Of course I would not trade my time at university for anything. I have met some amazing people along the way and had some crazy adventures. I don't plan on slowing down however!

The default option then is to get a "real" job. This default sucks, in my opinion. I've felt this way for quite a few years, but it was always due to thinking I'd make more money working for myself. Recently I have noticed a change in my outlook. Whilst making enough money to be secure and enjoy life is important for me, being stinking rich seems less so.

I want to make a difference. Most software sucks. Let's fix this.

I need to do lots more research of course, in fact I reckon that part will never end. The human factors of software are becoming more prevalent every day. We are in possession of powerful new tools with which to craft future software. But it is so easy for us geeks to become distracted by the bells and whistles of some new technology. We need to think carefully about to leverage all our tools to best help our users.

I want this blog to be a mix of hardcore geekery and more subtle discussion about making software better. If I ever get too "head in the clouds" however please do call me out! I'm just one voice after all.

So what is the plan?! Stick the formula of "Coffee => Code => Cash" (i.e. consultancy) to pay the bills and develop real products (new and existing). Over the summer a new version of Insight for primary schools will get created, hopefully with sexy new graphics! Facebook presents a new and interesting platform that also requires attention. As for technology, Silverlight and .NET 3.5 will be regular themes here.


Sunday, June 10, 2007 9:25:32 PM (GMT Standard Time, UTC+00:00)  #    Comments [0]