/// <summary> /// Retrieves a list of user accounts that are in the specified folder with the specified distinguished name. /// </summary> public LdapUserCollection GetUsersInFolder(string folderDN, bool includeSubFolders = false) { var users = new LdapUserCollection(); string filter = "(&(objectCategory=person)(objectClass=user))"; DirectoryEntry baseEntry = GetEntryByDN(folderDN); if (baseEntry == null) { throw new NullReferenceException("Unable to find LDAP organizational unit with DN=" + folderDN ?? ""); } SearchResultCollection resList = GetSearchResults(baseEntry, filter, searchSubtrees: includeSubFolders); foreach (SearchResult res in resList) { var entry = res.GetDirectoryEntry(); var user = entry.CopyTo(new LdapUserInfo()); users.Add(user); } return(users); }
/// <summary> /// Retrieves a list of user accounts that are assigned to the specified list of groups and/or the children of those groups. /// note: The the Groups list for each found user will not be populated. You will need to call the LoadGroupsAssignedToUser method to populate this list. /// </summary> public LdapUserCollection GetUsersInGroups(LdapGroupCollection groups) { var users = new LdapUserCollection(); if (groups.Count == 0) { return(users); } var childGroups = new LdapGroupCollection(); childGroups.AddRange(groups); foreach (var childGroup in groups) { LoadChildrenOfGroup(childGroup, childGroups); } var sb = new StringBuilder(); var dnList = new List <string>(); var groupIdList = new List <string>(); foreach (var group in childGroups) { if (!dnList.Contains(group.DistinguishedName)) { dnList.Add(group.DistinguishedName); sb.Append($@"(memberOf={group.DistinguishedName})"); } int dashPos = group.SID.LastIndexOf("-"); if (dashPos > -1) { string primaryGroupID = group.SID.Substring(dashPos + 1); if (!groupIdList.Contains(primaryGroupID)) { groupIdList.Add(primaryGroupID); sb.Append($@"(primaryGroupID={primaryGroupID})"); } } } if ((dnList.Count + groupIdList.Count) > 1) { sb.Insert(0, "(&(objectCategory=person)(objectClass=user)(|"); sb.Append("))"); } else { sb.Insert(0, "(&(objectCategory=person)(objectClass=user)"); sb.Append(")"); } string filter = sb.ToString(); SearchResultCollection resList = GetSearchResults(GetRootEntry(), filter, searchSubtrees: true); foreach (SearchResult userRes in resList) { var entry = userRes.GetDirectoryEntry(); var user = entry.CopyTo(new LdapUserInfo()); if (users.IndexOfDN(user.DistinguishedName) == -1) { users.Add(user); } } return(users); }