Search code examples
tfsbuildversionchangeset

Getting TFS to put the changeset in the assembly version


I have got a Team Foundation Server Build running cleanly. It produces several assemblies and I would like the assemblies versions to have the last number to be the changset number. That is, if I commit with a changeset11667 for example the assembly version number should be "x.y.z.11667". I've checked the availible macros, but none is the changeset number.

I would still like to be able to build the solution file on my dev machine as normal, just using the checked in version number.

How would I go about getting this in place?


Solution

  • In the end a colleague of mine wrote the following MSBuild task that solved the problem.

    public class GetNextBuildNumber : Task
    {
        [Required]
        public string TfsCommand { get; set; }
    
        [Required]
        public string TfsArgument { get; set; }
    
        [Output]
        public int BuildNumber { get; set; }
    
        public override bool Execute()
        {
            BuildNumber = GetLatestVersionNumber();
            return true;
        }
    
        private int GetLatestVersionNumber()
        {
            var process = new RunProcess();
            var result = process.ExecuteCommand(TfsCommand, TfsArgument);
    
            return ParseResult(result);
        }
    
        private int ParseResult(string result)
        {
            const string changeset = "Changeset:";
            const string user = "User:";
    
            if (string.IsNullOrEmpty(result) || !result.Contains(changeset))
            {
                // Invalid result
                Log.LogWarning("Could not get latest build number. Reason: " + result);
                return 0;
            }
    
            var indexOfChangeset = result.IndexOf(changeset, StringComparison.InvariantCulture) + changeset.Length;
            var indexOfUser = result.IndexOf(user, StringComparison.InvariantCulture);
            var revision = result.Substring(indexOfChangeset, indexOfUser - indexOfChangeset).Trim();
    
            return Convert.ToInt32(revision);
        }
    
    }