Tarun Arora

Visual Studio ALM MVP
posts - 58, comments - 187, trackbacks - 0

My Links

News


Tarun Arora is a Microsoft Certified professional developer for Enterprise Applications. He has extensively travelled around the world gaining experience learning and working in culturally diverse teams. Tarun has over 5 years of experience developing 'Energy Trading & Risk Management' solutions for leading Trading & Banking Enterprises. His passion for technology has earned him the Microsoft Community Contributor and Microsoft MVP Award.




View Tarun Arora's profile on LinkedIn

profile for Tarun Arora at Stack Overflow, Q&A for professional and enthusiast programmers

Tag Cloud

Article Categories

Archives

Post Categories

Image Galleries

TFS 2010 SDK: Connecting to TFS 2010 Programmatically–Part 1

 

Download Working Demo

Great! You have reached that point where you would like to extend TFS 2010. The first step is to connect to TFS programmatically.

1. Download TFS 2010 SDK => http://visualstudiogallery.msdn.microsoft.com/25622469-19d8-4959-8e5c-4025d1c9183d?SRC=VSIDE

image

2. Alternatively you can also download this from the visual studio extension manager

image

3. Create a new Windows Forms Application project and add reference to TFS Common and client dlls

Note - If Microsoft.TeamFoundation.Client and Microsoft.TeamFoundation.Common do not appear on the .NET tab of the References dialog box, use the Browse tab to add the assemblies. You can find them at %ProgramFiles%\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0.

using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;

 

image

4. There are several ways to connect to TFS, the two classes of interest are,

Option 1 – Class – TfsTeamProjectCollectionClass
namespace Microsoft.TeamFoundation.Client
{
    public class TfsTeamProjectCollection : TfsConnection
    {
        public TfsTeamProjectCollection(RegisteredProjectCollection projectCollection);
        public TfsTeamProjectCollection(Uri uri);
        public TfsTeamProjectCollection(RegisteredProjectCollection projectCollection, IdentityDescriptor identityToImpersonate);
        public TfsTeamProjectCollection(Uri uri, ICredentials credentials);
        public TfsTeamProjectCollection(Uri uri, ICredentialsProvider credentialsProvider);
        public TfsTeamProjectCollection(Uri uri, IdentityDescriptor identityToImpersonate);
        public TfsTeamProjectCollection(RegisteredProjectCollection projectCollection, ICredentials credentials, ICredentialsProvider credentialsProvider);
        public TfsTeamProjectCollection(Uri uri, ICredentials credentials, ICredentialsProvider credentialsProvider);
        public TfsTeamProjectCollection(RegisteredProjectCollection projectCollection, ICredentials credentials, ICredentialsProvider credentialsProvider, IdentityDescriptor identityToImpersonate);
        public TfsTeamProjectCollection(Uri uri, ICredentials credentials, ICredentialsProvider credentialsProvider, IdentityDescriptor identityToImpersonate);

        public override CatalogNode CatalogNode { get; }
        public TfsConfigurationServer ConfigurationServer { get; internal set; }
        public override string Name { get; }

        public static Uri GetFullyQualifiedUriForName(string name);
        protected override object GetServiceInstance(Type serviceType, object serviceInstance);
        protected override object InitializeTeamFoundationObject(string fullName, object instance);
    }
}
Option 2 – Class – TfsConfigurationServer

namespace Microsoft.TeamFoundation.Client
{
    public class TfsConfigurationServer : TfsConnection
    {
        public TfsConfigurationServer(RegisteredConfigurationServer application);
        public TfsConfigurationServer(Uri uri);
        public TfsConfigurationServer(RegisteredConfigurationServer application, IdentityDescriptor identityToImpersonate);
        public TfsConfigurationServer(Uri uri, ICredentials credentials);
        public TfsConfigurationServer(Uri uri, ICredentialsProvider credentialsProvider);
        public TfsConfigurationServer(Uri uri, IdentityDescriptor identityToImpersonate);
        public TfsConfigurationServer(RegisteredConfigurationServer application, ICredentials credentials, ICredentialsProvider credentialsProvider);
        public TfsConfigurationServer(Uri uri, ICredentials credentials, ICredentialsProvider credentialsProvider);
        public TfsConfigurationServer(RegisteredConfigurationServer application, ICredentials credentials, ICredentialsProvider credentialsProvider, IdentityDescriptor identityToImpersonate);
        public TfsConfigurationServer(Uri uri, ICredentials credentials, ICredentialsProvider credentialsProvider, IdentityDescriptor identityToImpersonate);

        public override CatalogNode CatalogNode { get; }
        public override string Name { get; }

        protected override object GetServiceInstance(Type serviceType, object serviceInstance);
        public TfsTeamProjectCollection GetTeamProjectCollection(Guid collectionId);
        protected override object InitializeTeamFoundationObject(string fullName, object instance);
    }
}

 

Note – The TeamFoundationServer class is obsolete. Use the TfsTeamProjectCollection or TfsConfigurationServer classes to talk to a 2010 Team Foundation Server. In order to talk to a 2005 or 2008 Team Foundation Server use the TfsTeamProjectCollection class.

5. Sample code for programmatically connecting to TFS 2010 using the TFS 2010 API

How do i know what the URI of my TFS server is,

image

image

Note – You need to be have Team Project Collection view details permission in order to connect, expect to receive an authorization failure message if you do not have sufficient permissions.

Case 1: Connect by Uri

string _myUri = @"https://tfs.codeplex.com:443/tfs/tfs30";

TfsConfigurationServer configurationServer =
                TfsConfigurationServerFactory.GetConfigurationServer(new Uri(_myUri));
Case 2: Connect by Uri, prompt for credentials

string _myUri = @"https://tfs.codeplex.com:443/tfs/tfs30";

TfsConfigurationServer configurationServer =
    TfsConfigurationServerFactory.GetConfigurationServer(new Uri(_myUri), new UICredentialsProvider());
configurationServer.EnsureAuthenticated();
Case 3: Connect by Uri, custom credentials

In order to use this method of connectivity you need to implement the interface ICredentailsProvider

    public class ConnectByImplementingCredentialsProvider : ICredentialsProvider
    {
        public ICredentials GetCredentials(Uri uri, ICredentials iCredentials)
        {
            return new NetworkCredential("UserName", "Password", "Domain");
        }

        public void NotifyCredentialsAuthenticated(Uri uri)
        {
            throw new ApplicationException("Unable to authenticate");
        }
    }

And now consume the implementation of the interface,

    string _myUri = @"https://tfs.codeplex.com:443/tfs/tfs30";

    ConnectByImplementingCredentialsProvider connect = new ConnectByImplementingCredentialsProvider();
    ICredentials iCred = new NetworkCredential("UserName", "Password", "Domain");
    connect.GetCredentials(new Uri(_myUri), iCred);
            
    TfsConfigurationServer configurationServer =
                       TfsConfigurationServerFactory.GetConfigurationServer(new Uri(_myUri), connect);
    configurationServer.EnsureAuthenticated();

 

6. Programmatically query TFS 2010 using the TFS SDK for all Team Project Collections and retrieve all Team Projects and output the display name and description of each team project.

CatalogNode catalogNode = configurationServer.CatalogNode;

ReadOnlyCollection<CatalogNode> tpcNodes = catalogNode.QueryChildren(
                new Guid[] { CatalogResourceTypes.ProjectCollection },
                false, CatalogQueryOptions.None);

// tpc = Team Project Collection
foreach (CatalogNode tpcNode in tpcNodes)
{
      Guid tpcId = new Guid(tpcNode.Resource.Properties["InstanceId"]);
      TfsTeamProjectCollection tpc = configurationServer.GetTeamProjectCollection(tpcId);

      // Get catalog of tp = 'Team Projects' for the tpc = 'Team Project Collection'
      var tpNodes = tpcNode.QueryChildren(
                new Guid[] { CatalogResourceTypes.TeamProject },
                false, CatalogQueryOptions.None);

      foreach (var p in tpNodes)
      {
          Debug.Write(Environment.NewLine + " Team Project : " + p.Resource.DisplayName + " - " + p.Resource.Description + Environment.NewLine);
      }
}

 

Output

image

 

You can download a working demo that uses TFS SDK 2010 to programmatically connect to TFS 2010.

Screen Shots of the attached demo application,

image

image

Share this post :
Digg This

Print | posted on Saturday, June 18, 2011 5:05 PM | Filed Under [ TFS2010 ]

Feedback

Gravatar

# re: TFS 2010 SDK: Connecting to TFS 2010 Programmatically–Part 1

Hi Sumit,

This is a very good question. There are several ways to access the TFS notification alerts, you have already listed two of them. I'll tell u the third one for which you will not require to make any changes to the TFS server.

Problem - In my enterprise the TFS server is really locked down and except for certain machine administrators not too many people have access to the server. I needed to hook up to the build notification alerts that are triggered by TFS every time a build is triggered, failed or completed.

Solution - I created a windows service that is installed on a client machine (this service can pretty much be installed any where and just needs to be in the same network as your server but not necessarily the same machine). This service runs under the user identity of an individual that has admin access to the team project collection and read access to the team project i am interested to listen to the alerts for. The service subscribes to the url that tfs publishes the alerts to and is continuously polling this url for any new alerts. As soon as the service receives an alerts it start to execute the business logic i want to run against it. If you are interested to see this in action have a look at tfsdeployer.codeplex.com. The service code is also available for download.

Feel free to touch base if you have further questions.

HTH.
Cheers, Tarun
10/16/2011 6:42 PM | Tarun Arora
Gravatar

# re: TFS 2010 SDK: Connecting to TFS 2010 Programmatically–Part 1

Thanks for such an elaborate response, for now i have got TFS access and i am following this blog post for TFS events
http://www.ewaldhofman.nl/post/2010/08/02/How-to-use-WCF-to-subscribe-to-the-TFS-2010-Event-Service-rolling-up-hours.aspx
10/27/2011 11:46 AM | Sumit
Gravatar

# re: TFS 2010 SDK: Connecting to TFS 2010 Programmatically–Part 1

Can you please let me know how to Log defect in TFS using program
1/15/2012 3:15 PM | Kapil Sharma
Gravatar

# re: TFS 2010 SDK: Connecting to TFS 2010 Programmatically–Part 1

Hi Kapil,

Defects are work items, you want to create bug type work item programmatically. If that is correct, please refer to this link that shows you how to create work items using the TFS object model. http://msdn.microsoft.com/en-us/library/bb130322.aspx

Cheers, Tarun
1/15/2012 3:36 PM | Tarun Arora
Gravatar

# re: TFS 2010 SDK: Connecting to TFS 2010 Programmatically–Part 1

I am not able to connect to TFS2011 preview version using this sample. It fails on EnsureAuthentication method.

I am using the code as below:

ICredentials iCred = new NetworkCredential("windowsliveemail@live.com", "pwd", "Windows Live ID");

Let me know how we connect to TFS 2011 (TFSPreview) using the sample above. Thanks.

2/28/2012 9:30 PM | Pranav
Gravatar

# re: TFS 2010 SDK: Connecting to TFS 2010 Programmatically–Part 1

Simple, descriptive, useful (and even works :)). Thanks!!
2/29/2012 3:19 PM | Mario
Gravatar

# re: TFS 2010 SDK: Connecting to TFS 2010 Programmatically–Part 1

Doesnt work for us... Getting an error:
Message: Team Foundation services are not available from server http://XXXXXX (server uri) (for administrator):
HTTP code 404: Not Found Inner Exception: System.Net.WebException: The remote server returned an error: (404) Not Found.
at System.Net.HttpWebRequest.GetResponse()
at Microsoft.TeamFoundation.Client.TeamFoundationClientProxyBase.AsyncWebRequest.Exec.Request(Object obj)


I am running it on my machine, the uri is correct. I am in the project collection administrators group.
3/15/2012 8:41 PM | Corey
Gravatar

# re: TFS 2010 SDK: Connecting to TFS 2010 Programmatically–Part 1

Hi Corey,

Can you try the following code and see if you are able to connect?

private TfsTeamProjectCollection _tfs;
private string _selectedTeamProject;
private IBuildServer _bs;
private WorkItemStore _wis;

// Connect to TFS and pick team project
private void ConnectToTfsAndPickAProject()
{
TeamProjectPicker tfsPP = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false);
tfsPP.ShowDialog();
this._tfs = tfsPP.SelectedTeamProjectCollection;
this._selectedTeamProject = tfsPP.SelectedProjects[0].Name;
}

Thanks
Tarun
3/16/2012 9:20 AM | Tarun Arora
Gravatar

# re: TFS 2010 SDK: Connecting to TFS 2010 Programmatically–Part 1

Hi Pranav,

You will be able to connect to TFS Preview, simply do the following. Connect using the below code, this will in theory give you a pop up and allow you to specify the details and connect.

private TfsTeamProjectCollection _tfs;
private string _selectedTeamProject;
private IBuildServer _bs;
private WorkItemStore _wis;

// Connect to TFS and pick team project
private void ConnectToTfsAndPickAProject()
{
TeamProjectPicker tfsPP = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false);
tfsPP.ShowDialog();
this._tfs = tfsPP.SelectedTeamProjectCollection;
this._selectedTeamProject = tfsPP.SelectedProjects[0].Name;
}

Once you are connected look at the identity of the user, that should be in the _tfs. <space> i.e. AuthorizedIdentity, Credentials. http://msdn.microsoft.com/en-us/library/ff732550.aspx

Last i tried I had my domain as ClaimsIdentity, username as arora.tarun@hotmail.com. Please let me know if this works for you.

Cheers, Tarun
3/16/2012 9:25 AM | Tarun Arora
Gravatar

# re: TFS 2010 SDK: Connecting to TFS 2010 Programmatically–Part 1

I can't find the .dlls to reference. They're not on the .NET tab or in the folder you referenced above. I'm using VS 2010.
3/19/2012 7:17 PM | Laurie
Gravatar

# re: TFS 2010 SDK: Connecting to TFS 2010 Programmatically–Part 1

The code you posted for Case 3, using custom credentials, will yield unexpected results.

If you are running that code from a machine in the domain, and the user you are logged in as (or are running as) has the proper permissions in TFS, then it will work fine, but a problem arises if you are trying to connect to a TFS server from outside of the domain or say, across a vpn.

Essentially, the credentials provider seems to be ignored, and regardless of the credentials that it returns, you will fail to authenticate.

The easy solution is to not use the factory to get the TfsConfigurationServer, but to call one of the constructors of TfsConfigurationServer directly, ie;

configurationServer = new Microsoft.TeamFoundation.Client.TfsConfigurationServer(new Uri(_myUri), iCred, connect);

This call will use the credentials in iCred and allow you to properly authenticate.




5/3/2012 2:40 PM | Gary
Gravatar

# re: TFS 2010 SDK: Connecting to TFS 2010 Programmatically–Part 1

Hi Tarun,

This really helps but I just have one issue.

Message: Team Foundation services are not available from server http://XXXXXX (server uri) (for administrator):
HTTP code 404: Not Found Inner Exception: System.Net.WebException: The remote server returned an error: (404) Not Found.
at System.Net.HttpWebRequest.GetResponse()
at Microsoft.TeamFoundation.Client.TeamFoundationClientProxyBase.AsyncWebRequest.Exec.Request(Object obj)

Please help!!

Regards
Dinesh
5/15/2012 12:42 PM | Dinesh Kumar Jain N
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: