Tuesday, March 17, 2015

How to connect to TFS to get build information onto SharePoint

All the TFS assemblies are available at the below location from where it can be added on the VS project -
c:\ Program Files (x86)\ Microsoft Visual Studio 12.0\ Common7\ IDE\ ReferenceAssemblies\ v2.0\

The code to connect to TFS looks like below -


using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.VersionControl.Client;

namespace TFSClientObjectModel

{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnConnect_Click(object sender, EventArgs e)

        {

            string TfsUrl = "https://tfsurl";

            var server = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(TfsUrl));
            server.EnsureAuthenticated();

            var vcs = server.GetService();

            var teamProjects = vcs.GetAllTeamProjects(true);

            var buildServer = server.GetService();


            foreach (TeamProject proj in teamProjects)

            {
                var defs = buildServer.QueryBuildDefinitions(proj.Name);

                foreach (IBuildDefinition def in defs)

                {
                    if (!def.Name.Contains("Matched Name"))
                    {
                        continue;
                    }
                    this.lstMain.Items.Add(def.Name);

                    IBuildDetailSpec spec = buildServer.CreateBuildDetailSpec(proj.Name, def.Name);

                    // Set InformationTypes to null, otherwise query performance takes 10 min vs. a few seconds
                    spec.InformationTypes = null;
                    spec.MaxBuildsPerDefinition = 1;
                    spec.QueryOrder = BuildQueryOrder.FinishTimeDescending;

                    var builds = buildServer.QueryBuilds(spec);


                    if (builds.Builds.Length > 0)

                    {
                        var buildDetail = builds.Builds[0];

                        this.lstBuilds.Items.Add(string.Format("{0} - {1} - {2} - {3}", def.Name, buildDetail.Status.ToString(), buildDetail.FinishTime, buildDetail.LabelName));

                    }
                }
            }
        }
    }

}

This provides the basic information about the build details. Similarly we can get more information about version and other properties also.

No comments: