In my last post I discussed code reuse in the form of an abstract CrudController class: a means of providing create, read, update and delete actions for a given entity. In addition, that class provided the ability to work with an entity specification class to allow for filtered reads - which is just another name for search results.

I’m going to show C# code samples for building with a class like this, but you’ll have to fill in the gaps in terms of how you can work with it. The code to list entities is the most interesting and will demonstrate the concept best, so I’m going to focus on that. To begin with, let’s assume a very simple entity:

public class Post
{
	public DateTime CreatedOn { get; set; }
	public string Headline { get; set; }
	public string Body { get; set; }
	public string Username { get; set; }
}

So, to begin with we’d like to list Posts. A typical method to do so would be:

public void List()
{
    PropertyBag["posts"] = PostRepository.FindAll();
}

But remember that in my case, I’m trying to create a reusable method of doing this, and that I’m also going to be working with ExtJS which is going to consume JSON. So, I have the following class:

public abstract class CrudController<Entity>
{
	private IRepository<Entity> _repository;

	public void GetJsonList()
	{
		RenderText(
			JsonHelper.Serialize(_repository.FindAll())
		);
	}
}

public class PostController : CrudController<Post>{}

I need a shell PostController, but most of the action is happening in the CrudController, and I’m using the magic of Windsor and generics to make it happen. By passing Post as a type parameter to CrudController, Windsor will then give me the correct IRepository<T> to work with, and from there it’s a simple matter of fetching the list of Post Entities in the same way I did in the previous code sample. I want to get a JSON string back, so I’m passing that list to a helper to serialize to JSON.

The next step is to make this listing method a bit more flexible and a bit more powerful. I want to do a couple of things - paging, sorting, and searching. Here’s my new method signature for GetListJson:

void GetListJson(int start, int limit, string sort, string dir, EntitySpecification spec)

The arguments “start” and “limit” are for paging, saying which record I should start from and how many I should return. The “sort” argument tells me the column I should sort on, and “dir” gives me the sort direction. But what about EntitySpecification? Let’s show it in context:

public abstract class CrudController<Entity, EntitySpecification> where EntitySpecification : ISpec
{
	private IRepository<Entity> _repository;

	public void GetJsonList(int start, int limit, string sort, string dir, [DataBind("spec")]EntitySpecification spec)
	{
		spec.AddOrder(sort, dir);
		spec.FindAll(_repository, start, limit);
	}
}

public class PostController : CrudController<Post, PostSpecification>{}

As you can see, EntitySpecification is databound by Monorail; incoming parameters are passed to the specification to build up a criteria for querying, as described in Ayende’s search specification post. That means that I don’t have to explicitly handle searching in my CrudController at all, because it’s all handled by the EntitySpecification. A sample PostSpecification could look like this:

public class PostSpecification : ISpec
{
	private ICriteria _criteria;
	private string _username;

	public virtual string Username
	{
		get { return _username; }
		set {
			_username = value;

			if (value == null)
				return;

			_criteria.Add(
					Expression.Eq("Username", value)
				);
		}
	}

	public void AddOrder(string sort, string dir)
	{
		var order = (dir == "ASC" ? .Order.Asc(sort) : Order.Desc(sort));

		_criteria.AddOrder(new Order());
	}
	public IList<Post> FindAll(IRepository<Post> repo, int start, int limit)
	{
		repo.Find(_criteria, start, limit);
	}
}

When Monorail runs the databinder, the Username property’s getter will be called and the private criteria will be altered. When the specification’s FindAll method is called, that criteria is passed through to filter the returned records.

Let me know if you have any improvements or suggestions, and thank you again to Ayende for the specification ideas.

I’ve previously talked about my dislike for code generation in Javascript. I still standby that, but I am beginning to have a change of heart for certain scenarios. I’ve been working on a couple of ExtJS applications recently and I’ve got lots of code which is purely ExtJS stuff on its own - no HTML or other code in there really. It’s been a project where I’ve been using C# 3 and it’s partly the similarities between the two languages which have triggered this rethink.

Take a look at this code:

var win = new Ext.Window({
	title: 'Order Viewer', layout: 'border',
	width: 500, height: 500,
	modal: true, resizable: false, closable: false, draggable: false,
	items: [ frm, lst ]
});

win.on('render', function() {
	load(5);
});

win.show();

That’s pretty standard stuff for what I’m doing with Ext right now - I create a new window with a load of configuration options, then add in an event handler for the window’s render event, and finally show the window on screen. Now imagine that you could write the following in C# 3:

var win = new Ext.Window{
	Title = "OrderViewer", Layout = Layout.Border,
	Width = 100, Height = 200,
	Modal = true, Resizable = false, Closable = false, Draggable = false,
	Items = new [] { frm, lst }
};

win.Render += delegate {
	load(5);
};

win.show();

As far as I’m aware, all of the above is valid C# 3 code. I’ve basically written it as I’d like to use it, with an enum for the Layout type, and C# style event handler syntax, but the interesting thing to me is how very similar it is to the Javascript version.

The ExtSharp project allows you to write your Ext code in C# and have it rendered as Javascript. I’m going to explore it in my next post, and examine how closely it can be made to fit the code sample above.

Web-Based Build Server

March 11th 2008, 10:12 am in Development, Web.

It surprises me that no-one offers a web-based build server - specify your source control connection details, set up a couple of tasks (build, test, report) and hit “go”. Is there some obvious problem with this idea that I’ve missed?

I want a build server but I don’t want to have to maintain the install or faff around with configs. I’ve tried TeamCity, which seemed ok, but the interface wasn’t great and it doesn’t support MbUnit.

I’ve started using Beanstalk for Subversion hosting, and it works very well indeed, so maybe that’s what’s got my thirst for web-bases apps going.

My Solution Template

January 27th 2008, 1:53 am in Development, Visual Studio.

For a while I’ve been meaning to come up with a repeatable starting point for my projects. Not only is adding references, configuration and structure to a solution labourious, it’s also pretty difficult to remember every step. Ideally, I wanted to be able to start a project with everything ready for me.

I spent a while today doing just that; a solution which matches the starting point for most of my projects. Firstly, there’s a Monorail project with Windsor, NHibernate and logging integration switched on. All of the required DLL’s have been moved into a Libs directory in the solution folder - the idea behind that is to allow a developer to be able to build the project without needing to install Monorail or any other components. Secondly, there’s a unit tests project with a couple of folders; Controllers and Persistance. These suggest a future structure for this project, with Persistance being used to check the NH mappings work as expected. In addition it contains an NHTestBase class which allows my unit tests to run with a SqlCe database. Thirdly, a project called Core; this holds core functionality for the solution, such as entities and services, exceptions and utility methods.

The whole thing can be found here: http://dev.plastiscenic.co.uk/svn/projects/Plastiscenic.Sample/ but it’s missing one thing - a good way to customise it. Namespaces, directory names, etc, need to be manually changed. For me that’s still better than building it up from scratch but it’s still a pain. If anyone’s got any suggestions, I’d love to hear them.

One final note; this has pushed me to collect together a couple of classes I use often, and I’ve stolen Ayende’s naming convention by creating Plastiscenic Commons. This contains a repository implementation, stuff for setting up a SqlCe database, a static container accessor, and a few other bits. Nothing exciting but I always need them.

Feedback appreciated.