# 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]  | 
# Friday, March 13, 2009

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]  | 
# 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, August 24, 2008

There are currently two approaches when using L2S. Either adding attributes to classes to denote columns, or creating an external XML mapping definition. Neither of these is great. Attributes mix non domain concerns, namely database schema, into domain objects. XML mapping needs to be kept in sync with the classes it describes. During the early stages of a new project, the structure of classes can vary and morph over time. So manual mapping is annoying.

My suggestion is to create a "convention-based" mapping. Where you can define POCOs and then have reflection to build the mapping, based on some simple naming conventions. This mapping can then be used by a DataContext and a database created from it. (Note that I am only considering green field developments, where we are working "code-first".)

The conventions I have thought about so far include:

  • A property named "Id" will be the primary key.
  • If Id is an int then make it auto incrementing.
  • All primitive, string and DateTime properties are columns.
  • All properties having the type of another entity in the DataContext are associations.
  • All properties of type EntityRef<T> are associations.
  • There must be a foreign key Id property defined for associations.
  • Any property with subtype a of IList<T> is an association.

One-to-many associations need to be a bit smart with their names. Consider:

class Customer {
  public Employee ReferringEmployee { get; set; }
}
class Employee {
  public List<Customer> ReferredCustomers { get; set; }
}

The mapping needs to understand the "ing" and "ed" relation. Also, we'll perhaps need support for TechSupportEmployee <--> TechSupportedCustomers.

The conventions should follow the usual rules of English grammar. I hope, therefore, that they do not interfere with the universal language discovered by domain driven design.

As a project begins to settle down, there will be requirements that the convention mapping doesn't support. Rather than having to switch to full manual XML mapping, perhaps an augmentation layer could applied. This could describe specific cases of the mapping that are different. For example, a certain primary key column using GUIDs instead of integers.

c# | linq | linq-to-sql | orm
Sunday, August 24, 2008 11:09:43 AM (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]  | 
# 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, 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]  | 
# 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]  |