# Sunday, October 11, 2009

Say hello to ProntoCMS a new open-source web content management system.

The project is hosted here: http://code.google.com/p/prontocms/

Pronto is built on ASP.NET MVC and uses JQuery and FCKeditor. It is very light-weight and ideal for small websites.

The code in subversion contains a couple of (very minimal) sample projects. Hopefully I will get around to writing some documentation soon.

Please take a look at the code and let me know what you think.

.net | cms | prontocms | web
Sunday, October 11, 2009 1:47:03 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [3]  | 
# Saturday, October 10, 2009

Thanks to everyone who left encouraging comments on my previous post about a new CMS I’ve created.

I have decided that I will be open sourcing the project. However I now need a snappy name for it. Naming is so hard for some reason!

Any ideas are greatly appreciated. The CMS is light-weight, very simple, runs on asp.net mvc and has plenty of ajax goodness.

.net | cms | mvc | oss | web
Saturday, October 10, 2009 6:24:40 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, October 08, 2009

Over the course of a couple of website developments I created a simple content management system. I know there are loads our there already, but I wanted something simple and easy for non-techie users. It runs on ASP.NET MVC, has an elegant extensibility model and produces clean HTML 5. I very happy with it and plan to use it on all upcoming simple websites.

The system is file based, so no SQL database is needed. This makes it ideal for running in shared hosting. It’s perfect for the ~10 page website. But there’s no reason it can’t scale up to larger sites too.

So I’m obviously enamoured with my own work :) but is it worth sharing? I would love to get the code out there for people to poke at. However, is it really worth my time doing so – setting up a project, documentation etc? My recent open sourced work seems to have taken off like a lead balloon (Snooze, Hasic, etc)! Do you want to see my new CMS? Or shall I just keep it to myself?

.net | c# | cms | mvc | web
Thursday, October 08, 2009 3:55:37 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [5]  | 

Hasic is a kick-ass view engine for ASP.NET MVC, with a completely different approach. It uses VB.NET's XML literals instead of nasty strings like most other view engines.

That's right, VB! If you are already closing your web browser upon reading that then shame on you. I'm not saying your whole app is in VB, just the views.

Using VB means this stuff comes for free:

  • Syntax colouring
  • Full intellisense in Visual Studio
  • Compiled views
  • Extensibility using regular CLR classes, functions etc

I’m looking for feedback. So please try out Hasic and let me know what you think – thanks!

.net | mvc | vb.net | web
Thursday, October 08, 2009 3:30:43 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Friday, March 13, 2009

Another approach I'm investigating for HTML form generation is using VB's XML literals.

Check out this screencast for a demo: http://screencast.com/t/WSoDB4B9M2

 

XML literals + Expression Trees gives us some serious power!

.net | html | screencast | vb.net | web | xml
Friday, March 13, 2009 6:44:33 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 

HTML forms seem to be general enough to warrant a better abstraction than manually creating the HTML, or even using simple HTML helpers. Ideally the semantics of the form should be enough to generate all the HTML content.

I have been prototyping some ideas in this area. Here is some code that demonstrates a simple (but incomplete) login form.

class LoginData
{
    public string Username { get; set; }
    public string Password { get; set; }
    public bool Persist { get; set; }
}
 
 
class LoginForm : Form<LoginData>
{
    public LoginForm()
    {
        FieldContainer = new DivFieldContainer();
 
        Add(d => d.Username);
        Add(d => d.Password).AsPassword();
        Add(d => d.Persist).WithLabel("Stay logged in on this computer");
    }
}
 
class Program
{
    static void Main(string[] args)
    {
        var data = new LoginData() { Username = "test" };
        var form = new LoginForm();
 
        var html = form.Create(data);
        Console.WriteLine(html.ToString());
    }
}

This generates the following HTML.

<form method="POST" action="http://localhost/">
  <div>
    <label for="Username">Username</label>
    <input id="Username" type="text" name="Username" value="test" />
  </div>
  <div>
    <label for="Password">Password</label>
    <input id="Password" type="password" name="Password" />
  </div>
  <div>
    <input id="Persist" type="checkbox" name="Persist" />
    <label for="Persist">Stay logged in on this computer</label>
  </div>
</form>

There is a clear separation of the data from the form meta-data. This lets me do interesting things like applying conventions, for example, the generation of label text from property names. I want to use mostly global conventions for a form, and then override a few specific fields where needed.

I think validation can also fit nicely into this approach. Validation logic can be put on the data model. The form model can then specify how errors are added to the HTML.

Has anyone else seen anything like this before? I don’t want the reinvent the wheel. Or at least I can steal some good ideas ;)

.net | c# | html | web
Friday, March 13, 2009 11:51:16 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [1]  | 
# Monday, January 19, 2009

Don't call SmtpClient.SendMail directly within your controller actions because it directly couples your controller to SmtpClient.

Don't even create an interface IMailer and wrapping implementation of this to SmtpClient.

