Friday, 27 March 2009

Castle WCF Integration Facility

I work predominantly on a multi-tenant application which is experiencing an upsurge in sales.  The client has recently dropped the price significantly which has resulted in a rush of sales.

The model I have chosen, rightly or wrongly is for each customer to have their own website and database instance.  The obvious problem with this approach is rolling out releases and database schema updates.  In order to minimise the pain of a release, I have grouped certain functionality into discreet services that each customer website instance accesses via MSMQ. The obvious logic being that software updates are rolled out to one location and not 20 websites.

Using WCF to listen and pick messages of the MSMQ was an easy choice. A windows service is employed to host the service. In the past this is tedious code I have written manually.

Prior to this post, I have used svcutil.exe to generate my client proxies and xml configuration files which initially is not a problem but can be an irritating habit to acquire. A bigger problem I faced was how to incorporate some of my technology stack such as dependency injection into the windows service. I was very against going down the service locator route which is a concept I do not favour.

Enter the hero of the piece in the form of the impressive Castle WcfFacility. I use a lot of the castle stack as is, so this was the gateway to a seamless experience from my windows service. The WcfFacility facilitates Wcf configuration for both hosting a service and creating Wcf clients in the form of a fluent interface.

Finding an example of the configuration for hosting the service from a windows service drew a blank. I googled and searched through the excellent unit tests that are included in the castle source but nothing returned.

After much trial and error, coffee and profanity I eventually got there.

First up, the code to load the container in the windows service. This code is the body of the OnStart method of the windows service:

var returnFaults = new ServiceDebugBehavior{
                           IncludeExceptionDetailInFaults = true
                       };

var metadata = new ServiceMetadataBehavior {HttpGetEnabled = true};
var serviceModel = new DefaultServiceModel();

serviceModel.BaseAddresses.Add(new Uri("http://localhost:8080/Distribution/"));

_container = new WindsorContainer();

var binsorFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Windsor.boo");

BooReader.Read(_container, binsorFilePath);

_container.AddFacility<WcfFacility>().Register(
   Component.For<IDistributionProcessor>()
       .ImplementedBy<DistributionProcessor>()
       .ActAs(serviceModel.AddEndpoints(
                  WcfEndpoint.ForContract<IDistributionProcessor>()
                      .BoundTo(new NetMsmqBinding(NetMsmqSecurityMode.None)
                                   {
                                       UseActiveDirectory = false
                                   })
                      .At("net.msmq://localhost/private/distribution") //TODO: Move into configuration
                  ).Hosted()
       ),
      Component.For<IServiceBehavior>().Instance(returnFaults),
      Component.For<IServiceBehavior>().Instance(metadata)
    );

To start the service:

_serviceHost = (ServiceHost) new DefaultServiceHostFactory().CreateServiceHost(typeof (IDistributionProcessor).AssemblyQualifiedName, new Uri[0]);
_serviceHost.Open();


On the client side, I register the Wcffacility like so:

_container = new WindsorContainer().AddFacility<WcfFacility>().Register(
    WcfClient.ForChannels(
        new DefaultClientModel
        {
            Endpoint = WcfEndpoint.ForContract<IDistributionProcessor>()
                .BoundTo(new NetMsmqBinding(NetMsmqSecurityMode.None)
                {
                    UseActiveDirectory = false
                })
                .At("net.msmq://localhost/private/distribution") //TODO: Move into configuration
        })
    );


Job done!!

Horn Architecure Overview

Horn Architecure Overview

This is the third in a series of posts to introduce the horn package management system.  An introduction to horn can be found here with a further explanation of the horn dsl here.

The following text will give an overview of the code structure and architecture that currently exists for horn.

Firstly let us examine the project structure of horn:

Hopefully the project names of the solution are fairly self explanatory.

  • Horn.Core is the chief player of the piece with hopefully the majority of all business logic contained here.

  • Horn.Console is the current command line client used to invoke horn commands.

  • Hron.Core.Spec contains the BDD style unit tests to drive out the functionality of Horn.Core

  • Horn.Core.Integration contains the end to end integration tests used to fully test the horn functionality.

  • Horn.Core.Spec.Framework contains base classes used by both the testing project


