- Posted by liammclennan on August 20, 2010
In a recent podcast Scott Hanselman accurately, and delicately, exposed some of the weaknesses of NHibernate.
Scott focused on the difficulty of getting started with NHibernate, referring to the number of assemblies required, and on the oversupply of choice that plagues the NHibernate user, such as with mapping and query options.
The best products require a strong leader, with a singular vision and clear purpose. In contrast, NHibernate appears to have been assembled by a committee divided by space, time and goal. Whatever the goals are, it is clear that simplicity is not one of them.
The situation is frustrating because NHibernate is currently my data access tool of choice. For all of its shortcomings I do not know of a better alternative.
To celebrate the more-features-is-always-better mentality I put together a mockup of what the iPhone may have looked like if designed by the .NET open source community.

- Posted by liammclennan on June 14, 2010
After more time than I care to admit I have finally released a rudimentary Http Handler for serving compiled CoffeeScript from Asp.Net applications.
It was a long and painful road but I am glad to finally have a usable strategy for client-side scripting in CoffeeScript.
Why CoffeeScript?
As Douglas Crockford discussed in detail, Javascript is a mixture of good and bad features.
The genius of CoffeeScript is to treat javascript in the browser as a virtual machine.
By compiling to javascript CoffeeScript gets a clean slate to re-implement syntax, taking the best of javascript and ruby and combining them into a beautiful scripting language. The only limitation is that CoffeeScript cannot do anything that javascript cannot do.
Here is an example from the CoffeeScript website. First, the coffeescript syntax:
reverse: (string) ->
string.split('').reverse().join ''
alert reverse '.eeffoC yrT'
and the javascript that it compiles to:
var reverse;
reverse = function(string) {
return string.split('').reverse().join('');
};
alert(reverse('.eeffoC yrT'));
Areas For Improvement ;)
The current implementation is deeply flawed, however, at this point I’m just glad it works. When the server receives a request for a coffeescript file the following things happen:
- The CoffeeScriptHandler is invoked
- If the script has previously been compiled then the compiled version is returned.
- Else it writes a script file containing the CoffeeScript compiler and the requested coffee script
- The process shells out to CScript.exe to to execute the script.
- The resulting javascript is sent back to the browser.
This outlandish process is necessary because I could not find a way to directly execute the coffeescript compiler from .NET. If anyone can help out with that I would appreciate it.
- Posted by liammclennan on June 11, 2010
Rake is a ruby internal DSL for build scripting. With (or without) the help of albacore rake makes an excellent build scripting tool for .NET projects.
The albacore documentation does a good job of explaining how to build solutions with rake but there is nothing to assist with another common build task – updating configuration files.
The following ruby script provides some helper methods for performing common configuration changes that are required as part of a build process.
class ConfigTasks
def self.set_app_setting(config_file, key, value)
ovsd_element = config_file.root.elements['appSettings'].get_elements("add[@key='#{key}']")[0]
ovsd_element.attributes['value'] = value
end
def self.set_connection_string(config_file, name, connection_string)
conn_string_element = config_file.root.elements['connectionStrings'].get_elements("add[@name='#{name}']")[0]
conn_string_element.attributes['connectionString'] = connection_string
end
def self.set_debug_compilation(config_file, debug_compilation)
compilation_element = config_file.root.elements['system.web'].get_elements("compilation")[0]
compilation_element.attributes['debug'] = false
end
private
def self.write_xml_to_file(xml_document, file)
File.open(file, 'w') do |config_file|
formatter = REXML::Formatters::Default.new
formatter.write(xml_document, config_file)
end
end
end
To use, require the file and call the class methods, passing the configuration file name and any other parameters.
require 'config_tasks'
ConfigTasks.set_app_setting 'web.config', 'enableCache', 'false'
- Posted by liammclennan on May 27, 2010
This post is a message in a bottle. I cast it into the sea in the hope that it will one day return to me, stuffed to the cork with enlightenment. Yesterday I tweeted,
what is the name of the pattern where you replace a multi-way conditional with an associative array?
I said ‘pattern’ but I meant ‘refactoring’. Anyway, no one replied so I will describe the refactoring here.
Programmers tend to think imperatively, which leads to code such as:
public int GetPopulation(string country)
{
if (country == "Australia")
{
return 22360793;
} else if (country == "China")
{
return 1324655000;
} else if (country == "Switzerland")
{
return 7782900;
}
else
{
throw new Exception("What ain't no country I ever heard of. They speak English in what?");
}
}
which is horrid. We can write a cleaner version, replacing the multi-way conditional with an associative array, treating the conditional as data:
public int GetPopulation(string country)
{
if (!Populations.ContainsKey(country))
throw new Exception("The population of " + country + " could not be found.");
return Populations[country];
}
private Dictionary<string, int> Populations
{
get
{
return new Dictionary<string, int>
{
{"Australia", 22360793},
{"China", 1324655000},
{"Switzerland", 7782900}
};
}
}
Does this refactoring already have a name? Otherwise, I propose
Replace multi-way conditional with associative array
- Posted by liammclennan on May 18, 2010
The above error occurred when I executed a linq query using the following expression:
(s) => s.Book.Slug.Equals(bookslug) && ids.Contains(s.Id);
ids in this case is of type IEnumerable<Guid>. As indicated by the error message the fix is to change ids to ICollection<Guid>, then the query executes successfully.
- Posted by liammclennan on March 23, 2010
When writing tests, other than end-to-end integration tests, we often need to construct test data objects. Of course this can be done using the class’s constructor and manually configuring the object, but to get many objects into a valid state soon becomes a large percentage of the testing effort.
After many years of painstakingly creating builders for each of my domain objects I have finally become lazy enough to bother to write a generic, reusable builder class for .NET. To use it you instantiate a instance of the builder and configure it with a builder method for each class you wish it to be able to build. The builder method should require no parameters and should return a new instance of the type in a default, valid state. In other words the builder method should be a Func<TypeToBeBuilt>. The best way to make this clear is with an example. In my application I have the following domain classes that I want to be able to use in my tests:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public bool IsAndroid { get; set; }
}
public class Building
{
public string Street { get; set; }
public Person Manager { get; set; }
}
The builder for this domain is created like so:
build = new Builder();
build.Configure(new Dictionary<Type, Func<object>>
{
{typeof(Building), () => new Building {Street = "Queen St", Manager = build.A<Person>()}},
{typeof(Person), () => new Person {Name = "Eugene", Age = 21}}
});
Note how Building depends on Person, even though the person builder method is not defined yet. Now in a test I can retrieve a valid object from the builder:
var person = build.A<Person>();
If I need a class in a customised state I can supply an Action<TypeToBeBuilt> to mutate the object post construction:
var person = build.A<Person>(p => p.Age = 99);
The power and efficiency of this approach becomes apparent when your tests require larger and more complex objects than Person and Building. When I get some time I intend to implement the same functionality in Javascript and Ruby. Here is the full source of the Builder class:
public class Builder
{
private Dictionary<Type, Func<object>> defaults;
public void Configure(Dictionary<Type, Func<object>> defaults)
{
this.defaults = defaults;
}
public T A<T>()
{
if (!defaults.ContainsKey(typeof(T))) throw new ArgumentException("No object of type " + typeof(T).Name + " has been configured with the builder.");
T o = (T)defaults[typeof(T)]();
return o;
}
public T A<T>(Action<T> customisation)
{
T o = A<T>();
customisation(o);
return o;
}
}
- Posted by liammclennan on March 20, 2010
Last week on Software Craftsman Pilgrimage I was trying to organise where I will be travelling, and the companies I will be pairing with.
I now have a confirmed itinerary.
| 9 - 11th April |
Alt.NET Seattle |
| 12th April |
Craftsman visit with Didit (Long Island) |
| 13th April |
rest day :) |
| 14th April |
Craftsman visit with Obtiva (Chicago) |
| 15th – 16th April |
Craftsman visit with 8th Light (Chicago) |
| 17th – 18th April |
Seattle Code Camp |
I am looking forward to all of my visits and talking to all the smart people who work there. I will be blogging my progress and hopefully shooting some video.
If you are in Seattle, New York or Chicago and would like to meet up to chat about craftsmanship, programming, ruby or .NET please email me.