Instead, create a new ActionResult subclass called EmailResult. Make this class have the properties From, To, Subject and BodyData. In the ExecuteResult method use the ViewEngine infrastructure to render a view of the BodyData into your own StringWriter. You can then send the resulting content via email using SmtpClient.

.net | asp | mvc | web
Monday, January 19, 2009 4:39:44 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Monday, December 08, 2008

Avoid using HttpContext in controller actions to make testing much easier. Therefore all inputs to an action needs to be passed as parameters. In my new REST framework that builds on ASP.NET MVC I have created some useful model binders to make this easy.

[ResourceUriTemplate("")]
public class RootUri : ResourceUri
{
    public ResourceResponse Get([HttpCookie] string visited, [AppSetting] int visitTimeout)
    {
    ...
    }
}

The HttpCookieAttribute looks for a cookie called "visited". The AppSettingAttribute looks in web.config for an appSetting with the key "visitTimeout". The method is now easy to test and has very readable definition. :)

 

Both attributes will cast the raw string found into the required type by using a TypeConverter.

The AppSettingAttribute constructor can also take a key name if you want something different from the parameter name.

The code is in SubVersion, but I'll repeat some here to show just how easy it was:

namespace Snooze
{
    public class AppSettingAttribute : CustomModelBinderAttribute
    {
        public AppSettingAttribute()
        {
        }

        public AppSettingAttribute(string key)
        {
            _key = key;
        }

        string _key;

        public override IModelBinder GetBinder()
        {
            return new AppSettingModelBinder(_key);
        }
    }

    public class AppSettingModelBinder : IModelBinder
    {
        public AppSettingModelBinder(string key)
        {
            _key = key;
        }

        string _key;

        public ModelBinderResult BindModel(ModelBindingContext bindingContext)
        {
            string setting = WebConfigurationManager.AppSettings[_key ?? bindingContext.ModelName];
            object value;
            if (bindingContext.ModelType == typeof(string))
            {
                value = setting;
            }
            else
            {
                value = TypeDescriptor.GetConverter(bindingContext.ModelType).ConvertFromString(setting);
            }
            return new ModelBinderResult(value);
        }
    }
}

.net | mvc | REST | web
Monday, December 08, 2008 8:55:53 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [1]  | 
# Sunday, December 07, 2008

Filters in ASP.NET MVC provide a great way to attach functionality around controllers. By building on top of the MVC framework, my ResourceUri class (which inherits from Controller) gets all the filter goodness as well.

My library also has a SubResourceUri class. Any filters applied to the parent ResourceUri are also executed for the SubResourceUri.

[ResourceUriTemplate("customers/{CustomerId}")]
[MyLoggingFilter]
public class CustomerUri : ResourceUri { ... }

[ResourceUriTemplate("orders/{OrderId}")]
public class OrderUri : SubResourceUri<CustomerUri> { ...}

For example, when we GET an order the filter still catches the request and outputs logging information.

Another use is authorization. You can place an authorization filter on top level URI and it will protect all sub-URIs beneath it.

 

Keep track of the latest developments on the code here: http://svn2.assembla.com/svn/snooze/branches/aspnet

.net | mvc | REST | web
Sunday, December 07, 2008 9:34:25 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Sunday, November 30, 2008

Continued work on my resource-oriented library for ASP.NET MVC has expanded to include an XDocument based view engine for ASP.NET MVC.

This means we can now use VB.NET XML literals to define XHTML views (or any XML views).

Get the latest from SVN.

.net | html | mvc | REST | vb.net | web | xml
Sunday, November 30, 2008 10:49:44 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [2]  | 
# Wednesday, November 26, 2008

Now that the ASP.NET MVC API has settled down I decided to bring some of my ideas about REST and resource-oriented programming to it.

The following screencast shows my current prototype in action:
http://www.aboutcode.net/screencasts/snooze-aspnet-mvc.wmv

I'm keen for comments and feedback.

The source code is currently available via SVN here:
http://svn2.assembla.com/svn/snooze/branches/aspnet

.net | c# | mvc | REST | screencast | web
Wednesday, November 26, 2008 3:23:02 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [1]  | 
# Sunday, July 13, 2008

Sending data from a resource to a view in a strongly-typed, but syntactically lightweight manner is not possible with C# or VB.NET.

So check out this screencast of the new "render" macro in NRest!

In a nutshell, my resource looks like:

[Resource("")]
public class RootResource
{
    public Get() : void
    {
        def test = 42;
        render (Foo = "Hello", Bar = "World", test);
    }
}

My VB.NET view looks like:

Public Class RootPage
    Inherits Page(Of RootPageContent)

    Public Overrides Function GetHtml() As XElement
        Return _
        <html>
            <body><%= Content.Foo %>, <%= Content.Bar %></body>
        </html>
    End Function
End Class

The RootPageContent DTO class is generated at compile time by the render macro. Everything is strongly-typed.

