Alan Dean

CTO, Developer, Agile Practitioner

Photograph of Alan Dean

Thursday, November 17, 2011

A Definition of Done is ...

Those who work with me know that the Definition of Done is something which I consider to be vital to effective software development. For me the subtitle of any Definition of Done should be along the lines of:

As a professional, when I say that my work is Done, it means that I genuinely believe that I have no further work to do and that I have myself verified that the work is of necessary quality and completeness as well as having the work appropriately checked by others. I will honestly be surprised if my work is defective in some manner when I say it is done. Please take a look at the list below of the characteristics that I consider to be important to my work:

After this subtitle, there is the list that most Agile practitioners are familiar with.

Saturday, November 12, 2011

Unit test naming convention

I have been using TDD since before it was even called that. The practice was called test-first at the time and I learnt to do it with ComUnit against VB6 code. I suspect that there aren't many people who can put down more than a decade of of TDD on their CV. Probably due to this, I employ somewhat idiosyncratic practices, such as a distinct interface focus (both the default interface and those additionally implemented). Accordingly, I have a fairly well elaborated naming convention for my unit tests in order to make test scenario coverage more rigorous and visible.

The overall convention is public void memberKind_parameterType_parameterType_whenScenarioInfo()

Member Kinds (when default or implicit interface implementation)

  • Constructors: ctor
  • Properties: prop
  • Indexers: index
  • Methods: op, opImplicit, opExplicit
  • Generic Methods: op_MethodNameOfT, op_MethodNameOfClass, op_MethodNameOfNew, op_MethodNameOfIInterfaceName

Member Kinds (when explicit interface implementation)

  • Properties: IInterfaceName_prop
  • Indexers: IInterfaceName_index
  • Methods: IInterfaceName_op

Special Names

  • Type definition assertions: a_definition
  • Assert deserialization: xmlDeserialize, jsonDeserialize
  • Assert serialization: xmlSerialize, jsonSerialize

Parameter Types

  • Keywords: int, string
  • Null types: stringNull, TypeNameNull
  • Empty string: stringEmpty
  • Invalid string: stringInvalid
  • Specific values: longZero, intOne, decimalNegative, floatEpsilon, shortMin, DateTimeNow

When
Used to disambiguate two or more tests which otherwise have the same name, e.g. op_ToString_whenDefault(), op_ToString_whenDescriptionIsNull()

Examples
Cavity has almost complete test coverage so there are plenty of examples. Here are some:

Update

So obvious that I forgot to mention it, but worth putting on the record: each class should have exactly one test class, i.e. Example.cs has Example.Facts.cs (if xUnit) or Example.Tests.cs (if NUnit, MSTest, etc.). The period in Example.Facts or Example.Tests is to force the same sort order of units and tests in the Visual Studio solution explorer tree view. I use a pair of templates to assist me (installer available in downloads).

Wednesday, October 12, 2011

Not-so-simple NuGet Packaging

Moving beyond the simple case, here is what I did to package the Cavity log4net trace listener which I'm sharing because I encountered some frustration points.

First, the .nuspec file:

<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
  <metadata>
    <id>Cavity.Diagnostics.Log4Net</id>
    <version>1.1.0.444</version>
    <title>Cavity log4net trace listener</title>
    <authors>Alan Dean</authors>
    <owners />
    <licenseUrl>http://www.opensource.org/licenses/mit-license.php</licenseUrl>
    <projectUrl>http://code.google.com/p/cavity/</projectUrl>
    <iconUrl>http://www.alan-dean.com/nuget.png</iconUrl>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>A trace listener for log4net, allowing provider-agnostic tracing.</description>
    <summary />
    <copyright>Copyright © 2010 - 2011 Alan Dean</copyright>
    <language />
    <tags>Diagnostics</tags>
    <releaseNotes>Switched off license acceptance dialog.</releaseNotes>
    <dependencies>
      <dependency id="log4net" version="1.2.10" />
    </dependencies>
  </metadata>
  <files>
    <file src="content\app.config.transform" target="content\app.config.transform" />
    <file src="content\log4net.config.transform" target="content\log4net.config.transform" />
    <file src="content\web.config.transform" target="content\web.config.transform" />
    <file src="content\Properties\log4net.cs" target="content\Properties\log4net.cs" />
    <file src="lib\net35\Cavity.Diagnostics.Log4Net.dll" target="lib\net35\Cavity.Diagnostics.Log4Net.dll" />
    <file src="lib\net40\Cavity.Diagnostics.Log4Net.dll" target="lib\net40\Cavity.Diagnostics.Log4Net.dll" />
    <file src="tools\Install.ps1" target="tools\Install.ps1" />
  </files>
</package>

Right off the bat. you can see that more is going on here. The trace listener is dependent on log4net and I also have a bunch of content in additional to my two assemblies.

The target project will need to have either its' app.config or web.config extended so there is a transform for each. The target will need an assembly attribute applied, so I took the simple expedient of dropping log4net.cs into Properties alongside AssemblyInfo.cs. However, log4net also requires XmlConfigurator.Configure() to be called. This call needs to be in either Main() or Application_Start() and therefore existing code needs to be edited (rather than a new code file dropped in). To accomplish this, we have to use EnvDTE, as exposed in the Install.ps1 PowerShell script (I also mark the log4net.config file to copy to output during build):

param($installPath, $toolsPath, $package, $project)

$project.ProjectItems.Item("log4net.config").Properties.Item("CopyToOutputDirectory").Value = 1

try
{
  $item = $project.ProjectItems.Item("Program.cs")
}
catch [System.Management.Automation.MethodInvocationException]
{
}

if (!$item)
{
  $item = $project.ProjectItems.Item("global.asax").ProjectItems.Item("global.asax.cs")
}

$terminator = ""
if ($item.FileCodeModel.Language -eq "{B5E9BD34-6D3E-4B5D-925E-8A43B79820B4}")
{
  $terminator = ";"
}

$win = $item.Open("{7651A701-06E5-11D1-8EBD-00A0C90F26EA}")
$text = $win.Document.Object("TextDocument");
$namespace = $item.FileCodeModel.CodeElements | where-object {$_.Kind -eq 5}
$class = $namespace.Children | where-object {$_.Kind -eq 1}

$methods = $class.Children | where-object {$_.Name -eq "Main"}
if (!$methods)
{
  $methods = $class.Children | where-object {$_.Name -eq "Application_Start"}
  if (!$methods)
  {
    [system.windows.forms.messagebox]::show("methods is null")
  }
}

$edit = $methods.StartPoint.CreateEditPoint();
$edit.LineDown()
$edit.CharRight(1)
$edit.Insert([Environment]::NewLine)
$edit.Insert(" log4net.Config.XmlConfigurator.Configure()")
$edit.Insert($terminator)

I have to say that the PowerShell + EnvDTE experience was rather less than enjoyable but I got the basics of what I needed to work.

Simple NuGet Packaging

Over the last week I have started publishing my Cavity libraries on to NuGet, starting with my Unit Testing Fluent API.

The API is implemented in a single assembly with no non-BCL dependencies, which makes it the simplest case to pack for NuGet.

This is the .nuspec file:

<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
  <metadata>
    <id>Cavity.Testing.Unit</id>
    <version>1.1.0.444</version>
    <title>Cavity Unit Testing</title>
    <authors>Alan Dean</authors>
    <owners />
    <licenseUrl>http://www.opensource.org/licenses/mit-license.php</licenseUrl>
    <projectUrl>http://code.google.com/p/cavity/</projectUrl>
    <iconUrl>http://www.alan-dean.com/nuget.png</iconUrl>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>Fluent API for asserting types and properties.</description>
    <summary />
    <copyright>Copyright © 2010 - 2011 Alan Dean</copyright>
    <language />
    <tags>TDD</tags>
    <releaseNotes>Switched off license acceptance dialog.</releaseNotes>
  </metadata>
  <files>
    <file src="lib\net35\Cavity.Testing.Unit.dll" target="lib\net35\Cavity.Testing.Unit.dll" />
    <file src="lib\net40\Cavity.Testing.Unit.dll" target="lib\net40\Cavity.Testing.Unit.dll" />
  </files>
</package>

I have implemented framework targeting in my build process, so in this case I have two assemblies (.NET 3.5 and .NET 4.0) which I have copied into the lib subdirectory.

For a simple package like this, that is all you need to configure; just pack and push.

Sunday, February 20, 2011

How to conditionally skip compilation

As I mentioned in my last post, I was having problems getting an MVC web application to play nice with my framework targeting builds. Specifically, my CI server would fall over if I tried to build using Framework 3.5 when the web application was using 4.0 (due to 4.0-specific web.config settings that 3.5 does not recognise). I managed to spend a large portion of the afternoon searching for an answer until I had one of those “eureka” moments. My objective was to simply not build the web application unless the framework was 4.0 (the same would apply to any project that is framework version-specific). I tried putting a conditional on the project element. No Joy. I tried a whole bunch of other things and it was starting to look like I would have to manually configure each project to be built – very nasty, not at all what I want.

My “eureka” moment happened as I was gazing forlornly at a project file. My eye alighted upon an attribute of DefaultTargets="Build" on the project element. Build? I thought… I’ve not seen a target called that. A quick check confirmed my suspicion. The “Build” target is effectively inherited. In a flash I thought I wonder if I can intercept this? I changed the attribute to DefaultTargets="Conditional" and then added the following target and all is well again in Narnia:

<Target Name="Conditional">
<CallTarget Targets="Build" Condition=" '$(TargetFrameworkVersion)' == 'v4.0' " />
</Target>

Framework version targeting with MSBUILD

I faced a question this weekend: how best should I support conditional compilation by framework? The proximate reason for asking this was a need to use BigInteger in the Cavity project in order to be able to support 128-bit base-36 notation with a minimum of fuss. This is a new value type in Framework 4.0 and up until now Framework 3.5 have been the target for Cavity assemblies. As 3.5 is going to be around for a good while yet (heck, there is still plenty of 2.0 in production today) I didn’t want to orphan support for that version. I also didn’t want to add complexity to my build or maintenance activities. This ruled out brute force options such as creating a branch for 3.5 or creating a new solution and project files for one or other of the framework versions.

A search yielded a varied collection of advice. Some was plainly potty but a couple of StackOverflow answers [1] [2] looked promising. Taking the answers and combining a bit of common sense, I put together a quick spike to verify that I had the gist of it. Here is what I learnt:

  1. The best way to control targeting is to use property parameters with a build file. Here is a .bat file to build release versions targeting each major framework version:
    MSBUILD build.xml /p:Configuration=Release /p:TargetFrameworkVersion=v2.0
    MSBUILD build.xml /p:Configuration=Release /p:TargetFrameworkVersion=v3.5
    MSBUILD build.xml /p:Configuration=Release /p:TargetFrameworkVersion=v4.0

  2. You don’t need to do anything in the build.xml or the .sln file for this to work. You do, however, need to do a little work in the .csproj files:
    • First, you need to decide which framework version you want to work with in Visual Studio (typically, this will be the latest version) and configure TargetFrameworkVersion accordingly:

      <TargetFrameworkVersion Condition=" '$(TargetFrameworkVersion)' == '' ">v4.0</TargetFrameworkVersion>

    • To make the build output obvious, set the OutputPath to use properties:

      <OutputPath>bin\$(Configuration) $(TargetFrameworkVersion)\</OutputPath>

    • Next, you should set up some conditional property groups:
      <PropertyGroup Condition=" '$(TargetFrameworkVersion)' == 'v2.0' ">
          <DefineConstants>NET20</DefineConstants>
          <TargetFrameworkVersionNumber>2.0</TargetFrameworkVersionNumber>
      </PropertyGroup>
      <PropertyGroup Condition=" '$(TargetFrameworkVersion)' == 'v3.5' ">
          <DefineConstants>NET35</DefineConstants>
          <TargetFrameworkVersionNumber>3.5</TargetFrameworkVersionNumber>
      </PropertyGroup>
      <PropertyGroup Condition=" '$(TargetFrameworkVersion)' == 'v4.0' ">
          <DefineConstants>NET40</DefineConstants>
          <TargetFrameworkVersionNumber>4.0</TargetFrameworkVersionNumber>
      </PropertyGroup>

    • This allows you to configure framework-specific assembly references, such as System.Core and Microsoft.CSharp:

      <Reference Include="System.Core" Condition=" '$(TargetFrameworkVersionNumber)' >= '3.5' " />
      <Reference Include="Microsoft.CSharp" Condition=" '$(TargetFrameworkVersionNumber)' >= '4.0' " />

    • You should now be able to target framework versions in a straightforward manner by running the batch file above.

  3. If you want to conditionally include classes, simply apply a framework condition:
    <Compile Include="Class20.cs" Condition=" '$(TargetFrameworkVersion)' == 'v2.0' " />

  4. I also defined constants above to allow conditional compilation at code level:
    namespace Example
    {
        public sealed class Class1
        {
    #if NET20
            public void Net20()
            {
            }
    #endif
    
    #if NET35
            public void Net35()
            {
            }
    #endif
    
    #if NET40
            public void Net40()
            {
            }
    #endif
        }
    }



The only pain I have really encountered so far is getting MVC web applications to play nicely.

Tuesday, June 29, 2010

Object Pool Pattern

In the last post I discussed the Multiton pattern and this post continues the theme of non-GoF patterns by looking at Object Pool, another specialised Singleton. The purpose of this pattern is to re-use object instances to avoid creation / destruction. My mnemonic this time is a Car Pool which is just a collection of cars for my purposes:

public sealed class Car
{
    public Car(string registration)
    {
        this.Registration = registration;
    }

    public string Registration
    {
        get;
        set;
    }

    public override string ToString()
    {
        return this.Registration;
    }
}

The pool implementation also uses weak references to handle garbage collected cars which have not been explicitly returned to the pool:

using System;
using System.Collections.Generic;
using System.Linq;

public sealed class CarPool
{
    private static CarPool _pool = new CarPool();

    private CarPool()
    {
        this.Cars = new Dictionary<Car, WeakReference>();
    }

    public static int Availability
    {
        get
        {
            int value = 0;

            lock (_pool)
            {
                value = _pool.Cars.Where(x => null == x.Value || !x.Value.IsAlive).Count();
            }

            return value;
        }
    }

    private Dictionary<Car, WeakReference> Cars
    {
        get;
        set;
    }

    public static void Add(params Car[] cars)
    {
        foreach (var car in cars)
        {
            lock (_pool)
            {
                _pool.Add(car);
            }
        }
    }

    public static Car Get()
    {
        Car result = null;

        if (0 < CarPool.Availability)
        {
            lock (_pool)
            {
                var item = _pool.Cars.Where(x => null == x.Value || !x.Value.IsAlive).FirstOrDefault();

                var value = new WeakReference(item.Key);
                _pool.Cars[item.Key] = value;

                result = (Car)value.Target;
            }
        }

        return result;
    }

    public static void Return(Car car)
    {
        if (null == car)
        {
            throw new ArgumentNullException("car");
        }

        lock (_pool)
        {
            _pool.Cars[car] = null;
        }
    }

    private void Add(Car car)
    {
        this.Cars.Add(car, new WeakReference(null));
    }
}

Here is a test which verifies the expected behaviour:

using Xunit;

public sealed class ObjectPoolFacts
{
    [Fact]
    public void car_pooling()
    {
        Car one = new Car("ABC 111");
        Car two = new Car("ABC 222");
        CarPool.Add(one, two);

        Car first = CarPool.Get();
        Assert.Same(one, first);

        Car second = CarPool.Get();
        Assert.Same(two, second);

        Assert.Null(CarPool.Get());

        CarPool.Return(first);
        CarPool.Return(second);

        second = CarPool.Get();
        Assert.Same(one, second);
    }
}

Multiton Pattern

I’m doing a little ‘brushing up on the basics’ at the moment and as part of that effort I am working up some pattern examples, starting with creational patterns. These include staples such as Factory Method, Abstract Factory, Prototype, Singleton and so on but there are other creational patterns which weren’t in the Gang of Four (GoF) Design Patterns book. One of these is the Multiton. I don’t know what it’s provenance is, but it is an extension to the Singleton pattern which provides centralised access to a single collection making keys unique within scope. In my example, the singleton is declared as a static member so it has application domain scope.

I like to work up examples that feel (at least somewhat) real-world as I find that these are easier to remember later on. For the Multiton pattern I decided to use the Rolodex which is simply a collection of cards for my purposes:

public sealed class Card
{
    internal Card(string key)
    {
        this.Key = key;
    }

    public string Information
    {
        get;
        set;
    }

    public string Key
    {
        get;
        set;
    }
}

The pattern defines that item creation is handled by a static factory if the key does not exist in the collection:

using System;
using System.Collections.ObjectModel;
using System.Linq;

public sealed class Rolodex
{
    private static Rolodex _rolodex = new Rolodex();

    private Rolodex()
    {
        this.Cards = new Collection<Card>();
    }

    private Collection<Card> Cards
    {
        get;
        set;
    }

    public static Card Open(string key)
    {
        Card result = null;

        lock (_rolodex)
        {
            result = _rolodex.Cards
                .Where(x => string.Equals(x.Key, key, StringComparison.Ordinal))
                .FirstOrDefault();

            if (null == result)
            {
                result = new Card(key);
                _rolodex.Cards.Add(result);
            }
        }

        return result;
    }
}

Here is a test which verifies the expected behaviour:

Xunit;

public sealed class MultitonFacts
{
    [Fact]
    public void rolodex_card()
    {
        string key = "John Doe";

        Card expected = Rolodex.Open(key);
        expected.Information = "john.doe@example.com";

        Card actual = Rolodex.Open(key);

        Assert.Same(expected, actual);
    }
}

It’s worth pointing out that, as with all Singleton patterns, the plain vanilla pattern doesn’t lend itself to unit testing as-is. The answer is to provide a wrapper for mocking purposes. Here is an example of doing so for DateTime.UtcNow:

using System;

public static class DateTimeFactory
{
    [ThreadStatic]
    private static DateTime? _mock;

    public static DateTime Today
    {
        get
        {
            DateTime value = DateTime.Today;

            if (null != _mock)
            {
                value = _mock.Value.Date;
            }

            return value;
        }
    }

    public static DateTime UtcNow
    {
        get
        {
            DateTime value = DateTime.UtcNow;

            if (null != _mock)
            {
                value = _mock.Value;
            }

            return value;
        }
    }

    public static DateTime? Mock
    {
        get
        {
            return _mock;
        }

        set
        {
            _mock = value;
        }
    }

    public static void Reset()
    {
        DateTimeFactory.Mock = null;
    }
}

Sunday, June 27, 2010

Routing TcpClient HTTP requests through the default proxy

I’m coding an HttpClient at the moment: mostly for self-education but something useful might arise as well. Here is a trivial example of making an HTTP request using the TcpClient class:

string response = null;
System.Net.Sockets.TcpClient tcp = null;
try
{
    tcp = new System.Net.Sockets.TcpClient("www.example.com", 80);

    using (var stream = tcp.GetStream())
    {
        using (var writer = new System.IO.StreamWriter(stream))
        {
            writer.WriteLine("GET / HTTP/1.1");
            writer.WriteLine("Host: www.example.com");
            writer.WriteLine("Connection: close");
            writer.WriteLine(string.Empty);
            writer.Flush();
            using (var reader = new System.IO.StreamReader(stream))
            {
                response = reader.ReadToEnd();
            }
        }
    }
}
finally
{
    if (null != tcp)
    {
        tcp.Close();
    }
}

HTTP is simply an application-level protocol layered on top of TCP, so this works fine. However, as soon as the HttpClient becomes non-trivial then debugging becomes an issue. Thankfully we have tools in place to see at what’s happening on the wire. Wireshark is an excellent tool which watches all TCP traffic on a network adapter but it is somewhat overkill for watching just HTTP traffic. Fiddler, on the other hand, is my own tool of choice for monitoring HTTP traffic. Unfortunately the code shown above won’t appear in Fiddler as-is. Fiddler acts as a proxy and the code doesn’t cater for that. The TcpClient class doesn’t either because a web proxy works at the HTTP layer rather than TCP.

In over to overcome this limitation, we can use the WebClient class to resolve the default proxy.

var requestUri = new System.Uri("http://www.example.com/");
Uri proxy = null;
using (var web = new System.Net.WebClient())
{
    proxy = web.Proxy.GetProxy(requestUri);
}