- Posted by liammclennan on March 17, 2010
I have made a change to my code-based BDD style. I start with a scenario such as:
Pre-Editing
* Given I am a book editor
* And some chapters are locked and some are not
* When I view the list of chapters for editing
* Then I should see some chapters are editable and are not locked
* And I should see some chapters are not editable and are locked
and I implement it using a modified SpecUnit base class as:
[Concern("Chapter Editing")]
public class when_pre_editing_a_chapter : BaseSpec
{
private User i;
// other context variables
protected override void Given()
{
i_am_a_book_editor();
some_chapters_are_locked_and_some_are_not();
}
protected override void Do()
{
i_view_the_list_of_chapters_for_editing();
}
private void i_am_a_book_editor()
{
i = new UserBuilder().WithUsername("me").WithRole(UserRole.BookEditor).Build();
}
private void some_chapters_are_locked_and_some_are_not()
{
}
private void i_view_the_list_of_chapters_for_editing()
{
}
[Observation]
public void should_see_some_chapters_are_editable_and_are_not_locked()
{
}
[Observation]
public void should_see_some_chapters_are_not_editable_and_are_locked()
{
}
}
and the output from the specunit report tool is:
Chapter Editing specifications 1 context, 2 specifications
Chapter Editing, when pre editing a chapter 2 specifications
- should see some chapters are editable and are not locked
- should see some chapters are not editable and are locked
The intent is to provide a clear mapping from story –> scenarios –> bdd tests.
- Posted by liammclennan on November 27, 2009
Javascript does not have classes in the traditional sense, but we can achieve something similar in a number of ways. C# and Ruby both have standard class syntax.
This post is part of a series comparing the language features of the C#, Javascript and Ruby programming languages.
C#
public class Vehicle
{
protected string Make { get; private set; }
protected string Model { get; private set; }
public Vehicle(string make, string model)
{
Make = make;
Model = model;
}
public virtual void Print()
{
Console.WriteLine(GetDescription());
}
protected string GetDescription()
{
// string formatting syntax return string.Format("Make: {0} Model: {1}", Make, Model);
}
}
public class Helicopter : Vehicle // inheritance syntax {
public int NumberOfRotorBlades { get; private set; }
public Helicopter(int numberOfRotorBlades, string make, string model)
: base(make, model)
{
NumberOfRotorBlades = numberOfRotorBlades;
}
public override void Print()
{
// string concatenation syntax Console.WriteLine(GetDescription() + " Number of Rotor Blades:" + NumberOfRotorBlades);
}
}
Javascript
Class:
// declare vehicle 'class' var vehicle = function(seed) {
var that = {};
// private method var getDescription = function() {
return "Make: " + seed.make + " Model: " + seed.model;
};
// public method that.print = function() {
alert(getDescription());
};
return that;
};
// instantiate a vehicle var magna = vehicle({
make: 'Mitsubishi',
model: 'Magna' }); magna.print();
Derived class:
// declare helicopter 'class' var helicopter = function(seed) {
var that = {};
that.prototype = vehicle(seed);
var getDescription = function() {
return "Make: " + seed.make + " Model: " + seed.model;
};
that.print = function() {
alert(getDescription() + " Number of Rotor Blades:" + seed.numberOfRotorBlades);
};
return that;
};
// instantiate a helicopter var ah64 = helicopter({
make: 'Hughes Helicopters',
model: 'AH-64',
numberOfRotorBlades: 4 }); ah64.print();
Ruby
class Vehicle def initialize(make, model) @make = make;
@model = model;
end
def print
puts get_description
end
private
def get_description
return "Make: #{@make} Model: #{@model}" end end magna = Vehicle.new('Mitsubishi', 'Magna')
magna.print
class Helicopter < Vehicle
def initialize(make, model, number_of_rotors)
super(make, model)
@number_of_rotors = number_of_rotors
end
def print
puts get_description + " Number of Rotors: #{@number_of_rotors}" end end ah64 = Helicopter.new("Hughes Helicopters", "AH-64", 4)
ah64.print