Search code examples
command-linetfssdkworkspace

How do tf.exe and tfpt.exe establish connections to a TFS instance based on execution directory?


I'm doing some work at the command line using using the TFS object model, and I want to reproduce the workspace-detection bahavior seen in tf.exe and tfpt.exe without introducing artifacts because of my own particular implementation. Currently, my scripts require more information than what tf.exe needs--a significant amount of my parameters are there simply to instantiate the connection.

Specifically, I have to require users to explicitly pass in the server Uri (tfsUriString) and the collection name (tfsCollectionName), but this seems needless and annoying since tf.exe is able to do it.

    Uri tfsUri = new Uri(tfsUriString);
    TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);
    ReadOnlyCollection<CatalogNode> collectionNodes = configurationServer.CatalogNode.QueryChildren( new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None);
    CatalogNode collectionNode = collectionNodes.Where(node => node.Resource.DisplayName == tfsCollectionName).SingleOrDefault();
    Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);
    TfsTeamProjectCollection teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);
    var vcServer = teamProjectCollection.GetService<VersionControlServer>();

What classes and methods can be used to perform this detection in the same way that tf.exe does?


Solution

  • Team Foundation Server clients use a workspace cache that contains all the user's workspaces for each Team Project Collection that they've used from the current machine. tf.exe uses this cache to determine the TfsTeamProjectCollection and Workspace to use for the paths given on the command line.

    You can get the cached WorkspaceInfo for a particular local path by using:

    Workstation.Current.GetLocalWorkspaceInfo(localPath)
    

    Or you can get the entire workspace cache by calling:

    Workstation.Current.GetAllLocalWorkspaceInfo()
    

    The WorkspaceInfo.ServerUri property will contain the server URI you can use to create a TfsTeamProjectCollection with.