Connect TFS Azure using API

Many user ask’s how i connect to TFS service using new API’s, here is a sample of TFS connection and getting workitem using TFS API version 11.0.0.0

  • Open VS 2011 and create new C# project.
  • From references right click and choose add reference (Microsoft.TeamFoundation.Client.Microsoft.TeamFoundation.WorkItemTracking.Client)
  • Add this namespaces in top of the class
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
  •  Add below code to connect to TFS collection and show the ‘created by’ field for workitem number 4.
        TfsTeamProjectCollection server;
        WorkItemStore store;

        private void TFSconnect()
        {
            try
            {
                TeamProjectPicker tpp = new TeamProjectPicker(TeamProjectPickerMode.MultiProject, false);
                tpp.ShowDialog();
                if (tpp.SelectedTeamProjectCollection != null)
                {
                    server = tpp.SelectedTeamProjectCollection;
                    server.EnsureAuthenticated();
                    store = server.GetService(typeof(WorkItemStore)) as WorkItemStore;
                    WorkItem _WI = store.GetWorkItem(4);
                    MessageBox.Show(_WI.CreatedBy);
                }

            }
            catch (Exception _ex)
            {
                System.Windows.Forms.MessageBox.Show(_ex.Message);
                throw;
            }
        }

If you want to connect without using ‘TeamProjectPicker’ use this code to get TFS collection

TfsTeamProjectCollection server = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("https://NAME.tfspreview.com/defaultcollection"));

Enjoy 🙂

 

Leave a Reply

Your email address will not be published. Required fields are marked *