tcp = new System.Net.Sockets.TcpClient(proxy.DnsSafeHost, proxy.Port);

Now Fiddler will now happily monitor the traffic. My thanks to @srstrong, @serialseb, @blowdart, @benlovell for helping me figure this out.

Saturday, June 26, 2010

Run StyleCop on every build

I first started using StyleCop during a couple of projects with Microsoft Services when it was called Source Analysis and I’m a big fan because it helps makes code consistently formatted across a codebase. In order to have StyleCop run on every build, simply open the project file in the text editor of your choice (or you can unload the project from within the solution and then right-click to edit within Visual Studio) and add the Microsoft.StyleCop.targets import (I normally add it immediately after the Microsoft.CSharp.targets import):

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    ...
    <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
    <Import Project="$(MSBuildExtensionsPath)\Microsoft\StyleCop\v4.3\Microsoft.StyleCop.targets" />
    ...
</Project>

P.S. A plea to Microsoft: can we have the standard project and class templates pass StyleCop by default please?

Deploying to IIS7 from MSBuild

Here is an example of how to configure deployment of a web application on a development machine using MSBuild with the Extension Pack:

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Run" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">

    <Import Project="$(MSBuildProjectDirectory)\lib\trove\Framework\v2.0\MSBuild.Community.Tasks.Targets" />
    <Import Project="$(MSBuildProjectDirectory)\lib\trove\Framework\v3.5\MSBuild.ExtensionPack.tasks" />

    <Target Name="Run">
        <CallTarget Targets="Clean" />
        <CallTarget Targets="Build" />
        <CallTarget Targets="Deploy" Condition="'$(registry:HKEY_LOCAL_MACHINE\Software\Microsoft\InetStp@MajorVersion)'=='7'" />
    </Target>

    <Target Name="Clean">
        <MSBuild
            Projects="$(MSBuildProjectDirectory)\src\Example.sln"
            Targets="Clean"
            Properties="Configuration=$(Configuration)"
            />
    </Target>

    <Target Name="Build">
        <MSBuild
            Projects="$(MSBuildProjectDirectory)\src\Example.sln"
            Targets="Rebuild"
            Properties="Configuration=$(Configuration)">
            <Output
                TaskParameter="TargetOutputs"
                ItemName="CodeAssemblies"
                />
        </MSBuild>
    </Target>

    <PropertyGroup>
        <WebApplicationName>www.example.net</WebApplicationName>
        <WebApplicationPath>$(MSBuildProjectDirectory)\src\Web Applications\Example</WebApplicationPath>
    </PropertyGroup>

    <Target Name="Deploy">
        <MSBuild.ExtensionPack.Web.Iis7Website
            TaskAction="CheckExists" 
            Name="$(WebApplicationName)">
            <Output
                TaskParameter="Exists"
                PropertyName="WebApplicationExists"
                />
        </MSBuild.ExtensionPack.Web.Iis7Website>
        <MSBuild.ExtensionPack.Web.Iis7Website
            TaskAction="Create"
            Name="$(WebApplicationName)"
            Path="$(WebApplicationPath)"
            Port="80"
            AppPool="ASP.NET v4.0"
            Condition="'$(WebApplicationExists)'=='False'"
            />
        <MSBuild.ExtensionPack.Web.Iis7Binding
            TaskAction="Remove"
            Name="$(WebApplicationName)"
            BindingInformation="*:80:"
            BindingProtocol="http"
            />
        <MSBuild.ExtensionPack.Web.Iis7Binding
            TaskAction="Add"
            Name="$(WebApplicationName)"
            BindingInformation="127.0.0.127:80:$(WebApplicationName)"
            BindingProtocol="http"
            Condition="'$(WebApplicationExists)'=='False'"
            />
        <MSBuild.Community.Tasks.Sleep Milliseconds="3000" />
        <MSBuild.ExtensionPack.Web.Iis7Website
            TaskAction="Stop"
            Name="$(WebApplicationName)"
            />
        <MSBuild.Community.Tasks.Sleep Milliseconds="3000" />
        <MSBuild.ExtensionPack.Web.Iis7Website
            TaskAction="Start"
            Name="$(WebApplicationName)"
            />
    </Target>

</Project>

Friday, June 25, 2010

Consistent Assembly Versioning

Personally, I like to have consistent versioning applied to all assemblies from the same build. Doing this manually is a PITA so I version from my build file and I have a pattern which I apply to achieve this. I typically use subversion for my source control and I will use the Cavity project as an example:

Subversion project structure

I build from the trunk folder:

Subversion trunk folder

I have a batch file for each ‘potted’ configuration I want and, of course, the MSBuild file. Here is the release batch file:

MSBUILD build.xml /p:Configuration=Release
PAUSE

In order to apply consistent versioning, I want to emit a Build.cs file and then link that to each project. If I want this to be a static number, I can simply configure the version directly and use AssemblyInfo task from the MSBuild Community Tasks Project:

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Run" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
    <Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets" />

    <PropertyGroup>
        <Configuration Condition="'$(Configuration)'==''">Release</Configuration>
        <Version Condition="'$(Version)'==''">1.2.3.4</Version>
    </PropertyGroup>

    <Target Name="Run">
        <CallTarget Targets="Clean" />
        <CallTarget Targets="Build" />
    </Target>

    <Target Name="Clean">
        <MSBuild
            Projects="$(MSBuildProjectDirectory)\src\Cavity.sln"
            Targets="Clean"
            Properties="Configuration=$(Configuration)"
        />
    </Target>

    <Target Name="Versioning">
        <AssemblyInfo
            CodeLanguage="CS"
            OutputFile="$(MSBuildProjectDirectory)\src\Build.cs"
            AssemblyVersion="$(Version)"
            AssemblyFileVersion="$(Version)"
            AssemblyInformationalVersion="$(Version)"
            />
    </Target>

    <Target Name="Build" DependsOnTargets="Versioning">
        <MSBuild
            Projects="$(MSBuildProjectDirectory)\src\Cavity.sln"
            Targets="Rebuild"
            Properties="Configuration=$(Configuration)">
            <Output
                TaskParameter="TargetOutputs"
                ItemName="CodeAssemblies"
                />
        </MSBuild>
    </Target>

</Project>

This will emit the following Build.cs:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.1
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: AssemblyVersion("1.2.3.4")]
[assembly: AssemblyFileVersion("1.2.3.4")]
[assembly: AssemblyInformationalVersion("1.2.3.4")]

