# 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 24, 2007

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 1:42:14 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
# Saturday, September 22, 2007

Check out Joel's post: Strategy Letter VI

He seems to make a lot of sense. It'll be interesting to see the JavaScript compiler coming with some future version of Silverlight. It should mean that I can generate JavaScript from C# using Script#, and send a compiled version to those web clients with support.

Let's face it, a few mini-killer apps written using Silverlight will soon get the numbers using the plug-in way up to near Flash levels. I wonder what politics would stop Microsoft pushing Silverlight down via Windows Update? Then again, the tiny download and easy install should not stop standard web-based deployment as well.

Saturday, September 22, 2007 5:31:38 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
# 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]  | 
# Friday, September 07, 2007

Asher Charman and myself have just released a new Facebook application called One Million Friends:

http://apps.facebook.com/onemillionfriends/

It's still early days, but join up while the spots are still free! ;)

Friday, September 07, 2007 2:03:21 AM (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]  |