How to efficiently get a list of users from an active Windows directory using C #

I made a decision on this issue. How to get a list of users from the active directory? and get the list of users from AD. The problem I am facing is that loading all the records takes 35 seconds.

There should be a more efficient way to query all the data at once, instead of waiting 35 seconds so that it can return 700+ records. I wrote a method to return a list of users. I added extra code to try to filter out all users who are not human accounts.

public List<ActiveUser> GetActiveDirectoryUsers()
{
    List<ActiveUser> response = new List<ActiveUser>();
    using (var context = new PrincipalContext(ContextType.Domain, "mydomain"))
    {
        using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
        {
            foreach (var result in searcher.FindAll())
            {
                DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                if (de.NativeGuid != null && !Convert.ToBoolean((int)de.Properties["userAccountControl"].Value & 0x0002) &&
                    de.Properties["department"].Value != null && de.Properties["sn"].Value != null) response.Add(new ActiveUser(de));
            }
        }
    }
    return response.OrderBy(x => x.DisplayName).ToList();
}

ActiveUser entry.property [ "whataver" ] . , -,

DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;

, , 30 . .

+4
2

, , .

, , , adspath, Console.WriteLine .

# , IEnumerator DirectoryEntry, PrincipleSearcher , ,

, , . , .

. / powershell , Visual Studio.

$Source = @"
// " "  <-- this just makes the code highlighter work
// Syntax:  [soexample.search]::Get("LDAP Path", "property1", "property2", "etc...")
// Example: [soexample.search]::Get("LDAP://CN=Users,DC=mydomain,DC=com","givenname","sn","samaccountname","distinguishedname")

namespace soexample
{
    using System;
    using System.DirectoryServices;

    public static class search
    {
        public static string Get(string ldapPath, params string[] propertiesToLoad)
        {
            DirectoryEntry entry = new DirectoryEntry(ldapPath);
            DirectorySearcher searcher = new DirectorySearcher(entry);
            searcher.SearchScope = SearchScope.OneLevel;
            foreach (string p in propertiesToLoad) { searcher.PropertiesToLoad.Add(p); }
            searcher.PageSize = 100;
            searcher.SearchRoot = entry;
            searcher.CacheResults = true;
            searcher.Filter = "(sAMAccountType=805306368)";
            SearchResultCollection results = searcher.FindAll();

            foreach (SearchResult result in results)
            {
                foreach (string propertyName in propertiesToLoad)
                {
                    foreach (object propertyValue in result.Properties[propertyName])
                    {
                        Console.WriteLine(string.Format("{0} : {1}", propertyName, propertyValue));
                    }
                }
                Console.WriteLine("");

            }
            return "";
        }
    }
}
"@
$Asem = ('System.DirectoryServices','System')
Add-Type -TypeDefinition $Source -Language CSharp -ReferencedAssemblies $Asem

, 160 , :

example :

PS > Measure-Command { [soexample.search]::Get(args as above..) }

:

givenname : John
sn : Surname
samaccountname : john.surname
distinguishedname : CN=John Surname,CN=Users,DC=mydomain,DC=com 

etc ... 159 more ...

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 431
Ticks             : 4317575
TotalDays         : 4.99719328703704E-06
TotalHours        : 0.000119932638888889
TotalMinutes      : 0.00719595833333333
TotalSeconds      : 0.4317575
TotalMilliseconds : 431.7575 

, , 100 .

samaccountname 0,1 , 160 , .

Microsoft , , 3 , .

:

, , , , DirectorySearcher, , , System System.DirectoryServices .

, "//do stuff" , , , , - .

+1

, . , , . , ive, , -

SELECT id FROM sometable
foreach row in table
SELECT * FROM sometable where id = ?

, , . . , , , .

, .

DirectoryEntry de = new DirectoryEntry("ldap://mydomain");
using (DirectorySearcher search = new DirectorySearcher())
{
    search.Filter = "(&(objectClass=user)(objectCategory=person))";
    search.PropertiesToLoad.Add("userAccountControl");
    search.PropertiesToLoad.Add("sn");
    search.PropertiesToLoad.Add("department");
    search.PropertiesToLoad.Add("l");
    search.PropertiesToLoad.Add("title");
    search.PropertiesToLoad.Add("givenname");
    search.PropertiesToLoad.Add("co");
    search.PropertiesToLoad.Add("displayName");
    search.PropertiesToLoad.Add("distinguishedName");
    foreach (SearchResult searchrecord in search.FindAll())
    {
        //do stuff
    }
}
0

Source: https://habr.com/ru/post/1676136/


All Articles