C# Code to check whether the workspace exist on TFS

谁说胖子不能爱 提交于 2019-12-10 07:35:53

问题


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;

}

回答1:


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?
             }
       }
  }


来源:https://stackoverflow.com/questions/21749968/c-sharp-code-to-check-whether-the-workspace-exist-on-tfs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!