Team Foundation Server (TFS)工具的亮点之一是文件的版本控制。在TFS中实现文件版本控制的类型:
Microsoft.TeamFoundation.Client.TfsTeamProjectCollection;
Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer;
Microsoft.TeamFoundation.VersionControl.Client.ItemSet;
Microsoft.TeamFoundation.VersionControl.Client.Workspace;
Microsoft.TeamFoundation.VersionControl.Client.GetStatus;
Microsoft.TeamFoundation.VersionControl.Client.PendingChange;
Microsoft.TeamFoundation.VersionControl.Client.Conflict;
1. 访问TFS服务器。
TfsTeamProjectCollection server = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("https://vstf-cooper.com:8080/tfs/learning")); VersionControlServer controlServer = server.GetService<VersionControlServer>();
2. 获取服务器文件列表。
ItemSet set = controlServer.GetItems(@"$/tfs/path1", VersionSpec.Latest, RecursionType.OneLevel, DeletedState.NonDeleted, ItemType.Folder); foreach (var item in set.Items) { string file = item.ServerItem; }
3. 创建工作区,建立本地映射。工作区文件的影射可以到非常小的子集,如服务器有很多文件夹结点,用户只想更新一个文件夹下文件,则可以直接映射到待更新文件的父文件夹。
Workspace tfsWSpace = controlServer.CreateWorkspace("MyWorkSpace", @"cooper"); tfsWSpace.Map(@"$/tfs/", @"c:\myTFS");
4. 检测服务器文件是否存在。
bool isSourceExist = controlServer.ServerItemExists("$/tfs/path1", ItemType.Folder);
5. 删除服务器上某路径下的文件。
// check if destination folder exist, if yes, delete existing folder first bool isFolderExist = controlServer.ServerItemExists("$/tfs/path1", ItemType.Folder); if (isFolderExist) { // download server files to local GetStatus status = tfsWSpace.Get(new string[] { "$/tfs/path1"}, VersionSpec.Latest, RecursionType.Full, GetOptions.Overwrite); // delete server files, deleting requires the files exist in local first int toDelete = tfsWSpace.PendDelete(item.TargetPath, RecursionType.Full); if (toDelete > 0) { // get pending items in current work space PendingChange[] pendings = tfsWSpace.GetPendingChanges(); if (pendings.Length > 0) { Conflict[] conflicts = tfsWSpace.QueryConflicts(new string[] { "$/tfs/path1" }, true); foreach (Conflict conflict in conflicts) { conflict.Resolution = Resolution.AcceptMerge; tfsWSpace.ResolveConflict(conflict); } // checkin pending changes, return the changeset number as int32 int changeSetNumber = tfsWSpace.CheckIn(tfsWSpace.GetPendingChanges(), "Tool:Delete existing folder and preparing for branch"); } } }
6. 添加新文件。首先确保本地文件存在。
// add local files to server, return the total number added int totalAddFolders = tfsWSpace.PendAdd(@"c:\myTFS\path1\newFolder"); tfsWSpace.CheckIn(tfsWSpace.GetPendingChanges(), "Tool:Add Folder");
7. 分支文件。分支文件,若是文件夹到文件夹,则目标文件夹必须不存在,其父文件夹必须存在。
//Branch items from Developement to Publication int changeSetID = controlServer.CreateBranch("$/tfs/path1/original", "$/tfs/path1/target", VersionSpec.Latest); Changeset changeSet = controlServer.GetChangeset(changeSetID); changeSet.Comment = "Tool:Branch from original to target."; changeSet.Update();