Category Archives: Uncategorized

Continuous integration build traffic lights with TeamCity

Summary: Put simply we had a requirement to make a broken build of our software incredibly obvious to everyone, the purpose was to get everyone’s buy in (developers, testers, and management alike) to build quality, after all everyone knows what a red traffic light means!

In my current contract we have recently switched from an incredibly monolithic Team Foundation Server custom build to using the frankly awesome TeamCity.

Due to the historical nature of this company the true continuous integration ethic had never really been instilled, with lack of responsibility for broken builds an unfortunate by product. The switch to TeamCity was mainly a technical decision, with more in house experience of CI using TeamCity and to be honest it seemed like a far less daunting (and more enjoyable) task than getting it right with TFS. Our new TeamCity build has given us the following benefits:

  • Reduced build times by over 60%.
  • Focused us on only ever building once, every developer integration with a successful build is a potential release candidate, i.e. everything is built in Release mode.
  • Improved build notification options, the TeamCity WebUI, taskbar notifier and RSS feeds.

The final point is what I will focus on in this post, put simply we had a requirement to make a broken build off our software incredibly obvious to everyone, the purpose was to get everyone’s buy in (developers, testers, and management alike) to build quality, after all everyone knows what a red traffic light means!

So a home project ensued, which started with me winning the following Ebay auction.

