How can I programmatically check-out an item for edit in TFS?

我与影子孤独终老i 提交于 2019-11-30 10:55:17

问题


I'm working on a utility processing files being under source control using TFS 2010.

If an item is not yet checked-out for edit, I'm getting an exception, what is definitely predictable because file is in read-only mode.

What ways exist to check-out a file?

P.S. I want something for programmatic rather then Process.Start("tf.exe", "..."); if that's applicable.


回答1:


Some of the other approaches mentioned here only work for certain versions of TFS or make use of obsolete methods. If you are receiving a 404, the approach you are using is probably not compatible with your server version.

This approach works on 2005, 2008, and 2010. I don't use TFS any longer, so I haven't tested 2013.

var workspaceInfo = Workstation.Current.GetLocalWorkspaceInfo(fileName);
using (var server = new TfsTeamProjectCollection(workspaceInfo.ServerUri))
{
    var workspace = workspaceInfo.GetWorkspace(server);    
    workspace.PendEdit(fileName);
}



回答2:


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

Note that Microsoft.TeamFoundation.Client.TeamFoundationServerFactory is obsolete: The TeamFoundationServer class is obsolete. Use the TeamFoundationProjectCollection or TfsConfigurationServer classes to talk to a 2010 Team Foundation Server. In order to talk to a 2005 or 2008 Team Foundation Server use the TeamFoundationProjectCollection class. The corresponding factory class for that is the TfsTeamProjectCollectionFactory.




回答3:


You can use Team Foundation Version Control client API. The method is PendEdit()

workspace.PendEdit(fileName);

Checkout detailed example on MSDN http://blogs.msdn.com/b/buckh/archive/2006/03/15/552288.aspx




回答4:


First get the workspace

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

With the workspace you can checkout the file

workspace.PendEdit(fileName);



回答5:


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



回答6:


I have two approaches how to do that: simple and advanced.

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). Advanced (with receiving status):

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


来源:https://stackoverflow.com/questions/5097946/how-can-i-programmatically-check-out-an-item-for-edit-in-tfs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!