擴充版本控制的功能

Visual Studio Team Foundation Server 2010 表示 Team Foundation Server結構上的變更。在閱讀本主題的範例程式碼,您應該了解 Team Foundation Server 結構至少有一個非常高的層級上,下列資訊,並應該可以協助您了解 Team 專案和 Team 專案集合的目的是在專案集合中。這個組織變更可以讓您在 Team 專案集合的內容中執行相關項目的控制項作業。

在 Team Foundation Server 2010 的主要組織結構是 Team 專案集合。Team 專案集合是 Team 專案群組的組織結構可用於定義及管理共用資源或程式碼基底專案的群組。這種組織階層架構的優點是 Team 專案的管理變得更有效率,當您將測試分組並指定資源給這些儲存格。因為它們是針對資料庫作業,例如分支或合併程式碼,備份和還原資料和報表專案資訊變得更容易。如需 Team Foundation Server 2010的 Team 專案集合的詳細資訊,請參閱 Organizing Your Server with Team Project Collections

本主題內容

注意事項注意事項

您可以存取並更新項目擴充 Team Foundation 版本控制 在版本控制儲存機制和本機電腦上的工作區對應會建立自訂簽入原則並將它們套用至 Team 專案。藉由使用繼承,則在您原則的實作來取代現有的功能,當套用至版本控制。如需詳細資訊,請參閱 Microsoft 網站上的下列網頁: HOW TO:建立自訂簽入原則.

範例:在版本控制儲存機制中的項目。

下列範例使用物件 VersionControlServer 列出每個 .xaml 檔案每個版本在版本控制儲存機制中。

使用這個範例

  1. 建立主控台應用程式,並加入下列組件的參考:

  2. 在這個範例會取代 Program.cs (或 Module1.vb) 的內容。

using System; 
using System.Text; 
using Microsoft.TeamFoundation.Client; 
using Microsoft.TeamFoundation.Framework; 
using Microsoft.TeamFoundation.VersionControl.Client; 

namespace VCSample
{
    class Program
    {
        static void Main(string[] args) 
        {
            // Connect to the team project collection and the server that hosts the version-control repository. 
            TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(
               new Uri("https://Server:8080/tfs/DefaultCollection"));
            VersionControlServer vcServer = tpc.GetService<VersionControlServer>(); 

            // List all of the .xaml files.
            ItemSet items = vcServer.GetItems("$/*.xaml", RecursionType.Full); 
            foreach(Item item in items.Items) 
            {
                Console.Write(item.ItemType.ToString());
                Console.Write(": ");
                Console.WriteLine(item.ServerItem.ToString());
            }
        }
    }
}
Imports System
Imports System.Text
Imports Microsoft.TeamFoundation.Client
Imports Microsoft.TeamFoundation.VersionControl.Client

Module Module1

    Sub Main()
        ' Connect to the team project collection and the server that hosts the version-control repository.
        Dim tfsUri As Uri
        tfsUri = New Uri("https://Server:8080/tfs/DefaultCollection")

        Dim tpc As New TfsTeamProjectCollection(tfsUri)

        Dim vcServer As VersionControlServer
        vcServer = tpc.GetService(Of VersionControlServer)()

        ' List all of the .xaml files.
        Dim items As ItemSet
        items = vcServer.GetItems("$/*.xaml", RecursionType.Full)
        Dim item As Item
        For Each item In items.Items
            System.Console.Write(item.ItemType.ToString())
            System.Console.Write(": ")
            System.Console.WriteLine(item.ServerItem.ToString())
        Next
    End Sub

End Module

範例:已更新項目在工作區

您可以使用檔案在工作區中執行作業,例如 get 旁邊的簽出和簽入,以程式設計的方式設定屬性。下列範例會在工作區中取得檔案的最新版本。

使用這個範例

  1. 在上述範例中,會尋找清單 .xaml 檔程式碼的一部分,並以下列程式碼取代。

  2. 是使用工作區名稱取代 WorkspaceName ,通常與電腦的工作區域。

  3. 在擁有工作區使用者的完整名稱來取代 使用者名稱 。

如需詳細資訊,請參閱Workstation.GetLocalWorkspaceInfo管理工作區