These lights are pretty simple, being 24Volt DC and coming supplied with two 24volt/40W bulbs (unfortunately only one of which worked, I bought replacements online from BLT Direct, opening up the traffic lights by removing the lenses I was pleasantly surprised to find the wiring all in excellent condition.

Next step was to put together some sort of parts list to get these lamps lighting up our TeamCity build status.

  1. Traffic lights – Got.
  2. Some spare bulbs BLT Direct – Got.
  3. A power supply capable of running the bulbs continuously, so around 2Amps rating, i.e. 40W/24volt = 1.6Amps.
  4. An Arduino Uno prototyping microprocessor board.
  5. An Arduino ethernet shieldto allow the Arduino board to chat to TeamCity over the network.
  6. A suitable relay, Single Poll Double Throw (SPDT), capable of switching 2Amps at 24 volts with a 5volt control signal (from the Arduino board).
  7. A plastic case to house the Arduino board and ethernet shield off board of the traffic lights.
  8. A power supply capable of running the Arduino board, nominal 5volts output.
  9. Minimum 2 Amp rated wire, for internal lamp wiring.
  10. A handful of insulated crimp butt connectors.
  11. Some low rated in equipment wire various colours (for the power, ground and control wires from the Arduino to the relay).
  12. Insulating tape (to keep things tidy).
  13. Heatshrink tubing (to keep the power, ground and control wires from the Arduino to the relay nice and tidy).
  14. Double sided sticky pads.

For 2. I found a 19volt laptop AC-DC power supply that would do nicely (it had a 3.42A rating so could handle powering a traffic lamp continuously, i.e. 40W/19volt = 2.1Amps).

For 6. I used a multi voltage AC-DC power supply, that would output 6Volts at up to 300mA, perfect for the Arduino which can handle a voltage input of around 3-10Volts.

The rest of the parts I bought from the links in the parts list, mostly from and

The build Part #1, checking the lights

I began the build by simply wiring up each traffic light bulb directly to a low voltage power supply to check the integrity of the supplied wiring which passed with flying colours.

The build Part #2, switching the relay

The next step was to prove how to control the relay with the Arduino, I started by simply wiring it up as follows. See here for an explanation of Normally Open (NO) and Normally Closed (NC) states.

I adapted an example that did nothing more than simply switch digital pin 8 of the Arduino on and off as below.

/* Blink without Delay

Turns on and off a light emitting diode(LED) connected to a digital
 pin, without using the delay() function. This means that other code
 can run at the same time without being interrupted by the LED code.

The circuit:
 * LED attached from pin 13 to ground.
 * Note: on most Arduinos, there is already an LED on the board
 that's attached to pin 13, so no hardware is needed for this example.

created 2005
 by David A. Mellis
 modified 8 Feb 2010
 by Paul Stoffregen

This example code is in the public domain.

// constants won't change. Used here to
 // set pin numbers:
 const int ledPin = 8; // the number of the LED pin

// Variables will change:
 int ledState = LOW; // ledState used to set the LED
 long previousMillis = 0; // will store last time LED was updated

// the follow variables is a long because the time, measured in miliseconds,
 // will quickly become a bigger number than can be stored in an int.
 long interval = 1000; // interval at which to blink (milliseconds)

void setup() {
 // set the digital pin as output:
 pinMode(ledPin, OUTPUT);

void loop()
 // here is where you'd put code that needs to be running all the time.

// check to see if it's time to blink the LED; that is, if the
 // difference between the current time and last time you blinked
 // the LED is bigger than the interval at which you want to
 // blink the LED.
 unsigned long currentMillis = millis();

if(currentMillis - previousMillis > interval) {
 // save the last time you blinked the LED
 previousMillis = currentMillis;

// if the LED is off turn it on and vice-versa:
 if (ledState == LOW)
 ledState = HIGH;
 ledState = LOW;

// set the LED with the ledState of the variable:
 digitalWrite(ledPin, ledState);

With the script loaded on to the Arduino board the on board LED on the relay flashed as the NO (Normally Open) state was made… not particularly exciting but proved that side of the circuit.

Arduino blinking relay LED from NO (Normally Open) to NC (Normally Closed)

The build Part #3, switching the lights with the relay

The next step was to get the relay wired up as per the diagram and schematic below, the relay can also be clearly seen in the top right of the traffic light housing in the picture below.

You can see from the schematic that I chose to wire the Normally Closed (NC) terminal of the relay to the red light of the traffic lights. The thought behind this is that in an errored or unknown state I always wanted the traffic light to display red and to switch to green only with a known good build state.  So with the above all in place I could prove (using the same Arduino sketch as in step 2) that we could switch between NC (red light on) and NO (green light on).

The build Step #4, talking to TeamCity

I went with a very simple approach for querying TeamCity for a build status, I have described in more detail when working out the best approach in the TeamCity developer forum but basically it involved developing a simple TeamCity plugin that returns just an HTTP header response, reflecting the status of a selected TeamCity build project, the plugin does the following:

  1. Exposes a non authenticated simpleBuildStatus page “http://<myTeamCityServer>:<port>/simpleBuildstatus.html?projectName=<myTeamCityProjectName>&guest=1” that returns an HTTP Response Header (no HTML page content in the response).
  2. The simpleBuildStatus page returns an ‘HTTP/1.1 200 OK’ in the HTTP Response Header if all build configurations under the selected build project are currently successful.
  3. The simplebuildStatus page returns an ‘HTTP/1.1 409 CONFLICT’ in the HTTP Response Header if any build configurations under the selected build project are currently unsuccessful

For reference I found the following resources useful when developing my first TeamCity plugin; I used IntellijIDEA 10.5 (Community Edition)as my Java IDE of choice.; The sample TeamCity development package that demonstrates how to develop various plugins; Needed as a prerequisite to building the above sample TeamCity development package.; This helped me understand the options for packaging the TeamCity Plugin, i.e. as a JAR that you drop into the TeamCity data directory/plugins folder.; And some more general basic information about installing TeamCity plugins.

The following two screen shots show the HTTP 200 OK and HTTP 409 CONFLICT status codes that the SimpleBuildStatus plugin returns for successful and failed builds respectively.

If a build name isn’t provided in the url the following HTTP 400 error is displayed.

To get the Arduino Uno chatting to TeamCity I bought an Arduino Ethernet shield at the same time as the board.  A “shield” in the Arduino world is simply an expansion board that sits on top of the Arduino board, providing additional functionality, in this case ethernet capability. is a great resource for working out shield and board compatibility for more complex projects.

It was now time to author an Arduino sketch that would pole the TeamCity SimpleBuildStatus plugin for a project build status, checking the returned HTTP status code and switching the relay to Normally Open (NO) if it’s a 200 and to Normally Closed (NC) if it’s a 409.  Remember I have already wired the traffic lights up to the relay in step 3 above.

The resulting first cut at the sketch was as follows:
Traffic lights client

This sketch connects to a software build, continuous integration (CI) server
 (e.g. TeamCity) using an Arduino Wiznet Ethernet shield and switches a SPDT relay
 depending on the state (HTTP response code) returned from a buildStatus page.

HTTP/200 -> Build(s) successful, Green light on
 HTTP/400 or any other value -> Build(s) broken, Red light on

 * Ethernet shield attached to pins 10, 11, 12, 13
 * VEZ Single Pole Double Through (SPDT) Relay attached to pins +5v, gnd, 8

created 23 April 2011
 by Lloyd Holman
 This code is in the public domain.

Based on WebClient and BlinkWithoutDelay examples (by David A. Mellis)

#include <SPI.h>
 #include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
 // The IP address will be dependent on your local network:
 byte mac[] = { 0xD90, 0xDA2, 0xDDA, 0xD00, 0xD3D, 0xDB8 };
 byte subnet[] = { 255, 255, 255, 0 };
 byte ip[] = { 192,168,4,30 };
 byte gateway[] = { 192, 168, 4, 1 };
 byte server[] = { 10,100,101,8 };

// Initialize the Ethernet client library
 // with the IP address and port of the server
 // that you want to connect to (port 80 is default for HTTP):
 Client client(server, 80);

int pinState = LOW; // used to set the digital pin driving the relay, HIGH or LOW
 const int relayPin = 8; // the digital pin driving the relay

int GetServerStatus();

void setup() {
 // set the digital pin as output:
 pinMode(relayPin, OUTPUT);

// start the Ethernet connection:
 Ethernet.begin(mac, ip, gateway);
 // start the serial library:
 // give the Ethernet shield a second to initialize:

void loop()
 int buildStatus = GetServerStatus();
 Serial.print("buildStatus: ");

if (buildStatus == 200 && pinState == LOW)
 pinState = HIGH;
 else if (buildStatus != 200 && pinState == HIGH)
 pinState = LOW;

digitalWrite(relayPin, pinState);


static int GetServerStatus()
 int httpStatus = 0; //indicate a connection error with 0
 int parseStatus = 0;

 if (client.connect()) {
 // Make the HTTP Get request:
 client.println("GET /simpleBuildStatus.html?projectName=DCP_R17&guest=1 HTTP/1.0");
 else {
 // if you didn't get a connection to the server:
 Serial.println("connection failed");

// wait for the response from the CI server.
 bool gotStatus = false;
 while (1){
 while (client.available()) {
 char c =;

switch(parseStatus) {
 case 0:
 if (c == ' ') parseStatus++; break; // skip "HTTP/1.1 "
 case 1:
 if (c >= '0' && c <= '9') {
 httpStatus *= 10;
 httpStatus += c - '0';
 } else {

 if (!client.connected()) {

 return httpStatus;

I have hosted the code for the TeamCity SimpleBuildStatusPlugin (discussed earlier), along with the corresponding Arduino sketch (above) to control the Arduino digital pin and Ethernet shield in a public github repo here:

The build Step #5, packaging it all up

I wanted to make a neat job so I modified the plastic case from the parts list, with a carful bit of measuring, drilling and cutting with a stanley knife I ended up with a rather neat little case made for the Arduino.

I then simply stuck the packaged Arduino box to the side of the traffic lights with some double sided sticky pads.  It was always my aim from the start to have the Arduino circuitry mounted outside of the lights, mainly to avoid the heat from the 40watt bulbs frying it.

The end product is a very noticeable build traffic light on the wall in our office:

Keep an eye on the Github repo as I plan to update with some of the following ideas:

  1. Multi project support for TeamCity.
  2. An audible piezo buzzer when status changes.
  3. Other CI server support, by simple plugins.

Executing psake build scripts from TeamCity

I came across an issue with a few of our TeamCity build configurations the other day; We had a situation where TeamCity was reporting ‘Success’ instead of ‘Failure’, lucky we spotted this early.

Executing psake build scripts from TeamCity



As can be seen above the build is failing with the following zero exit code.

[code language=”bash”]
`default.ps1:Error executing command: msbuild $sln_file /t:Build /p:Configuration=Release /v:q [17:15:08]: Process exited with code 0`

I had a sniff around and came to the conclusion the problem was in the way we were calling our psake build script from within a batch file. After a bit of googling I found this is a common stumbling block, there were some rather confusing and over the top approaches but I finally found this very useful article, this post builds on this approach and adds a bit more detail.

So we identified we were doing the following in our `build.bat`:

[code language=”powershell”]powershell.exe -command &quot;&amp; {.build.ps1 Package}&quot;[/code]

This is potentially wrong due to the following reasons:

  1. PowerShell by default continues running scripts on errors
  2. The executing batch file `build.bat` was not trapping the error status returned from the psake PowerShell script `default.ps1`.
  3. We weren’t importing the psake PowerShell module and therefore the $psake hashtable variables weren’t getting set.

I didn’t need to do anything for point 1 as we had however already implemented the exec {} helper function which forces psake to throw an error.

To resolve point 2 I referred to Dusty’s article , split it out a bit more and implemented the following in the original batch file `build.bat` and new build.ps1 script respectively

[code language=”bash”]@echo off
powershell.exe -NoProfile -ExecutionPolicy unrestricted -command &quot;.build.ps1 %1;exit $LASTEXITCODE&quot;

[code language=”bash”]
if %ERRORLEVEL% == 0 goto OK
echo ##teamcity[buildStatus status=’FAILURE’ text='{build.status.text} in compilation’]



[code language=”powershell”]
param([string]$task = &quot;compile&quot;)
Import-Module ‘.libpsakepsake.psm1’;
Invoke-psake -t $task;
if ($Error -ne ”)
Write-Host &quot;ERROR: $error&quot; -fore RED;
exit $error.Count
Remove-Module psake -ea ‘SilentlyContinue’;

The above do the following:

  • `build.bat` wraps `build.ps1` and executes it, passing the first parameter passed to the batch file in, i.e. the psake task.
  • `build.ps1` then starts by importing the psake PowerShell module (we have this in a relative path in source control).
  • `build.ps1` then invokes the default psake build script in the current working folder i.e. `default.ps1`, passing the first parameter passed to the batch file in as the psake task. `Default.ps1` obviously does all the build work for us.
  • the if block then simply checks the Powershell $error array and returns a count of the errors to `build.bat`
  • `build.bat` echo’s out a nice TeamCity buildStatus which then shows up in the TeamCity gui.
  • `build.bat` fails with the ERRORLEVEL returned by `build.ps1`.
  • finally the psake PowerShell module is removed.

Point 3 was resolved above by explicitly importing the psake PowerShell module. I also tapped the following into a PowerShell command line.

[code language=”powershell”]Get-Help Invoke-psake –full[/code]

Which gives, amongst other detail, the following Output definition.

[code language=”bash”]…..
If there is an exception and ‘$psake.use_exit_on_error’ -eq $true
then runs exit(1) to set the DOS lastexitcode variable
otherwise set the ‘$psake.build_success variable’ to $true or $false depend
on whether an exception was thrown


When the psake module is loaded a variabled called $psake is created it
is a hashtable
containing some variables that can be used to configure psake:

$psake.use_exit_on_error = $false # determines if psake uses the &quot;exi
t()&quot; function when an exception occurs
$psake.log_error = $false # determines if the exception detai
ls are written to a file
$psake.build_success = $false # indicates that the current build
was successful
$psake.version = &quot;4.00&quot; # contains the current version of p
$psake.build_script_file = $null # contains a System.IO.FileInfo for
the current build file
$psake.framework_version = &quot;&quot; # contains the framework version #
for the current build

$psake.use_exit_on_error and $psake.log_error are boolean variables tha
t can be set before you call Invoke-Psake.

You should see the following when you display the contents of the $psak
e variable right after importing psake

PS projects:psake&gt; Import-Module .psake.psm1
PS projects:psake&gt; $psake

Name Value
—- —–
version 4.00
use_exit_on_error False
build_success False
log_error False

I therefore modified the `build.ps1` psake script above set the $psake.use_exit_on_error variable to true and forced it to always use the 64 bit version of the .NET 3.5 framework:

[code language=”powershell”]param([string]$task = &quot;compile&quot;)
Import-Module ‘.libpsakepsake.psm1’;
$psake.use_exit_on_error = $true
Invoke-psake -t $task -framework ‘3.5×64’;
if ($Error -ne ”)
Write-Host &quot;ERROR: $error&quot; -fore RED;
exit $error.Count
Remove-Module psake -ea ‘SilentlyContinue’;

Executing the batch file on the command line within my development environment was now returning the correct results. Therefore I purposefully checked in a dodgy change into our Source control system (TFS) and watched a TeamCity build kick off……

The correct error code and the buildStatus from `build.bat` displaying nicely.



….much to my delight the build failed with the correct error code this time

[code language=”bash”]
[13:47:47]: ControllersAccountController.cs(73,62): error CS1002: ; expected
[13:47:48]: default.ps1:Error executing command: &amp; msbuild $sln_file /t:Build /p:Configuration=Release /v:q
[13:47:48]: ##teamcity[buildStatus status=’FAILURE’ text='{build.status.text} in compilation’]
[13:47:48]: Process exited with code 1

No more fibbing build status’ for us.

AppHarbor supports lib and src style folder structures

I’m currently using AppHarbor on a small freelance piece of work and I must say I’m seriously impressed, all the usual things are making me happy, the simplicity of pushing code from a Git repothe execution of tests and pushing of code live (i.e. continuous integration in the cloud) and not to mention the support for SQL Server and MySQL.

This is hopefully the first of a few posts about my recent experiences  with, as their tagline says “Azure done right”.

I’m currently using AppHarbor on a small freelance piece of work and I must say I’m seriously impressed, all the usual things are making me happy, the simplicity of pushing code from a Git repothe execution of tests and pushing of code live (i.e. continuous integration in the cloud) and not to mention the support for SQL Server and MySQL.

However the thing that impressed me recently was the way it all “just works”, after starting with a basic “Hello World” app I decided to restructure my source control tree and start pushing some more serious code up.  I changed from a simple single solution folder to some thing more akin to how I like to structure my projects:


As you can see I have nice ‘lib’ and ‘src’ folders, now the AppHarbor getting started guide states that you need to create your Git repository in the ‘pathtomyapplication’.  As you can see above this isn’t the case in my example above, my repo is created right up in the ‘~DevelopmentAYH.CHP’ folder, the .sln file for the solution is down in ‘DevelopmentAYH.CHPtrunksrc’.  I was unsure whether this was going to work, but pressed on and ran:

[code language=”bash”]$ git push appharbor master[/code]

Much to my delight AppHarbor didn’t sniff, it simply enumerated my repo and found the one and only .sln file and built it, see the latest successful build here:


So don’t be scared of trying something different, the guys at seem to have most things covered.