public GetStatus Get(GetRequest request, GetOptions options, GetFilterCallback filterCallback, object userData) { GetRequest[] requests = new GetRequest[1]; requests[0] = request; return(Get(requests, options, filterCallback, userData)); }
private IDisposable TrackProgress(ISolutionProjectModel projectViewModel, out GetFilterCallback filterCallback, CancellationToken cancellationToken = default(CancellationToken)) { filterCallback = (workspace, operations, data) => {}; if (cancellationToken.IsCancellationRequested || projectViewModel == null) { return(new DisposableCookie(() => { })); } double total = 0; double progress = 0; var server = tfsContext.VersionControlServer; projectViewModel.ResetProgress(); filterCallback = (workspace, operations, data) => { if (cancellationToken.IsCancellationRequested) { return; } total = operations.Length + 4; }; var projectBaseServerPath = Path.GetDirectoryName(projectViewModel.ServerItem).Replace(@"\", "/"); GettingEventHandler handler = (sender, e) => { var model = projectViewModel; if (cancellationToken.IsCancellationRequested) { return; } if (e.SourceServerItem == projectBaseServerPath || e.SourceServerItem.StartsWith(projectBaseServerPath)) { model.CurrentOperation?.SetProgress(total, (++progress)); Output.WriteLine(e.Status + " " + e.ServerItem); } }; cancellationToken.Register(() => server.Getting -= handler); server.Getting += handler; return(new DisposableCookie(() => { server.Getting -= handler; })); }
public GetFilterCallback GetFilterCallback( Dictionary <StatTypes, int> filterStats, CancellationToken token) { var fc = new GetFilterCallback((workspace, operations, userData) => { if (token.IsCancellationRequested) { foreach (var o in operations) { o.Ignore = true; } return; } var spec = userData as ItemSpec; $"TFS filter callback: workspace name = {workspace.Name} | spec.item = {spec?.Item} | number of operations {operations.Length}".Trace(); foreach (var operation in operations) { if ( operation.TargetServerItem != null && Constants.Exclusions.Any(s1 => operation.TargetServerItem.ToLowerInvariant().Contains(s1)) && !Constants.Exceptions.Any(s2 => operation.TargetServerItem.ToLowerInvariant().Contains(s2))) { operation.Ignore = true; filterStats[StatTypes.Skipped]++; } if ( operation.SourceLocalItem != null && File.Exists(operation.SourceLocalItem) && (DateTime.UtcNow - File.GetLastWriteTimeUtc(operation.SourceLocalItem) < Constants.MaxTfsItemAge) ) { filterStats[StatTypes.Skipped]++; operation.Ignore = true; } if (operation.TargetLocalItem == null) { filterStats[StatTypes.Deleted]++; } filterStats[StatTypes.Added]++; } }); return(fc); }
public GetStatus Get(GetRequest[] requests, GetOptions options, GetFilterCallback filterCallback, object userData) { bool force = ((GetOptions.Overwrite & options) == GetOptions.Overwrite); bool noGet = false; // not implemented below: ((GetOptions.Preview & options) == GetOptions.Preview); SortedList<int, DateTime> changesetDates = new SortedList<int, DateTime>(); GetOperation[] getOperations = Repository.Get(Name, OwnerName, requests, force, noGet); if (null != filterCallback) filterCallback(this, getOperations, userData); UpdateLocalVersionQueue updates = new UpdateLocalVersionQueue(this); foreach (GetOperation getOperation in getOperations) { string uPath = null; GettingEventArgs args = new GettingEventArgs(this, getOperation); // Console.WriteLine(getOperation.ToString()); if (getOperation.DeletionId != 0) { if ((getOperation.ItemType == ItemType.Folder)&& (Directory.Exists(getOperation.SourceLocalItem))) { UnsetDirectoryAttributes(getOperation.SourceLocalItem); Directory.Delete(getOperation.SourceLocalItem, true); } else if ((getOperation.ItemType == ItemType.File)&& (File.Exists(getOperation.SourceLocalItem))) { UnsetFileAttributes(getOperation.SourceLocalItem); File.Delete(getOperation.SourceLocalItem); } } else if ((!String.IsNullOrEmpty(getOperation.TargetLocalItem))&& (!String.IsNullOrEmpty(getOperation.SourceLocalItem))&& (getOperation.SourceLocalItem != getOperation.TargetLocalItem)) { uPath = getOperation.TargetLocalItem; try { File.Move(getOperation.SourceLocalItem, getOperation.TargetLocalItem); } catch (IOException) { args.Status = OperationStatus.TargetIsDirectory; } } else if (getOperation.ChangeType == ChangeType.None && getOperation.VersionServer != 0) { uPath = getOperation.TargetLocalItem; string directory = uPath; if (getOperation.ItemType == ItemType.File) directory = Path.GetDirectoryName(uPath); if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); if (getOperation.ItemType == ItemType.File) { DownloadFile.WriteTo(uPath, Repository, getOperation.ArtifactUri); // ChangesetMtimes functionality : none standard! if (mTimeSetting) { int cid = getOperation.VersionServer; DateTime modDate; if (!changesetDates.TryGetValue(cid, out modDate)) { Changeset changeset = VersionControlServer.GetChangeset(cid); modDate = changeset.CreationDate; changesetDates.Add(cid, modDate); } File.SetLastWriteTime(uPath, modDate); } // do this after setting the last write time! SetFileAttributes(uPath); } } versionControlServer.OnDownloading(args); updates.QueueUpdate(getOperation.ItemId, uPath, getOperation.VersionServer); } updates.Flush(); return new GetStatus(getOperations.Length); }
public GetStatus Get(GetRequest request, GetOptions options, GetFilterCallback filterCallback, object userData) { GetRequest[] requests = new GetRequest[1]; requests[0] = request; return Get(requests, options, filterCallback, userData); }
private void DoFullGet() { try { #if DEBUG Thread.Sleep(5000); #endif Configuration = new Config(); Configuration.Init(); var cts = new CancellationTokenSource(); $"Get info for all TPCs and all projects".Info(); var sw = new Stopwatch(); sw.Start(); var lpc = GetTeamProjectCollections().AsParallel(); Func <TfsTeamProjectCollection, string> workspaceName = projColl => { var str = $"{Guid.NewGuid()}_{projColl.GetProjectCollectionName()}"; $"workspaceName: {str}".Trace(); return(str); }; Func <VersionControlServer, string, Workspace> createWorkSpace = (vcs, wsName) => { try { if (vcs.DeleteWorkspace(wsName, vcs.AuthorizedUser)) { // TODO log } } catch (Exception e) { $"createWorkspace: {e.Message}".Error(); } try { var options = new CreateWorkspaceParameters(wsName) { WorkspaceOptions = WorkspaceOptions.None, OwnerName = vcs.AuthorizedUser, Location = WorkspaceLocation.Server }; var workSpace = vcs.CreateWorkspace(options); $"Workspace created: {workSpace.Name}".Trace(); return(workSpace); } catch (Exception e) { $"createWorkspace: {e.Message}".Error(); throw; } }; Action <TfsTeamProjectCollection> dropWorkspaces = collection => { try { var vcs = collection.GetService <VersionControlServer>(); var wss = vcs.QueryWorkspaces(null, vcs.AuthorizedUser, Environment.MachineName); foreach (var workspace in wss) { if (!workspace.Delete()) { $"Failed to delete {workspace.Name}".Error(); } else { $"Deleted {workspace.Name}".Info(); } } } catch (Exception e) { e.Error(); throw; } }; Action <TfsTeamProjectCollection> dropMappings = (collection) => { try { var vcs = collection.GetService <VersionControlServer>(); var wss = vcs.QueryWorkspaces(null, vcs.AuthorizedUser, null); var localPath = collection.GetProjectCollectionLocalPath(Globals.TfsRoot); var withPath = wss.Select(workspace => Tuple.Create(workspace, workspace.TryGetWorkingFolderForServerItem(collection.Uri.AbsoluteUri))); foreach (var tuple in withPath) { if (tuple.Item1 != null && tuple.Item2 != null) { $"Dropping {tuple.Item2.LocalItem} for workspace {tuple.Item1.Name}".Info(); tuple.Item1.DeleteMapping(tuple.Item2); } } } catch (Exception e) { e.Error(); } }; Func <Workspace, TfsTeamProjectCollection, Workspace> mapWorkspace = (ws, pc) => { try { var serverPath = "$/"; var localPath = pc.GetProjectCollectionLocalPath(Globals.TfsRoot); $"mapWorkspace: {nameof(serverPath)} = {serverPath}".Trace(); $"mapWorkspace: {nameof(localPath)} = {localPath}".Trace(); var vcs = pc.GetService <VersionControlServer>(); var lws = Workstation.Current.RemoveCachedWorkspaceInfo(vcs); var wss = vcs.QueryWorkspaces(null, vcs.AuthorizedUser, null); foreach (var workspace in wss) { $"Checking workspace {workspace.Name} for mapping of local path {localPath}".Info(); if (workspace.IsLocalPathMapped(localPath)) { var wf = workspace.TryGetWorkingFolderForLocalItem(localPath); workspace.DeleteMapping(wf); $"Deleted {localPath} mapping from workspace {workspace.Name}".Info(); } } ws.Map(serverPath, localPath); return(ws); } catch (Exception e) { e.Error(); } return(null); }; // get the workspaces for this user on this machine and their working folders, if any, for the project collection they belong to var pcsAndAllTheirWorkspaces = from pc in lpc.AsParallel() let vcs = pc.GetService <VersionControlServer>() let localPath = pc.GetProjectCollectionLocalPath(Globals.TfsRoot) select new { LocalPath = localPath, VersionControlServer = vcs, ProjectCollection = pc, WorkspaceAndWorkingFolderList = vcs .QueryWorkspaces(null, vcs.AuthorizedUser, null) .Where(workspace => workspace.Computer.Equals(Environment.MachineName, StringComparison.OrdinalIgnoreCase)) .Select(workspace => Tuple.Create(workspace, workspace.TryGetWorkingFolderForLocalItem(localPath))) }; $"{nameof(pcsAndAllTheirWorkspaces)}: {string.Join(",", pcsAndAllTheirWorkspaces.Select(arg => arg.LocalPath))}".Trace(); $"{nameof(pcsAndAllTheirWorkspaces)}: {string.Join(",", pcsAndAllTheirWorkspaces.Select(arg => arg.WorkspaceAndWorkingFolderList.Count()))}".Trace(); // select the relevant information from the above gross and create workspace and mapping where necessary var pcsAndMappedWorkspaces = from a in pcsAndAllTheirWorkspaces let workspaceAndFolder = a.WorkspaceAndWorkingFolderList.SingleOrDefault(tuple => tuple.Item2 != null) let name = workspaceAndFolder?.Item1.Name ?? workspaceName(a.ProjectCollection) let workspace = workspaceAndFolder?.Item1 ?? mapWorkspace(createWorkSpace(a.VersionControlServer, name), a.ProjectCollection) let workingFolder = workspaceAndFolder?.Item2 ?? workspace.TryGetWorkingFolderForLocalItem(a.LocalPath) select new { a.ProjectCollection, a.VersionControlServer, Workspace = workspace, WorkingFolder = workingFolder }; $"{nameof(pcsAndMappedWorkspaces)}: {string.Join(",", pcsAndMappedWorkspaces.Select(arg => arg.WorkingFolder.LocalItem))}".Trace(); var allProjects = from p in pcsAndMappedWorkspaces from pp in p.ProjectCollection.GetTeamProjects() let sp = pp.GetProjectServerPath(p.ProjectCollection) let wf = p.Workspace.TryGetWorkingFolderForServerItem(sp) where wf.LocalItem.ToLowerInvariant().Contains(Configuration.SourceRoot.ToLowerInvariant()) select new { ProjectCollection = p, Project = pp, LocalPath = pp.GetProjectLocalPath(p.ProjectCollection), ServerPath = sp, WorkspaceInfo = p.Workspace, WorkingFolder = wf }; $"{nameof(allProjects)}: {string.Join(",", allProjects.Select(arg => arg.LocalPath))}".Trace(); var filterStats = new Dictionary <StatTypes, int> { [StatTypes.Added] = 0, [StatTypes.Deleted] = 0, [StatTypes.Ignored] = 0, [StatTypes.Skipped] = 0 }; string[] exceptions = { @"vnext", @"-oem" }; string[] exclusions = { @"/development/", @"/release/", @"/team/" }; var maxAge = TimeSpan.FromHours(6.0); var fc = new GetFilterCallback((Workspace workspace, ILocalUpdateOperation[] operations, object userData) => { var spec = userData as ItemSpec; $"TFS filter callback: workspace name = {workspace.Name} | spec.item = {spec.Item} | number of operations {operations.Length}".Trace(); foreach (var operation in operations) { if ( operation.TargetServerItem != null && exclusions.Any(s1 => operation.TargetServerItem.ToLowerInvariant().Contains(s1)) && !exceptions.Any(s2 => operation.TargetServerItem.ToLowerInvariant().Contains(s2))) { operation.Ignore = true; filterStats[StatTypes.Skipped]++; } if ( operation.SourceLocalItem != null && File.Exists(operation.SourceLocalItem) && (DateTime.UtcNow - File.GetLastWriteTimeUtc(operation.SourceLocalItem) < maxAge) ) { filterStats[StatTypes.Skipped]++; operation.Ignore = true; } if (operation.TargetLocalItem == null) { filterStats[StatTypes.Deleted]++; } filterStats[StatTypes.Added]++; } }); $"Getting all files from {allProjects.Count()} projects".Trace(); // get all the files allProjects.AsParallel().WithDegreeOfParallelism(1).ForAll(obj => { var subs = obj.ProjectCollection.VersionControlServer.GetItems($"{obj.WorkingFolder.ServerItem}/*"); for (int i = 0; i < subs.Items.Length; i++) { foreach (var ext in Extensions) { $"get files: {nameof(ext)} = {ext}".Trace(); var pattern = $"{subs.Items[i].ServerItem}/*.{ext}"; var itemSpec = new ItemSpec(pattern, RecursionType.Full); var getRequest = new GetRequest(itemSpec, VersionSpec.Latest); $"get files: {nameof(pattern)} = {pattern}".Trace(); $"get files: {nameof(itemSpec)} = {itemSpec.Item}".Trace(); try { obj.WorkspaceInfo.Get(getRequest, GetOptions.GetAll, fc, itemSpec); } catch (Exception e) { e.Error(); } } } }); sw.Stop(); $"Finished get info for all TPCs and all projects. Time elapsed: {sw.ElapsedMilliseconds.ToString("F")}".Info(); } catch (Exception e) { e.Error(); throw; } }
public GetStatus Get(GetRequest[] requests, GetOptions options, GetFilterCallback filterCallback, object userData) { bool force = ((GetOptions.Overwrite & options) == GetOptions.Overwrite); bool noGet = false; // not implemented below: ((GetOptions.Preview & options) == GetOptions.Preview); SortedList <int, DateTime> changesetDates = new SortedList <int, DateTime>(); GetOperation[] getOperations = Repository.Get(Name, OwnerName, requests, force, noGet); if (null != filterCallback) { filterCallback(this, getOperations, userData); } UpdateLocalVersionQueue updates = new UpdateLocalVersionQueue(this); foreach (GetOperation getOperation in getOperations) { string uPath = null; GettingEventArgs args = new GettingEventArgs(this, getOperation); // Console.WriteLine(getOperation.ToString()); if (getOperation.DeletionId != 0) { if ((getOperation.ItemType == ItemType.Folder) && (Directory.Exists(getOperation.SourceLocalItem))) { UnsetDirectoryAttributes(getOperation.SourceLocalItem); Directory.Delete(getOperation.SourceLocalItem, true); } else if ((getOperation.ItemType == ItemType.File) && (File.Exists(getOperation.SourceLocalItem))) { UnsetFileAttributes(getOperation.SourceLocalItem); File.Delete(getOperation.SourceLocalItem); } } else if ((!String.IsNullOrEmpty(getOperation.TargetLocalItem)) && (!String.IsNullOrEmpty(getOperation.SourceLocalItem)) && (getOperation.SourceLocalItem != getOperation.TargetLocalItem)) { uPath = getOperation.TargetLocalItem; try { File.Move(getOperation.SourceLocalItem, getOperation.TargetLocalItem); } catch (IOException) { args.Status = OperationStatus.TargetIsDirectory; } } else if (getOperation.ChangeType == ChangeType.None && getOperation.VersionServer != 0) { uPath = getOperation.TargetLocalItem; string directory = uPath; if (getOperation.ItemType == ItemType.File) { directory = Path.GetDirectoryName(uPath); } if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } if (getOperation.ItemType == ItemType.File) { DownloadFile.WriteTo(uPath, Repository, getOperation.ArtifactUri); // ChangesetMtimes functionality : none standard! if (mTimeSetting) { int cid = getOperation.VersionServer; DateTime modDate; if (!changesetDates.TryGetValue(cid, out modDate)) { Changeset changeset = VersionControlServer.GetChangeset(cid); modDate = changeset.CreationDate; changesetDates.Add(cid, modDate); } File.SetLastWriteTime(uPath, modDate); } // do this after setting the last write time! SetFileAttributes(uPath); } } versionControlServer.OnDownloading(args); updates.QueueUpdate(getOperation.ItemId, uPath, getOperation.VersionServer); } updates.Flush(); return(new GetStatus(getOperations.Length)); }
public static Task <GetStatus> GetAsync(this Workspace workspace, GetRequest request, GetOptions getOptions, GetFilterCallback filterCallback, object userData, CancellationToken cancellationToken = default(CancellationToken)) { return(Task.Run(() => workspace.Get(request, getOptions, filterCallback, userData), cancellationToken).IgnoreCancellation(cancellationToken)); }