How to get TFS server address from a local folder mapped to a workspace

Sometimes you need to operate to a Tfs Version Control System with API starting from a local folder. There are a lot of API to work with workspaces, but the main problem is that you need to pass through a VersionControlServer object, and to obtain such an object you need to know the address of the Tfs server the workspace is mapped to?

The exercise is the following one :) – Write a snippet of code, based on TFS API that, given a local path, retrieve ChangesetId that is currently mapped on the workspace.

The key part is the Workstation class that permits you to obtain a WorkspaceInfo object from a simple Path, thanks to the GetLocalWorkspaceInfo method.

   1: Workstation workstation = Workstation.Current;

   2: WorkspaceInfo info = workstation.GetLocalWorkspaceInfo(path);

Now that you have a workspace info, getting the info you need is really simple, first of all you can know the Team Project Collection address thanks to the ServerUri property of the WorkspaceInfo object, moreover the WorkspaceInfo object can create a valid Workspace object with a simple call to GetWorkspace method, passing a valid TfsTeamProjectCollection object. Here is the code.

   1: TfsTeamProjectCollection collection = new TfsTeamProjectCollection(info.ServerUri);

   2: Workspace ws = info.GetWorkspace(collection);

   3: String servername = ws.GetServerItemForLocalItem(path);

   4: VersionControlServer vcs = collection.GetService<VersionControlServer>();

Now you have both the VersionControlServer object and the Workspace object, and you can use the QueryHistory method to know the information you need.

   1: IEnumerable changesets = null;

   2: VersionSpec spec = VersionSpec.ParseSingleSpec("W", ws.OwnerName);

   3:  

   4: WorkspaceVersionSpec wvs = spec as WorkspaceVersionSpec;

   5: if (null != wvs && null == wvs.Name)

   6: {

   7:     spec = new WorkspaceVersionSpec(ws.Name, ws.OwnerName);

   8: }

   9: changesets = vcs.QueryHistory(servername, VersionSpec.Latest, 0, RecursionType.Full, null,

  10: new ChangesetVersionSpec(1), spec, 1, false, false).OfType<Changeset>().ToList();

  11: int changesetId = changesets.Cast<Changeset>().First().ChangesetId;

And you have the ChangesetId currently mapped to the local folder.

Alk

Published by

Ricci Gian Maria

.Net programmer, User group and community enthusiast, programmer - aspiring architect - and guitar player :). Visual Studio ALM MVP