Tuesday, December 20, 2011

Get the TFS build (MSBuild) information from C#.Net code

Suppose you have daily build going on which is created using TFS 2010 and if you want to get the information like how many build created, how many fails etc.

You can write small C#.net program to get all this information, you requires to pass TFS url and Team project name, see the following code for details

using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Build.Common;
using Microsoft.TeamFoundation.VersionControl.Client;

Source Code
private void button1_Click(object sender, EventArgs e)
 //prepare list view to set column header
 lstResult.View = View.Details;
 // add columns in ListView
 lstResult.Columns.Add("Build Status", 70, HorizontalAlignment.Left);
 lstResult.Columns.Add("BuildDefinition", 150, HorizontalAlignment.Left);
 lstResult.Columns.Add("LabelName", 120, HorizontalAlignment.Left);
 lstResult.Columns.Add("Reason", 100, HorizontalAlignment.Left);
 lstResult.Columns.Add("StartTime", 100, HorizontalAlignment.Left);
 lstResult.Columns.Add("FinishTime", 100, HorizontalAlignment.Left);
 lstResult.Columns.Add("RequestedBy", 100, HorizontalAlignment.Left);
 lstResult.Columns.Add("Drop Location", 100, HorizontalAlignment.Left);
 // add Items in ListView

TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri("VSTS URL"));

var vcs = tfs.GetService<VersionControlServer>();

var proj = vcs.GetTeamProject("Team Project Name");

IBuildServer buildServer = (IBuildServer)tfs.GetService(typeof(IBuildServer));

var builds = buildServer.QueryBuilds(proj.Name);

//Bind all column in listview
foreach (IBuildDetail build in builds)
string [] columns = new string [8];
       ListViewItem Item;
       columns[0] = build.Status.ToString();
       columns[1] = build.BuildDefinition.Name;
       columns[2] = build.LabelName;
       columns[3] = build.Reason.ToString();
       columns[4] = build.StartTime.ToString();
       columns[5] = build.FinishTime.ToString();                   
       columns[6] = build.RequestedBy;
       columns[7] = build.DropLocation;
       Item = new ListViewItem(columns);

Note: I am unable to get the information, if build fails then why fails complete details (Log) in one of the columns in above list view column, if someone able to do that please let me know, Thanks

No comments: