Click here to Skip to main content
0 members
Click here to Skip to main content
Add your own
alternative version


43 bookmarked
Posted 18 May 2012
Licenced CPOL

.NET REST service

, 25 May 2012
Rate this:
Please Sign up or sign in to vote.
Self-installing version tracking REST service for builds


This project is ambitious for its size;

  • REST web service (socket listener/HTTP parser)
  • Self-installing Windows services
  • 12.5 KB
  • Does something useful (get/set/increment/persist version numbers)


I set out to create a service to centralize build version number control, but ended up with an interesting study in light-weight RESTful service implementations in .NET. In build environments, version increments are typically solved with a hand written script, custom action, or workflow activity. It's typically not the prettiest aspect of a build solution. This project builds a more elegant REST service, it utilizes a RESTful service called directly from the build which directly increments and fetches any number of build versions. As an example, opening your web browser and putting the URL:


..would return

The version of your favorite LodeRunner knock-off project build.


The self-installing aspects of this service actually came from this article... Thanks you much. The critical aspects are that you need to define a Service and an Installer, then funnel the incoming arguments as appropriate (see Versioner.Install.cs and Versioner.Services.cs).


public class Installer : inst.Installer
    public Installer()
        Installers.Add(new ServiceProcessInstaller() { Account = ServiceAccount.LocalSystem });
        Installers.Add(new ServiceInstaller()
            DelayedAutoStart = false,
            StartType = ServiceStartMode.Automatic,
            Description = "Tracks version numbers for build resources",
            ServiceName = Service.Name,
            DisplayName = "Versioner Service",

This is required by the service manager to provide the basic information that you would see from the service manager. The service itself is in Versioner.Service. That is effectively the "main" of the service. We'll discuss that later when we talk about how it all works.


There's a lot to setting up sockets correctly, so I created a helper. The class encapsulates the basic concept of listening and gives an Action<T> callback when a socket connects.

public class SimplyListen : IDisposable
    private Action<Socket> _onConnect;
    private SimplyListen Listen(int port, Action<Socket> onConnect)
        _onConnect = onConnect;
        // Create the listener socket in this machines IP address
        _socketLast = new Socket(AddressFamily.InterNetwork,
                          SocketType.Stream, ProtocolType.Tcp);
        _socketLast.Bind(new IPEndPoint(LocalHost, port));
        //listener.Bind( new IPEndPoint( IPAddress.Loopback, 399 ) );
        // For use with localhost
        // Setup a callback to be notified of connection requests
        _socketLast.BeginAccept(new AsyncCallback(OnConnectRequest), _socketLast);
        return this;

The key call here is OnConnectRequest. That is a callback method that the socket layer calls when it's time to respond to a an incoming socket connection. The key to understanding this code is realizing there are two sockets... the one we've had open that's "listening" and the one the client is connecting to that you can receive incoming bytes.  The _socketLast.EndAcccept() call fetches that inner socket and passes it to our _onConnect Action<T>. From there, the caller can handle just the connection aspects without propping up all the other complexities of a socket. 

private Socket _socketLast = null;
private void OnConnectRequest(IAsyncResult ar)
    lock (_socketLast)
        _socketLast = ar.AsyncState as Socket;
    _socketLast.BeginAccept(new AsyncCallback(OnConnectRequest), _socketLast);

What's the Versioning Kenneth?!

So all this goop surrounds the real code, which is a persistent version tracking mechanism. The idea is that we store on disk a comma-separated list of version strings. It looks like this: 


I use a pretty basic LINQ command to translate that into a Directory so it's handy in memory...

Versions = !File.Exists (filename) ? new Dictionary<string, string>() :
    File.ReadAllLines(filename).Select(l =>
        l.Split(',')).Where(v=>v.Length==2).ToDictionary(k => k[0], v => v[1])

And this is  similar linq to save it

    Versions.Select(v=>string.Format("{0},{1}", v.Key, v.Value)).ToArray());

The dirty work, putting it all together

The commands coming in from the URL parameters can be either the version you want to set or one or more pluses ('+') which means "increment" the version number by one. The count of pluses indicates which position in the version number to increment.  One plus means increment the last digit, two, the second to last, etc.  I've coded this such that there's no limit on the count of separators in the version number, 4 is standard, but I purposefully left the implementation robust so any will work. 

private static string Increment(string name, string version)
    string response = version;
    if (!string.IsNullOrEmpty(version))
        int plusCount = version.Count(c => '+' == c);

        if (plusCount > 0)
            if (!vers.Versions.TryGetValue(name, out response))
                response = "";

            response = Versioner.Increment(response, plusCount);
    return response;

This uses a static method in the Versioner to do the actual number increment.  It splits the version string into an array, parses to integer, increments the correct location, then re-joins.  

