Connect to TFS using CSharp
Introduction
In this article, we learn how to connect TFS (Team Foundation Server) or VSO (Visual Studio Online) or Azure DevOps using C#(csharp). We can create console application based on TFS API.
Description
Prerequisite
Before starting to working on authenticating TFS using C#, we required TFS Client library reference in the project. You can add the required library using a command in NuGet Package Manager.
You can install the latest version of the Library for the project. I have referenced NuGet package when I have created this article for my demo app.
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 a required reference Namespace in your project.
Source Code:
NetworkCredential credential = new NetworkCredential("username", "password");
BasicAuthCredential basicCred = new BasicAuthCredential(credential);
TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(
new Uri("https://project.visualstudio.com/DefaultCollection"),
basicCred);
tpc.Authenticate();
As per above code, we require valid username and password which is passed to NetworkCredential instance and also require valid TFS URL which you are trying to connect using C#. Here, TFS URI is your project or project collection URI.
For Active directory user, If System or VM is configured with Active Directory user then windows credential can be directly used and no need to store static credential for TFS Project.
We can authenticate a user with basic authentication mechanism without prompting for TFS login dialog, that’s why we have passed credential as an argument in a BasicAuthCredential object. Without basic authentication mechanism app prompt for login information.
You can save this credential on Web.Config file and update code accordingly.
TfsTeamProjectCollection instance accept two arguments 1) Default collection Url 2) Credential with basic authentication wrapper.
TfsTeamProjectCollection instance has authenticate() method which actually requests for authentication and returns result or exception based on the credential.
Exception varies from simple credential error to role, permission, and network related error etc.
Conclusion
In this article, we have explored Basic TFS API and authenticated TFS without prompt for username and password.
Comments
Post a Comment