Horn is invoked from the command line with a familiar DOS application/swtch instruction set:

horn -install:horn

This install switch is parsed out by a command line parser utility.  This triggers a runtime search for a specific package tree directory node.  In the above example the search will be performed for a directory named horn.

One of the artifacts included in each specific package directory node is the package specific build.boo file containing the install instructions for the requested package.

The philosophy of how commands are invoked is unsurprisingly based on the command design pattern.  We are able to resolve which specific command is required by examining the instructions that are sent via the command line.  In the case of "horn -install:horn", an install command is required.

Our command abstraction is a simple .NET interface with one method contract:

public interface IPackageCommand
{
    void Execute(IPackageTree packageTree, IDictionary<string, IList<string>> switches);
}

The execute method takes as an argument an in memory representation of the package specific tree node.  All nodes of the tree or indeed the tree itself are defined in terms of an interface to allow mocking or stubbing that should encourage futher unit testing. A further IDictionary argument is passed to represent the command line switches.

We use the Castle Windsor Inversion Of Control container to loosely couple our dependencies and also promote testability.  This means we can pull the concrete implementation of the install package command like this:

IoC.Resolve<IPackageCommand>(parsedArgs.First().Key).Execute(packageTree, parsedArgs);

It should be noted that we are resolving the dependecy by the string key AND the type. The string we are using to retrieve the implementation is the first command line switch.
In this case the -install part of the horn -install:horn command.

Each IPackageCommand implementation will be inserted into the container at application start up:

innerContainer.Register(
    Component.For<IPackageCommand>()
                .Named("install")
                .ImplementedBy<PackageBuilder>()
                .LifeStyle.Transient
    );

Once the install command is resolved from the IOC container the following method will be executed.

public void Execute(IPackageTree packageTree, IDictionary<string, IList<string>> switches)
{
   string packageName = GetPackageName(switches);
   IBuildMetaData buildMetaData = GetBuildMetaDataFor(packageTree, packageName);
   IPackageTree componentTree = GetComponentTreeFrom(packageTree, packageName);
   ExecuteSourceControlGet(buildMetaData, componentTree);
   BuildComponentTree(nextMetaData, nextTree);
}

The first step is to retrieve the package name from the right hand side of the install switch.

Once we know which component to retrieve we can get the exact package tree node from the over all package tree.  Typically we have wrapped the package tree implementation in an IPackageTree interface to promote both testability and to decouple the implementation:

public interface IPackageTree : IComposite<IPackageTree>
{
   string Name { get; }
   bool IsRoot { get; }
   Dictionary<string, string> BuildFiles { get; set; }
   IPackageTree Retrieve(string packageName);
   IBuildMetaData GetBuildMetaData(string packageName);
   DirectoryInfo CurrentDirectory { get; }
   DirectoryInfo WorkingDirectory { get; }
   bool IsBuildNode { get; }   
   DirectoryInfo OutputDirectory { get; }
   List<IPackageTree> BuildNodes();
}

The package tree is based on the composite design pattern which states that a group ofobjects can be treated in the same way as a single instance.Each package will have its own child directory structure node of the overall package treecontaining such elements as a WorkingDirectory where the source will be built and an outputdirectory which is the where the output of the build will be placed in the result of an errorless build.
At the time of writing this is the default behaviour of a successful build.

We plan to add to the dsl for post build instructions. Once we have the location for the package's node in the oveall package tree directory structure we can then locate the build.boo file.

The build.boo file contains the package's metadata and install instructions.

Horn's install instructions are defined in the following DSL instance:

install horn:
   description "This is a description of horn"
   get_from svn("https://scotaltdotnet.googlecode.com/svn/trunk/")
   build_with msbuild, buildfile("source/Horn/horn.sln"), frameworkVersion35

The following method takes care of retrieving the file and parsing it's contents:

private IBuildMetaData GetBuildMetaData(IPackageTree packageTree, string packageName)
{
    var buildFileResolver = new BuildFileResolver().Resolve(packageTree.CurrentDirectory, packageName);
    var reader = IoC.Resolve<IBuildConfigReader>(buildFileResolver.Extension);
    return reader.SetDslFactory(packageTree).GetBuildMetaData(packageTree, packageName);
}

This method will return an IBuildMetaData implementation which is defined in the following
contract:

public interface IBuildMetaData
{
    BuildEngine BuildEngine { get; set; }
    SourceControl SourceControl { get; set; }
}

The IBuildMetaData contract has two members, a BuildEngine and a SourceControl member.

SourceControl is an abstract class which will have a number of subclasses to implement the various SourceControl types.  We only have one implementation so far which is the SVNSourceControl subclass which quite obviously is for subversion retrieval.

The SVNSourceControl class uses the excellent SharpSVN open source project to handle the downloading of source code from subversion.

We chose a different route for the BuildEngine's implementation. We favoured composition
over inheritance.

With this in mind, an IBuildTool concrete implementation is passed into
the BuildEngine's constructor:

public BuildEngine(IBuildTool buildTool, string buildFile, FrameworkVersion version)
{
    BuildTool = buildTool;
    BuildFile = buildFile;
    Version = version;
}

The IBuildTool is an abstraction to allow realizations such as MSBuild, Nant
and Rake to be used.

The IBuildTool Contract contains only one method:

public interface IBuildTool
{
    void Build(string pathToBuildFile, IPackageTree packageTree, FrameworkVersion version);
}

Once we have retrieved the source code from the particular SourceControl subclass,
we can then build the source with a concrete IBuildTool implementation.
In the case of horn, we are using an MSBuild subclass as specified in the DSL:
build_with msbuild, buildfile("source/Horn/horn.sln"), frameworkVersion35

The above line specifies which builder we are using, the location the of the build file,
the build tool that will be used and the .NET framework version to build against.

We have plans to create build tool concrete implementations for NAnt, Rake
and just about any other build tool realizatrion that we need.

The IBuildTool implementation for MSBuild is defined as follows:

public void Build(string pathToBuildFile, IPackageTree packageTree, FrameworkVersion version)
{
    var pathToMsBuild = FrameworkLocator.Instance[version].MSBuild.AssemblyPath;
    var args = string.Format("\"{0}\" /p:OutputPath=\"{1}\" /p:TargetFrameworkVersion={2} /p:NoWarn=1591 /consoleloggerparameters:Summary", pathToBuildFile, packageTree.OutputDirectory, GetCmdLineFrameworkVersion(version));
    var psi = new ProcessStartInfo(pathToMsBuild, args)
        {
        UseShellExecute = false,
        RedirectStandardOutput = true,
        WorkingDirectory = packageTree.WorkingDirectory.FullName
        };
    var msBuild = Process.Start(psi);
    while (true)
    {
        var line = msBuild.StandardOutput.ReadLine();
        if (line == null)
            break;
            log.Info(line);
    }
    msBuild.WaitForExit();
}

The previous snippet illustrated the method that will build the source code that we havedownloaded from subversion.

The above method outputs the binary files of the build into the output directory as specified in horn's package tree node.At this time of writing this is where we stand.  The next steps are to do some rigorous refactoring followed by adding a nant IBuildTool implementation.Once we are happy with iteration one and we have a good process for building horn, we can then touch on the main point of the product.

That being dependency management. Which is where it gets very interesting.

Castle Windsor
Rhino.Mocks
XUnit
Rhino.DSL
log4Net

If any of this is of interest to you then please join the Horn user group for updates or check out the source here.

The Horn Dsl

An introduction to the horn project can be found here.

In my last post, I finished up by mentioning that the first task was to outline a DSL syntax containing metadata and build instructions for each package dependency.

We are basing our package manager on the Portage build system and hope to replicate their metaphor of the Portage Tree.  The DSL build instructions will reside in our package tree structure in the form of a build.boo file.

The choice of language for the DSL was an obvious one and we went with Boo which is a statically typed language for the CLI with a python inspired syntax and a special focus on language and compiler extensibility.

Below is the current DSL syntax for defining the package metadata and build instructions:

install horn:
    description "This is a description of horn"
    get_from svn("https://scotaltdotnet.googlecode.com/svn/trunk/")
    build_with msbuild, buildfile("source/Horn/horn.sln"), frameworkVersion35


This is our first iteration DSL and I expect the above prose to go through multiple metamorphic transformations as the ebb and flow of horn twists and turns through its development evolutionary cycle. I am also expecting that this is a fairly readable grammar and should explain what the purpose is.

First we are defining some basic metadata by way of the description of the install package.  I want to further open the metadata details out to contain other information points like the project’s home page URL and a category definition containing key words to make the packages searchable through the horn application.  I have pencilled in lucene.net as a proposed means of indexing the horn package tree.

Next we have the following line:

get_from svn("https://scotaltdotnet.googlecode.com/svn/trunk/")

Hopefully this sentence structure is perfectly readable and it is indeed clear that the sentence is a command that gets the source from subversion at the parenthesisised URI.

I should add at this point that we are using the excellent Rhino.DSL tool developed by Oren Eini. It makes getting started with Boo DSL much easier and I highly recommend its use to develop your own DSL.  The steps that were completed to allow the horn Boo DSL syntax to be parsed are as follows:

  • A subclass was christened from the DslEngine base class of Rhino.DSL named ConfigReaderEngine. Then an AnonymousBaseClassCompilerStep was added to the compiler pipeline.

  • created an abstract class named BaseConfigReader that the AnonymousBaseClassCompilerStep will use to parse the DSL syntax into.


Below is the listing of the horn install Dsl’s AnonymousBaseClassCompilerStep:

public class ConfigReaderEngine : DslEngine
{
    protected override void CustomizeCompiler(Boo.Lang.Compiler.BooCompiler compiler, Boo.Lang.Compiler.CompilerPipeline pipeline, string[] urls)
    {
        pipeline.Insert(1, new ImplicitBaseClassCompilerStep(typeof(BooConfigReader), "Prepare", "Horn.Core.Dsl"));
        pipeline.InsertBefore(typeof(ProcessMethodBodiesWithDuckTyping), new RightShiftToMethodCompilerStep());
        pipeline.Insert(2, new UnderscorNamingConventionsToPascalCaseCompilerStep());
        pipeline.Insert(3, new UseSymbolsStep());
 
    }
}

I will now attempt and I must stress attempt to explain how the build_with grammar can both be constructed and parsed out with regular C# code.  Let us remind ourselves of the syntax we want to parse:

build_with msbuild, buildfile("source/Horn/horn.sln"), frameworkVersion35
The BaseConfigReader abstract class mentioned previously will be entrusted with the job of making sense of our install grammar. Let us now start breaking the sentence structure down into it’s constituent parts.

The first part of our sentence is the build_with construct and this verb will be used to inform horn which build engine to use, where the build file is situated relative to where the package’s position is in the package tree directory hive and lastly which .NET framework version to build against.

A programmatic view of how to view this sentence is to observe build_with as the method name and the other parts as parameters delimited by commas that will be passed to the method. One of the reasons that boo is such a good fit for authoring DSLs is the absence of parenthesis needed for defining methods.

The following C# method is charged with making sense of the boo statement:

[Meta]
public static Expression build_with(ReferenceExpression builder, MethodInvocationExpression build, ReferenceExpression frameWorkVersion)
{
    var targetName = builder.Name;
 
    return new MethodInvocationExpression(
            new ReferenceExpression(targetName),
            build.Arguments[0],
            new StringLiteralExpression(frameWorkVersion.Name)
        );
}

The first thing of note is the Boo.Lang Meta attribute.  Static methods tagged with the Meta attribute should be perceived as a shortcut to the compiler that accepts AST (Abstract Syntax Tree) Nodes and returns an AST node.

An AST is the most common way for computers to work with structured text.  They turn the structured text into a graph on which operations can be performed against instead of manual parsing.