.net | dsl | macro | nemerle | nrest | REST | web
Sunday, July 13, 2008 3:27:17 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, July 02, 2008

This is a very quick video showing the work I've been doing with Nemerle, ASP.NET routing and VB 9 XML literals.
I'm trying to find the most efficient way to create RESTful web applications. I'm willing to use all the tools in the box and even make my own to achieve this.

.net | nemerle | REST | screencast | vb.net
Wednesday, July 02, 2008 11:19:24 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
# Saturday, May 10, 2008

A demo website using my Hasic view engine for ASP.NET MVC.

HasicDemo.zip (275.95 KB)

.net | vb.net | web | hasic
Saturday, May 10, 2008 5:37:41 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, April 29, 2008

I have started using Ninject a dependency injection framework for .NET. I find it very easy to use and recommend that people take a look.

Something in particular that I found useful is the ability to bind open generic types.

class Program
{
    static void Main(string[] args)
    {
        var k = new StandardKernel(new MyModule());

        var di = k.Get<Data<int>>();
        di.Content = 14;
        Console.WriteLine(di.Content);

        var ds = k.Get<Data<string>>();
        ds.Content = "hello";
        Console.WriteLine(ds.Content);
    }
}

class MyModule : StandardModule
{
    public override void Load()
    {
        Bind(typeof(IData<>)).To(typeof(Data<>));
    }
}

class Data<T> : IData<T>
{
    public T Content { get; set; }
}

interface IData<T>
{
    T Content { get; set; }
}

Very cool!

.net | c# | ninject | programming
Tuesday, April 29, 2008 7:36:59 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [2]  | 
# Monday, March 24, 2008

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;
    }
}

.net | mvc | thinking | web
Monday, March 24, 2008 4:08:16 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, February 19, 2008

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.

.net | html | thinking | vb.net | web | xml
Tuesday, February 19, 2008 12:12:17 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, January 10, 2008

I have released an initial version of Snooze. http://www.assembla.com/wiki/show/snooze

Snooze is an REST framework for ASP.NET. It puts the emphasis back on the "R" of URI. The Resource concept is a first-class citizen.

In Snooze you create a resource class that defines the URI template and HTTP methods it supports.

[HttpResource("customer/{CustomerId}")] // Defines the URI template for this resource
public class CustomerResource : HttpResource // A useful base class that implements IHttpResource
{
    // URI template variables are mapped to properties
    public int CustomerId { get; set; }

    // Handles the HTTP GET method
    public override void Get()
    {
        RenderView("Customer", Data.Customers[CustomerId]);
    }

    public override void Put()
    {
        // Read data sent in Request body and update the customer...
    }

    public override void Delete()
    {
        // Delete the customer...
    }

    // HTTP POST can also be provided if it makes sense for the resource.
}

This will mean a URI like "http://yourserver.com/customer/42" will invoke the Get method of an instance where CustomerId equals 42.

What about creating a new Customer?

Well you don't have an ID for the new customer since that is probably created in the database. Therefore you don't know what the URI will be yet. The correct solution here is to POST the new customer data to a CustomerList resource, with URI "/customers".

Alternative GET Views

You can create extra GET methods:

[HttpGetView("edit")]
public void GetEdit()
{
    RenderView("CustomerEdit", Data.Customers[CustomerId]);
}

This results in URIs like "/customer/42?edit"

File Extensions

To support different file formats, such as XML and JSON use:

[HttpGetFile(".xml")]
public void GetEdit()
{
    SendXml(Data.Customers[CustomerId]);
}

This will be mapped to by URIs like /customer/42.xml

Sub-Resources

Resources can be naturally nested. For example, a Customer may have Orders.

[HttpSubResource(typeof(CustomerResource), "order/{OrderId}", true)]
public class OrderResource : HttpSubResource<CustomerResource>
{
    public int OrderId { get; set; }
    // ...
}

In this sub-resource, you can have access the parent CustomerResource, using the strongly-typed, ParentResource property.

URIs for this sub-resource will look like: "/customer/42/order/123"

The "true" argument in the attribute, specifies that parent query string parameters are added to this sub-resource URI as well. So a parent with URI template "customer/{CustomerId}?foo={Foo}" will yield sub-resource URI template "/customer/{CustomerId}/order/{OrderId}?foo={Foo}".

Nullable Resource Properties

Imagine a blog posts resource. Its URI could be /posts/{Year}/{Month}/{Day} to get all the posts on a given date. Now what if you want to naturally get the posts for a whole month, year, or ever?

By declaring the properties as nullable, e.g. "int?" in C#, Snooze will also map the "reduced" URIs to your class. You can then test the properties for "null" and return data accordingly.

Reusing Resource URIs

When rendering an HTML view it is likely you will need to link to other resources. Instead of manually typing the URI string, you can call the Uri property available on HttpResource.

new CustomerResource { CustomerId = 42 } .Uri

Resource Areas

