버전 제어 확장

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 웹 사이트의 다음 페이지를 참조 하십시오: 방법: 사용자 지정 체크 인 정책.

예: 버전 제어 저장소에서 항목에 액세스

다음 샘플 사용 하는 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")

예: 항목을 버전 제어 리포지토리에 추가

파일 및 위치를 사용 하 여 버전 제어에 추가 기능 메서드를 만들 수 있습니다.

경고

코드는 읽고 파일을 체크 하 여 작업 영역에서 사용 권한이 없는 경우 예외가 발생 합니다.이러한 권한은 소스 제어에 대 한 권한이 됩니다 읽기 및 체크 인 에 소스 제어 탐색기.

이 샘플에서는 다음 메서드를 호출 합니다.

  • 프로젝트 컬렉션에서 식별 하는 첫째, Team Foundation Server 를 호출 하 여 [M:Microsoft.TeamFoundation.Client.RegisteredTfsConnections.GetProjectCollection()] 또는 [M:Microsoft.TeamFoundation.Client.RegisteredTfsConnections.GetProjectCollections()].

  • 프로젝트 컬렉션을 확인 한 후 다음 각 팀 프로젝트 컬렉션을 호출한 식별 [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 메서드. 이 예제에서는 개체 모델을 사용 하 여 편집 하 고 기존 파일을 체크 인할 방법을 보여 줍니다. 파일을 만들기 위한 코드 샘플을 수정 하 고 코드이 예제에서는 몇 줄의 코드 예제에서 대체 합니다. 또한이 예제 파일에 사용자 지정 속성을 추가 하는 데 사용할 항목 사양을 소개 합니다.

이 예제를 사용 하려면

  • 만든 C# 콘솔 응용 프로그램을 열고는 Add a File to Version Control 예를 들어, 및 다음 바꾸기 내부 시도 다음 코드 블록:
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 매개 변수는 파일 및 폴더 경로 지정 합니다. 이 경우 저장소에서의 경로 지정 하려면이 매개 변수를 사용할 수 있지만 로컬 경로 지정 합니다. 속성 및 값을 정의할 수도 있습니다.

경고

항목 사양에 대 한 로컬 경로 사용할 때 주의 해야 합니다.또한 저장소에 존재 하지 않는 매핑을 지정 하는 경우 예외가 throw 됩니다.

//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 샘플 및 개체 모델을 사용 하 여 만들고 기존 파일의 분기를 확인 하는 방법을 보여 줍니다. 파일을 만들기 위한 코드 샘플을 수정 하 고 몇 줄의 코드 예제에서는 코드이 예제에서 대체 합니다. 이러한 변경 내용을 적용 한 후 다음 버전 제어에 파일의 분기를 만들 수 있습니다.

이 예제를 사용 하려면

  • 만든 C# 콘솔 응용 프로그램을 열고는 Add a File to Version Control 항목 및 다음 바꾸기 내부 시도 다음 코드 블록:
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);

대신 단순히 파일의 최신 버전을 사용 하 여 분기를 만들 때 버전 사양을 추가할 수 있습니다. 예를 들어, 호출 하면 변경 집합 ID 및 사용자 이름으로 지정할 수 있습니다 PendBranch. 여러 클래스 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 샘플 및 개체 모델을 사용 하 여 폴더를 삭제 하 고 해당 변경 확인 하는 방법을 보여 줍니다. 파일을 만들기 위한 코드 샘플을 수정 하 고 몇 줄의 코드 예제에는 다음 예제로 바꿉니다. 이러한 변경 내용을 적용 한 후 다음 버전 제어에서 폴더를 삭제할 수 있습니다.

이 예제를 사용 하려면

  • 만든 C# 콘솔 응용 프로그램을 열고는 Add a File to Version Control 항목 및 다음 바꾸기 내부 시도 원래 예제는 다음 코드를 차단:
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 확장

기타 리소스

버전 제어 사용