// Get the workspace that is mapped to c:\BuildProcessTemplate
WorkspaceInfo wsInfo = Workstation.Current.GetLocalWorkspaceInfo(
   vcServer, @"WorkspaceName", @"UserName");
Workspace ws = vcServer.GetWorkspace(wsInfo); 

// Update the workspace with most recent version of the files from the repository.
GetStatus status = ws.Get();
Console.Write("Conflicts: ");
Console.WriteLine(status.NumConflicts);
' Get the workspace that is mapped to c:\BuildProcessTemplate
Dim wsInfo As WorkspaceInfo
wsInfo = Workstation.Current.GetLocalWorkspaceInfo(vcServer, "WorkspaceName", "UserName")
Dim ws As Workspace
ws = vcServer.GetWorkspace(wsInfo)

' Update the workspace with the most recent version of the files from the repository.
Dim status As GetStatus
status = ws.Get
Console.Write("Conflicts: ")
Console.WriteLine(status.NumConflicts)

您也可以取得對應至本機電腦上的資料夾傳遞該資料夾的完整路徑 Workstation.GetLocalWorkspaceInfo的工作區。

WorkspaceInfo wsInfo = Workstation.Current.GetLocalWorkspaceInfo(@"c:\MyWorkspace");
Dim wsInfo As WorkspaceInfo
wsInfo = Workstation.Current.GetLocalWorkspaceInfo("c:\MyWorkspace")

範例:將項目加入至版本控制儲存機制

您可以建立檔案,並將它放在版本控制下使用加入和註冊方法。

注意事項警告

程式碼會擲回例外狀況,如果您在工作區中有讀取並簽入檔案。這些權限是原始檔控制使用 讀取 權限和 簽入 在 [原始檔控制總管] 的。

在這個範例中,您會呼叫下列方法:

  • 首先,您可以呼叫 [M:Microsoft.TeamFoundation.Client.RegisteredTfsConnections.GetProjectCollection()] 或 [M:Microsoft.TeamFoundation.Client.RegisteredTfsConnections.GetProjectCollections()]識別在 Team Foundation Server 專案的專案集合。

  • 在您識別專案集合之後,您可以呼叫 [M:Microsoft.TeamFoundation.Client.TfsConfigurationServer.GetTeamProjectCollection()]然後識別每個 Team 專案集合。

  • 在 Team 專案集合中,您可以呼叫 [M:Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer.GetAllTeamProjects()]識別個別的 Team 專案。

  • 對於每一個 Team 專案,您可以呼叫 [M:Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer.GetWorkspace()] 或 [M:Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer.CreateWorkspace()]取得關聯的工作區,然後將工作區與本機磁碟藉由呼叫 [M:Microsoft.TeamFoundation.VersionControl.Client.Workspace.CreateMapping()]。

  • 若要將檔案複製到本機磁碟,呼叫您工作區的 [M:Microsoft.TeamFoundation.VersionControl.Client.Workspace.Get()] 。

如果您有適當的權限,您可以將檔案加入至版本控制。

使用這個範例

  1. 建立 C# 主控台應用程式,然後加入下列組件的參考:

  2. 以範例程式碼取代 Program.cs 內容。

  3. 變更 Uri 的值加入至應用程式層伺服器的名稱在環境中執行。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;

namespace VControl
{
    class Program
    {
        static void Main(string[] args)
        {
            List<RegisteredProjectCollection> projectCollections;

            if (args.Count() == 0)
            {
                // Try the default URI as the name of a registered project collection.
                projectCollections = new List<RegisteredProjectCollection> { RegisteredTfsConnections.GetProjectCollection(new Uri("https://Server:8080/tfs/DefaultCollection")) };   
            }
            else
            {
                // Get all registered project collections
                projectCollections = new List<RegisteredProjectCollection>(RegisteredTfsConnections.GetProjectCollections());
            }
            
            foreach (var registeredProjectCollection in projectCollections)
            {
                TfsTeamProjectCollection projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(registeredProjectCollection);
                
                Workspace workspace = null;
                Boolean createdWorkspace = false;
                String newFolder = String.Empty;
                try
                {
                    VersionControlServer versionControl = projectCollection.GetService<VersionControlServer>();
                    
                    var teamProjects = new List<TeamProject>(versionControl.GetAllTeamProjects(false));
                    
                    if (teamProjects.Count < 1)
                        continue;
                    String workspaceName = String.Format("{0}-{1}", Environment.MachineName, "Test");
                    try
                    {
                        workspace = versionControl.GetWorkspace(workspaceName, versionControl.AuthorizedUser);
                    }
                    catch (WorkspaceNotFoundException)
                    {
                        workspace = versionControl.CreateWorkspace(workspaceName, versionControl.AuthorizedUser);
                        createdWorkspace = true;
                    }
                    var serverFolder = String.Format("$/{0}", teamProjects[0].Name);
                    var localFolder = Path.Combine(Path.GetTempPath(), "Test");
                    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));
                    }
                    
                    // Get the files from the repository.
                    workspace.Get();

                    // Create a file
                    newFolder = Path.Combine(workspace.Folders[0].LocalItem, "For Test Purposes");
                    Directory.CreateDirectory(newFolder);
                    String newFilename = Path.Combine(newFolder, "Safe To Delete.txt");

                    // Determine whether the user has check-in permissions.
                    if (!workspace.HasCheckInPermission)
                    {
                        throw new SecurityException(
                            String.Format("{0} does not have check-in permission for workspace {1}", workspace.VersionControlServer.AuthorizedUser,
                            workspace.DisplayName));
                    }

                    try
                    {
                        // Create the file.
                        using (var streamWriter = new StreamWriter(newFilename))
                        {
                            streamWriter.WriteLine("Revision 1");
                        }

                        workspace.PendAdd(Path.GetDirectoryName(newFilename), true);

                        //  Create a list of pending changes.
                        var pendingAdds = new List<PendingChange>(workspace.GetPendingChanges());
                        
                        //  Enumerate the pending changes
                        pendingAdds.ForEach(add => Console.WriteLine("\t{0}: {1}", add.LocalItem,
                            PendingChange.GetLocalizedStringForChangeType(add.ChangeType)));
                        
                        // Check in the items that you added.
                        int changesetForAdd = workspace.CheckIn(pendingAdds.ToArray(), "Initial revision");
                        Console.WriteLine("Checked in changeset {0}", changesetForAdd);
                    }
                    catch (IOException ex)
                    {
                        Console.Error.WriteLine("Error writing {1}: {0}", ex.Message, newFilename);
                        throw;
                    }
                    catch (VersionControlException ex)
                    {
                        Console.Error.WriteLine("Error adding file: {0}", ex.Message);
                        throw;
                    }
                }
                finally 
                {
                    if ((workspace != null) && createdWorkspace)
                    {
                        workspace.Delete();
                    }
                    if (!String.IsNullOrEmpty(newFolder) && Directory.Exists(newFolder))
                    {
                        Directory.Delete(newFolder);
                    }
                }
                break;
            }
            
        }
    }
}

範例:編輯項目

您可以使用下列程式碼,您可以修改現有檔案受到版本控制, PendEditCheckIn 呼叫和方法。這個範例顯示如何使用物件模型編輯並簽入現有檔案。您將會修改建立檔案的程式碼範例會在這個範例中的程式碼會取代該範例的某些程式碼。此外,此範例展示項目規格,可以用來將自訂屬性加入至檔案。

使用這個範例

  • 開啟您在 Add a File to Version Control 範例中所建立的 C# 主控台應用程式,然後以下列程式碼取代內部 嘗試。 區塊:
try
{
    // Check out and modify a file.
    workspace.PendEdit(newFilename);

    using (var streamWriter = new StreamWriter(newFilename))
    {
        streamWriter.WriteLine("Revision 2");
    }

    // Get the pending change, and check in the new revision.
    var pendingChanges = workspace.GetPendingChanges();
    int changesetForChange = workspace.CheckIn(pendingChanges, "Modified file contents");
    Console.WriteLine("Checked in changeset {0}", changesetForChange);
}