Snooze supports resource "areas". These let you map all the resources of a given assembly into a given sub-path. If, for example, a third-party blogging package was built using Snooze you could include it as follows:

web.config:

<configuration>
  <restAreas>
    <area path="" assembly="MyWebsiteAssembly"/>
    <area path="blog" assembly="SomeCompany.BlogEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
  </restAreas>

So the blog resource URIs would look something like: http://mysite.com/blog/posts/2007/01

HTML Form Support

HTML forms only support GET and POST. To overcome this limitation you can include: <input type="hidden" name="__method" value="DELETE" /> to override the name of the HTTP method used by Snooze.

Feedback

This project came mostly out of curiosity! I wanted to see if REST could be done better under ASP.NET. The code is still very new (less than two days!) It is open source (BSD license) and available via SubVersion. A quick sample project is also provided.

Let me know what you think. Everything is open to changes. Join the assembla project if you would like to contribute your help.

.net | c# | programming | REST | web
Thursday, January 10, 2008 9:42:04 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [1]  | 
# Sunday, December 23, 2007

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!)

.net | programming | REST | ria | thinking | web
Sunday, December 23, 2007 4:02:00 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [5]  | 
# Sunday, November 04, 2007

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...

.net | c# | programming | thinking
Sunday, November 04, 2007 11:02:13 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [1]  | 
# Wednesday, October 17, 2007

My latest screencast is online: Mobile Model in MVP web app

This screencast continues from the work I demonstrated in a previous screencast: http://channel9.msdn.com/Showpost.aspx?postid=344711
When implemented a Model-View-Presenter pattern client-side in JavaScript there is a need to get data from the server. Rather than make this divide explicit with HTTP request, etc, I have used the idea of a model object that moves between the client and server.
So the programmer simply writes the client and server pieces of functionality and lets my framework do the plumbing.
I use code generation and Script# to make writing a client-side web app much more seemless than the usual javascript/XML/JSON/web service madness.
I'm developing the ideas shown here in a project at the moment. If there is sufficient interest I may extract a framework to give to the community.
How do people feel about this approach to web development? What kinds of additions/modifications should be made?
p.s. I have a bit of a cold at the moment, so sorry for the croaky voice in the recording!

.net | c# | mvp | programming | ria | screencast | tier_split | web
Wednesday, October 17, 2007 9:32:19 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [11]  | 
# Tuesday, October 02, 2007

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!

.net | c# | linq | thinking
Tuesday, October 02, 2007 9:39:56 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
# Sunday, September 30, 2007

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.

.net | mvp | thinking | tier_split
Sunday, September 30, 2007 10:02:14 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Saturday, September 29, 2007

Check out my latest screencast over at Channel 9. It demonstrates how to implement a model-view-presenter architecture that runs client-side in a web browser. I am using Script# to compile a C# project into JavaScript.

.net | c# | mvp | programming | screencast
Saturday, September 29, 2007 5:08:52 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [3]  | 
# Thursday, September 27, 2007

Imagine we have a set of complex expressions. A subset of these need to be evaluated at runtime, depending on some state external to the program (e.g. user input). If these subsets are not distinct from each other then the code will likely become messy and unstructured.

What we would like to so is define all the expressions first and then pick and choose those required. This would of course involve evaluating all of the them. This wasteful of time if only a few are required.

Enter lazy evaluation! From my rather limited exposure to Haskell, I hear that lazy evaluation is all the rage. :)

Using lambdas in C# 3.0 we can create code like this:

long x = 42;
var lx = Lazy.Eval(() => x * x * x * x * x * x);
if (some_boolean_expression)
{
  UseNumber(lx);
}

where UseNumber is some function that takes a "long" as input.

Now this example is over-simplified, but it shows the mechanics. We use a call to Lazy.Eval to return a wrapper around the lambda. So at that point we have not calculated the expensive expression. Later in the program the variable "lx" is used. lx is of type Lazy<long> and there exists an implicit cast from Lazy<long> to long. At this point the original expression is evaluated and saved by the lazy wrapper. So next time the value is required the cached value is returned.

Here is the Lazy<T> class:

public class Lazy<T>
{      
    bool _gotValue;
    T _value;
    Func<T> _expr;

    public Lazy(Func<T> expr)
    {
        _expr = expr;
    }

    public T Value
    {
        get
        {
            if (!_gotValue)
            {
                _value = _expr();
                _gotValue = true;
            }
            return _value;
        }
    }

    public static implicit operator T(Lazy<T> l)
    {
        return l.Value;
    }
}

And to allow the C# 3.0 compiler to infer types for us, we use a separate Lazy class:

public class Lazy
{
    public static Lazy<T> Eval<T>(Func<T> expr)
    {
        return new Lazy<T>(expr);
    }
}

Whilst lazy evaluation may not be useful in everyday programming, this example does show some of what can be achieved with lambdas in C# 3.0.

