Query TFS/VSTS for past build history

April 20, 2017    VSTS DevOps TFS

Query TFS/VSTS for past build history

We’re using TFS on premise (2017, not an update) to run builds, track work, etc at my current client. This should also work on VSTS (which I hope we will get to move towards someday).

I was asked to figure out why our build times have increased over the last couple months. My first task was to get the metrics. After not finding the graph I wanted in the charts in the TFS dashboard, I turned to the TFS API.

I used this starting point from the Microsoft docs.

There was also some info from StackOverflow that was helpful.

I created a plain old .Net Console application to spit out a .csv file.

I added a few Nuget packages

  • Microsoft.TeamFoundationServer.Client
  • Microsoft.VisualStudio.Services.Client
  • Microsoft.VisualStudio.Services.InteractiveClient

Then I added some code

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.TeamFoundation.Build.WebApi;
using Microsoft.VisualStudio.Services.Client;
using Microsoft.VisualStudio.Services.WebApi;`

namespace GetBuildHistory
    class Program
        static void Main(string[] args)

        static async Task MainAsync()
            var collectionUri = "http://tfs:8080/collection/";
            var teamProjectName = "{Your_Project_Name}";
            var targetBuildName = "{Your_BUILD_Name}";

            VssConnection connection = new VssConnection(new Uri(collectionUri), new VssClientCredentials());
            var buildserver = connection.GetClient<BuildHttpClient>();
            var builds = await buildserver.GetBuildsAsync(
                statusFilter: BuildStatus.Completed,
                project: teamProjectName);
            var targetedBuilds = builds
                .Where(definition => definition.Definition.Name.Contains(targetBuildName))
                .OrderBy(b => b.FinishTime)


        private static void ProcessBuilds(List<Build> targetedBuilds)
            var pathString = $@"C:\results\general_fullBuildResults.csv";
            var stringBuilder = new StringBuilder();
            stringBuilder.AppendLine("Name, Date, Passed, Build Time, Queue Time");
            foreach (var build in targetedBuilds)
                var buildInfo = new BuildInfo
                    Name = build.BuildNumber,
                    Passed = build.Result != null && build.Result.Value == BuildResult.Succeeded,
                    FinishTime = build.FinishTime.Value,
                    Started = build.StartTime.Value,
                    QueueStartTime = build.QueueTime.Value


            File.WriteAllText(pathString, stringBuilder.ToString());

    internal class BuildInfo
        public string Name { private get; set; }
        public bool Passed { private get; set; }
        public DateTime Started { private get; set; }
        public DateTime FinishTime { private get; set; }
        public DateTime QueueStartTime { private get; set; }

        private string InQueueTimeMinutes => this.CalculateTimeInQueue();

        /// <summary>
        /// The time the build took to run.
        /// </summary>
        public string TimeRanInMinutes => this.CalculateTimeRan();

        private string CalculateTimeRan()
            var diff = this.FinishTime - this.Started;
            return (diff.TotalSeconds / 60).ToString(CultureInfo.CurrentCulture);

        private string CalculateTimeInQueue()
            var diff = this.Started - this.QueueStartTime;
            return (diff.TotalSeconds / 60).ToString(CultureInfo.CurrentCulture);

        public override string ToString()
            return $"{this.Name}, {this.Started.ToLocalTime():g}, {this.Passed}, {this.TimeRanInMinutes}, {this.InQueueTimeMinutes}";

I will probably add to this, but this works for me. It spits out a csv that I can use Excel to create an easy chart. This could morph into a TFS extension chart (which would be great, but more work and time than I have right now). We could even run this automatically and alert if the build time goes over a certain threshold. That could mean we have problems (see the DevOps Handbook Chapter 14 on the importance of metrics).

I’m authenticating through my Windows Active Directory account, so the console didn’t prompt me. Check the docs link above for more information about that.

But wait, there’s more

We can even drill into the task level of the builds and use Power BI to visualize the timings there too.

 /// <summary>
    /// Get the timeline information from the REST API
    /// </summary>
    /// <remarks>
    /// reference of the REST API: https://www.visualstudio.com/en-us/docs/integrate/api/build/builds
    /// </remarks>
    /// <param name="buildId"></param>
    private static async Task<Timeline> GetTimelineAsync(int buildId)
        Console.WriteLine($"Getting timeline for {buildId}....");
        return await buildServerClient.GetBuildTimelineAsync(teamProjectName, buildId);

I added this to my BuildInfo.cs object and used it to create the CSV rows.

public string GetTimelineCsvRow()
    // Build Name, Date, Passed, Task Name, Time in Minutes, State, Result
    var sb = new StringBuilder();
    var orderedRecords = this.Timeline.Records
        .OrderBy(record => record.StartTime).ToList();

    orderedRecords.ForEach(record =>

        sb.AppendLine($"{this.Name}, {record.StartTime.Value.ToLocalTime():g}, " +
                    $"{this.Passed}, {record.Name}, " +
                    $"{this.CalculateTimeRan(record.StartTime.Value, record.FinishTime.Value)}, ${record.State}, ${record.Result}, ${record.Url}");

        catch (Exception e)

    return sb.ToString();

comments powered by Disqus