However, I normally use the subversion Revision number as the build number to be able to identify what was built. To do this you will need to install the CollabNet Subversion client in order to be able to query the subversion repository. Once installed, you can then use the following build file to emit a dynamic version number by utilising the SvnVersion task:

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Run" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
    <Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets" />

    <PropertyGroup>
        <Configuration Condition="'$(Configuration)'==''">Release</Configuration>
        <Version Condition="'$(Version)'==''">1.2.3</Version>
        <Revision>0</Revision>
    </PropertyGroup>

    <Target Name="Run">
        <CallTarget Targets="Clean" />
        <CallTarget Targets="Build" />
    </Target>

    <Target Name="Clean">
        <MSBuild
            Projects="$(MSBuildProjectDirectory)\src\Cavity.sln"
            Targets="Clean"
            Properties="Configuration=$(Configuration)"
            />
    </Target>

    <Target Name="Versioning">
        <SvnVersion LocalPath=".">
            <Output TaskParameter="Revision" PropertyName="Revision" />
        </SvnVersion>
        <AssemblyInfo
            CodeLanguage="CS"
            OutputFile="$(MSBuildProjectDirectory)\src\Build.cs"
            AssemblyVersion="$(Version).$(Revision)"
            AssemblyFileVersion="$(Version).$(Revision)"
            AssemblyInformationalVersion="$(Version).$(Revision)"
            />
    </Target>

    <Target Name="Build" DependsOnTargets="Versioning">
        <MSBuild
            Projects="$(MSBuildProjectDirectory)\src\Cavity.sln"
            Targets="Rebuild"
            Properties="Configuration=$(Configuration)">
            <Output
                TaskParameter="TargetOutputs"
                ItemName="CodeAssemblies"
                />
        </MSBuild>
    </Target>

</Project>

Saturday, June 19, 2010

Abstracting Service Location

A couple of days ago I blogged about the Common Service Locator, how to use the ServiceLocator and how to mock the IServiceLocator interface for unit testing purposes. However, I personally feel that the Common Service Locator library didn’t complete the job. Ideally, I should not need to choose specific IoC provider whilst writing my code (or at least should not be forced to recompile my application in order to change provider) and the library doesn’t enable this.

In order to enable this use case, I’ve published a set of lightweight libraries in the Cavity project. The key library is Cavity.ServiceLocation.dll which contains one interface and one concrete class. The interface is, frankly, trivial:

namespace Cavity.Configuration
{
    public interface ISetLocatorProvider
    {
        void Configure();
    }
}

The interface is trivial simply because it’s a hook to load the provider-specific configuration data. I have provided a plain vanilla implementation for Autofac, Castle Windsor, StructureMap and Unity because each of these supports XML configuration. Here is the implementation of the Castle Windsor ISetLocatorProvider:

namespace Cavity.Configuration
{
    using Castle.Windsor;
    using Castle.Windsor.Configuration.Interpreters;
    using CommonServiceLocator.WindsorAdapter;
    using Microsoft.Practices.ServiceLocation;

    public sealed class XmlServiceLocatorProvider : ISetLocatorProvider
    {
        public void Configure()
        {
            var container = new WindsorContainer(new XmlInterpreter());
            ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
        }
    }
}

As you can see, the code is lightweight: create a container, load it with configuration data and apply the configured container to the generic ServiceLocator and you’re done. To set up Castle Windsor as your provider, you must edit your app.config or web.config, as appropriate, as follows (having a separate castle.config is optional but generally considered preferable):

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section
            name="castle"
            type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
        <section
            name="serviceLocation"
            type="Cavity.Configuration.ServiceLocation, Cavity.ServiceLocation"/>
    </configSections>
    <castle configSource="castle.config" />
    <serviceLocation type="Cavity.Configuration.XmlServiceLocatorProvider, Cavity.ServiceLocation.CastleWindsor" />
</configuration>

The <serviceLocation> element type attribute points to the ISetLocatorProvider implementation you wish to use. To learn more about castle.config, see Initializing with an external configuration. To see examples of each provider, you can browse the Cavity source code.

If you prefer to specific your container via a fluent interface, then you can still employ the ISetLocatorProvider abstraction by writing a custom implementation.

More detail about using the Cavity.ServiceLocation.dll library can be seen on the Cavity Wiki. Packages for each of the four plain vanilla implementations can be downloaded as zips and the binaries are also available via trove.

Thursday, June 17, 2010

Mocking IServiceLocator

Using IoC has become far more popular in recent years but it is very easy to end up decoupling your components but at the same time end up tightly coupled to a specific provider, such as Castle Windsor. The first step to decouple the IoC provider is to utilize the Common Service Locator published by the Microsoft patterns & practices team. Here is a trivial example of decoupling using the ServiceLocator:

namespace Example
{
    using Microsoft.Practices.ServiceLocation;

    public interface IFoo
    {
        void Foo();
    }

    public sealed class FooImplementation : IFoo
    {
        public void Foo()
        {
        }
    }

    public sealed class Class1
    {
        public Class1()
        {
            this.Foo = ServiceLocator.Current.GetInstance<IFoo>();
        }

        public IFoo Foo
        {
            get;
            private set;
        }
    }
}

However, if you run the following test, a System.ArgumentNullException will be thrown as the ServiceLocator does not have a provider set:


namespace Example
{
    using Xunit;

    public sealed class Class1Facts
    {
        [Fact]
        public void ctor()
        {
            Assert.NotNull(new Class1());
        }
    }
}

Rather than configure a specific provider, it’s much cleaner to mock out the ServiceLocator. The following example uses Moq but the principle applies regardless of your preferred mocking framework:


namespace Example
{
    using Microsoft.Practices.ServiceLocation;
    using Moq;
    using Xunit;

    public sealed class Class1Facts
    {
        [Fact]
        public void ctor()
        {
            try
            {
                var mock = new Mock<IServiceLocator>();
                mock.Setup(x => x.GetInstance<IFoo>()).Returns(new FooImplementation()).Verifiable();
                ServiceLocator.SetLocatorProvider(new ServiceLocatorProvider(() => mock.Object));

                Assert.NotNull(new Class1());

                mock.VerifyAll();
            }
            finally
            {
                ServiceLocator.SetLocatorProvider(null);
            }
        }
    }
}

Trove

Treasure ChestOver the last couple of months I have been thinking about package management in the .net ecosystem. If you only develop using assemblies from Microsoft then you will not have had to think much about this but if you utilize open source assemblies then it can rapidly become a real bugbear. Some open source packages are standalone and thus don’t suffer reference problems; the HtmlAgilityPack is a good example of this as it only references the System assemblies. If you start utilizing the Castle Project (the IoC functionality in Windsor or the NHibernate functionality in ActiveRecord are commonly employed) then you will rapidly encounter reference problems, especially if you also use other libraries that also depend on Castle.

Now I’m not the first to consider this problem. HornGet takes the direct approach of building the source and publishing the binaries. I don’t know how much, if any, verification work is done but I have noticed that the builds seem to break rather frequently which doesn’t inspire confidence. As an experiment, I decided to carry out a poor man’s replication of that approach by simply writing a batch build file of a sequence of projects. One of the first issues I discovered was that the trunk often doesn’t build successfully on open source project. I suppose that I should not have been surprised, of course. I then carried out a second experiment, building from branches where available. This typically built successfully but the dependencies were incompatible, leaving you choose this or that rather than this and that. So my conclusion was that direct build doesn’t meet the need.

After direct build, there is Ruby Gems envy. I’m convinced that there was an NGem project at one time but I can’t find it and it certainly didn’t get any adoption by the community. At present I’m aware of at least three projects that want to create a solution to the problem: OpenWrap, Bricks, and CoApp. The problem is that all of these are either vapourware or alpha code and I want something useful right now.

After musing for a little while, it was clear to me that simply starting yet-another-package-management-project would be wasteful duplication. Maybe one of the currently active projects will come to something, who knows. I then got to thinking about what would be the simplest thing that could possibly work? (Ward Cunningham). Well, maybe the simplest thing would be just to work on a single package of mutually consistent assemblies. Not so hard to do either, so long as you put together some verification tests to check that the package as a whole is stable and mutually dependent. How to distribute? An easy way would be just zip up the assemblies to share that but then it occurred to me that I could simply create a Subversion repo and consumers could simply link to it using svn:externals which is really simple to configure with TortoiseSVN.

Thus was born http://code.google.com/p/trove/

There is a manifest of the contained assemblies. All you need to do is add an svn:externals property on your lib folder of “trove http://trove.googlecode.com/svn/trunk/lib” and update :-)

If you pull down the whole project, you will also get the verification tests.

At the moment, the trove contains:

If there are other libraries you think I should have in the trove, please let me know.

Wednesday, June 16, 2010

NDepend Review

[Disclaimer: I have been given a free copy of NDepend in order to be able to write this review]

As I have released my unit testing DSL on Cavity, I thought that this would be a good opportunity to take a look at NDepend (a tool which I already knew about but hadn’t taken out for a ride, in no small part because I was not sure that I would get enough benefit to justify the license price which starts from €299). It is worth pointing out that before I ran NDepend, the assembly passed both Code Analysis and Source Analysis.

Installation is simple: unzip the download to your preferred location and run the application. Also included is support for MSBuild, CruiseControl and NAnt. Although installation is simple, I do think that also providing an MSI installer would be useful but that’s not a deal-breaker for me.

The application provides a start screen:

NDepend Start Screen

I didn’t bother with creating a project, I just went straight ahead and selected the Cavity.Testing.Unit.dll to analyze. When this is done, an html report is emitted and the application shifts into Quick Project mode so that you can browse the assembly. The html report provides a great deal of information and here are some sections:

Application Metrics

Application Metrics Section

This section provides an overview of the gross topology of the assembly, the contained types (classes, interfaces and so on) and the maximum statistical result such as the highest cyclomatic complexity.

Assemblies Metrics

Assemblies Metrics Section

This section provides headline metrics which indicate how maintainable the assembly is. At first glance, this is all rather obtuse so the report next provides an easy-to-understand graph.

Assemblies Abstractness vs. Instability

Abstractness vs. Instability Graph

My assembly is sitting inside the green zone, so I’m going to infer that it is broadly maintainable.

Assemblies Dependencies Diagram

Assemblies Dependencies Diagram

I’m only looking at one assembly (and a rather trivial one at that) so this diagram isn’t very informative but I imagine that for multi-assembly situations in more complex situations it would be more useful.

CQL Queries and Constraints

CQL Queries and Constraints Section

At the top of this section, a colour-coded list is provided. For my assembly, eight constraints are green (pass) and nine are yellow (warning). I assume that items also can be coloured red (fail) but that my assembly doesn’t warrant it.

{Code Quality \ Type Metrics}

CQL Constraint {Code Quality - Type Metrics}

Three classes have warnings:

  • Resources: this warning is due to the tool not ignoring classes marked as [GeneratedCode].
  • PropertyExpectations<T> and TypeExpectations<T>: these are my two internal DSLs, so it's not a surprise that they have a large number of methods as I have employed method chaining.
{Design}

CQL Constraint {Design}

This isn’t especially informative so I swapped over to the application and looked at the Dependency Matrix:

Dependency Matrix - # namespaces

Browsing through this matrix indicates that the constraint failed due to the method chaining implementation of the internal DSL. As an observation, I should say that method chaining does indeed lead to less maintainable code as changing the decision flow is non-trivial but here is an example of deliberately accepting a burden in order to achieve an objective.

There are a bunch of other constraints reported on but I think that you get the picture. Time to have a look at the application in a little more detail.

CQL Query Explorer

I’m going to take a trivial example to illustrate usage. At the bottom of the application screen there is an explorer-style listing of the CQL report information, colour-coded as in the report. I have selected Abstract base classes should be suffixed with ‘Base’ from the Naming Conventions node. When I do so, the relevant classes are highlighted in blue in the map above. When I hover my mouse over a highlighted class it changes to a pink highlight and the tooltip window on the right displays CQL information about that class. It all feel very slick and responsive. In this particular case, I have no objection to renaming the two classes with a suffix of ‘Base’ so I have gone ahead and made that change.

CQL Query Explorer

Conclusion

NDepend is clearly a powerful tool and I can see myself finding it useful in future projects but it is clearly an expert tool, best employed by those already comfortable with static analysis or as a means for self-education. It isn’t a ‘must-have’ tool. What would make it so, for me, would be to have the same type of Visual Studio integration as Code Analysis and Source Analysis do. I like being able to configure the static analysis at project inception, having warnings and errors emitted during build. This feels very natural to me and having to leave the IDE simply means that I’m far less likely to utilise the tool.

[Update] I should make clear that NDepend does integrate with Visual Studio. In the text above I am specifically referring to the build warning / error integration that both Code Analysis and Source Analysis provide. This means that as soon as you write the code, you will discover if you have caused an analysis issue. I am a firm believer that raising issues as soon as you write the code makes writing clean code a cheaper proposition.

Tuesday, June 15, 2010

Cavity Unit Testing

I have started a new open source project on google code which I've named Cavity for no particular reason other than it's somewhat memorable: http://code.google.com/p/cavity/ and I plan on pushing up some of the code I use to accelerate and assist development, starting with an internal DSL for unit testing type and property definitions.

I’ve been doing TDD for about 9 years now and have, I admit, derived a somewhat idiosyncratic style which involves asserting all of the external characteristics of a type. I don’t agree with those who argue in favour of not testing properties (I disagree because properties have behaviour and thus ought to be verifiable). I also believe that interface implementations and attribute decorations should be verifiable (which also speaks to my belief in what I call intentional development). However there is a downside to this, which is that asserting type and property definitions is slower than not doing so (obviously) and so I use my unit test DSL to accelerate the process and thus mitigate the impedance. This has been living inside the SimpleWebServices project for a while now but I thought it was time to promote it to a more formal offering and so it is the first library available from Cavity.

To give you a flavour, here are a couple of examples of testing a class and a property:

[Fact]
public void type_definition()
{
    Assert.True(new TypeExpectations<Class1>()
        .DerivesFrom<object>()
        .IsConcreteClass()
        .IsUnsealed()
        .HasDefaultConstructor()
        .Implements<IFoo>()
        .IsDecoratedWith<CustomAttribute>()
        .Result);
}

