May 08, 2013

Adding onto TFS with their API

Just had the need to get a list of all changesets for a given list of user stories. Unfortunately, TFS does not have functionality to merge work items or user stories. So I decided to write a small program to give me a list of all the changesets for a given set of user stories. Hopefully this will give me a foundation for later tools in TFS.

TFS has a large API and it can be crazy to go through, but I found out through looking on the internet what to look for in finding changesets. First, let’s add the assemblies:

 Microsoft.TeamFoundation.Client Microsoft.TeamFoundation.Common Microsoft.TeamFoundation.VersionControl.Client Microsoft.TeamFoundation.WorkItemTracking.Client 

If you have Visual Studio installed, these assemblies should be GAC’d. Next, we need to connect to a project collection, which is the collection of code you are working in. ProjectCollection object gets the objects we can use to get work items, so let’s see that code:

 var projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(\_myUri)); var versionControlServer = projectCollection.GetService(); var workItemStore = projectCollection.GetService(); WorkItemCollection workItemCollection = workItemStore.Query( " SELECT [System.Id], [System.WorkItemType]," + " [System.State], [System.AssignedTo], [System.Title] " + " FROM WorkItems " + " WHERE [System.TeamProject] = '" + teamProject + "' ORDER BY [System.WorkItemType], [System.Id]"); </pre> 

You might notice 2 things, the \_myurl and the “query”. The _myurl is the url to the TFS server, easy, and the query is the query for a work item, based on your team project. After you throw all this together, you get a work item collection. With this collection you can get all the work item/user story links and change set links.

SPECIAL NOTE: TFS can link anything, this means you could have a circular reference. Be aware of this.

Now that we got the note out of the way, let’s check out some of the code:

 WorkItem wiDeliverable = workItemStore.GetWorkItem(workItemId); foreach (var changeset in wiDeliverable.Links .OfType() .Select(link => versionControlServer.ArtifactProvider.GetChangeset(new Uri(link.LinkedArtifactUri)))) { Console.WriteLine(changeset.ChangesetId); } foreach (WorkItemLink child in wiDeliverable.WorkItemLinks) { GetChangeSetValues(versionControlServer, workItemStore, child.TargetId); } </pre> 

The last thing that is weird is that there are 2 different links. One is an artifact link and the other is work item link. Artifact is the changeset and the work item link is the link to other work items. Super easy, but confusing to navigate. That is it though, that is how you can get a list of changesets for a given user story.