Srikanth
Srikanth

Reputation: 1010

C# Code to check whether the workspace exist on TFS

I am trying to create a automation tool to get latest code from TFS. I need to check whether any workspace with same name exist on system. If exist get the workspace instance. Else create the workspace and mappings.

I found that Microsoft.TeamFoundation.VersionControl.ClientVersionControlServer has method Workspace GetWorkspace(string workspaceName, string workspaceOwner); to get existing workspace. But this will throw exception if workspace not exist on the system.

So please give me a code that checks the existence of workspace and mappings.

At present i have the following code which i know its not correct way

try
{
    //**Expected** an exception  as sometimes the workspace may not exist or Deleted    manually.
    workspace = versionControl.GetWorkspace(workspaceName, versionControl.AuthorizedUser);
    versionControl.DeleteWorkspace(workspaceName, versionControl.AuthorizedUser);
    workspace = null;
}
catch (Exception e)
{
    DialogResult res = MessageBox.Show("There are no workspace mapped. I am creating a new workspace mapped to your local folder named DevFolder.", "Error", MessageBoxButtons.YesNo);

    if (res == DialogResult.No)
    {
        return;
    }
}

if (workspace == null)
{
    var teamProjects = new List<TeamProject>(versionControl.GetAllTeamProjects(false));

    // if there are no team projects in this collection, skip it
    if (teamProjects.Count < 1)
    {
        MessageBox.Show("Please select a team project.");
        return;
    }

    // Create a temporary workspace2.
    workspace = versionControl.CreateWorkspace(workspaceName, versionControl.AuthorizedUser);

    // For this workspace, map a server folder to a local folder              
    ReCreateWorkSpaceMappings(workspace);

    createdWorkspace = true;

}

Upvotes: 4

Views: 3626

Answers (1)

rene
rene

Reputation: 42453

If you don't want to rely on catching an exception you can call QueryWorkspaces

 workspace = versionControl.QueryWorkspaces(
                     workspaceName, 
                     versionControl.AuthorizedUser, 
                     Environment.MachineName).SingleOrDefault();

This code will query for the workspace for a user on the computer this code runs. If the collection is empty it will return null in workspace or it will return the single item in the list. In the case QueryWorkspaces returns more items (seems not possible) it will still throw but that seems OK to me.

Now you can check for the mappings

  if (workspace !=null)
  {
       foreach(var folder in workspace.Folders)
       {
             if (!folder.IsCloaked && folder.LocalItem != "some expected path")
             {
                  // mapping invalid, throw/log?
             }
       }
  }

Upvotes: 5

Related Questions