public static void GetAllProjectAdmins(TeamFoundationIdentity identity, IIdentityManagementService ims, ref List <TeamFoundationIdentity> ids) { if (identity.IsContainer) { TeamFoundationIdentity[] groupMembers; try { groupMembers = ims.ReadIdentities(identity.Members, MembershipQuery.Expanded, ReadIdentityOptions.None); foreach (TeamFoundationIdentity tfi in groupMembers) { GetAllProjectAdmins(tfi, ims, ref ids); } } catch (Exception e) { groupMembers = ims.ReadIdentities(identity.Members, MembershipQuery.None, ReadIdentityOptions.None); ids.AddRange(groupMembers); } } else { ids.Add(identity); } }
private static void BatchUpMembershipThatExceedsSizeLimit(TeamFoundationIdentity membershipGroup, int batchSizeLimit, IIdentityManagementService ims, List <TeamFoundationIdentity> membershipGroups, Dictionary <IdentityDescriptor, TeamFoundationIdentity> allIdentities) { var batchNum = 0; var remainder = membershipGroup.Members.Length; var descriptors = new IdentityDescriptor[batchSizeLimit]; while (remainder > 0) { var startAt = batchNum * batchSizeLimit; var length = batchSizeLimit; if (length > remainder) { length = remainder; descriptors = new IdentityDescriptor[length]; } Array.Copy(membershipGroup.Members, startAt, descriptors, 0, length); var memberIdentities = ims.ReadIdentities(descriptors, MembershipQuery.Direct, ReadIdentityOptions.None); AddCollectionUsersAndGroupsToLists(memberIdentities, membershipGroups, allIdentities); remainder -= length; } }
public override IReadOnlyDictionary <string, object> Map(IEnumerable <string> values) { if (values == null) { return(Empty); } var identities = _identityManagementService.ReadIdentities(IdentitySearchFactor.DisplayName, values); var retval = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase); foreach (var identity in identities) { var c = identity.Value?.Count(); if (c.GetValueOrDefault(0) == 0) { retval.Add(identity.Key, new IdentityFieldValue(identity.Key)); continue; } if (c > 1) { var m = $"Multiple identities found matching '{identity.Key}'. Please specify one of the following identities:{string.Join("\r\n- ", identity.Value)}"; throw new MultipleIdentitiesFoundException(m); } var v = new IdentityFieldValue(identity.Value.FirstOrDefault()); retval.Add(identity.Key, v); } return(retval); }
public static IEnumerable <TeamFoundationIdentity> ReadTFSUsers(TfsTeamProjectCollection tfsTeamProjectCollection, ILogger logger) { try { logger.Information("Querying Team Foundation Identities from TFS."); IIdentityManagementService identityService = tfsTeamProjectCollection.GetService <IIdentityManagementService>(); TeamFoundationIdentity teamFoundationIdentity = identityService.ReadIdentity(IdentitySearchFactor.AccountName, "Project Collection Valid Users", MembershipQuery.Expanded, ReadIdentityOptions.ExtendedProperties); TeamFoundationIdentity[][] teamFoundationIdentities = identityService .ReadIdentities( IdentitySearchFactor.Identifier, teamFoundationIdentity .Members .Select(id => id.Identifier) .ToArray(), MembershipQuery.None, ReadIdentityOptions.ExtendedProperties); return(teamFoundationIdentities .SelectMany(tfi => tfi) .Where(tfi => !tfi.IsContainer)); } catch (Exception e) { logger.Error(e.Message); return(null); } }
static void Main(string[] args) { TfsConfigurationServer tcs = new TfsConfigurationServer(new Uri("http://server:8080/tfs")); IIdentityManagementService ims = tcs.GetService <IIdentityManagementService>(); TeamFoundationIdentity tfi = ims.ReadIdentity(IdentitySearchFactor.AccountName, "Project Collection Valid Users", MembershipQuery.Expanded, ReadIdentityOptions.None); TeamFoundationIdentity[] ids = ims.ReadIdentities(tfi.Members, MembershipQuery.None, ReadIdentityOptions.None); using (StreamWriter file = new StreamWriter("userlist.txt")) foreach (TeamFoundationIdentity id in ids) { if (id.Descriptor.IdentityType == "System.Security.Principal.WindowsIdentity") { Console.WriteLine(id.DisplayName); } //{ Console.WriteLine(id.UniqueName); } file.WriteLine("[{0}]", id.DisplayName); } var count = ids.Count(x => ids.Contains(x)); Console.WriteLine(count); Console.ReadLine(); }
private static void BatchUpMembershipThatExceedsSizeLimit(TeamFoundationIdentity membershipGroup, int batchSizeLimit, IIdentityManagementService ims, List<TeamFoundationIdentity> membershipGroups, Dictionary<IdentityDescriptor, TeamFoundationIdentity> allIdentities) { var batchNum = 0; var remainder = membershipGroup.Members.Length; var descriptors = new IdentityDescriptor[batchSizeLimit]; while (remainder > 0) { var startAt = batchNum*batchSizeLimit; var length = batchSizeLimit; if (length > remainder) { length = remainder; descriptors = new IdentityDescriptor[length]; } Array.Copy(membershipGroup.Members, startAt, descriptors, 0, length); var memberIdentities = ims.ReadIdentities(descriptors, MembershipQuery.Direct, ReadIdentityOptions.None); AddCollectionUsersAndGroupsToLists(memberIdentities, membershipGroups, allIdentities); remainder -= length; } }
public static void Main(string[] args) { LogArguments(args); Uri projectCollectionUri = new Uri(args.ElementAt(0)); Guid projectCollectionId = Guid.Parse(args.ElementAt(1)); Guid requestedByUserId = Guid.Parse(args.ElementAt(2)); string artifactsFolder = Path.GetFullPath(args.ElementAt(3)); string emailSubject = args.ElementAt(4); string emailBody = args.ElementAt(5); Console.WriteLine("Project collection URI: " + projectCollectionUri); Console.WriteLine("Project collection id: " + projectCollectionId); Console.WriteLine("User identifier: " + requestedByUserId); Console.WriteLine("Artifacts folder: " + artifactsFolder); Console.WriteLine("Email subject: " + emailSubject); Console.WriteLine("Email body: " + emailBody); string tfsUriFromCollectionUri = projectCollectionUri.AbsoluteUri.Replace(projectCollectionUri.Segments.Last(), string.Empty); TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(new Uri(tfsUriFromCollectionUri)); TfsTeamProjectCollection teamProjectCollection = configurationServer.GetTeamProjectCollection(projectCollectionId); IIdentityManagementService identityServiceManager = teamProjectCollection.GetService <IIdentityManagementService>(); TeamFoundationIdentity[] tfsIdentities = identityServiceManager.ReadIdentities(new Guid[1] { requestedByUserId }, MembershipQuery.Direct); SendArtifacs(tfsIdentities, emailSubject, emailBody, artifactsFolder); }
/// <summary> /// Gets the list of project users in a TFS project /// </summary> /// <param name="projectCollection">TFS PROJECT COLLECTION</param> /// <param name="projectName">TFS PROJECT NAME</param> /// <returns></returns> public static List <TeamFoundationIdentity> ListContributors(TfsTeamProjectCollection tfsTeamProjectCollection, string projectName) { List <TeamFoundationIdentity> tfsUsers = new List <TeamFoundationIdentity>(); IIdentityManagementService ims = (IIdentityManagementService)tfsTeamProjectCollection.GetService(typeof(IIdentityManagementService)); // get the tfs project ReadOnlyCollection <CatalogNode> projectNodes = tfsTeamProjectCollection.CatalogNode.QueryChildren(new[] { CatalogResourceTypes.TeamProject }, false, CatalogQueryOptions.None); CatalogNode projectCatalogNode = projectNodes.FirstOrDefault(c => c.Resource.DisplayName == projectName); if (projectCatalogNode != null && ims != null) { TeamFoundationIdentity[] groups = ims.ListApplicationGroups(projectName, ReadIdentityOptions.None); foreach (TeamFoundationIdentity group in groups) { TeamFoundationIdentity sids = ims.ReadIdentity(IdentitySearchFactor.DisplayName, group.DisplayName, MembershipQuery.Expanded, ReadIdentityOptions.IncludeReadFromSource); if (sids != null) { tfsUsers.AddRange(ims.ReadIdentities(sids.Members, MembershipQuery.Expanded, ReadIdentityOptions.None)); } } } //Remove any duplicates (by user-id) return(tfsUsers.GroupBy(u => u.UniqueName).Select(u => u.First()).ToList()); }
public static void FeedIdentityData(ICollection <ApplicationGroupDefinition> applicationGroupCollection, ICollection <User> userCollection, IIdentityManagementService ims, string projectUri) { //Get the project application groups TeamFoundationIdentity[] lightApplicationGroups = ims.ListApplicationGroups(projectUri, ReadIdentityOptions.IncludeReadFromSource); //Read the project application groups identities with an expended membership query to populate the Members properties TeamFoundationIdentity[] fullApplicationGroups = ims.ReadIdentities(lightApplicationGroups.Select(x => x.Descriptor).ToArray(), MembershipQuery.Expanded, ReadIdentityOptions.None); foreach (TeamFoundationIdentity applicationGroup in fullApplicationGroups) { ApplicationGroupDefinition applicationGroupDefinition = new ApplicationGroupDefinition() { Name = applicationGroup.DisplayName }; TeamFoundationIdentity[] applicationGroupMembers = ims.ReadIdentities(applicationGroup.Members, MembershipQuery.None, ReadIdentityOptions.None); foreach (TeamFoundationIdentity applicationGroupMember in applicationGroupMembers) { if (!applicationGroupMember.IsContainer) { User user = userCollection.SingleOrDefault(x => x.Name == applicationGroupMember.DisplayName); if (user == null) { user = new User() { Name = applicationGroupMember.DisplayName, IsActive = applicationGroupMember.IsActive, Mail = applicationGroupMember.GetAttribute("Mail", string.Empty), Domain = applicationGroupMember.GetAttribute("Domain", string.Empty), Account = applicationGroupMember.GetAttribute("Account", string.Empty), DN = applicationGroupMember.GetAttribute("DN", string.Empty), SID = applicationGroupMember.Descriptor.Identifier }; userCollection.Add(user); } user.ApplicationGroups.Add(applicationGroupDefinition.Name); applicationGroupDefinition.UserCollection.Add(user); } } applicationGroupCollection.Add(applicationGroupDefinition); } }
/// <summary> /// Gets the users. /// </summary> /// <returns></returns> public List <TeamFoundationIdentity> GetUsers() { TfsTeamProjectCollection projectCollection = this.GetTeamProjectCollection(); ICommonStructureService css = (ICommonStructureService)projectCollection.GetService(typeof(ICommonStructureService)); IGroupSecurityService gss = projectCollection.GetService <IGroupSecurityService>(); IIdentityManagementService ims = projectCollection.GetService <IIdentityManagementService>(); // get the tfs project var projectList = css.ListAllProjects(); var project = projectList.FirstOrDefault(o => o.Name.Equals(this.TfsServer.ActiveProjectContext.ProjectName, StringComparison.InvariantCultureIgnoreCase)); // project doesn't exist if (project == null) { return(null); } // get the tfs group var groupList = gss.ListApplicationGroups(project.Uri); List <Identity> groups; if (ConfigurationManager.CurrentConfiguration.UserGroups != null && ConfigurationManager.CurrentConfiguration.UserGroups.Count > 0) { groups = groupList.Where(o => ConfigurationManager.CurrentConfiguration.UserGroups.Contains(o.AccountName)).ToList(); // you can also use DisplayName } else { groups = groupList.ToList(); } List <TeamFoundationIdentity> contributors = new List <TeamFoundationIdentity>(); foreach (Identity group in groups) { Identity sids = gss.ReadIdentity(SearchFactor.Sid, group.Sid, QueryMembership.Expanded); // there are no users if (sids.Members.Length == 0) { continue; } // convert to a list contributors.AddRange(ims.ReadIdentities(IdentitySearchFactor.Identifier, sids.Members, MembershipQuery.Direct, ReadIdentityOptions.None).SelectMany(x => x).Where(x => x.IsContainer == false)); } return(contributors.GroupBy(x => x.DisplayName).Select(g => g.First()).OrderBy(x => x.DisplayName).ToList()); }
private static void DisplayGroupTree(IIdentityManagementService ims, TeamFoundationIdentity node, int level) { DisplayNode(node, level); if (!node.IsContainer) return; TeamFoundationIdentity[] nodeMembers = ims.ReadIdentities(node.Members, MembershipQuery.Direct, ReadIdentityOptions.None); int newLevel = level + 1; foreach (TeamFoundationIdentity member in nodeMembers) DisplayGroupTree(ims, member, newLevel); }
public IdentityDescriptor GetIdentityToImpersonate(Uri projectCollectionUrl) { var configurationServer = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(projectCollectionUrl); // TODO: Find a way to read the identity from the server object model instead. IIdentityManagementService identityManagementService = configurationServer.GetService <IIdentityManagementService>(); Microsoft.TeamFoundation.Framework.Client.TeamFoundationIdentity identity = identityManagementService.ReadIdentities( new[] { new Guid(this.Notification.ChangerTeamFoundationId) }, MembershipQuery.None).FirstOrDefault(); return(identity?.Descriptor); }
private ICollection <UserInfo> GetAllUsers() { // Read "everyone" group var group = _identityManagementService.ReadIdentity(GroupWellKnownDescriptors.EveryoneGroup, MembershipQuery.Expanded, ReadIdentityOptions.None); // Read identities of that groups members var resultIdentities = _identityManagementService.ReadIdentities(group.Members, MembershipQuery.Direct, ReadIdentityOptions.DoNotQualifyAccountNames); // Filter machine accounts var validLocalUsers = resultIdentities.Where( identity => identity.Descriptor.IdentityType == "System.Security.Principal.WindowsIdentity" && identity.IsActive && identity.IsContainer == false) .ToArray(); return(validLocalUsers.Select(x => new UserInfo(x.DisplayName, x.UniqueName)).OrderBy(x => x.DisplayName).ToArray()); }
// For call to create TR we need Ericsson user id (also domain?) - seems like we have what we want here. // TDOD: Try and make sure we are getting the correct attribute. // See http://stackoverflow.com/questions/19911368/using-the-tfs-2012-api-how-do-i-get-the-email-address-of-a-user static public String GetSignumForChangeNotification( Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem workItem, WorkItemChangedEvent notification) { TfsTeamProjectCollection tpc = workItem.Store.TeamProjectCollection; String userId = notification.ChangerTeamFoundationId; IIdentityManagementService mgmntService = tpc.GetService <IIdentityManagementService>(); Guid[] ids = new Guid[1]; ids[0] = new Guid(notification.ChangerTeamFoundationId); TeamFoundationIdentity[] members = mgmntService.ReadIdentities(ids, MembershipQuery.Direct); return(GetUserFromSignum(members[0].UniqueName)); }
private IdentityDescriptor GetIdentityToImpersonate(TeamFoundationRequestContext requestContext, WorkItemChangedEvent workItemChangedEvent) { Uri server = this.GetCollectionUriFromContext(requestContext); var configurationServer = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(server); // TODO: Find a way to read the identity from the server object model instead. IIdentityManagementService identityManagementService = configurationServer.GetService <IIdentityManagementService>(); TeamFoundationIdentity identity = identityManagementService.ReadIdentities( new Guid[] { new Guid(workItemChangedEvent.ChangerTeamFoundationId) }, MembershipQuery.None).FirstOrDefault(); return(identity?.Descriptor); }
public static void ScanUsers(TfsTeamProjectCollection tfsTeamProjectCollection, ProjectInfo projectInfo) { IIdentityManagementService identityManagementService = tfsTeamProjectCollection.GetService <IIdentityManagementService>(); TeamFoundationIdentity[] projectSecurityGroups = identityManagementService.ListApplicationGroups( projectInfo.Uri, ReadIdentityOptions.None); // Get projectValidUsersIdentity Identifier TeamFoundationIdentity projectValidUsersIdentity = projectSecurityGroups .FirstOrDefault(psg => psg.GetProperty("SpecialType").ToString().Equals("EveryoneApplicationGroup")); if (projectValidUsersIdentity == null) { return; } // Expand projectValidUsersIdentity from Identifier to get the list of Members projectValidUsersIdentity = identityManagementService.ReadIdentity( IdentitySearchFactor.Identifier, projectValidUsersIdentity.Descriptor.Identifier, MembershipQuery.Expanded, // Number of Members: Direct gives 20, Expanded gives 111, ExpandedDown gives 111, ExpandedUp gives 0. ReadIdentityOptions.None); // Expand projectValidUsersIdentity with Members into collection of identities TeamFoundationIdentity[] projectUsersIdentities = identityManagementService.ReadIdentities(projectValidUsersIdentity.Members, MembershipQuery.Direct, ReadIdentityOptions.None); // First build map from Identifier (which is part of the Descriptor) to Identity object. foreach (TeamFoundationIdentity userIdentity in projectUsersIdentities) { TeamFoundationIdentity currentIdentity = userIdentity; if (!currentIdentity.BelongsToProject(projectInfo.Uri)) { continue; } TeamProjectScanner.IdToIdentity[currentIdentity.Descriptor.Identifier] = currentIdentity; TeamProjectScanner.DisplayNameToIdentity[currentIdentity.DisplayName] = currentIdentity; //Debug.WriteLine("{0}: Members = {1}, MemberOf = {2}", currentIdentity.DisplayName(), currentIdentity.Members.Length, currentIdentity.MemberOf.Length); } }
private static string GetNameFromIdentity(string identity) { TfsConfigurationServer tcs = new TfsConfigurationServer(new Uri(serverUrl)); IIdentityManagementService ims = tcs.GetService <IIdentityManagementService>(); TeamFoundationIdentity tfi = ims.ReadIdentity(IdentitySearchFactor.AccountName, "[TEAM FOUNDATION]\\Team Foundation Valid Users", MembershipQuery.Expanded, ReadIdentityOptions.None); TeamFoundationIdentity[] ids = ims.ReadIdentities(tfi.Members, MembershipQuery.None, ReadIdentityOptions.None); foreach (TeamFoundationIdentity id in ids) { if (id.Descriptor.Identifier.ToString().Equals(identity)) { return(id.DisplayName); } } return("N/A"); }
private IDictionary <string, string[]> GetAliasesForDisplayNames(string[] displayNames) { if (displayNames == null) { throw new ArgumentNullException(nameof(displayNames)); } return(_identityManagementService.ReadIdentities(IdentitySearchFactor.DisplayName, displayNames) .ToDictionary( kvp => kvp.Key, kvp => kvp .Value.Where( identity => identity != null && !identity.IsContainer && identity.UniqueUserId == IdentityConstants.ActiveUniqueId) .Select(i => i.GetUserAlias()) .Distinct(StringComparer.OrdinalIgnoreCase) .ToArray())); }
public static IDictionary <string, string[]> GetAliasesForDisplayNames(this IIdentityManagementService ims, string[] displayNames) { if (ims == null) { throw new ArgumentNullException(nameof(ims)); } if (displayNames == null) { throw new ArgumentNullException(nameof(displayNames)); } return(ims.ReadIdentities(IdentitySearchFactor.DisplayName, displayNames) .ToDictionary( kvp => kvp.Key, kvp => kvp.Value .Where(identity => identity != null && !identity.IsContainer && identity.IsActive) .Select(i => i.GetUserAlias()) .Distinct(StringComparer.OrdinalIgnoreCase) .ToArray())); }
private Dictionary <string, object> GetIdentitiesForAliases( IDictionary <string, ICollection <IIdentityDescriptor> > aliasDescriptors) { var descriptors = aliasDescriptors.SelectMany(ad => ad.Value).ToList(); var descriptorToAliasLookup = aliasDescriptors .SelectMany(ad => ad.Value.Select(d => new KeyValuePair <string, string>(d.ToString(), ad.Key))) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value, StringComparer.OrdinalIgnoreCase); var validIdentities = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase); var lookupResults = _identityManagementService.ReadIdentities(descriptors); foreach (var identity in lookupResults.Where(id => id != null)) { var lookupKey = identity.Descriptor.ToString(); var alias = descriptorToAliasLookup[lookupKey]; if (!validIdentities.ContainsKey(alias)) { validIdentities.Add(alias, identity); } } return(validIdentities); }
private static void AddExpandedMembershipOfValidUsersGroup(IIdentityManagementService ims, List<TeamFoundationIdentity> membershipGroups, Dictionary<IdentityDescriptor, TeamFoundationIdentity> allIdentities) { // Get expanded membership of the Valid Users group, which is all identities in this host var validUsersGroupMembers = ims.ReadIdentity(GroupWellKnownDescriptors.EveryoneGroup, MembershipQuery.Expanded, ReadIdentityOptions.None); // If total membership exceeds batch size limit for Read, break it up const int batchSizeLimit = 100000; if (validUsersGroupMembers.Members.Length > batchSizeLimit) { BatchUpMembershipThatExceedsSizeLimit(validUsersGroupMembers, batchSizeLimit, ims, membershipGroups, allIdentities); } else { var memberIdentities = ims.ReadIdentities(validUsersGroupMembers.Members, MembershipQuery.Direct, ReadIdentityOptions.None); AddCollectionUsersAndGroupsToLists(memberIdentities, membershipGroups, allIdentities); } }
private static void AddExpandedMembershipOfValidUsersGroup(IIdentityManagementService ims, List <TeamFoundationIdentity> membershipGroups, Dictionary <IdentityDescriptor, TeamFoundationIdentity> allIdentities) { // Get expanded membership of the Valid Users group, which is all identities in this host var validUsersGroupMembers = ims.ReadIdentity(GroupWellKnownDescriptors.EveryoneGroup, MembershipQuery.Expanded, ReadIdentityOptions.None); // If total membership exceeds batch size limit for Read, break it up const int batchSizeLimit = 100000; if (validUsersGroupMembers.Members.Length > batchSizeLimit) { BatchUpMembershipThatExceedsSizeLimit(validUsersGroupMembers, batchSizeLimit, ims, membershipGroups, allIdentities); } else { var memberIdentities = ims.ReadIdentities(validUsersGroupMembers.Members, MembershipQuery.Direct, ReadIdentityOptions.None); AddCollectionUsersAndGroupsToLists(memberIdentities, membershipGroups, allIdentities); } }
static void Main(string[] args) { TfsConfigurationServer tcs = new TfsConfigurationServer(new Uri("http://tfsserver:8080/tfs")); IIdentityManagementService ims = tcs.GetService <IIdentityManagementService>(); TeamFoundationIdentity tfi = ims.ReadIdentity(IdentitySearchFactor.AccountName, "[TEAM FOUNDATION]\\Team Foundation Valid Users", MembershipQuery.Expanded, ReadIdentityOptions.None); TeamFoundationIdentity[] ids = ims.ReadIdentities(tfi.Members, MembershipQuery.None, ReadIdentityOptions.None); foreach (TeamFoundationIdentity id in ids) { if (id.Descriptor.IdentityType == "System.Security.Principal.WindowsIdentity") { Console.WriteLine(id.DisplayName); Console.WriteLine(id.UniqueName); } } Console.ReadLine(); }
public IEnumerable <TeamFoundationIdentity> GetIdentities(IdentityDescriptor[] identities) { return(_identityService.ReadIdentities(identities, MembershipQuery.Direct, ReadIdentityOptions.None)); }
private static IEnumerable <KeyValuePair <string, ITeamFoundationIdentity> > SearchForIdentitiesForAliases(IIdentityManagementService ims, IEnumerable <string> aliases) { var missingIdentitiesList = ims.ReadIdentities(IdentitySearchFactor.AccountName, aliases.ToList()); return(missingIdentitiesList.Select(mil => new KeyValuePair <string, ITeamFoundationIdentity>(mil.Key, mil.Value.FirstOrDefault()))); }
private void btnConnect_Click(object sender, EventArgs e) { string connectionString = this.txtUrl.Text; string windowsDomain = this.txtDomain.Text; string externalLogin = this.txtLogin.Text; string externalPassword = this.txtPassword.Text; //Configure the network credentials - used for accessing the MsTfs API //If we have a domain provided, use a NetworkCredential, otherwise use a TFS credential TfsClientCredentials tfsCredential = null; NetworkCredential networkCredential = null; if (String.IsNullOrEmpty(windowsDomain)) { //Windows Live credentials networkCredential = new NetworkCredential(externalLogin, externalPassword); BasicAuthCredential basicCredential = new BasicAuthCredential(networkCredential); tfsCredential = new TfsClientCredentials(basicCredential); tfsCredential.AllowInteractive = false; } else { //Windows credentials networkCredential = new NetworkCredential(externalLogin, externalPassword, windowsDomain); } //Create a new TFS 2012 project collection instance and WorkItemStore instance //This requires that the URI includes the collection name not just the server name WorkItemStore workItemStore = null; Uri tfsUri = new Uri(connectionString); TfsTeamProjectCollection tfsTeamProjectCollection; if (String.IsNullOrEmpty(windowsDomain)) { tfsTeamProjectCollection = new TfsTeamProjectCollection(tfsUri, tfsCredential); tfsTeamProjectCollection.Authenticate(); } else { tfsTeamProjectCollection = new TfsTeamProjectCollection(tfsUri, networkCredential); } LogTraceEvent("Created new TFS Project Collection instance"); //Get access to the work item server service WorkItemServer workItemServer = tfsTeamProjectCollection.GetService <WorkItemServer>(); LogTraceEvent("Got access to the WorkItemServer service"); //Get the global security service to retrieve the TFS user list TeamFoundationIdentity[] tfsUsers; IIdentityManagementService ims = (IIdentityManagementService)tfsTeamProjectCollection.GetService(typeof(IIdentityManagementService)); if (ims != null) { TeamFoundationIdentity SIDS = ims.ReadIdentity(IdentitySearchFactor.AccountName, "Project Collection Valid Users", MembershipQuery.None, ReadIdentityOptions.IncludeReadFromSource); if (SIDS != null) { tfsUsers = ims.ReadIdentities(SIDS.Members, MembershipQuery.Expanded, ReadIdentityOptions.ExtendedProperties); } } LogTraceEvent("Got access to the IIdentityManagementService"); //Get access to the work item store try { tfsTeamProjectCollection.Authenticate(); workItemStore = new WorkItemStore(tfsTeamProjectCollection); } catch (Exception exception) { //We can't authenticate so end LogErrorEvent("Unable to connect to Team Foundation Server, please check that the connection information is correct (" + exception.Message + ")", EventLogEntryType.Error); LogErrorEvent(exception.Message + ": " + exception.StackTrace); if (exception.InnerException != null) { LogErrorEvent("Inner Exception=" + exception.InnerException.Message + ": " + exception.InnerException.StackTrace); } } if (workItemStore == null) { //We can't authenticate so end LogErrorEvent("Unable to connect to Team Foundation Server, please check that the connection information is correct", EventLogEntryType.Error); } LogTraceEvent("Got access to the WorkItemStore"); }
private void Init() { if (TfsAddress == null || TfsAddress == string.Empty) { return; } string serverName = Regex.Replace(TfsAddress.ToLower(), @"\A[h][t][t][p][:]\/\/|[:][8][0][8][0]\S+\z", string.Empty); Uri tfsUri = new Uri(TfsAddress); TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri); ReadOnlyCollection <CatalogNode> collectionNodes = configurationServer.CatalogNode.QueryChildren( new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None); ProjectCollections = new Dictionary <string, TfsTeamProjectCollection>(); TeamProjects = new Dictionary <string, ProjectInfo[]>(); foreach (CatalogNode collectionNode in collectionNodes) { #region Init TeamProject // Use the InstanceId property to get the team project collection Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]); TfsTeamProjectCollection projectCollection = configurationServer.GetTeamProjectCollection(collectionId); string nodeCollectionName = projectCollection.Uri.ToString().Replace(tfsUri + "/", string.Empty); #region Acting behalf of PM user //var identityService = teamProjectCollection.GetService<IIdentityManagementService>(); //var identity = identityService.ReadIdentity( // IdentitySearchFactor.AccountName, // "ProjectManager", // MembershipQuery.None, // ReadIdentityOptions.None); //var impersonatedTeamProjectCollection = new TfsTeamProjectCollection(teamProjectCollection.Uri, identity.Descriptor); //teamProjectCollection = impersonatedTeamProjectCollection; #endregion ProjectCollections.Add(nodeCollectionName, projectCollection); // Retrieve team projects ICommonStructureService4 css4 = projectCollection.GetService <ICommonStructureService4>(); ProjectInfo[] projectInfos = css4.ListAllProjects(); TeamProjects.Add(nodeCollectionName, projectInfos); WorkItemStore = projectCollection.GetService <WorkItemStore>(); //WorkItemStore = (WorkItemStore)projectCollection.GetService(typeof(WorkItemStore)); if (WorkItemStore == null) { throw new Exception("WorkItemStore not found!"); } CommonStructureService4 = projectCollection.GetService <ICommonStructureService4>(); #region Identities IIdentityManagementService identityManagementSrv = WorkItemStore.TeamProjectCollection.GetService <IIdentityManagementService>(); TeamFoundationIdentity _usersGroup = identityManagementSrv .ReadIdentity(IdentitySearchFactor.AccountName, "[" + nodeCollectionName + "]\\Project Collection Valid Users", MembershipQuery.Expanded, ReadIdentityOptions.None); TeamFoundationIdentity[] groupMember = identityManagementSrv.ReadIdentities(_usersGroup.Members, MembershipQuery.None, ReadIdentityOptions.None) .Where(member => member.IsContainer == false && member.UniqueName != "Domain\\UserName" && Regex.IsMatch(member.UniqueName, @"\G(\A[D][o][m][a][i][n]\\\D+\z)", RegexOptions.IgnoreCase)).ToArray(); #endregion if (!ProjectCollections.Any()) { string exceptionMessage = string.Format("Tfs team project collection with \"{0}\" name not found", nodeCollectionName); string projectCollectionsText = "projectCollections : \n" + ProjectCollections.Keys.Aggregate((str, next) => str = str + Environment.NewLine + next); string logText = string.Format("{0}\n\n{1}", exceptionMessage, projectCollectionsText); throw new Exception(exceptionMessage); } #endregion #region Init VersionControl VersionControlServer = projectCollection.GetService <VersionControlServer>(); #endregion #region Init Workspace string workspaceName = string.Format("{0}", Environment.MachineName); Workspace = VersionControlServer.GetWorkspace(workspaceName, VersionControlServer.AuthorizedUser); #endregion } }
private TeamFoundationIdentity[] allTfsUsers(TfsConnection tfs) { try { IIdentityManagementService ims = tfs.GetService <IIdentityManagementService>(); TeamFoundationIdentity[] projectGroups = ims.ListApplicationGroups(tfsProject.Project, ReadIdentityOptions.None); Dictionary <IdentityDescriptor, object> descSet = new Dictionary <IdentityDescriptor, object>(IdentityDescriptorComparer.Instance); foreach (TeamFoundationIdentity projectGroup in projectGroups) { descSet[projectGroup.Descriptor] = projectGroup.Descriptor; } projectGroups = ims.ReadIdentities(descSet.Keys.ToArray(), MembershipQuery.Expanded, ReadIdentityOptions.None); foreach (TeamFoundationIdentity projectGroup in projectGroups) { foreach (IdentityDescriptor mem in projectGroup.Members) { descSet[mem] = mem; } } TeamFoundationIdentity[] identities = new TeamFoundationIdentity[0]; int batchSizeLimit = 100000; var descriptors = descSet.Keys.ToArray(); if (descriptors.Length > batchSizeLimit) { int batchNum = 0; int remainder = descriptors.Length; IdentityDescriptor[] batchDescriptors = new IdentityDescriptor[batchSizeLimit]; while (remainder > 0) { int startAt = batchNum * batchSizeLimit; int length = batchSizeLimit; if (length > remainder) { length = remainder; batchDescriptors = new IdentityDescriptor[length]; } Array.Copy(descriptors, startAt, batchDescriptors, 0, length); identities = ims.ReadIdentities(batchDescriptors, MembershipQuery.Direct, ReadIdentityOptions.None); remainder -= length; } } else { identities = ims.ReadIdentities(descriptors, MembershipQuery.Direct, ReadIdentityOptions.None); } return(identities.Where(_ => !_.IsContainer && _.Descriptor.IdentityType != "Microsoft.TeamFoundation.UnauthenticatedIdentity").ToArray()); } catch { /* Do nothing */ } return(tfs != null? new TeamFoundationIdentity[] { tfs.AuthorizedIdentity } : new TeamFoundationIdentity[0]); }