If we can return to the boo sentence under examination:
build_with msbuild, buildfile("source/Horn/horn.sln"), frameworkVersion35
Each sentence part after the build_with expression can be viewed as an AST node that will be passed into the buildWith static meta method in the form of the boo language construct of an expression.

  • The msbuild snippet is translated as a ReferenceExpression. A ReferenceExpression can be viewed as string literal without the double quotes.

  • The buildFile node is a MethodInvocationExpression. A MethodInvocationExpression contains the method name we want to invoke an the arguments if any that are needed to complete the method call.

  • The frameWorkVersion35 is another ReferenceExpression.


The return call of the meta method will invoke the following method.

protected void msbuild(string buildFile, string frameWorkVersion)
{
    var version = (FrameworkVersion)Enum.Parse(typeof(FrameworkVersion), frameWorkVersion);
 
    BuildEngine = new BuildEngine(new MSBuildBuildTool(), buildFile, version);
}

We construct the call from the ‘msbuild’ reference expression.

This leaves the door open to call other build engines like nant for example.  We then satisfy the method call by selecting the argument from the buildFile method invocation and the framework version reference expression.

While constructing this DSL, I found the boo documentation pretty non existent but was able to extract knowledge both from Ayendes’s DSL book and the Rhino.DSL test fixtures.

If any of this is of interest to you then please join the Horn user group for updates or check out the source here.

The Horn Package Management System

By way of starting off my newly birthed blog, I want to self promote the open source project horn that the members of the scotalt.net community have commenced work on.  The goal of the project was to firstly promote the tenets we believe are important for writing robust and maintainable software.

These tenets are in no particular order:
  • TDD with a bit of a BDD splash to specify the code pickings
  • Inversion Of Control for dependency resolution
  • High level modules should not depend on low level components, both should depend upon abstractions.
  • Continuous integration for feedback on every source control check in

After the usual exchange of everyone self promoting their own personal ideas somebody came up with the extremely bright idea of creating a package management system along the lines of maven that can take the pain away from building .net source code packages that usually come from open source projects. Rather upsettingly this idea did not stem from me.

Let me paint a pain scenario that I am currently experiencing. I use a stack that is probably quite similar to a lot of developers who follow some of the ALT.NET ideologies. That stack consists of Rhino, Castle, NHibernate, MVCContrib etc.  One of the ill affects of such a stack is the constant treadmill like upgrading of components where I can quite literally lose a day downloading the source, fiddling with the Nant scripts in order to get the damn thing to build.  For a man who possesses an infamous bad temper this can be quite disturbing for anybody in close proximity of __the__mad__man__ wrestling with the aforementioned components. The end result is that I quite literally loathe this never ending routine of upgrading.

The proposed scheme of horn is to take control of the building of source code packages from a scm repository and resolving any dependency management for you.

Unsuprisingly .NET is possibly the only platform without a recognised build system. Being a plagiaristic brute, the smart and only option was to base horn on an existing package manager.

This clearly led to the accustomed trawling through reams of scant open source documentation to find a good candidate for replication. I first read up on Maven which was instantly off putting because of the heavy dependency xml mark up used to define the build configuration. Then Craig Nicol suggested the portage system which intuitively felt like the ideal choice.  At the heart of portage is the metaphor of the Portage Tree.  This curious tree is simply a directory structure that categorises and constrains the package definitions. The package tree can be thought of as a database of components and dependencies. What is really interesting is how the tree is used to check such things as circular referencing. Some extra reading on the portage tree can be found here.

Scattered around the portage tree structure are build file definitions written in bash called ebuilds that contain metadata about the package and build instructions.

With the best template system in place we started work on defining a set of tasks in a expressive BDD syntax. The first iteration goal was quite simply to download horn from subversion, build the source and place the output of the build in a designated output directory. Our first draft of specifications can be found here.

With this in place we were up and running. We had a quick heads up over skype and got some basic architecture in place.

The first task was to define a syntax for defining both the build metadata and build instructions a.k.a. horn’s implementation of portage’s ebuild. With xml being desperately out of vogue we opted for a DSL syntax which would be written in boo.

If any of this interests you then please join the horn user group for updates or check out the source here.