Programming Team Foundation Server with the TFS SDK

Programming Team Foundation Server with the TFS SDK

hen working with Team Foundation Server (TFS), teams typically work on team projects, which are source-controlled collections of projects that let a manager track and assign individual tasks, called “work items.”

You can find out a great deal more general information on TFS and team projects by reading the articles and visiting the sites listed in the Related Resources section (in the left column of this article). You should be somewhat familiar with TFS before you continue, so if you need the background information, read those first.

While the TFS UI supports most of the common tasks you might want to do with team projects, the TFS SDK lets you go “under the hood” to manipulate nearly any feature programmatically. This article explains how you can use .NET code (C# in this case) to access team projects programmatically, extracting work items and other details so you can use them in reports, as the basis for future projects, etc.

What You Need
To execute the code examples used in this article, you need to have Team Foundation Server, Visual Studio Team System 2008, and SQL Server 2005 installed.

Creating a New Team Project
In this section, you’ll create a new project in Visual Studio, and then do the same in TFS Server. Here’s a step-by-step list of the actions you need to follow:

In the Team Explorer window, right click and click on “New Team Project” to create a new team project (see Figure 1).

Figure 1. Create a New Team Project: Right-click on “New Team Project” in the Team Explorer window to create a new project.

You’ll see the screen in Figure 2.

Figure 2. Name the Project: In the New Team Project dialog, specify a unique name for the new project.
Figure 3. Select a Process Template: Use the dropdown list to select the process template most appropriate for your project.

Type in a unique name for your new project and click “Next.” The next screen that appears (see Figure 3) prompts you to select a process template.

A process template defines how a TFS manages a team project is managed. When creating a project, you select the process template most appropriate for your project, usually deciding based on the project’s life cycle. As an example, Figure 3 shows the “MSF for Agile Software Development” process template selected from a dropdown list of templates. You can download additional process templates using the link visible in the dialog. After selecting a process template, click Next. You’ll see the screen in Figure 4, which requests a name for the team project portal, and displays the portal site address.

Figure 4. Project Portal: Enter a name for the project portal and note the portal site address that appears near the bottom of the screen.
Figure 5. Source Control Settings: You can create an empty source folder, a new source control branch, or opt to create a source control folder later.

When you click Next, the wizard requests source control settings. Choose one of the three possible options shown in Figure 5.

Select the first radio button as shown in the screen shot above to create an empty source control folder, and then click Next. You’ll see a confirmation screen (see Figure 6).

Figure 6. Project Confirmation: Review the settings you selected, and then click Finish.

Click the Finish button to complete the wizard and create the new team project. The Team Project Wizard displays a progress bar and lists the tasks as they’re performed, such as creating the project itself, team groups, and assigning permissions (see Figure 7).

Figure 7. Creation Status: The wizard displays a status bar as it creates the new project.
Figure 8. Team Explorer with New Project: You’ll see a number of items in the Team Explorer window for the new project.

The wizard displays a completion screen when the new team project has been successfully created. Click on Close to exit the wizard. At this point, your Team Explorer window should looks like Figure 8:

Accessing Projects Programmatically with the TFS SDK
With the new team project “DevX” successfully added to the Team Foundation Server, you can use the TFS SDK to work with the project programmatically. First, add a web project called WebApplication1 to the Team Project DevX created earlier (see Figure 9).

Figure 9. Adding a New Web Project: The dialog shows the process of adding a new web application to the team project named “DevX.”

After adding your project, you can check code in and out, view history, etc.

Creating and Reading Work Items from TFS
Now that you have a project in place, you can use the TFS SDK to create and read work items from the project’s work item repository. The first step is to add references to the TFS libraries. You can find these assemblies in the C:Program FilesMicrosoft Visual Studio 8Common7IDEPrivateAssemblies folder (see Figure 10).

Figure 10. TFS Assemblies: This screenshot of the TFS assembly location shows the DLLs that you may need to reference in your code.
Figure 11. Required References: The figure shows the list of assemblies that you must reference to run the sample project.

To work with the TFS SDK, you’ll need to add references to the assemblies in Figure 11.

The TFS SDK provides classes and methods for obtaining project information from TFS Server. The following example illustrates how to display various TFS Server details using the SDK:

   using System;   using System.Collections.Generic;   using System.Linq;   using System.Web;   using System.Web.UI;   using System.Web.UI.WebControls;   using System.Net;   using System.Collections;   using System.Text;       using Microsoft.TeamFoundation.Client;   using Microsoft.TeamFoundation.WorkItemTracking.Client;      namespace WebApplication1   {      public partial class _Default : System.Web.UI.Page      {         private String tfsServer = "TFSRTM08";            protected void Page_Load(object sender, EventArgs e)         {            DisplayTFSDetails(tfsServer);         }            private void DisplayTFSDetails(String tfsServerName)         {            TeamFoundationServer teamFoundationServer =               TeamFoundationServerFactory.GetServer(tfsServerName);            teamFoundationServer.Authenticate();            WorkItemStore workItemStore = new                WorkItemStore(tfsServerName);            Response.Write("
Displaying the Team " + "Foundation Server details
"); Response.Write("
TFS Server Name: " + teamFoundationServer.Name); Response.Write("
TFS Server URI: " + teamFoundationServer.Uri); Response.Write("
Authenticated User Name: " + teamFoundationServer.AuthenticatedUserName); Response.Write("
Authenticated User Display Name: " + teamFoundationServer.AuthenticatedUserDisplayName); } } }
Figure 12. TFS Server Details: This output shows TFS Server information requested using the TFS SDK.

When you execute the preceding code, you’ll see a window containing the requested information (see Figure 12).

You can easily display a list of all the projects in TFS:

   private void ListAllProjects(String tfsServerName)   {      TeamFoundationServer teamFoundationServer =         TeamFoundationServerFactory.GetServer(tfsServerName);         teamFoundationServer.Authenticate();         WorkItemStore workItemStore = new          WorkItemStore(tfsServerName);         foreach (Project pr in workItemStore.Projects)      {         Response.Write("
Project Name: " + pr.Name); } }

You can call the ListAllProjects method as follows:

Figure 13. Project List: You can easily generate a complete list of TFS projects from code.

Figure 13 shows the output.

Adding a Work Item to TFS
The following code snippet illustrates how to add a work item to TFS.

   private void WriteToTFS(String tfsServer,String workItemType,       String project, Hashtable values)   {      TeamFoundationServer teamFoundationServer =         TeamFoundationServerFactory.GetServer(tfsServer);      teamFoundationServer.Authenticate();           WorkItemStore workItemStore = new          WorkItemStore(tfsServer);         Project tfsProject = workItemStore.Projects["DevX"];      WorkItemType wIType =          tfsProject.WorkItemTypes[workItemType];      WorkItem workItem = new WorkItem(wIType);      workItem.Title = values["Title"].ToString();      workItem.Description = values["Description"].ToString();      workItem.State = values["State"].ToString();      workItem.Reason = values["Reason"].ToString();      workItem.Fields["Assigned to"].Value =          values["Assigned To"].ToString();         ArrayList result = workItem.Validate();         if (result.Count > 0)         Response.Write("There was an error adding this work item " +             "to the work item repository");      else             workItem.Save();   }

Here’s an partial example that calls the WriteToTFS method to add a new work item to the work item repository in TFS. Note that it declares several private class-level objects:

   private String tfsServer = "TFSRTM08";   private String[] WorkItemTypeStrings = {"Bug","Risk","Task","Others"};   private enum WorkItemCategory {Bug,Risk,Task,Others};   
Figure 14. New Work Item: The newly added "Bug" work item is highlighted in this figure.
Hashtable values = new Hashtable(); values.Add("Title", "This is a sample bug created using TFS SDK and C#"); values.Add("Description", "This is a sample description"); values.Add("State","Active"); values.Add("Reason", "New"); values.Add("Assigned To", "Administrator"); WriteToTFS("TFSRTM08",WorkItemTypeStrings[ (int)WorkItemCategory.Bug], "DevX",values);

When you execute the preceding code, it creates a new work item of type “Bug.” Figure 14 shows the new work item in TFS:

Retrieving Work Item Details with WIQL
In TFS, work items themselves are complex objects with methods and properties, but you don’t access them directly. Instead, you can use Work Item Query Language (WIQL) to query work item details and retrieve them from the work item repository.

As an example, the following ReadWorkItems method connects to TFS, retrieves project and work item details from the work item repository, and then displays the relevant details.

   public void ReadWorkItems(String tfsServer, int? workItemID)   {      TeamFoundationServer tfs =          TeamFoundationServerFactory.GetServer(tfsServer);      tfs.Authenticate();         WorkItemStore workItemStore = new WorkItemStore(tfsServer);         foreach (Project tfsProject in workItemStore.Projects)      {         WorkItemCollection workItemCollection = workItemStore.Query(             " SELECT [System.Id], [System.WorkItemType],"+             " [System.State], [System.AssignedTo], [System.Title] "+             " FROM WorkItems " +             " WHERE [System.TeamProject] = '" + tfsProject.Name +              "' ORDER BY [System.WorkItemType], [System.Id]");            foreach (WorkItem workItem in workItemCollection)         {            if (workItemID != null)            {               if (workItem.Id == workItemID)               {                  Response.Write("
"+ " Title: "+workItem.Title + "[" + workItem.Type.Name + "]" + " Description:" + workItem.Description); break; } } else Response.Write("WorkItem ID :" + workItem.Id + " Title: " + workItem.Title + "[" + workItem.Type.Name + "]" + " Description: " + workItem.Description); } } } }
Figure 15. Reading a Specific Work Item: Calling the ReadWorkItems method and passing the ID of the “Bug” work item produces this output.

The last parameter of the ReadWorkItems method accepts a nullable int?a WorkItemId. If that parameter is null, the method displays the details of all the work items in the repository; otherwise, it displays the details for the specified work item. So, to get a single work item, you’d call:

   ReadWorkItems(tfsServer, 500); 

Executing the preceding line produces the output shown in Figure 15.

You can also use WIQL to manage work items. The following code snippet illustrates how to display the version history of a particular work item.

   private void DisplayWorkItemHistory(int workItemID)   {    WorkItemStore workItemStore = new WorkItemStore(tfsServer);              WorkItem workItem = workItemStore.GetWorkItem(workItemID);         Response.Write("Status: " +            workItem.Fields["State"].Value.ToString());               foreach (Revision revision in workItem.Revisions)         {           Response.Write("
Changed By: " + revision.Fields[ "Changed By"].Value.ToString()); Response.Write("
Changed Date: " + revision.Fields[ "Changed Date"].Value.ToString()); } }
Figure 16. Work Item History: The figure shows some typical output produced by calling the DisplayWorkItem method and passing a specific work item ID.

Now, you can call the above method to retrieve the work item history details of a particular work item in the work item repository:


Figure 16 shows the output from executing that call.

In this article you’ve seen the basics of how to use the TFS SDK and WIQL to retrieve project information, and create, display and manage work items in the work item repository. You can implement your own application using the using the TFS SDK and the concepts discussed in this article to track work item history details, pending work items, and so forth to help manage your team.

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes

ransomware cyber attack

Why Is Ransomware Such a Major Threat?

One of the most significant cyber threats faced by modern organizations is a ransomware attack. Ransomware attacks have grown in both sophistication and frequency over the past few years, forcing