2009-12-01 12 views
12

Estoy intentando tirar de la última versión del código fuente de TFS mediante programación utilizando el SDK, y lo que he hecho alguna manera no funciona:¿Cómo se obtiene la última versión del código fuente con Team Foundation Server 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(); 
    } 
} 

El enfoque está creando básicamente un espacio de trabajo temporal, utilizando el método Get() para tomar todos los elementos de este proyecto y luego quitar el espacio de trabajo. ¿Es esta la forma correcta de hacer esto? Cualquier ejemplo sería útil.

Respuesta

5

Su enfoque es válido.

Su error está en la ruta de su proyecto. Use algo como esto en su lugar:

string projectPath = "$/PathToApp/TestApp"; 
1

Estoy de acuerdo con Joerage que la ruta del servidor es probablemente la culpable. Para obtener más información sobre lo que está sucediendo, debe conectar algunos eventos en el objeto VersionControlServer. Como mínimo, querrás obtener, error no fatal y conflicto.

Lista completa: http://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.versioncontrol.client.versioncontrolserver_events(VS.80).aspx

+0

Me disculpo por el retraso en la respuesta, ya que quedó atrapado en un tema diferente, pero cambiando el camino tampoco parecía funcionar. Intenté conectar todos los eventos y ninguno de ellos disparó. Terminé usando una estrategia completamente diferente (item.DownloadFile) y de esa manera parecía funcionar bien, y no se necesitaban espacios de trabajo. –

+0

@JohnRasch, ¿podría compartir el fragmento de código ya que tengo el mismo problema? :( – UserAR

10

que terminó usando un enfoque diferente que parece funcionar, sobre todo teniendo ventaja de la Item.DownloadFile() método:

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; 
    } 
} 
6

he completado e implementado el código en un botón como Web solución asp.net.

Para el proyecto para trabajar en las referencias que debe agregarse el Microsoft.TeamFoundation.Client y Microsoft.TeamFoundation.VersionControl.Client referencias y en el código de las declaraciones using Microsoft.TeamFoundation.Client; y 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; 
      } 
     } 
    } 
0

tuve una situación similar en el que necesitaba para descargar contenidos de 'una 'carpeta de tfs en un espacio de trabajo existente, sin crear un nuevo espacio de trabajo. Con la ayuda de las respuestas anteriores, pude armar algo que funciona bien para mí a partir de ahora. Sin embargo, hay una limitación. Esto funciona para los contenidos de la carpeta 'a' con solo archivos y sin otra carpeta dentro. No lo he intentado. Tal vez eso implicaría algunas actualizaciones menores. Código de uso compartido, por si acaso alguien está buscando esto. Me gusta mucho el hecho de que este enfoque no se relaciona con el área de trabajo [-create and delete], ya que no es deseable.

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; 
       } 
      } 
     } 
    } 
} 

Mientras se ejecuta esto desde la línea de comandos copiar todos los archivos DLL de apoyo, junto con exe cmd >>DownloadFolder.exe "$/<TeamProject>/<FirstLevelFolder>/<SecondLevelFolder>" "C:\MyTempFolder"

Cuestiones relacionadas