Connect to TFS using C#

Introduction

In this article we will learn how to connect TFS (Team Foundation Server) or VSO (Visual Studio Online) using C#. We can create console applicatiosn based on TFS API.

Description

Prerequisite

Before starting to work on authenticating TFS using C#, we require TFS Client library reference in project. You can add required libraru using below command in Nuget Package Manger.

Install-Package Microsoft.TeamFoundationServer.Client -Version 14.95.3
Install-Package Microsoft.VisualStudio.Services.Client -Version 14.95.3


After adding reference library you can copy below code in your app and add required reference in project.

Source Code:

  1. NetworkCredential credential = new NetworkCredential("username""password");  
  2. BasicAuthCredential basicCred = new BasicAuthCredential(credential);  
  3.   
  4. TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(  
  5. new Uri("https://project.visualstudio.com/DefaultCollection"),  
  6. basicCred);  
  7.   
  8. tpc.Authenticate();  
As per above code we require valid username and password which is passed to NetworkCredential instance and also requires valid TFS url which you are trying to connect using C#.

We can authenticate user with basic authentication mechanism without prompting for TFS login dialog, that’s why we have passed credential as argument in BasicAuthCredential object without basic authentication mechanism app prompt for login information.

TfsTeamProjectCollection instance acceps two argument 1) Default collection Url 2) Credential with basic authentication wrapper.

TfsTeamProjectCollection instance have authenticate() method which is actually requested for authentication and return results or exceptions based on credential.

Conclusion

In this article we have explored Basic TFS API and authenticated TFS without prompt for username and password.

 

Ebook Download
View all
Learn
View all