¿Cómo puedo extraer mediante programación un elemento para editarlo en TFS?


Estoy trabajando en una utilidad procesando archivos bajo control de código fuente usando TFS 2010.

Si un elemento aún no está listo para editar, estoy obteniendo una excepción, lo que es definitivamente predecible porque el archivo está en modo de solo lectura.

¿Qué formas existen de retirar un archivo?

P.D. Quiero algo programático en lugar de Process.Start("tf.exe", "..."); si eso es aplicable.

Author: Zoe, 2011-02-24

6 answers

Algunos de los otros enfoques mencionados aquí solo funcionan para ciertas versiones de TFS o hacen uso de métodos obsoletos. Si está recibiendo un 404, el enfoque que está utilizando probablemente no sea compatible con la versión de su servidor.

Este enfoque funciona en 2005, 2008 y 2010. Ya no uso TFS, así que no he probado 2013.

var workspaceInfo = Workstation.Current.GetLocalWorkspaceInfo(fileName);
using (var server = new TfsTeamProjectCollection(workspaceInfo.ServerUri))
{
    var workspace = workspaceInfo.GetWorkspace(server);    
    workspace.PendEdit(fileName);
}
 35
Author: Ben,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-31 19:35:11
private const string tfsServer = @"http://tfsserver.org:8080/tfs";

public void CheckOutFromTFS(string fileName)
{
    using (TfsTeamProjectCollection pc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(tfsServer)))        
    {
        if (pc != null)
        {
            WorkspaceInfo workspaceInfo = Workstation.Current.GetLocalWorkspaceInfo(fileName);
            if (null != workspaceInfo)
            {                   
                Workspace workspace = workspaceInfo.GetWorkspace(pc);
                workspace.PendEdit(fileName);
            }
        }
    }
    FileInfo fi = new FileInfo(fileName);
}

Tenga en cuenta que Microsoft.TeamFoundation.Client.TeamFoundationServerFactory es obsoleto: La clase TeamFoundationServer es obsoleta. Utilice las clases TeamFoundationProjectCollection o TfsConfigurationServer para hablar con un Servidor Team Foundation 2010. Para hablar con un Servidor Team Foundation de 2005 o 2008 use la clase TeamFoundationProjectCollection. La clase de fábrica correspondiente es TfsTeamProjectCollectionFactory.

 5
Author: wp9omp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-26 17:19:17

Puede utilizar la API de cliente de Control de versiones de Team Foundation. El método es PendEdit ()

workspace.PendEdit(fileName);

Ejemplo detallado de pago en MSDN http://blogs.msdn.com/b/buckh/archive/2006/03/15/552288.aspx

 4
Author: ukhardy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-23 22:27:47

Primero obtenga el espacio de trabajo

var tfs = new TeamFoundationServer("http://server:8080/tfs/collection");
var version = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));
var workspace = version.GetWorkspace("WORKSPACE-NAME", version.AuthorizedUser);

Con el espacio de trabajo puede obtener el archivo

workspace.PendEdit(fileName);
 2
Author: BrunoLM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-27 13:29:36
var registerdCollection = RegisteredTfsConnections.GetProjectCollections().First();
var projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(registerdCollection);
var versionControl = projectCollection.GetService<VersionControlServer>();

var workspaceInfo = Workstation.Current.GetLocalWorkspaceInfo(_fileName);
var server = new TeamFoundationServer(workspaceInfo.ServerUri.ToString());
var workspace = workspaceInfo.GetWorkspace(server);

workspace.PendEdit(fileName);
 1
Author: abatishchev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-27 13:38:42

Tengo dos enfoques para hacer eso: simple y avanzado.

1). Simple:

  #region Check Out
    public bool CheckOut(string path)
    {
        using (TfsTeamProjectCollection pc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(ConstTfsServerUri)))
        {
            if (pc == null) return false;

            WorkspaceInfo workspaceInfo = Workstation.Current.GetLocalWorkspaceInfo(path);
            Workspace workspace = workspaceInfo?.GetWorkspace(pc);
            return workspace?.PendEdit(path, RecursionType.Full) == 1;
        }
    }

    public async Task<bool> CheckoutAsync(string path)
    {
        return await Task.Run(() => CheckOut(path));
    }
    #endregion

2). Avanzado (con estado receptor):

    private static string GetOwnerDisplayName(PendingSet[] pending)
    {
        var result = pending.FirstOrDefault(pendingSet => pendingSet.Computer != Environment.MachineName) ?? pending[0];
        return result.OwnerDisplayName;
    }
    private string CheckoutFileInternal(string[] wsFiles, string folder = null)
    {
        try
        {

            var workspaceInfo = Workstation.Current.GetLocalWorkspaceInfo(folder);
            var server = new TfsTeamProjectCollection(workspaceInfo.ServerUri);
            var workspace = workspaceInfo.GetWorkspace(server);
            var request = new GetRequest(folder, RecursionType.Full, VersionSpec.Latest);
            GetStatus status = workspace.Get(request, GetOptions.None);
            int result = workspace.PendEdit(wsFiles, RecursionType.Full, null, LockLevel.None);
            if (result == wsFiles.Length)
            {
                //TODO: write info (succeed) to log here - messageText
                return null;
            }
            var pending = server.GetService<VersionControlServer>().QueryPendingSets(wsFiles, RecursionType.None, null, null);
            var messageText = "Failed to checkout !.";
            if (pending.Any())
            {
                messageText = string.Format("{0}\nFile is locked by {1}", messageText, GetOwnerDisplayName(pending));
            }

            //TODO: write error to log here - messageText
            return messageText;
        }
        catch (Exception ex)
        {
            UIHelper.Instance.RunOnUiThread(() =>
            {
                MessageBox.Show(Application.Current.MainWindow, string.Format("Failed checking out TFS files : {0}", ex.Message), "Check-out from TFS",
                               MessageBoxButton.OK, MessageBoxImage.Error);
            });
            return null;
        }
    }

    public async Task<string> CheckoutFileInternalAsync(string[] wsFiles, string folder)
    {
        return await Task.Run(() => CheckoutFileInternal(wsFiles, folder));
    }
 0
Author: Mr.B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-04 15:19:11