public override void Connect(string serverUri, string remotePath, string localPath, int fromChangeset, string tfsUsername, string tfsPassword, string tfsDomain) { this._serverUri = serverUri; this._remotePath = remotePath; this._localPath = localPath; this._startingChangeset = fromChangeset; try { NetworkCredential tfsCredential = new NetworkCredential(tfsUsername, tfsPassword, tfsDomain); this._teamFoundationServer = new OpenTF.TeamFoundation.Client.TeamFoundationServer(this._serverUri, tfsCredential); this._versionControlServer = (VersionControlServer)this._teamFoundationServer.GetService(typeof(VersionControlServer)); } catch (Exception ex) { throw new Exception("Error connecting to TFS", ex); } //clear hooked eventhandlers BeginChangeSet = null; EndChangeSet = null; FileAdded = null; FileEdited = null; FileDeleted = null; FileUndeleted = null; FileBranched = null; FileRenamed = null; FolderAdded = null; FolderDeleted = null; FolderUndeleted = null; FolderBranched = null; FolderRenamed = null; ChangeSetsFound = null; }
public TFSService(MergeOptions opts) { _collection = new TfsTeamProjectCollection(new Uri(opts.CollectionUrl)); _collection.EnsureAuthenticated(); _sourceControl = _collection.GetService <VersionControlServer>(); Workstation.Current.EnsureUpdateWorkspaceInfoCache(_sourceControl, _sourceControl.AuthorizedUser); _workspace = _sourceControl.GetWorkspace(opts.Workspace, _sourceControl.AuthorizedUser); // Or WindowsIdentity.GetCurrent().Name _workitemStore = _collection.GetService <WorkItemStore>(); _workitemStore.RefreshCache(); _source = opts.Source; _target = opts.Target; _workitemID = opts.Workitem; SubscribeEvents(); }
public void GetShelveSetDetails(VersionControlServer vcs) { BindingList <KeyValuePair <string, string> > shelvedata = new BindingList <KeyValuePair <string, string> >(); var shelve = vcs.QueryShelvesets(null, userName); foreach (var shelveName in shelve) { string[] shelveSet = shelveName.DisplayName.Split(';'); shelvedata.Add(new KeyValuePair <string, string>("p1", shelveSet[0])); } cmbShelveSet.DataSource = new BindingSource(shelvedata, null); cmbShelveSet.DisplayMember = "Value"; cmbShelveSet.ValueMember = "Key"; }
internal Values(byte b) { noRecurse = false; server = null; srcPath = null; srcVer = null; target = null; targetVer = null; fromVer = null; toVer = null; vcs = null; printWhat = HistoryViewer.Printwhat.None; allowBranchRevisiting = false; forceDecomposition = false; branchesToo = false; }
internal Values(byte b) { server = null; srcPath = null; srcVer = null; target = null; targetVer = null; fromVer = null; toVer = null; vcs = null; printWhat = HistoryViewer.Printwhat.None; branchesToo = false; maxDistance = -1; count = -1; threads = -1; }
private static List <Change> GetFilesAssociatedWithBuild(VersionControlServer versionControlServer, int changesetId) { List <Change> files = new List <Change>(); Changeset changeset = versionControlServer.GetChangeset(changesetId); if (changeset.Changes != null) { foreach (Change changedItem in changeset.Changes) { files.Add(changedItem); } } changeset = null; versionControlServer = null; return(files); }
/// <summary> /// Refresh version control status and update associated fields. /// </summary> /// <returns> /// Returns <c>false</c>, if no connection to a team project. /// Returns <c>false</c>, if current text document (file) not associated with version control. /// Otherwise, returns <c>true</c>. /// </returns> private bool RefreshVersionControl() { string tfsServerUriString = _tfExt.ActiveProjectContext.DomainUri; if (string.IsNullOrEmpty(tfsServerUriString)) { _versionControl = null; _versionControlItem = null; return(false); } TfsTeamProjectCollection tfsProjCollections = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(tfsServerUriString)); _versionControl = (VersionControlServer)tfsProjCollections.GetService(typeof(VersionControlServer)); return(true); }
static void Main(string[] args) { TeamFoundationServer server = new TeamFoundationServer("<TFS path of folders you want>"); VersionControlServer version = server.GetService(typeof(VersionControlServer)) as VersionControlServer; ItemSet items = version.GetItems(@"$\", RecursionType.Full); foreach (Item item in items.Items) { if (item.ItemType == ItemType.Folder) { System.Console.WriteLine(item.ServerItem); } } Console.Read(); }
static void Main(string[] args) { string collection = @"http://ictfs2015:8080/tfs/DefaultCollection"; TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(TfsTeamProjectCollection.GetFullyQualifiedUriForName(collection)); tfs.EnsureAuthenticated(); VersionControlServer vcs = tfs.GetService <VersionControlServer>(); TeamProject[] teamProjects = vcs.GetAllTeamProjects(true); foreach (TeamProject proj in teamProjects) { System.Console.WriteLine(string.Format("Team Project: {0}", proj.Name)); } System.Console.ReadLine(); }
static void Main(string[] args) { string tfscollection = "http://xxx:8080/tfs/defaultcollection"; TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(new Uri(tfscollection)); VersionControlServer vcs = ttpc.GetService <VersionControlServer>(); string labelname = null; string labelscope = "$/"; string owner = null; bool includeitem = false; int labelnumber; VersionControlLabel[] labels = vcs.QueryLabels(labelname, labelscope, owner, includeitem); labelnumber = labels.Length; Console.WriteLine(labelnumber); Console.ReadLine(); }
private void MainForm_Load(object sender, EventArgs e) { _vcs = tfsinterface.SCMUtils.GetTFSServer(Properties.Settings.Default.TFSServer); VersionSpec ver = VersionSpec.Latest; List <BranchItem> items = new List <BranchItem>(); BranchItemCont branches = tfsinterface.SCMUtils.GetBranches(_vcs, "$/IGT_0803/main/EGS/", ver); BranchItemCont.iterator it = branches.begin(); for (; it != branches.end(); ++it) { items.Add(new BranchItem(it.value())); } _branchesCB.DataSource = items; }
/// <summary> /// Получить список ChangeSet, отфильтрованный по предикату. /// </summary> /// <param name="versionControlServer">Класс для доступа к TFS.</param> /// <param name="tfsDevelopmentPath">Путь к папке с разработкой в TFS.</param> /// <param name="predicate">Предикат.</param> /// <returns>Список ChangeSet, отфильтрованный по предикату.</returns> private List <Changeset> GetHistoryFilteredByPredicate(VersionControlServer versionControlServer, string tfsDevelopmentPath, Predicate <Changeset> predicate) { var result = new List <Changeset>(); var changesets = versionControlServer.QueryHistory(tfsDevelopmentPath, VersionSpec.Latest, 0, RecursionType.Full, null, null, VersionSpec.Latest, ProcessedChangeSetCount, true, false); foreach (Changeset changeset in changesets) { if (predicate(changeset)) { result.Add(changeset); } } return(result); }
public VersionControlScope(VersionControlServer server, ActivityContext context) { this.Server = server; if (context != null) { this.ActionInvoker = context.GetExtension <ScheduleActionExtension>(); if (this.ActionInvoker == null) { throw new ServiceMissingException(typeof(ScheduleActionExtension)); } } this.GettingHandlers = new List <Tuple <string, GettingEventHandler> >(); this.NonFatalErrorHandlers = new List <Tuple <string, ExceptionEventHandler> >(); this.NewPendingChangeHandlers = new List <Tuple <string, PendingChangeEventHandler> >(); }
public void Connect() { try { _logger.Information("Connecting to TFS."); _tfsTeamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(Properties.Settings.Default.TFSUrl)); _tfsTeamProjectCollection.EnsureAuthenticated(); _versionControlServer = _tfsTeamProjectCollection.GetService <VersionControlServer>(); } catch (Exception e) { _logger.Error(e.Message); } }
private void LogInAsync(object state) { // The user is allowed to select only one project var tfsPicker = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false); if (tfsPicker.SelectedTeamProjectCollection == null) { var tResult = tfsPicker.ShowDialog(); } //TfsConfigurationServer confServer = new TfsConfigurationServer(CurrentServer.ServerUrl); //ReadOnlyCollection<CatalogNode> collectionNodes = confServer.CatalogNode.QueryChildren( // new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None); //if (collectionNodes == null || collectionNodes.Count() == 0) { throw new ApplicationException("Project list in TFS repo is empty"); } //// it returns collection, but it should be only one node for project. and we need first //var collectionNode = collectionNodes[0]; //Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]); //get current project from TFS repo //TeamProjectCollection = confServer.GetTeamProjectCollection(collectionId); TeamProjectCollection = tfsPicker.SelectedTeamProjectCollection; SelectedProjects = tfsPicker.SelectedProjects; TeamProjectCollection.EnsureAuthenticated(); BuildServer = TeamProjectCollection.GetService <IBuildServer>(); TeamVersionControl = TeamProjectCollection.GetService <VersionControlServer>(); if (TeamVersionControl != null) { //CurrentUser.Name = TeamVersionControl.AuthorizedUser; //AuthorizedUser = '******' CurrentUser.Name = TeamVersionControl.AuthenticatedUser; //AuthenticatedUser = '******' } if (LogInCompleted != null) { LogInCompleted(this, new LogInCompletedEventArgs() { IsSucceeded = true, User = CurrentUser }); } _backgroundTimer = new Timer(MonitorBuilds, null, new TimeSpan(0, 0, 10), new TimeSpan(0, 0, 10)); }
private void ProcessFileList(SortedList <string, bool> files) { List <ItemSpec> itemSpecs = new List <ItemSpec>(); foreach (string file in files.Keys) { itemSpecs.Add(new ItemSpec(file, RecursionType.None)); } // pull item list based on WorkspaceVersion. otherwise might get // new items on server that haven't been pulled yet in the list returned WorkspaceVersionSpec version = new WorkspaceVersionSpec(workspace); SortedList <string, byte[]> itemList = new SortedList <string, byte[]>(PathComparer); // get item list from TFS server ItemSet[] itemSets = VersionControlServer.GetItems(itemSpecs.ToArray(), version, DeletedState.NonDeleted, ItemType.File, true); foreach (ItemSet itemSet in itemSets) { foreach (Item item in itemSet.Items) { string localItem = workspace.GetLocalItemForServerItem(item.ServerItem); itemList.Add(localItem, item.HashValue); } } // process adds and edits foreach (string file in files.Keys) { // skip files we're not interested in here if (IsExcludedFile(file)) { continue; } if (!File.Exists(file)) { if (OptionDeleted && itemList.ContainsKey(file)) { Console.WriteLine("Deleted: " + file); deletedFiles.Add(file); } continue; } ProcessFile(itemList, file); } }
/// <summary> /// Initializes a new instance of the <see cref="DownloaderSourceControlCopy"/> class and ensures it is connected to the team project collection uri. /// </summary> /// <param name="collectionUri">The collection URI.</param> /// <param name="workspaceName">The name of the workspace.</param> /// <param name="workspaceOwner">The workspace owner.</param> public DownloaderSourceControlCopy(string collectionUri, string workspaceName, string workspaceOwner) { if (collectionUri == null) { throw new InvalidProviderConfigurationException( "Could not connect to version control on server (No collection url was provided)"); } var tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(collectionUri)); tpc.EnsureAuthenticated(); _vcs = tpc.GetService <VersionControlServer>(); if (_vcs == null) { throw new InvalidProviderConfigurationException( string.Format("Could not connect to version control on server {0}", collectionUri)); } if (string.IsNullOrEmpty(workspaceName)) { throw new InvalidProviderConfigurationException( string.Format( "Could not fetch workspace information for workspace from tfs server {0} (No workspace name was provided)", collectionUri)); } if (string.IsNullOrEmpty(workspaceOwner)) { throw new InvalidProviderConfigurationException( string.Format( "Could not fetch workspace information for workspace from tfs server {0} (No workspace owner was provided)", collectionUri)); } Workstation.Current.EnsureUpdateWorkspaceInfoCache(_vcs, ".", new TimeSpan(0, 1, 0)); _workspace = _vcs.GetWorkspace(workspaceName, workspaceOwner); if (_workspace == null) { throw new InvalidProviderConfigurationException( string.Format( "Could not fetch workspace information for workspace '{0};{1}'from tfs server {2}", workspaceName, workspaceOwner, collectionUri)); } }
/// <summary> /// Gets if the version control service is available or not. /// </summary> /// <returns></returns> protected override async Task <bool> GetIfVersionControlServiceIsAvailable() { // Make sure we have a connection to Team Foundation. ITeamFoundationContext context = this.CurrentContext; if (context == null || !context.HasCollection) { return(false); } // Make sure we can access the Version Control Server. VersionControlServer versionControlService = null; await Task.Run(() => versionControlService = context.TeamProjectCollection.GetService <VersionControlServer>()); // Return if we could connect to the TFS Version Control or not. return(versionControlService != null); }
private void GetPathAndScope(string szFile, out VersionControlServer sourceControl, out Workspace workspace) { // Figure out the server based on either the argument or the // current directory. WorkspaceInfo wsInfo = null; workspace = null; if (!VersionControlPath.IsServerItem(szFile)) { wsInfo = Workstation.Current.GetLocalWorkspaceInfo(szFile); } TeamFoundationServer tfs = null; if (wsInfo == null) { wsInfo = Workstation.Current.GetLocalWorkspaceInfo(Environment.CurrentDirectory); } if (wsInfo != null) { //Just in case our local file is hooked to a different server m_szServerAddress = wsInfo.ServerUri.AbsoluteUri; } tfs = TeamFoundationServerFactory.GetServer(m_szServerAddress); sourceControl = (VersionControlServer)tfs.GetService(typeof(VersionControlServer)); // Pick up the label scope, if supplied. string scope = VersionControlPath.RootFolder; // The scope must be a server path, so we convert it here if // the user specified a local path. if (!VersionControlPath.IsServerItem(szFile)) { workspace = wsInfo.GetWorkspace(tfs); scope = workspace.GetServerItemForLocalItem(szFile); } else { scope = szFile; } }
/// <summary> /// Retreive User List of the Project /// </summary> /// <returns>List<string> of users</string></returns> public static List <string> RetreiveUserList() { List <string> userList = new List <string>(); dicoUser = new Dictionary <string, string>(); dicoUserMail = new Dictionary <string, string>(); //Call to Work Item Store to have access tfscoll and Get Services IGroupSecurityService GetWorkItemStore(); IGroupSecurityService groupsecurityservice = (IGroupSecurityService)tfsColl.GetService <IGroupSecurityService>(); if (vcs == null) { vcs = (VersionControlServer)tfsColl.GetService <VersionControlServer>(); } TeamProject teamProject = vcs.GetTeamProject(tfsExt.ActiveProjectContext.ProjectName); Identity[] appGroups = groupsecurityservice.ListApplicationGroups(teamProject.ArtifactUri.AbsoluteUri); //Identity idSid = groupsecurityservice.ReadIdentity() foreach (Identity group in appGroups) { Identity[] groupMembers = groupsecurityservice.ReadIdentities(SearchFactor.Sid, new string[] { group.Sid }, QueryMembership.Expanded); foreach (Identity member in groupMembers) { if (member.Members != null) { foreach (string memberSid in member.Members) { Identity memberInfo = groupsecurityservice.ReadIdentity(SearchFactor.Sid, memberSid, QueryMembership.None); if (userList.Contains(memberInfo.DisplayName)) { continue; } userList.Add(memberInfo.DisplayName); dicoUser.Add(memberInfo.DisplayName, memberInfo.AccountName); dicoUserMail.Add(memberInfo.DisplayName, memberInfo.MailAddress); } } } } userList.Sort(); return(userList); }
private List <string> GetRecentUsers() { List <string> names = new List <string>(); ITeamFoundationContext context = this.ParentSection.GetContext(); if (context != null && context.HasCollection && context.HasTeamProject) { // first we get the recent users who committed code changes VersionControlServer vcs = context.TeamProjectCollection.GetService <VersionControlServer>(); if (vcs != null) { // Ask the derived section for the history parameters string path = "$/" + context.TeamProjectName; foreach (Changeset changeset in vcs.QueryHistory(path, VersionSpec.Latest, 0, RecursionType.Full, string.Empty, null, null, 250, false, true, false).Cast <Changeset>().Where(changeset => !names.Contains(changeset.CommitterDisplayName))) { names.Add(changeset.CommitterDisplayName); } } // next we get the users who recently committed work item changes WorkItemStore wis = context.TeamProjectCollection.GetService <WorkItemStore>(); if (wis != null) { WorkItemCollection wic = wis.Query("SELECT [System.Id] FROM WorkItems WHERE [System.WorkItemType] <> '' AND [System.State] <> '' AND [System.TeamProject] = '" + context.TeamProjectName + "' ORDER BY [System.ChangedDate] desc"); int i = 0; foreach (WorkItem wi in wic) { if (!names.Contains(wi.ChangedBy)) { names.Add(wi.ChangedBy); } i++; if (i >= 250) { break; } } } names.Sort(); } return(names); }
private async Task RefreshAsync() { try { // Set our busy flag and clear the previous data this.IsBusy = true; this.Changesets.Clear(); ObservableCollection <Changeset> lchangesets = new ObservableCollection <Changeset>(); // Make the server call asynchronously to avoid blocking the UI await Task.Run(() => { ITeamFoundationContext context = this.CurrentContext; if (context != null && context.HasCollection && context.HasTeamProject) { VersionControlServer vcs = context.TeamProjectCollection.GetService <VersionControlServer>(); if (vcs != null) { // Ask the derived section for the history parameters string user; int maxCount; GetHistoryParameters(vcs, out user, out maxCount); string path = "$/" + context.TeamProjectName; foreach (Changeset changeset in vcs.QueryHistory(path, VersionSpec.Latest, 0, RecursionType.Full, user, null, null, maxCount, false, true)) { lchangesets.Add(changeset); } } } }); // Now back on the UI thread, update the bound collection and section title this.Changesets = lchangesets; } catch (Exception ex) { this.ShowNotification(ex.Message, NotificationType.Error); } finally { // Always clear our busy flag when done this.IsBusy = false; } }
/// <summary> /// Получить список ChangeSet, отфильтрованный по заданным номерам ChangeSet. /// </summary> /// <param name="versionControlServer">Класс для доступа к TFS.</param> /// <param name="tfsDevelopmentPath">Путь к папке с разработкой в TFS.</param> /// <param name="changeSetIds">Список номеров ChangeSet.</param> /// <returns>Список ChangeSet, отфильтрованный по заданным номерам ChangeSet.</returns> private List <Changeset> GetHistoryFilteredByChangeSets(VersionControlServer versionControlServer, string tfsDevelopmentPath, List <int> changeSetIds) { if (changeSetIds == null) { return(null); } var result = new List <Changeset>(); foreach (var changesetId in changeSetIds) { var changesets = versionControlServer.QueryHistory(tfsDevelopmentPath, VersionSpec.Latest, 0, RecursionType.Full, null, this.CreateVersionSpecForChangeset(changesetId), this.CreateVersionSpecForChangeset(changesetId), 1, true, false); result.AddRange(changesets.Cast <Changeset>()); } return(result); }
private static bool UpdateCache(TfsCache cache, Uri serverUri) { try { cache.EnsureAuthenticated(serverUri); } catch (Exception e) { FailOnProject("raised the following authentication exception: " + e.Message); return(false); } VersionControlServer versionControlServer = cache.GetVersionControlServer(serverUri); Workstation.Current.EnsureUpdateWorkspaceInfoCache(versionControlServer, versionControlServer.AuthorizedUser); return(true); }
/// <summary> /// Creates a migration item using the provided TFS Target instance and version control session. /// </summary> /// <param name="changeItem">The TFS item this migration item represents</param> public TfsMigrationItem(Item changeItem) { if (changeItem == null) { throw new ArgumentNullException("changeItem"); } m_Server = changeItem.VersionControlServer; ServerPath = changeItem.ServerItem; Changeset = changeItem.ChangesetId; m_deletionId = changeItem.DeletionId; if (m_Server != null) { m_serverUrl = m_Server.TeamProjectCollection.Uri.AbsoluteUri; } }
public override void Run() { workspace = GetWorkspaceFromCache(); workspace.RefreshMappings(); if (Arguments.Length < 1) { Console.WriteLine("No changeset specified."); Environment.Exit((int)ExitCode.Failure); } int cid = Convert.ToInt32(Arguments[0]); Changeset changeset = VersionControlServer.GetChangeset(cid, true, false); // fetch all items in one fell swoop List <int> ids = new List <int>(); foreach (Change change in changeset.Changes) { if ((change.ChangeType & ChangeType.Add) == ChangeType.Add) { if (change.Item.ItemType != ItemType.Folder) { string localItem = workspace.GetLocalItemForServerItem(change.Item.ServerItem); Console.WriteLine("Undo add: " + change.Item.ServerItem); deletedFiles.Add(localItem); } continue; } ids.Add(change.Item.ItemId); } ProcessEdits(changeset, ids.ToArray(), cid); if (OptionPreview) { return; } changeCount += workspace.PendAdd(addedFiles.ToArray(), false); changeCount += workspace.PendEdit(editedFiles.ToArray(), RecursionType.None); changeCount += workspace.PendDelete(deletedFiles.ToArray(), RecursionType.None); Console.WriteLine("{0} pending changes.", changeCount); }
private static IEnumerable GetMergeHistory(VersionControlServer vcs, MergeSource ms) { var changesetVersionSpec = new ChangesetVersionSpec(ms.VersionFrom); var versionTo = new ChangesetVersionSpec(ms.VersionTo); return(vcs.QueryHistory( ms.ServerItem, changesetVersionSpec, 0, RecursionType.Full, null, changesetVersionSpec, versionTo, 2147483647, true, true)); }
public static Workspace GetWorkspace(VersionControlServer versionControlServer, IEnumerable <Workspace> userWorkspaces) { var workspace = GetLastPendingChangesWorkspace(versionControlServer); if (workspace != null) { return(FindWorkspace(userWorkspaces, workspace)); } workspace = GetLastSourceControlExplorerWorkspace(versionControlServer); if (workspace != null) { return(FindWorkspace(userWorkspaces, workspace)); } return(userWorkspaces.FirstOrDefault()); }
/// <summary> /// Initializes a new instance of the <see cref="TfsBuildHelper"/> class with a connection to the TFS server, version control and to the build server. /// </summary> /// <param name="tpcUrl">The team project collection url.</param> public TfsBuildHelper(Uri tpcUrl) { _buildServer = null; _tpcUrl = tpcUrl; if (null == _tpcUrl) { throw new ArgumentNullException("tpcUrl"); } // Connect to tfs server _tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(_tpcUrl); _tpc.EnsureAuthenticated(); // Connect to version control service & build server _versionControl = _tpc.GetService <VersionControlServer>(); _buildServer = _tpc.GetService <IBuildServer>(); }
public static void GetLatestFromSourceCodeControl(string rootFolder, string workspaceDirectory, GetRequest[] filesToRetrieve) { VersionControlServer versionControlServer = ServiceHelper.GetService <VersionControlServer>(); string workspaceName = GetWorkspaceName(); string workingDirectory = workspaceDirectory; TraceHelper.TraceInformation(TraceSwitches.TfsDeployer, "Getting files from Source code control. RootFolder{0}, Workspace Directory:{1}, Working Directory: {2}", rootFolder, workspaceDirectory, workingDirectory); try { Workspace workspace = GetWorkspace(rootFolder, versionControlServer, workspaceName, workingDirectory); workspace.Get(filesToRetrieve, GetOptions.Overwrite); } finally { RemoveWorkspace(workspaceName, versionControlServer); } }
public MockEnvironment End() { if (_changeset != null) { var changesCopy = _changes.ToList(); VersionControlServer .Setup(vcs => vcs.GetChangesForChangeset(_changeset.Object.ChangesetId)) .Returns(changesCopy); var itemsCopy = _items.ToList(); VersionControlServer .Setup(vcs => vcs.GetItems(It.IsAny <string>(), _changeset.Object.Version)) .Returns((string path, Version version) => itemsCopy.Where(i => i.ServerItem.StartsWith(path))); } return(this); }
private IEnumerable<IChangeset> GetAssociatedChangesets(VersionControlServer vcs, WorkItem workItem) { if (workItem != null) { return workItem.Links.OfType<ExternalLink>() .Where(x => String.Equals(LinkingUtilities.DecodeUri(x.LinkedArtifactUri).ArtifactType, "Changeset", StringComparison.Ordinal)) .Select(x => vcs.ArtifactProvider.GetChangeset(new Uri(x.LinkedArtifactUri))) .Select(_ChangesetFactory.Create) .OrderBy(x => x) .AsReadOnly(); } return Enumerable.Empty<IChangeset>(); }
/// <summary> /// Extracts version control permissions for a specific identity. /// </summary> /// <param name="server">TFS Security service</param> /// <param name="groups">Security groups</param> /// <param name="userIdentity">User Identity</param> /// <param name="projectSecurityToken">Project Security Token</param> /// <param name="ims">TFS Identity service</param> /// <param name="vcs">TFS VC Service</param> /// <returns>The list of the permissions</returns> private static List<Permission> ExtractVersionControlPermissions( ISecurityService server, IEnumerable<string> groups, TeamFoundationIdentity userIdentity, string projectSecurityToken, IIdentityManagementService ims, VersionControlServer vcs) { Console.WriteLine("== Extract Version Control Permissions =="); var teamProject = vcs.TryGetTeamProject(projectSecurityToken); if (teamProject == null) { return new List<Permission>(); } return ExtractGenericSecurityNamespacePermissions(server, PermissionScope.SourceControl, userIdentity, teamProject.ServerItem, ims, groups); }
/// <summary> /// Sample method on how to extracts the git version control permissions. /// </summary> /// <param name="server">The server.</param> /// <param name="groups">The groups.</param> /// <param name="userIdentity">The user identity.</param> /// <param name="projectSecurityToken">The project security token.</param> /// <param name="identityManagementService">The identityManagementService.</param> /// <param name="vcs">The VCS.</param> /// <param name="gitService">The git service.</param> /// <returns>List of Permissions</returns> private static List<Permission> ExtractGitVersionControlPermissions(ISecurityService server, IEnumerable<string> groups, TeamFoundationIdentity userIdentity, string projectSecurityToken, IIdentityManagementService identityManagementService, VersionControlServer vcs, TeamFoundation.Git.Client.GitRepositoryService gitService) { Console.WriteLine("== Extract Git Version Control Permissions =="); SecurityNamespace gitVersionControlSecurityNamespace = server.GetSecurityNamespace(Helpers.GetSecurityNamespaceId(PermissionScope.GitSourceControl, server)); var gitProjectRepoService = gitService.QueryRepositories(projectSecurityToken); // This sample handle only the default repository, you can iterate through all repositories same way var defaultGitRepo = gitProjectRepoService.SingleOrDefault(gr => gr.Name.Equals(projectSecurityToken)); vcs.TryGetTeamProject(projectSecurityToken); if (defaultGitRepo == null) { return new List<Permission>(); } // Repository Security Token is repoV2/TeamProjectId/RepositoryId var repoIdToken = string.Format("repoV2{0}{1}{2}{3}", gitVersionControlSecurityNamespace.Description.SeparatorValue, defaultGitRepo.ProjectReference.Id, gitVersionControlSecurityNamespace.Description.SeparatorValue, defaultGitRepo.Id); // vcs.GetTeamProject(projectSecurityToken); AccessControlList versionControlAccessList = gitVersionControlSecurityNamespace.QueryAccessControlList( repoIdToken, new List<IdentityDescriptor> { userIdentity.Descriptor }, true); var gitVersionControlPermissions = new List<Permission>(); foreach (AccessControlEntry ace in versionControlAccessList.AccessControlEntries) { if (0 != ace.Allow) { var allowedVersionControlPermissions = ((EnumrationsList.GitPermissions)ace.Allow).ToString(); gitVersionControlPermissions.AddRange( Helpers.GetActionDetailsByName(allowedVersionControlPermissions, "Allow", PermissionScope.GitSourceControl)); } if (0 != ace.Deny) { var denyVersionControlPermissions = ((EnumrationsList.GitPermissions)ace.Deny).ToString(); gitVersionControlPermissions.AddRange( Helpers.GetActionDetailsByName(denyVersionControlPermissions, "Deny", PermissionScope.GitSourceControl)); } } if (gitVersionControlPermissions.Count == 0) { foreach (AccessControlEntry ace in versionControlAccessList.AccessControlEntries) { if (0 != ace.ExtendedInfo.EffectiveAllow) { var allowedVersionControlPermissions = ((EnumrationsList.GitPermissions)ace.ExtendedInfo.EffectiveAllow).ToString(); gitVersionControlPermissions.AddRange( Helpers.GetActionDetailsByName(allowedVersionControlPermissions, "Allow", PermissionScope.GitSourceControl)); } if (0 != ace.ExtendedInfo.EffectiveDeny) { var denyVersionControlPermissions = ((EnumrationsList.GitPermissions)ace.ExtendedInfo.EffectiveDeny).ToString(); gitVersionControlPermissions.AddRange( Helpers.GetActionDetailsByName(denyVersionControlPermissions, "Deny", PermissionScope.GitSourceControl)); } } } foreach (string group in groups) { TeamFoundationIdentity groupIdentity = identityManagementService.ReadIdentity(IdentitySearchFactor.Identifier, group, MembershipQuery.None, ReadIdentityOptions.IncludeReadFromSource); AccessControlList groupAccessList = gitVersionControlSecurityNamespace.QueryAccessControlList( repoIdToken, new List<IdentityDescriptor> { groupIdentity.Descriptor }, true); foreach (AccessControlEntry ace in groupAccessList.AccessControlEntries) { if (0 != ace.Allow) { var allowedPermissions = ((EnumrationsList.GitPermissions)ace.Allow).ToString(); var permissionsList = Helpers.GetActionDetailsByName(allowedPermissions, "Inherited Allow", PermissionScope.GitSourceControl); Helpers.AppendGroupInheritanceInformation(permissionsList, groupIdentity.DisplayName); gitVersionControlPermissions.AddRange(permissionsList); } if (0 != ace.Deny) { var denyPermissions = ((EnumrationsList.GitPermissions)ace.Deny).ToString(); var permissionsList = Helpers.GetActionDetailsByName(denyPermissions, "Inherited Deny", PermissionScope.GitSourceControl); Helpers.AppendGroupInheritanceInformation(permissionsList, groupIdentity.DisplayName); gitVersionControlPermissions.AddRange(permissionsList); } } } var modifiedPermissions = Helpers.RemoveDuplicatePermissionsAndCombineGroups(gitVersionControlPermissions); return modifiedPermissions; }
/// <summary> /// Retrieves the latest changeset ID associated with a path /// </summary> /// <param name="localPath">A path on the local filesystem</param> /// <param name="credentials">Credentials used to authenticate against the serer</param> /// <returns></returns> public int GetLatestChangesetId(string localPath, ICredentials credentials) { int latestChangesetId = 0; string server; Workstation workstation = new Workstation(versionControlClientAssembly); WorkspaceInfo workspaceInfo = workstation.GetLocalWorkspaceInfo(localPath); server = workspaceInfo.ServerUri.ToString(); VersionControlServer sourceControl = new VersionControlServer(clientAssembly, versionControlClientAssembly, server, credentials); Workspace workspace = sourceControl.GetWorkspace(localPath); WorkspaceVersionSpec workspaceVersionSpec = new WorkspaceVersionSpec(versionControlClientAssembly, workspace); VersionSpec versionSpec = new VersionSpec(versionControlClientAssembly); RecursionType recursionType = new RecursionType(versionControlClientAssembly); IEnumerable history = sourceControl.QueryHistory(localPath, versionSpec.Latest, recursionType.Full, workspaceVersionSpec); IEnumerator historyEnumerator = history.GetEnumerator(); Changeset latestChangeset = new Changeset(versionControlClientAssembly); if (historyEnumerator.MoveNext()) { latestChangeset = new Changeset(versionControlClientAssembly, historyEnumerator.Current); } if (latestChangeset.Instance != null) { latestChangesetId = latestChangeset.ChangesetId; } return latestChangesetId; }