.net | c# | linq | programming
Thursday, September 27, 2007 11:56:51 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Monday, September 17, 2007

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 5:24:00 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, September 05, 2007

When writing assertions it is annoying to write a string that basically mirrors what the code your testing says. For example:

Debug.Assert(input != null, "input != null");

Similar statements appear when unit testing with tools like NUnit.

With Linq it is now possible to avoid this by using expression trees. The basic idea is to take a boolean assertion function as an expression tree so that we can call ToString() to get the message for the assert.

void Assert<T>(T obj, Expression<Func<T, bool>> test)
{
  System.Diagnostics.Debug.Assert(test.Compile().Invoke(obj), test.ToString());
}

This is then called like:

Assert(input, i => i != null);

Given this idea, we can play with the syntax a bit. Using an extension method:

static class Exts
{
    public static void MustSatisfy<T>(this T obj, Expression<Func<T, bool>> test)
    {
        Debug.Assert(test.Compile().Invoke(obj), test.ToString());
    }
}

We then have:

input.MustSatisfy(i => i != null)

Another syntax option would be something like:

Assert.That(foo).Satisfies(
  i => i > 0,
  i => i < 100);

Where we are now passing an array of assertions (using a params arg in the Satisfies method).

.net | c# | linq | programming | syntax
Wednesday, September 05, 2007 12:46:23 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [3]  | 
# Monday, August 27, 2007

I have so far managed to avoid needing to use any fancy ORM tools. However, this doesn't mean I like writing all the standard ADO.NET code by hand. Using C# 2.0 anonymous methods I am able to write code like the following. (I'm not sure all of this is truly original work; if you have already done this then sweet! I just want to share the ideas with everyone.)

Customer c = With.Database<Customer>(delegate(Database db)
{
    return db.ExecuteReader<Customer>(
        "select Id, FirstName, Surname from Customer where Id = @id", // The SQL to execute
        delegate(IDbCommand cmd) // This anonymous function is called before executing so we can add params.
        {
            db.AddParameter(cmd, "@id", DbType.Int32, id);
        },
        delegate(IDataReader reader) // The IDataReader returned from ExecuteReader is passed here.
        {
            if (reader.Read())
                return new Customer(
                    reader.GetInt32(0),
                    reader.GetString(1),
                    reader.GetString(2));
            else
                return null;
        });
});

My Database class manages the creation of a connection and optionally a transaction. It then exposes methods to invoke SQL commands (Reader, Scalar and NonQuery). A transaction can be automatically provided by calling With.DatabaseInTransaction( ... ) instead. This then wraps the inputted action in a try-catch-finally block, commit and rolling back in the usual places.

("With" is a static class that provides convenient access to the Database object)

public static T DatabaseInTransaction<T>(Function<Database, T> function)
{
    using (Database db = new Database())
    {
        db.BeginTransaction();
        try
        {
            T result = function(db);
            db.CommitTransaction();
            return result;
        }
        catch
        {
            db.RollbackTransaction();
            throw;
        }
    }
}

There are generic and non-generic versions of the functions, depending on if we want to return a value.

For example, here is the non-generic ExecuteReader method from Database:

public void ExecuteReader(string sql, Action<IDbCommand> addParameters, Action<IDataReader> action)
{
    Debug.Assert(sql != null, "sql cannot be null.");
    Debug.Assert(action != null, "action cannot be null.");

    using (IDbCommand cmd = CreateCommand(sql))
    {
        if (addParameters != null)
        {
            addParameters(cmd);
        }
        using (IDataReader reader = cmd.ExecuteReader())
        {
            action(reader);
        }
    }
}

The IDbCommand is created using the following method. Notice that we also handle assigning the transaction if we're in one.

IDbCommand CreateCommand(string sql)
{
    Debug.Assert(_connection != null && _connection.State == ConnectionState.Open);

    IDbCommand cmd = _connection.CreateCommand();
    cmd.CommandText = sql;
    cmd.CommandType = CommandType.Text;
    if (_transaction != null)
    {
        cmd.Transaction = _transaction;
    }
    return cmd;
}

The Database class implements IDisposable, thus allowing the "using" syntax in the With class methods. In Dispose() I close the connection, if the transaction is still open I rollback first.

I anyone wants the full Database and With classes drop me a line. I'm looking forward to C# 3.0 since the improved type inference and lambda syntax will slim down the amount of keyboard time even more!

Monday, August 27, 2007 10:41:09 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
# Saturday, August 25, 2007

I recorded a screencast explaining my tier splitting tool for C#. It uses a Model-View-Presenter style application to demonstrate the features of the tool.

Check out the video (wmv format, 14.8 MB)

I'd love to get some feedback from people...

Saturday, August 25, 2007 5:18:50 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
# Tuesday, August 14, 2007

I am excited about Silverlight 1.1 – very excited! Whilst all the graphics and animations will be a wonder for creating great user experiences, I eagerly awaiting the chance to run managed code in the browser.