您可以將屬性設定為您在這個範例中建立的檔案。藉由呼叫 SetVersionedItemProperty 方法,可以將屬性設定為您選取檔案。在此範例中,您將使用 itemSpec 參數所指定檔案的路徑和資料夾。在這個案例中,您會指定本機路徑,不過,您可以在儲存機制中也可以使用這個參數指定路徑。您也會定義一個屬性和其值。

注意事項警告

將項目規格時,使用本機路徑時必須特別小心。擲回例外狀況,如果您指定或不存在於儲存機制的對應。

//Add a custom property to this file.
versionControl.SetVersionedItemProperty( new ItemSpec(“$/proj/Safe To Delete.txt”),VersionSpec.Latest,
    DeletedState.Any, ItemType.File,”MyProperty”, 24);

範例:建立分支

您可以使用下列程式碼,您可以建立現有檔案受到版本控制, PendBranchCheckIn 呼叫和方法。在 Add a File to Version Control 執行這個範例會建置這個範例也會示範如何使用物件模型建立並簽入現有檔案的分支。您可以修改建立檔案的程式碼範例會在這個範例中的程式碼取代該範例的某些程式碼。在套用這些變更之後,您可以建立檔案的分支在版本控制中。

使用這個範例

  • 開啟您在 Add a File to Version Control 主題中建立的 C# 主控台應用程式,然後以下列程式碼取代內部 嘗試。 區塊:
String branchedFilename = Path.Combine(Path.GetDirectoryName(newFilename),
    Path.GetFileNameWithoutExtension(newFilename)) + "-branch" + Path.GetExtension(newFilename);

workspace.PendBranch(newFilename, branchedFilename, VersionSpec.Latest, LockLevel.Checkin, true);

var pendingChanges = workspace.GetPendingChanges();
int changesetForBranch = workspace.CheckIn(pendingChanges, "Branched file");
Console.WriteLine("Branched {0} to {1} in changeset {2}", newFilename, branchedFilename, changesetForBranch);

使用檔案的最新版本時,,,當您建立分支 (而不是您可以將版本規格。例如,在中,當您呼叫 PendBranch時,您可以指定變更集 ID 以及使用者名稱。因為多個類別從 VersionSpec 衍生自類別,您可以使用的版本規格做為參數取得符合一個變更集 ID 或具有特定日期或標記的所有檔案。如需詳細資訊,請參閱 ChangeSetVersionSpecDateVersionSpecLabelVersionSpec

在下列範例中,您會指定變更集 ID 與分支中的檔案。在您進行變更之後,分支中檔案的變更集 ID 符合您所指定的值。

VersionSpec versionSpec = VersionSpec.ParseSingleSpec(changesetId, username);
String branchedFilename = Path.Combine(Path.GetDirectoryName(newFilename),
    Path.GetFileNameWithoutExtension(newFilename)) + "-branch" + Path.GetExtension(newFilename);
// Use the version spec in the method call.
workspace.PendBranch(newFilename, branchedFilename, versionSpec, LockLevel.Checkin, true);

範例:刪除資料夾

您可以使用下列程式碼,即可刪除版本控制的資料夾, PendDeleteCheckIn 呼叫和方法。在 Add a File to Version Control 執行這個範例會建置這個範例也會示範如何使用物件模型刪除資料夾中簽入變更。您可以修改建置的檔案和程式碼範例以下列範例取代該範例的某些程式碼。在套用變更之後,您可以刪除版本控制的資料夾。

使用這個範例

  • 開啟您在 Add a File to Version Control 主題中建立的 C# 主控台應用程式,然後以下列程式碼取代原始範例中的 嘗試。 內部區塊:
try
{
    // Delete the items
    workspace.PendDelete(workspace.GetServerItemForLocalItem(newFolder), RecursionType.Full);
    var pendingDeletes = workspace.GetPendingChanges();

    if (pendingDeletes.Length > 0)
    {
        workspace.CheckIn(pendingDeletes, "Clean up!");
    }
}
catch (VersionControlException ex)
{
    Console.Error.WriteLine("Error deleting file: {0}", ex.Message);
    throw;
}

請參閱

概念

擴充 Team Foundation 的功能

其他資源

使用版本控制