public static string Increment(string response, int incIndex)
    var ints = response.Split('.').Select(i => int.Parse(i)).ToArray();
    int pos = ints.Length - incIndex;

    if (pos < 0)
        return response;

    ints[pos] = ints[pos]+1;
    while (++pos < ints.Length)
        ints[pos] = 0;

    return string.Join(".", ints.Select(i => i.ToString()));

If we have determined our version number, now we need to update the in memory dictionary and save it.  This code also handles the case where we are just asking for the version number (no version parameters at all).  That's the "TryGet".

private static string UpdateVersions(string name, string response)
    if (!string.IsNullOrEmpty(response))
        if (vers.Versions.ContainsKey(name))
            vers.Versions[name] = response;
            vers.Versions.Add(name, response);
    else if (!vers.Versions.TryGetValue(name, out response))
        response = string.Empty;
    return response;

Finally, here's the code that wraps it all together.  It's in the service handler's lambda that responds to a connection attempt.  

  • ReadHttpRequestBuffer() reads from the socket and returns the name and versions parameter.
  • Increment() as requested by the version parameter
  • UpdateVersions() update the in-memory dictionary and persist the version to disk
  • Send response as a byte array
string name, version;
if (SimplyListen.ReadHttpRequestBuffer(s, out name, out version))
    var response = UpdateVersions(name, Increment(name, version));
    // Convert to byte array and send.

    var byteDateLine = System.Text.Encoding.ASCII.GetBytes(response);

    s.Send(byteDateLine, byteDateLine.Length, 0);

Using it  

To install:

  • Copy to where you want it
  • Start a command prompt AS ADMIN
  • Change directory to the copy location
  • Run...
Versioner.exe /i
Running a transacted installation.
Beginning the Install phase of the installation.

Once installed you can launch any browser and type this:



The end of the URL is the name of the project, the 'v' parameter has two modes:

  • If you specify a period separated list of integers, it will set the version number for that entity.
  • If you specify any number of '+' characters it will set the appropriate index in the version number...

Example: 'v=+' increments (and stores) the "build" number, 'v=+++' increments the minor version number.

Future: Putting to use in an actual build

You'll need to implement how you want to get this into your build, but over the next few weeks, I will likely add a second part to this article to update the build number in the actual TFS Build workflow.    


  • 17 May '12 - Created  
  • 19 May '12 - Rewrote intro to be more generic
  • 25 May '12 - Fixed bug in localhost 


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Engineer Big Company
United States United States
My professional career began as a developer fixing bugs on Microsoft Word97 and I've been fixing bad habits ever since. Now I do R&D work writing v1 line of business applications mostly in C#/.Net.

I've been an avid pilot/instructor for 13+ years, I've built two airplanes and mostly fly gliders now for fun. I commute in an all-electric 1986 BMW 325 conversion.

I'd like to get back to my academic roots of programming 3D analysis applications to organize complex systems.

You may also be interested in...


Comments and Discussions

GeneralWell done Pin
karenpayne30-Jul-12 10:02
memberkarenpayne30-Jul-12 10:02 
GeneralRe: Well done Pin
CodingBruce31-Jul-12 15:26
memberCodingBruce31-Jul-12 15:26 
GeneralMy vote of 5 Pin
Oleg Shilo25-May-12 17:14
memberOleg Shilo25-May-12 17:14 
GeneralMy vote of 5 Pin
Wooters25-May-12 6:06
memberWooters25-May-12 6:06 
QuestionGreat Article - Easy Step-nyStep, but REST/Web do not work. Pin
JanBorup22-May-12 11:32
memberJanBorup22-May-12 11:32 
AnswerRe: Great Article - Easy Step-nyStep, but REST/Web do not work. Pin
CodingBruce23-May-12 1:52
memberCodingBruce23-May-12 1:52 
GeneralRe: Great Article - Easy Step-by-Step, but REST/Web do not work. Pin
JanBorup23-May-12 10:17
memberJanBorup23-May-12 10:17 
GeneralRe: Great Article - Easy Step-by-Step, but REST/Web do not work. Pin
CodingBruce24-May-12 5:16
memberCodingBruce24-May-12 5:16 
GeneralRe: Great Article - Easy Step-by-Step, but REST/Web do not work. Pin
CodingBruce25-May-12 2:30
memberCodingBruce25-May-12 2:30 
GeneralMy vote of 3 Pin
robinson.netdevelop22-May-12 11:10
memberrobinson.netdevelop22-May-12 11:10 
QuestionRe: My vote of 3 Pin
Tim Corey25-May-12 2:38
professionalTim Corey25-May-12 2:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web06 | 2.8.190419.4 | Last Updated 25 May 2012
Article Copyright 2012 by CodingBruce
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid