Thoughts on Software by Andrew Davey
| | Sun | Mon | Tue | Wed | Thu | Fri | Sat |
|---|
| 29 | 30 | 1 | 2 | 3 | 4 | 5 | | 6 | 7 | 8 | 9 | 10 | 11 | 12 | | 13 | 14 | 15 | 16 | 17 | 18 | 19 | | 20 | 21 | 22 | 23 | 24 | 25 | 26 | | 27 | 28 | 29 | 30 | 31 | 1 | 2 | | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
Search
Navigation
Categories
Blogroll
|

Sunday, July 13, 2008
Strongly Typed View Data in NRest
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.
Sunday, July 13, 2008 2:27:17 PM (GMT Standard Time, UTC+00:00)
.net | dsl | macro | nemerle | nrest | REST | web

Wednesday, July 02, 2008
Quick NRest Video
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.
Wednesday, July 02, 2008 10:19:24 AM (GMT Standard Time, UTC+00:00)
.net | nemerle | REST | screencast | vb.net

Saturday, May 10, 2008

Tuesday, April 29, 2008
Ninject Open Generic Types
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!
Tuesday, April 29, 2008 6:36:59 PM (GMT Standard Time, UTC+00:00)
.net | c# | ninject | programming

Monday, March 24, 2008
Testing Controller RenderView
I've seen people testing that RenderView is called by a controller by inheriting into a "testable" controller. Madness!
RenderView is just a convenience method that calls to IViewEngine, so why not just test expectations on that with a mock? We basically want to test that the correct ViewContext is sent to the RenderView method of the view engine.
This is my test:
[TestFixture]
public class HomeControllerTests : ControllerTestsBase<HomeController>
{
public override HomeController CreateController()
{
return new HomeController();
}
[Test]
public void Renders_Index()
{
var render = ExpectRenderView();
Controller.Index();
Assert.That(render.Data.ViewName, Is.EqualTo("Index"));
}
}
I don't think we can get more straight forward than that!
This is my test base class:
(I'm using Moq as the mock framework.)
public abstract class ControllerTestsBase<T>
where T : Controller
{
public T Controller;
public Mock<IViewEngine> ViewEngine;
[SetUp]
public virtual void SetUp()
{
Controller = CreateController();
ViewEngine = new Mock<IViewEngine>();
Controller.ViewEngine = ViewEngine.Object;
Controller.ControllerContext = new Mock<ControllerContext>(new Mock<HttpContextBase>().Object, new RouteData(), Controller).Object;
}
public abstract T CreateController();
public RenderCall<ViewContext> ExpectRenderView()
{
var render = new RenderCall<ViewContext>();
ViewEngine.Expect(v => v.RenderView(It.IsAny<ViewContext>()))
.Callback(new Action<ViewContext>(render.Set));
return render;
}
}
The RenderCall class provides a place to receive the view context that is passed.
public class RenderCall<T>
{
bool _called;
T _data;
public T Data
{
get
{
if (!_called) throw new InvalidOperationException("View was not rendered.");
return _data;
}
}
public void Set(T data)
{
_data = data;
_called = true;
}
}
Monday, March 24, 2008 4:08:16 PM (GMT Standard Time, UTC+00:00)
.net | mvc | thinking | web

Tuesday, February 19, 2008
VB.NET 9 as an HTML View Engine
VB.NET 9 introduces a clean syntax for expressing XML data. XHTML is XML so why not use VB.NET to generate it, instead of ASPX pages? People are creating view engines for the new ASP.NET MVC framework. How about a view engine that uses VB.NET XML literals?
The benefits to this approach include full intellisense and access to a the full VB.NET language when creating HTML.
I see a view as a function from some data to an XML element (the <html> element):
Function CustomersPage(ByVal title As String, ByVal customers As IEnumerable(Of Customer)) As XElement
Return _
<html>
<head>
<title><%= title %></title>
</head>
<body>
<%= From customer In customers Select _
<div id=<%= customer.LastName %>>
<h1><%= customer.FirstName %></h1>
</div> %>
</body>
</html>
End Function
The important change from ASPX is that this is HTML in Code, rather than Code in HTML. As a result less "automagical" behaviour is required; It's just a function! This means AJAX features like "partial rendering", where a section of page needs to be updated, can be expressed by just calling a function that returns a <div> element. That same function can be used by the full HTML page function too.
ASPX "usercontrols" become simply functions as well. ASPX Master Pages are functions that have arguments for "placeholders" that get inserted into an template HTML page. Instead of having to reinvent a bunch of programming language concepts inside ASPX, we can just use a programming language that now support XML!
The only down side to this approach is we lose the IDE visual designer support. However, I find viewing an ASPX page that contains even simple conditional data rendering next to useless. I'd rather keep IE open and just refresh the page to see changes.
I am yet to embrace the MVC framework. I am waiting to see if the next release can better support Snooze framework ideas. However, there's no reason I can't use this VB XML magic in Snooze as it current is.
Tuesday, February 19, 2008 12:12:17 PM (GMT Standard Time, UTC+00:00)
.net | html | thinking | vb.net | web | xml

Thursday, January 10, 2008
Snooze - A REST Framework for .NET
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.
Thursday, January 10, 2008 9:42:04 PM (GMT Standard Time, UTC+00:00)
.net | c# | programming | REST | web

Sunday, December 23, 2007
REST Verbs in ASP.NET MVC
I am yet to play with the new ASP.NET MVC framework. However, I am spending time reading around the area to see if it will benefit me to get more involved.
A concern that came to mind when researching is the claims of it enabling a RESTful approach to web programming. Whilst this may be true, all the examples so far seem contrary to REST. My limited understanding of REST says that URLs represent a Resource. How is http://www.mysite.com/customers/delete/42 a resource?!
Yet that is indeed the format of URL we are being shown by Scott Guthrie and others. It makes ASP.NET MVC look more like another RPC system, just with parameters encoded into the address instead of message body.
So is it possible to specify a resource URL and then a number of HTTP verbs that can execute against it? It probably is, given the extensibility of ASP.NET MVC's architecture. However, one may ask, should I be hacking this into the framework? Would the end result look anything like the original MVC code at all? Probably not!
Is it time for a real REST framework built on top of ASP.NET? I think it is!
It needs to be Resource centered. It needs to fully leverage the rich feature set of HTTP, not just GET and POST! And just to be awesome, it needs to have a client-side story too. Real REST relies on the client-side to store state. Could this be Silverlight, or do we still want JavaScript? (I'm up for cross compiling to JS from C# or MSIL!)
Sunday, December 23, 2007 4:02:00 PM (GMT Standard Time, UTC+00:00)
.net | programming | REST | ria | thinking | web

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

Wednesday, October 17, 2007
Mobile Model Screencast
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!
Wednesday, October 17, 2007 8:32:19 PM (GMT Standard Time, UTC+00:00)
.net | c# | mvp | programming | ria | screencast | tier_split | web

Tuesday, October 02, 2007
ToJavaScript Extension Method
Has anyone looked into an extension method on the .NET 3.5 Expression class that returns a JavaScript method? This could then be sent to the client web browser.
So you could then write validation logic in C# and run it in the browser as JavaScript!
Tuesday, October 02, 2007 8:39:56 AM (GMT Standard Time, UTC+00:00)
.net | c# | linq | thinking

Sunday, September 30, 2007
Thoughts on client-server communication for the Model in MVP
I am thinking about my client-side MVP pattern and how best to communicate with the server. The current issue is how explicit to make the client/server divide. There are ways to make it feel like the Model is one consistent class, with tools doing all the marshalling to the server, invocation and return. This papering over of the "cracks" may however bite me in the ass at a later date. I reckon that adding the required flexibility to enable tweaking will just end up making the divide explicit again - rendering the exercise pointless.
So the alternative is to write the model with only client-side code. The server-side logic will then be in a service class somewhere. A benefit here is that the developer is free to choose the service style (SOAP, REST, etc).
I still want to avoid writing the client-side model proxy class that calls to the server. A tool is needed to take a service description and create a proxy class. In the context of a JavaScript model object, we need the proxy to be making XML HTTP requests.
I would like to use WCF to create the service. This is a good overview of getting WCF to talk JSON. If I enable meta-data transfer on the service, writing a tool to read this and create a proxy class should be simple.
Sunday, September 30, 2007 9:02:14 AM (GMT Standard Time, UTC+00:00)
.net | mvp | thinking | tier_split

Saturday, September 29, 2007

Thursday, September 27, 2007
Lazy Functions in LINQ
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.
Thursday, September 27, 2007 10:56:51 AM (GMT Standard Time, UTC+00:00)
.net | c# | linq | programming

Monday, September 17, 2007
Client-side MVP with Script#
Have you seen Script#? It is very impressive cross-compiler from C# to JavaScript. The libraries make it simple to program against the HTML DOM and Silverlight among other technologies. I have been using them recently to program Silverlight 1.0 without having to actually touch JavaScript. Using high-level OOP concepts makes creating complex user interactions much easier.
The Model-View-Presenter pattern has been very popular on the server-side when creating HTML applications. However, it seems that not many people have considered using it within the browser. With AJAX techniques becoming the way to make interactive web applications, it seems a little odd that people are not using more high-level concepts client-side. Of course, this mostly applies to the .NET space. I am aware there are Java toolkits that generate JavaScript.
I am therefore going to look into using Script# to implement a client-side, MVP-style, web application. The Model will contain local data and communicate with the server (via XML HTTP requests). The View will be a simple object that can get and set values from HTML/Silverlight elements and raise events when the user clicks on buttons, etc. The Presenter object will then orchestrate the user interaction logic. All this will be done within JavaScript by using Script# to convert C# classes, etc, into JavaScript concepts.
By writing all the code C#, it should be possible to tier split the Model class into server-side and client-side pieces. Whilst the JavaScript on the client-side is drastically different from the C# server-side model, they will share a common set of data fields. So it should be possible to serialize between the two worlds.
Monday, September 17, 2007 4:24:00 PM (GMT Standard Time, UTC+00:00)
.net | c# | programming | silverlight | thinking

Wednesday, September 05, 2007
Assertions via Linq Expressions
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).
Wednesday, September 05, 2007 11:46:23 AM (GMT Standard Time, UTC+00:00)
.net | c# | linq | programming | syntax

Monday, August 27, 2007
Data Access Syntax Using Anonymous Methods
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 9:41:09 AM (GMT Standard Time, UTC+00:00)
.net | c# | data_access | programming | syntax

Saturday, August 25, 2007
Tier Splitting C# Screencast
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 4:18:50 PM (GMT Standard Time, UTC+00:00)
.net | c# | programming | screencast | tier_split

Tuesday, August 14, 2007
A (somewhat) new approach to application development
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.
Tuesday, August 14, 2007 1:02:43 PM (GMT Standard Time, UTC+00:00)
.net | boo | c# | dsl | programming | rhino_mocks | ria | silverlight | tier_split

Wednesday, August 08, 2007
Tier Splitting C# Classes
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.
Wednesday, August 08, 2007 12:17:48 PM (GMT Standard Time, UTC+00:00)
.net | c# | programming | tier_split | ria

Tuesday, July 31, 2007
C# Syntactic Macros
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.
Tuesday, July 31, 2007 12:04:41 PM (GMT Standard Time, UTC+00:00)
.net | programming | c#
![]()