In my mind, and partially in code, I have already begun to formulate a new way to design applications. Of course, by new I really mean stealing a bunch of existing good ideas and gluing them together!

The first key idea is putting the users first – always. These auto-magic, drag-n-drop data binding tools are great for quick and dirty CRUD applications, but I am yet to see one produce an application that has great usability. We need to start by putting ourselves in the user’s position and thinking about why they are using our software in the first place. It is all about finding the simplest, cleanest, more beautiful way to enable the user to get their job done. Slapping another data grid on a page probably is the worst approach!

I am a new convert to the Model-View-Presenter way of writing client applications. Although, I think, the order of coding should be Presenter-View-Model (it does not have quite the same ring to it however). In addition, by View I mean the view implementation, not the UI design. I always sketch the view design on paper/white board first. I suppose using a tool like Microsoft Expression Blend would be OK as long as you are not precious about the XAML it creates. I am never afraid to throw out code and start afresh, so why should UI mark-up be any different? Use whatever tools you find easiest to knock up UI prototypes and shove them under the user’s nose. The key here is to know roughly what buttons, textboxes, etc, the UI will contain (we can leave all the fancy colouring in to some guy in a turtle neck). Once this is the case, we can begin the most important part of the coding: The User Interaction Logic (UIL).

The UIL is the Presenter. The UIL says stuff like when the user clicks this button, read this data from the UI, tell the underlying model to do something and then tell the view to update. Whilst for some applications this level of control may seem like overkill, I argue that having to slow down sometimes is OK. This approach means you have to think about what the user will be doing in your application.

The best way to develop this code is by being test-driven. Create unit tests that describe the behaviour of the Presenter in terms of how it interacts with View and Model object-oriented interfaces. Each user story then becomes testable.

Key tools I plan to use here are:

Rhino Mocks – to create mock objects of Views and Models

Boo + my Rhino Mocks DSL – to make the unit tests easy to read and write

SharpDevelop – because Boo is not readily usable in Visual Studio yet

Visual Studio 2008 – to write the implementation of the Presenter in C#

As awesome as the language Boo is, I just cannot stand SharpDevelop for more than simple projects like the unit tests. Refactoring, intellisense and code-completion are just way to well done in Visual Studio to ignore it. I have enough memory and screen space to run VS and SD side-by-side.

As the Presenter is written, the interfaces for the View and Model are being fleshed out. The refactoring tool adding the methods automatically to the interfaces usually does this.

The choice now is whether to develop the Model or the View next. The View is a very dumb object that simply maps data to and from the UI and raises events when the user does stuff (clicks, key presses, etc). Since Silverlight does not have data binding yet, this may lead to somewhat tedious code. Bear in mind also that the Presenter is meant to be doing tasks such as converting strings into numbers and back. However, I reckon a tool can generate most of the standard mapping code.

The declarative nature of XAML means it should be easy to add attributes to button elements that describe the event they should raise when clicked. A tool could scan this data and write the code for me.

If data binding was ever added to Silverlight, I would consider creating pure “data” objects that the Presenter tells the View to bind too. No logic would be contained within the data objects.

The Model is where things become more interesting from a software architecture point of view. Silverlight runs in the client’s web browser. So the Presenter is running client-side, as is the Model on which is depends. The Model is maintaining state about the client application. For example, which check boxes are checked, which customer is selected? However, the Model also will need to communicate with a database running back on the server to read and write data.

To solve this problem, I plan to use my tier splitting C# macro. I will write the Model class as one coherent class. By coherent I mean all the data is there and all the logic regarding the data is there. I do not believe manually splitting the class and messing about with proxies and web services makes any business sense. I am not developing some kind of SOA application that is to be called by numerous different clients. I am trying to get my Model to save its valuable data on the database that is only accessible from the web server from whence it came. This is a reasonable tight coupling between the client and server versions of the Model. The coupling is so tight; I argue that I do not even want to see it!

In the case where the data does come from a remote web service, we still have to return to the application’s home server since Silverlight disallows cross-domain calls. It makes sense to put any database calls/remote web services calls into the Model. The Model knows what data it needs, so why bother moving that knowledge outside of the class only to marshal all the data back in again.

With LINQ being available we do not even have to pollute the Model with database specific SQL.

The tier splitting macro will handle generating all the WCF services and proxies. I just have to decorate the Model’s remote methods with [RunAtServer].

Thorough unit testing of the Model is required. It should be possible to create a mock D-LINQ implementation. I can then make assertions about how the Model interacts with the data layer.

In summary, I want to have a Silverlight UI that is but a marionette to a Presenter running client-side. This presenter has complete unit testing to describe the different user interactions. The Presenter uses a Model object to store all data. This Model exists on both the client and server side. However, the split implementation is effectively invisible to the developer.

The application of adequate tooling (both 3rd party and custom made) will make this an excellent way to approach writing applications. As Silverlight 1.1 becomes more complete, I will continue to expand this topic.

