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
|

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

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

Monday, December 24, 2007
Nouns-Verbs, OOP-Functional, REST-Web Services
This is just a quick thought that came to me whilst making coffee this morning...
REST places focus on nouns (resources) in a system. Whereas it seems web services are more concerned with verbs. A service is a collection of operations. The data is passed to and from operations as messages.
Now both approaches have their merits. What strikes me as strange is our choice of programming languages when attempting to implement the aforementioned architectural styles. Object orientated programming is all about nouns (classes). Functional programming is all about verbs (functions).
I know that there is way more to web services than just a bunch of operations (because that would be simply RPC right?). However, my point is that surely OOP is ideally suited to describing a set of resources as required by a RESTful design.
Monday, December 24, 2007 9:44:48 AM (GMT Standard Time, UTC+00:00)
programming | REST | thinking | 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

Friday, November 02, 2007
Separating design and code with HTML and JavaScript
There is a lot of hype around Silverlight and WPF enabling true separation of developer and designer. This is certainly a great way to work. However, I don't think this is enabled only now by XAML. There is no reason the same cannot be achieved with HTML.
It seems like developers went so far down the server-side HTML generation route we left designers floundering with only CSS left in their toolkit. Whilst you can do some amazing things with CSS, sometimes you just need to change the HTML. If the HTML is riddled with <% %>, server controls or other template commands how is out poor designer going to work with the file?
My current attention is around using pure HTML and putting all dynamic content generation into JavaScript. The only thing to enforce on the HTML is that certain elements have known "id" attribute values.
Friday, November 02, 2007 4:42:04 PM (GMT Standard Time, UTC+00:00)
html | programming | ria | thinking | web

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

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#

Sunday, July 08, 2007
The Right Amount of Code Generation
David Hayen talks about the problem of using code generation at a large scale within software projects. The first use gives a lovely RAD hit, but over time you get more constrained and limited by the generated code. I always found this problem using any kind of data-n-drop data binding (although .NET 2.0 windows forms data binding seems almost flexible enough).
It is hard to get large scale code generation perfect - almost impossible in reality. I find using code generation at a smaller scale to actually raise the level of abstraction in code more useful. Languages such as Boo and Ruby have great syntax for defining mini domain specific languages to raise abstraction levels. Syntactic macros in Nemerle and Lisp are true compile-time code generators. The key to these methods is that the programmer has not lost the expressivity his language gives him. If a certain macro is not really fitting, you can always write out the code long-hand and refactor later if necessary.
Large scale code generation assumes software is smooth and regular. In the real-world we have to deal with special cases and, worse, changing requirements. Trying to make a code generation tool fit all of these requires it to be as expressive as a real programming language! Only now we are buried in stacks of XML config files and templates.
One area I do see a benefit for these quick-n-dirty code generators is in prototyping. You want to get something half-real in front of customers quickly to gather feedback. However, never be precious about your code. The best writing is re-writing! A lot of software hangs around for a lot longer than we expect, or even hope. It is probably best to make it as maintainable as humanly possible.
The fact that a magic tool generated thousands of lines of code for you doesn't stop them for existing. The more code that exists, more chance there is for something to be wrong. If your chosen programming language requires you to write reams of code to express something that you can conceptualise more simply, then I'm sorry you need a better language.
Sunday, July 08, 2007 12:03:08 AM (GMT Standard Time, UTC+00:00)
programming | thinking

Friday, July 06, 2007
Code for the Rhino Mock DSL
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 12:19:48 PM (GMT Standard Time, UTC+00:00)
.net | boo | dsl | mock_objects | programming | rhino_mocks

Wednesday, July 04, 2007
Better Syntax for Mocking
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 10:41:55 AM (GMT Standard Time, UTC+00:00)
.net | boo | dsl | mock_objects | programming | rhino_mocks

Monday, July 02, 2007
Rhino Mocks DSL in Boo
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():
&nbs