[Fact]
public void value_definition()
{
    Assert.True(new PropertyExpectations<Class1>("Value")
        .TypeIs<string>()
        .DefaultValueIs("default")
        .Set("example")
        .ArgumentNullException()
        .ArgumentOutOfRangeException(string.Empty)
        .FormatException("invalid")
        .IsNotDecorated()
        .Result);
}

The binaries and source are zipped for download and to see more examples, please visit the wiki:

Sunday, April 18, 2010

What would a rational constitutional settlement look like?

A diagram of a rational constitutional settlemtWith the General Election campaign in full flood, I’ve been thinking about what a rational constitutional settlement for the UK might look like. The current settlement, whereby Scotland, Wales and Northern Ireland have devolved government but England does not is causing a certain amount of constitutional stress and this is likely to increase in the coming years. English voters are becoming alienated by MPs who represent areas with devolved powers still being able to vote for policies that do not affect their own constituents. If we get a hung parliament from this election, but there is a majority party in England then I expect to hear a great deal of commentary about a caretaker government being sustained in power without legitimacy.

Rolling back devolution at this point is not a realistic proposition; that horse has left the stable. Given that political reality, how might we organise our representative democracy? I am deliberately excluding republicanism from this discussion. If you are in favour of keeping a monarch, simply imagine a world where our arrangements for Head of State are unchanged. If you are not, then imagine a world where an elected Head of State exercises broadly the same set of functions as the monarch currently does. Similarly, I am ignoring the question of the voting system(s) to be employed. Clearly, the voting system and seat distribution would have a profound political impact but my proposition stands as a constitutional model regardless of voting system, be it proportional or not.

The primary consideration I have employed to build this model is fairness as accountability is a much more difficult metric to measure. I simply ask would voters consider this model to be fair to all the other voters in the UK?. The secondary consideration is simplicity. I have tried to come up with a model that a voter can comprehend easily and that they know who to blame or acclaim when deciding how to vote.

Local Councils

My proposal does not change the constitutional role of local government, nor does it alter the current organisation of local government. However, my model devolves such decisions and local government funding entirely to the Regional Assemblies (see below).

Regional Assemblies

In this constitutional model, each constituent country in the UK (England, Scotland, Wales and Northern Ireland) would have an assembly (I use the term generically, it does not imply that the Scottish Parliament needs to be renamed).  The current model applied to Scotland would be applied equally to all of the other assemblies; that is to say that certain powers would be reserved to the UK Parliament (see below) and all powers not explicitly reserved become the responsibility of the regional assemblies within their geographic limits. At this point I am not going to enumerate the reserved powers: it is sufficient to say that there will be some and I envisage that they will likely be broadly in line with current Scottish arrangements. As is the case at present, each region would have an executive which is comprised of assembly members. Regional assemblies would be unicameral (i.e. they would have only one chamber). As to the question of where a new English Parliament might be based: I leave that up to you to discuss in the comments! I envisage that an English Parliament might comprise as many as 300 members, with a similar or greater reduction in the number of UK Parliamentarians (see below).

UK Parliament

The most significant changes in my model arise at the national level. With a devolved English Parliament, the structure of national government would need to change dramatically. I propose to keep the current bicameral model at Westminster, with an elected lower house and a revising upper house.

Federal Chamber (Upper House)

I propose that the current membership of the House of Lords should be replaced with a federal membership. The new Federal Chamber would have 100 seats, like the US Senate, with seats apportioned to each region by population recorded at the dicennial census. The seat proportions would approximately be: England 81, Scotland 10, Wales 6, Northern Ireland 3. The primary role of the Federal Chamber would be to revise legislation as the current House of Lords does. The restrictions that currently apply to the House of Lords would be maintained to ensure that the elected chamber would retains primacy (the Parliament Acts and the Salisbury Convention). Members from each region would be selected from the elected Regional Assembly members. Members of the Federal Chamber would not be permitted to take a position in the UK Government, unlike the current House of Lords.

Elected Chamber (Lower House)

The elected chamber would be the primary legislature of the UK, just as the current House of Commons is. Given the introduction of an English Parliament, the elected chamber would not need to be anything like as large as the current House of Commons due to the devolution of powers. I suspect that perhaps as few as 200 members would be sufficient. The arrangement of constituencies would depend upon the voting system employed. All Ministers of the UK Government would be required to have seats in the elected chamber.

European Union

I have long thought that one of the weaknesses in our current constitutional settlement is the poor integration of our institutions with those of the EU. Here is my perspective on how that might be improved.

European Commission, Consilium and Council

These bodies are defined by the Lisbon Treaty and are somewhat integrated with the UK Government already (although the actual interplay between them is rather murky) but I don’t propose significant changes as Ministers would remain accountable to Parliament.

European Parliament

I would make a very real change regarding the European Parliament. Currently, despite the Parliament gaining rather more power from the Lisbon Treaty, voting for it tends to be regarded as a protest opportunity (both in the UK and elsewhere in Europe). I would change this by having all British MEPs be elected via the UK Parliament. The exact mechanics of this election process would be subject to the electoral system decided up for the UK Parliament but the key point is that our MEPs would sit in our national Parliament and be accountable through it, rather than being divorced from normal national politics as they mostly are right now.

Fiscal Policy

These changes to our constitutional settlement would necessitate a clearer separation of responsibilities between the layers of government than currently exists (a good thing, in my opinion). One area in particular, fiscal policy, deserves special consideration as it is the lifeblood of all government. I propose that UK taxation would be explicitly split between the UK Parliament and the Regional Assemblies. The UK Parliament would set a base level of taxation (income, VAT, Duties and Excise) to pay for the reserved powers such as defence. On top of that, each Regional Assembly would levy regional taxation. This would mean that on your pay slip you would see two sets of income tax amounts. The base level of VAT would continue to include the proportion that flows to the EU. This way, voters in each region can elect representatives with high or low tax and spend manifestos without the effects being hidden as is currently the case. However, the Barnett Formula exists for a reason. Although there are many arguments about what the correct amount of fiscal transfer should be, these are properly a matter for budgetary votes in the UK Parliament. Any amounts of fiscal transfer voted for would form part of the base taxation level at a national level as it would be iniquitous, for example, to force an English Parliament to levy a direct transfer. Borrowing and the National Debt would remain a sovereign, reserved, power of the UK Parliament as it is now with interest and capital repayments forming part of the base national taxation level. Update: I envisage local and corporate taxation being devolved to the regions.

Conclusion

I appreciate that much of what I have set out above will be considered radical, possibly even unworkable, but I ask that you consider if we are at a point where we ought to embrace radicalism in order to lay down strong democratic foundations for a form of politics that is fit for our future and I accordingly commend this proposal to you.

Saturday, April 10, 2010

Spoofing my TabletPC as an iPad