The result should be a happier developer and, more importantly, a happier user.

.net | boo | c# | dsl | programming | rhino_mocks | ria | silverlight | tier_split
Tuesday, August 14, 2007 2:02:43 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, August 08, 2007

When developing a Model for an MVP architecture it needs at some point to access the database to read and write data. When this model is running on the client-side (in Silverlight for example) it has no access to the database. I suppose the standard solution here is to put the data access code in a separate class running on the server. The client then invokes this service passing the data required.

The approach obviously works, but I don't like it. The Model contains all the data relevant to the business problem. It has the validation logic for the data. Why do I need to suddenly create an entirely different service just to read and write to the database? Now with LINQ there are no code-level ties to a particular database technology.

The Model should be in charge of telling the database what data it needs, reading the data and storing into its fields. When saving data the Model should tell the database what query to execute to save the data.

The root of the problem here is that the Model needs to be split between the client and server sides. However, I want this to be done in such a way that the developer is not wading through plumbing and service layers. In essence, I want this:

[DataContract]
public class Model : IModel
{
  [DataMember] public string CustomerName { get; set; }
  [DataMember] public decimal InvoiceAmount { get; set; }
  [RunAtServer]
  public void Load(int id)
  {
    // Access database here. Get data. Save into properties.
  }
}

This needs to generate two Model classes, one for the server (which is basically the same as above) and one for the client that replaces the [RunAtServer] methods with calls to a service object.

I have this working! :) I have used my C# macro tool to take the above code and generate a new file that contains the two Models, a WCF service and client proxy. These classes are surrounded by "#IF SERVER" and "#IF !SERVER". I then have a WCF service project and Client project that both compile the generated file. The conditional preprocessor directives mean each project only gets what it needs.

This is all still prototype-level code, but it does work. I am waiting on Silverlight 1.1 to have better support for WCF, so for now I'm using XBAPs to test. However, there is nothing stopping me using WinForms for the client as well. I see this as being a great way to write rich internet applications. I can focus on modelling the business problem and just decorate any methods that need to be remote with an attribute.

.net | c# | programming | tier_split | ria
Wednesday, August 08, 2007 1:17:48 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, July 31, 2007

After a late night hacking session, I finally have a working syntactic macro system for C#! It is comprised of a VS custom tool that uses the CSparser. The end result allows me to do this:

using System;
[Macro(AutoClass)]
public interface IModel
{
  string FirstName { get; set; }
  string Surname { get; set; }
  int ID { get; }
  event EventHandler FirstNameChanged;
  event EventHandler SurnameChanged;
}

The CustomTool property of the IModel.cs file is set to "MacroExpander" and the Build action is set to None. This then generates a new file "under" the source file, called for example "IModel.generated.cs". This generated file contains the original interface (minus the bogus attribute) and a new class called "Model" that provides a stanard implementation of IModel. It includes private fields, a constructor, properties, events and event raising methods. The class is partial so you can still create a file called "Model.cs" alongside the interface and implement any methods. In addition, if you enter implementations of the interface properties/events in Model.cs then the generated class will not contain them. So it is easy to generate the 80% of standard members and custom write the others as required.

The sharp-minded out there will note that "AutoClass" is a parameter passed to the Macro attribute. The expansion process is able to load any IMacro implementation I care to write. The macro implementation is handed the parsed source tree and allowed to modify it as required. After all macros have expanded, the source tree is converted back to CS source text and outputted from the VS custom tool. This generated file is compiled by VS as usual.

I'm going to start using this AutoClass macro to generate most of my Model code (in the Model-View-Presenter architecture). Anywhere else I need code generation at this level I can create more macros easily.

If people are interested in seeing this product released in some way please get in contact. I will perhaps get a screen cast made up to show it in action.

.net | programming | c#
Tuesday, July 31, 2007 1:04:41 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [5]  | 
# Friday, July 06, 2007

I have attached the Boo code containing the Rhino Mocks DSL I'm currently working on. This is very much a work in progress release, just to get it out there. Please have a play and tell me what you think. Happy Mocking!

Dsl.boo (3.4 KB)

To use the DSL, add the following in your code to import the static methods into scope.

import Rhino.Mocks.Dsl

Friday, July 06, 2007 1:19:48 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [2]  | 
# Wednesday, July 04, 2007

I thought some more about the syntax of my Rhino Mock DSL. It can feel unnatural putting all the mock expectation code before the call to the object being tested. I came up with this working prototype instead:

[Test]
def Get_data_objects_for_nonexistent_company_throws():
    with_mocks:
        database = mocks.CreateMock[of IDatabase]()
        userProvider = StubUserProvider("andrew", "bad corp")
        userProvider.MakeCurrent()

        execute:
            uds = UserDataService(database, userProvider)
            expect_throw FaultException[of GetDataObjectsFault]:
                uds.GetDataObjects()
            assert thrown_exception.Detail.Type.Equals(GetDataObjectsFaultType.InvalidCompany)

        assuming:
            database.GetUserID("andrew", "bad corp")
            returned 1
        assuming:
            database.GetCompanyID("bad corp")
            returned 0 # returning 0 from database implies nonexistent company.

