How to get the active Team Foundation Server and Project from an Add-In

Ed Hintz posted "How to Write a Team Foundation Version Control Add-in for Visual Studio" which is a great guide to writing an add-in to integrate with Team Foundation version control. I won't repeat that info her. If you want to do something that is related to the active Team Server and/or Project from within a VS Add-In or VSIP package then read on.

First make sure you have a reference to Microsoft.VisualStudio.TeamFoundation - either follow Ed's steps to add them via the REG.EXE commands for convenience or load them using the Browse tab on the Add Reference dialog - in a default installation the assembly will be in "%programfiles%\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblies".

Next add a using clause:

 using Microsoft.VisualStudio.TeamFoundation;

Create a member variable in your Connect class for the TeamFoundationServerExt object:

 private TeamFoundationServerExt _tfsExt; 

In your OnConnection method, initialize the _tfsExt object:

 _tfsExt = _applicationObject.GetObject("Microsoft.VisualStudio.TeamFoundation.TeamFoundationServerExt") as TeamFoundationServerExt;

The TeamFoundationServerExt object exposes two things:

  1. ActiveProjectContext - a

property of type ProjectContextExt which contains the active server and project

ProjectContextChanged - an

event which is fired when the current project and/or server is changed

 public sealed class ProjectContextExt
{
    public string DomainName { get; }
    public string DomainUri { get; }
    public string ProjectName { get; }
    public string ProjectUri { get; }
}

DomainName is the display name of the current server and DomainUri is the actual URI of the current server.  And ProjectName is the display name of the current server and ProjectUri is the Team Project URI.  Note that these values can be null if there is no active server or project.

Your ProjectContextChanged handler should look like this:

 void _tfsExt_ProjectContextChanged(object sender, EventArgs e)
{
}

Within your handler you requery the ActiveProjectContext property of the TeamFoundationServerExt object.