Share via


使用 Team Foundation Version Control API 範例

這幾天在協助客戶轉移 VS 2005 到 TFS 2012 及 與現有系統整合, 大量運用 API 來操作 TFS 的 版本控管, 下列是簡易的範例供參考:

Create Console Application Project

Add Reference

  • Microsoft.TeamFoundation.Client.dll
  • Microsoft.TeamFoundation.Common.dll
  • Microsoft.TeamFoundation.VersionControl.Client.dll
  • Microsoft.TeamFoundation.VersionControl.Common.dll

 

using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;

 

            NetworkCredential myCred = new NetworkCredential("UserName", "Password", "YourDomainName");
            // Connect to the team project collection and the server that hosts the version-control repository.
            TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(
               new Uri("https://127.0.0.1:8080/tfs/dc"), myCred);
            VersionControlServer versionControl = tpc.GetService<VersionControlServer>();

            Workspace workspace = null;
            Boolean createdWorkspace = false;

            String workspaceName = "VSS"; // String.Format("{0}-{1}", Environment.MachineName, assemblyName);

            try
            {
                workspace = versionControl.GetWorkspace(workspaceName,
                                                         versionControl.AuthorizedUser);
            }
            catch (WorkspaceNotFoundException)
             {
                workspace = versionControl.CreateWorkspace(workspaceName,
                                                            versionControl.AuthorizedUser);

                var serverFolder = String.Format("$/{0}", "fabrikamfiber"); // Team Project Name
                var localFolder = "C:\\VSSWork"; //Path.Combine(Path.GetTempPath(), myPath);
                 var workingFolder = new WorkingFolder(serverFolder, localFolder);

                // Create a workspace mapping
                workspace.CreateMapping(workingFolder);

                if (!workspace.HasReadPermission)
                {
                     throw new SecurityException(
                         String.Format("{0} does not have read permission for {1}",
                                      versionControl.AuthorizedUser, serverFolder));
                }

                workspace.Get();

                createdWorkspace = true;
             }

            string fullPath = @"$/fabrikamfiber/Main/src/TFSVersionControl/TFSVersionControl/Properties/AssemblyInfo.cs";

            bool itemExist = versionControl.ServerItemExists(fullPath, ItemType.Any);

            if (itemExist)
             {
                 // Check in 

            }
             else
            {
                // Add items

            }

My Environment is VS 2012 with update 3 + TFS 2012 with upkdate 3

Enjoy.