The with_mocks method sets up the mock repository and a Store object. The execute and assumption methods then put their blocks into the Store. At the end of with_mocks I iterate through assumptions calling each to set up the Rhino Mock expectations. Following that is: mocks.ReplayAll(), call to the "execute" block, then mocks.VerifyAll().

The other clever bit in there is the expect_throw method. This runs the block inside a try...except and fails if no exception (or wrong exception type) is thrown. It puts the exception object into field that is readable using thrown_exception. This means we can then test assertions about the exception contents. I had to cheat a bit and declare thrown_exception as "duck" in Boo i.e. it is late bound. This is so we can access members on the actual object despite not really knowing about it at compile time.

I like the readability now. The outline is:

  • Initialize mocks and data objects
  • Call the object being tested
  • Assert about the result
  • State the assumptions about how dependencies are used

The key bit, I feel, is that the call to the object being tested is not buried down at the bottom of the method.

How does everyone else feel about this modified approach?

Wednesday, July 04, 2007 11:41:55 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, July 03, 2007

I recently learnt that Boo now supports a DSL-friendly syntax. A while back I created (and almost finished!) a set of syntactic macros in Boo to make using Rhino Mocks much more natural. Creating macros can be hard work though and gets pretty hacky in places.

The new DSL-friendly syntax in Boo means I can achieve 80% of the same easy-reading code, but using only methods and blocks!

In about 10 minutes I whipped up this:

namespace ConsoleDemo

import System
import Rhino.Mocks
import Rhino.Mocks.BooDsl.MockDsl

interface IModel:
    def CalculateScore(input as int) as int
interface IView:
    def DisplayScore(score as int)
interface IPresenter:
    def Init()

class Presenter(IPresenter):
    _model as IModel
    _view as IView
    def constructor(model as IModel, view as IView):
        _model = model
        _view = view
    def Init():
        score = _model.CalculateScore(0)
        _view.DisplayScore(score)

def Test_presenter_init():
    with_mocks:
        // Create mocks of the dependencies
        model = Mocks.CreateMock of IModel()
        view = Mocks.CreateMock of IView()
        // Create the object we are testing
        presenter = Presenter(model, view)
        // Record what we expect the presenter to
        // do with its dependencies.
        record:
            expect:
                model.CalculateScore(0)
                // Set the return value for the
                // previous mock call.
                mock_return 42
            expect:
                view.DisplayScore(42)
        // Now tell the presenter to do its stuff,
        // so we can verify it behaves correctly.
        verify:
            presenter.Init()
print "testing..."
Test_presenter_init()
print "all good!"
print "Press any key to continue . . . "
Console.ReadKey(true)

The import of "Rhino.Mocks.BooDsl.MockDsl" brings some new methods into scope. with_mocks initializes a MockRepository. "Mocks" is actually a property referencing that repository, so we can call CreateMock, etc, on it. The record and verify methods make use of the Mocks.Record() and Mocks.Playback() methods. I prefer using "verify" to "playback". The "expect" method runs the code in its block, usually that invokes some mock method. It then calls "LastCall.Repeat.Once()" to set up the expectation. The "mock_return" method calls "LastCall.Return(value)" to set up the return value for the last mock call.

This is all a bit messy for now I know. I have just being throwing code down into this prototype to get a feel for what is possible. I reckon this could be really useful for people using Rhino Mocks.

If you like what you've seen or have any ideas let me know.

The DSL methods are as follows:
I am aware of more than one glaring danger in the code(!) but it does show what can be done.

namespace Rhino.Mocks.BooDsl

import System
import Rhino.Mocks

callable Block()

static class MockDsl:

    private static _instance as MockDslImpl
    static def with_mocks(b as Block):
        _instance = MockDslImpl()
        b()
        _instance = null
    static def record(b as Block):
        assert _instance != null
        _instance.Record(b)
    static def verify(b as Block):
        assert _instance != null
        _instance.Verify(b)
    static def expect(b as Block):
        assert _instance != null
        _instance.Expect(b)
    static def mock_return(value as object):
        assert _instance != null
        _instance.MockReturn(value)
    static Mocks as MockRepository:
        get:
            assert _instance != null
            return _instance.Mocks

    private class MockDslImpl:
        mocks as MockRepository
        def constructor():
            mocks = MockRepository()
        public Mocks as MockRepository:
            get:
                return mocks
        public def Record(b as Block):
            using mocks.Record():
                b()
        public def Verify(b as Block):
            using mocks.Playback():
                b()
        public def Expect(b as Block):
            b()
            LastCall.Repeat.Once()
        public def MockReturn(value as object):
            LastCall.Return(value)

Tuesday, July 03, 2007 12:03:52 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  |