バージョン管理の拡張

Visual Studio Team Foundation Server 2010 は Team Foundation Serverアーキテクチャを変更することです。このトピックのサンプル コードを読み取る前に、非常に上位レベルで Team Foundation Server のアーキテクチャを理解し少なくとも次の情報は、プロジェクトのコレクション チーム内のプロジェクトおよびプロジェクト コレクション チームの目的を理解するのに役立ちます必要があります。この組織の変更は、回収チーム プロジェクトで関連する品目の制御操作を行うことができます。

Team Foundation Server 2010 の基本組織構造はプロジェクト チーム集合です。プロジェクト コレクション チームは組織構造にリソースまたはコード基準を共有するプロジェクト グループを定義および管理に使用できるのプロジェクト チームのグループです。組織階層のこの型のメリットは、それらをグループ化し、それらのリソースを割り当てると、プロジェクト チームの管理が有効であることです。コードの分岐または結合および、バックアップし、データを復元し、プロジェクト情報をレポートするなどの操作はデータベースに固有であるため、容易になります。Team Foundation Server 2010チーム プロジェクト グループに関する詳細については、Organizing Your Server with Team Project Collectionsを参照してください。

このトピックの内容

[!メモ]

バージョン管理リポジトリとローカル コンピュータのワークスペースの品目を注文とアクセスのチェック ポリシーを作成し、チーム プロジェクトに適用する更新すると、Team Foundation バージョン管理 を拡張できます。その継承使用して、バージョン管理に適用するときにポリシーに独自の実施と既存の機能を置き換えます。詳細については、Microsoft の Web サイトの次のページを参照してください: 方法: 注文のチェックイン ポリシーを作成します。

例: バージョン管理リポジトリの品目のアクセス

次のサンプルは、バージョン管理リポジトリの各 .xaml のファイルのすべてのバージョンの一覧に VersionControlServer のオブジェクトを使用します。

この例を使用します。

  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

例: ワークスペースの更新の品目

ワークスペースのファイルを工程などの実行によって取得し、チェック アウト、プログラムでチェックインに使用できます。次の例では、ワークスペースのファイルの最新バージョンが表示されます。

この例を使用します。

  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")

例: バージョン管理) への品目の追加

ファイルを作成して、それを使用して、バージョン管理の下に設定する方法を、小切手追加します。

Caution メモ注意

コードを読み取るワークスペースのアクセス許可が必要です。投げ、ファイルのチェックインを例外。このアクセス許可は、[ソース管理エクスプローラー]の [閲覧] ソースと [チェックイン] の管理のアクセス許可があります。

このサンプルで、次の方法:置

  • 最初に、[M:Microsoft.TeamFoundation.Client.RegisteredTfsConnections.GetProjectCollection()] または [M:Microsoft.TeamFoundation.Client.RegisteredTfsConnections.GetProjectCollections()]の呼び出し、Team Foundation Server のプロジェクトのコレクションを識別します。

  • プロジェクトのコレクションを識別した後、[M:Microsoft.TeamFoundation.Client.TfsConfigurationServer.GetTeamProjectCollection()]の呼び出し、各チーム プロジェクト グループを識別します。

  • プロジェクト コレクション チーム内では、[M:Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer.GetAllTeamProjects()]の呼び出し、個々のチーム プロジェクトを識別します。

  • 各チーム プロジェクトの場合、[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;
            }
            
        }
    }
}

例: 品目の編集

バージョン管理で PendEdit と CheckIn 方法を追加する次のコードを使用して、既存のファイルを変更できます。この例では、編集するにオブジェクト モデルを使用する方法に表示され、既存のファイルのチェックイン。ファイルを作成するためのサンプル コードを変更し、この例のコードとその例であるコード行を置き換えます。また、このしては、ファイルにカスタム プロパティを追加するために使用する品目の詳細を与えます。

この例を使用します。

  • Add a File to Version Control の例で作成した開き、次のコードと内部 [try] のブロックを置き換えます、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 のパラメータが使用されます。この場合) にパスを指定するには、このパラメータを使用すると、保管場所のパスを指定します。ものプロパティと値を定義します。

Caution メモ注意

品目の詳細に対して保管場所のパスを使用する場合は深くなければ必要があります。例外もリポジトリにないマッピングを指定します投げられます。

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

例: 分岐の作成

バージョン管理で PendBranch と CheckIn 方法を追加する次のコードを使用して、既存のファイルを分岐できます。この例では、Add a File to Version Control のサンプルで作成するに基づいて、オブジェクト モデルを使用する方法を表示し、既存のファイルの分岐をチェックイン。ファイルを作成するためのサンプル コードを変更する場合は、この例のコードとその例であるコード行を置き換えることができます。これらの変更を追加した後、バージョン管理のファイルの分岐を作成できます。

この例を使用します。

  • Add a File to Version Control のトピックで作成した開き、次のコードと内部 [try] のブロックを置き換えます、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 に一致するか、日付やラベルを持つすべてのファイルを確認するには、バージョンの仕様を使用できます。詳細については、「ChangeSetVersionSpec」、「DateVersionSpec」、または「LabelVersionSpec」を参照してください。

次の例では、支店ファイルに関連付けるために変更セット 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);

例: フォルダの削除

PendDelete と CheckIn 方法を追加する次のコードを使用して、バージョン管理からフォルダを削除できます。この例では、Add a File to Version Control 個に基づいて、フォルダを削除するにオブジェクト モデルを使用する方法が表示され、その変更をチェックイン。ファイルを作成するためのサンプル コードを変更し、次の例とその例であるコード行を置き換えることができます。これらの変更を追加した後、バージョン管理からフォルダを削除できます。

この例を使用します。

  • Add a File to Version Control のトピックで作成した開き、次のコードと元の例の内部 [try] のブロックを置き換えます、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 の拡張

その他の技術情報

バージョン管理の使用