Как получить последнюю версию исходного кода с помощью Team Foundation Server SDK?

Я пытаюсь вытащить последнюю версию исходного кода из TFS программно с помощью SDK, и то, что я сделал, почему-то не работает:

string workspaceName = "MyWorkspace";
string projectPath = "/TestApp";
string workingDirectory = "C:\Projects\Test\TestApp";

VersionControlServer sourceControl; // actually instantiated before this method...

Workspace[] workspaces = sourceControl.QueryWorkspaces(workspaceName, sourceControl.AuthenticatedUser, Workstation.Current.Name);
if (workspaces.Length > 0)
{
    sourceControl.DeleteWorkspace(workspaceName, sourceControl.AuthenticatedUser);
}
Workspace workspace = sourceControl.CreateWorkspace(workspaceName, sourceControl.AuthenticatedUser, "Temporary Workspace");
try
{
    workspace.Map(projectPath, workingDirectory);
    GetRequest request = new GetRequest(new ItemSpec(projectPath, RecursionType.Full), VersionSpec.Latest);
    GetStatus status = workspace.Get(request, GetOptions.GetAll | GetOptions.Overwrite); // this line doesn't do anything - no failures or errors
}
finally
{
    if (workspace != null)
    {
        workspace.Delete();
    }
}

Подход в основном заключается в создании временной рабочей области, использовании метода Get() для захвата всех элементов для этого проекта, а затем удалении рабочей области. Это правильный способ сделать это? Любые примеры будут полезны.


person John Rasch    schedule 01.12.2009    source источник


Ответы (5)


В итоге я использовал другой подход, который, кажется, работает, в основном используя преимущества Item.DownloadFile() метод:

VersionControlServer sourceControl; // actually instantiated...

ItemSet items = sourceControl.GetItems(sourcePath, VersionSpec.Latest, RecursionType.Full);

foreach (Item item in items.Items)
{
    // build relative path
    string relativePath = BuildRelativePath(sourcePath, item.ServerItem);

    switch (item.ItemType)
    {
    case ItemType.Any:
        throw new ArgumentOutOfRangeException("ItemType returned was Any; expected File or Folder.");
    case ItemType.File:
        item.DownloadFile(Path.Combine(targetPath, relativePath));
        break;
    case ItemType.Folder:
        Directory.CreateDirectory(Path.Combine(targetPath, relativePath));
        break;
    }
}
person John Rasch    schedule 09.12.2009

Я завершил и внедрил код в кнопку как веб-решение asp.net.

Для работы проекта в референсы нужно добавить референсы Microsoft.TeamFoundation.Client и Microsoft.TeamFoundation.VersionControl.Client а в код операторы using Microsoft.TeamFoundation.Client; и using Microsoft.TeamFoundation.VersionControl.Client;

    protected void Button1_Click(object sender, EventArgs e)
    {
        string workspaceName = "MyWorkspace";
        string projectPath = @"$/TeamProject"; // the container Project (like a tabel in sql/ or like a folder) containing the projects sources in a collection (like a database in sql/ or also like a folder) from TFS

        string workingDirectory = @"D:\New1";  // local folder where to save projects sources

        TeamFoundationServer tfs = new TeamFoundationServer("http://test-server:8080/tfs/CollectionName", System.Net.CredentialCache.DefaultCredentials);
                                                            // tfs server url including the  Collection Name --  CollectionName as the existing name of the collection from the tfs server 
        tfs.EnsureAuthenticated(); 

        VersionControlServer sourceControl = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));

        Workspace[] workspaces = sourceControl.QueryWorkspaces(workspaceName, sourceControl.AuthenticatedUser, Workstation.Current.Name);
        if (workspaces.Length > 0)
        {
            sourceControl.DeleteWorkspace(workspaceName, sourceControl.AuthenticatedUser);
        }
        Workspace workspace = sourceControl.CreateWorkspace(workspaceName, sourceControl.AuthenticatedUser, "Temporary Workspace");
        try
        {
            workspace.Map(projectPath, workingDirectory);
            GetRequest request = new GetRequest(new ItemSpec(projectPath, RecursionType.Full), VersionSpec.Latest);
            GetStatus status = workspace.Get(request, GetOptions.GetAll | GetOptions.Overwrite); // this line doesn't do anything - no failures or errors
        }
        finally
        {
            if (workspace != null)
            {
                workspace.Delete();
                Label1.Text = "The Projects have been brought into the Folder  " + workingDirectory;
            }
        }
    }
person Stefan    schedule 22.07.2011

Ваш подход действителен.

Ваша ошибка в вашем пути к проекту. Вместо этого используйте что-то вроде этого:

string projectPath = "$/PathToApp/TestApp";
person joerage    schedule 02.12.2009

Я согласен с Джоэреджем, что ваш путь к серверу, вероятно, является виновником. Чтобы лучше понять, что происходит, вам нужно подключить некоторые события к объекту VersionControlServer. Как минимум вам понадобятся Getting, NonFatalError и Conflict.

Полный список: http://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.versioncontrol.client.versioncontrolserver_events(VS.80).aspx

person Richard Berg    schedule 02.12.2009
comment
Приношу извинения за задержку с ответом, так как увяз в другой проблеме, но смена пути тоже не сработала. Я попытался подключить все события, и ни одно из них не сработало. В итоге я использовал совершенно другую стратегию (item.DownloadFile), и этот способ, казалось, работал нормально — и никаких рабочих пространств не требовалось. - person John Rasch; 09.12.2009
comment
@JohnRasch, не могли бы вы поделиться фрагментом кода, поскольку я столкнулся с той же проблемой?!! :( - person UserAR; 09.09.2015

У меня была аналогичная ситуация, когда мне нужно было загрузить содержимое папки «a» из tfs в существующую рабочую область без создания новой рабочей области. С помощью приведенных выше ответов я смог собрать что-то, что отлично работает для меня на данный момент. Однако есть ограничение. Это работает для содержимого папки «a», содержащей только файлы, а не другую папку внутри нее - я этого не пробовал. Возможно, это потребует некоторых незначительных обновлений. Делюсь кодом, на всякий случай, если кто-то ищет это. Мне очень нравится тот факт, что этот подход не касается рабочей области [-создать и удалить], так как это нежелательно.

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

namespace DownloadFolder
{
    class Program
    {
        static void Main(string[] args)
        {
            string teamProjectCollectionUrl = "http://<YourTFSUrl>:8080/tfs/DefaultCollection";  // Get the version control server
            TfsTeamProjectCollection teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(teamProjectCollectionUrl));
            VersionControlServer vcs = teamProjectCollection.GetService<VersionControlServer>();
            String Sourcepath = args[0]; // The folder path in TFS - "$/<TeamProject>/<FirstLevelFolder>/<SecondLevelFolder>"
            String DestinationPath = args[1]; //The folder in local machine - "C:\MyTempFolder"
            ItemSet items = vcs.GetItems(Sourcepath, VersionSpec.Latest, RecursionType.Full);
            String FolderName = null;
            foreach (Item item in items.Items)
            {
                String ItemName = Path.GetFileName(item.ServerItem);
                switch (item.ItemType)
                {
                    case ItemType.File:                        
                        item.DownloadFile(Path.Combine(DestinationPath, FolderName, ItemName));
                        break;
                    case ItemType.Folder:
                        FolderName = Path.GetFileName(item.ServerItem);
                        Directory.CreateDirectory(Path.Combine(DestinationPath, ItemName));
                        break;
                }
            }
        }
    }
}

При запуске этого из командной строки скопируйте все поддерживающие библиотеки DLL вместе с exe cmd>> DownloadFolder.exe "$/<TeamProject>/<FirstLevelFolder>/<SecondLevelFolder>" "C:\MyTempFolder"

person Sourav Kundu    schedule 20.09.2016