TabletPC DesktopHot on the heels of the release of the iPad, I decided to repave my TabletPC (an HP TX2520ea) with a fresh install of Windows 7. I haven’t been making real use of the tablet for about a year now as I have been highly development focussed and less managerial but it was time to upgrade from Vista.

I did have a quick look at some iPad-ready websites using Safari and spoofing the browser User Agent as an iPad but the configuration steps are clunky and need to be carried out each time you create a new Safari instance.

RocketDock Icon Settings Then yesterday I read “Use Gmail for iPad in Google Chrome” which shows how to easily open Chrome with spoofing enabled and a brainwave came to me. I use RocketDock (an excellent application launcher for Windows which emulates the Apple Dock) and I realised that it would be easy to configure docked shortcuts for spoofing.

You simply create a new docked shortcut to chrome.exe and configure the arguments, setting the desired app URI:

--app="http://www.example.com" --user-agent="Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10"


So far there aren’t a large number of sites which are iPad-ready but there are enough to make a difference to my TabletPC experience, especially as I am a heavy Google Apps user and significant work has been done by Goole on their properties to better support the iPad (it would have been nicer if they had already done this work for Windows 7 Touch devices, but there we are). Here is a selection of screenshots of Google Apps spoofed as an iPad:


Mail
Google Mail Google Mail
Docs
Google Docs (Folders) Google Docs
Calendar
Google Calendar
Tasks
Google Tasks


Here are some other Google sites:


Mobile
Google Mobile
Search
Google Search
Reader
Google Reader
News
Google News
Buzz
Google Buzz
Talk
Google Talk
Maps
Google Maps
YouTube
YouTube


Finally, here are some other iPad-Ready sites:


Twitter
Twitter
Facebook
Facebook
Delicious
Delicious
BBC iPlayer
BBC iPlayer


Of course, you can’t run iPad Apps on Windows 7 but the rush to roll-out tablet-style websites that look good on the iPad will coincidentally benefit TabletPC owners like me and that makes me happy.

Thursday, April 8, 2010

Agility is not Viral

Please note: This post was originally published on my Charteris blog in 2008 but is no longer accessible so I’m republishing it here as I feel it remains important.

At Charteris Day this week, we had a series of presentations discussing Agility. The various speakers covered both Business Consultancy (with a focus on our 'Customer Centricity' capability) and from the Technology Consultancy (with a focus on Agile software development). My contribution was to give a 20 minute talk explaining why I felt that the presentation ("Future Directions for Agile") by David Anderson at Agile 2008 in August was so important.

At the head of my presentation I discussed something that I have been articulating for some time now (including during the Park Bench session at the Alt.Net Conference) and I thought it would be worth repeating here to see if others agree with me or not.

First, a little background. During the late 90's I was developing shrinkwrap software using RAD. Whilst I was working for the IVIS Group on Tesco.com in 2002, I was introduced to eXtreme Programming. Since that time I have considered myself an extreme programmer, rather than an Agilist (for various reasons that I won't bore you with right now) and have acted as an agent of change at a number of organisations.

In hindsight, I think that at the beginning of the Millennium we genuinely believed that our principles and practices would prove to be viral and that the meme would spread. After all, we could demonstrate how effective the practices were. We could measure productivity and velocity in a far more transparent manner than  hitherto. The team members felt more empowered and gained more satisfaction from their work. Sponsors felt that, often for the first time, that they actually knew what their development staff were doing and how well. Sponsors especially appreciated the visibility of functional gain and the ability to direct the functional implementation. These characteristics were (and still are) real. It is not an illusion.

Given the reality of these powerful advantages, how could it not be viral? Why would the meme not spread? Yet it has not. At least, it has not in the way that we envisaged.

It is true that the term Agile Development has gained wide currency now, although perhaps not wide understanding. Many, possibly a majority, of development teams aspire to be Agile. It is also true that there are more agile teams now than there were. My observation about a lack of virality is separate to this.

So what do I mean? Over the years, I have engaged with a number of teams to, amongst other objectives, bring in Agile development practices; to act as an agent of change. To a greater or lesser extent, these engagements have proven successful and the teams grew demonstrably more Agile and effective. But then, the time comes to move on to the next engagement. After the departure of the agent of change, the team reverts to the status quo ante. Not immediately, but visibly and certainly. It isn't a deliberate, conscious decision to do so - it just happens, gradually. Six months or a year later, it is as if you had never been there.

Remember, this is a scenario where everyone was actually happier, more contented and fulfilled when they were Agile. Astonishing.

There have been times when I have questioned my own ability to effect change because of this phenomenon. It was very refreshing to hear David Anderson articulate that he has encountered the same problems.

If we accept that Agility is not viral then we are bound to start asking the question: why?

I will start by saying that I have no potted answer to this question, I am still in the process of seeking to gain understanding, but my first candidate explanation is this: "people are intrinsically lazy".

Ouch. That sounds contentious! Well, it shouldn't be. After all, there is a reason why we prefer to buy labour-saving devices. There is a reason why people walk across the grass along the hypotenuse of the trianglewhen the path follows the other two sides.

So why might laziness be an issue? I suspect it is because Agility is hard work. The practices we espouse are difficult and require us to work at a more challenging pace. Even if we feel better for doing it, it is easier not to do it. It is much the same as exercise. Why do gyms offer 'new joiner deals' in January? It is because they know full well that only a fraction of people will actually use their facilities all year and after the Christmas break people feel guilty about all that excess consumption.

Sponsors love the transparency of agile functional gain but it takes effort from them to achieve it. Sponsors are busy and in the absence of that agent of change hounding them to set aside time to contribute to the development process they start to miss meetings, they stop engaging fully with the development team and so agility is lost. The development team is just as guilty though. They too are busy people and it takes effort to ensure that the quality control practices are maintained. Knowing that the agent of change isn't around anymore to catch them out, they start cutting corners on their TDD. Before long, the team reverts to being less agile; possibly even entirely ceasing TDD for example.

The direction that David is taking in his talk is to look again at the CMM and he certainly marshals some strong arguments. He also challenges some of our practices by asking if Lean and Kanban are Agile. I am not yet wholly sure that these are the right answers but he is certainly asking the right questions.

I have a feeling that perhaps we have historically had a very mechanistic view of people and process. Perhaps this is why we assumed that agility would be viral, because we assumed utility was inherently compelling. When I use the term 'we' here, I suppose that I am really talking about alpha geeks. The same people who naturally gravitated to extreme programming, agile and now to alt.net. This is why there are so many discussions about "is alt.net elite.net?" and so on. If so, we need to recognise that most people are not like us. Even most software developers, I suspect. We therefore face the very real challenge of how to make agility sticky.

My suspicion is that we need to become sociologists and learn how to enculture organisations with agility.

I am very happy to say that I think that the agility presentations at Charteris Day look like they have succeeded in sparking the debate I believe is needed to grow our capability further as a consultancy; to better leverage the depth of knowledge in the company and to harness this for our clients. I'm sure that I will have more to say on this subject in the future.