user948060
user948060

Reputation: 973

What info do I need to connect to Active Directory in C#?

I need to connect to a clients AD server to display information for all users. They've given me the following: fqdn, netbios name and a domain controller. Is this enough to connect?

using (var context = new PrincipalContext(ContextType.Domain, "",)) 
using (var searcher = new PrincipalSearcher(new UserPrincipal(context))) 
{ 
   foreach (var result in searcher.FindAll()) 
   { 
            DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry; 
   }
}

Thanks!

Upvotes: 0

Views: 309

Answers (2)

hal9000
hal9000

Reputation: 852

I think Ryan was showing you the old way to do it. From your code it looks like you are using the newer classes.

            // create a principal searcher for running a search operation 
        using (PrincipalSearcher pS = new PrincipalSearcher(uParams))
        {
            // assign the query filter property for the principal object you created 
            // you can also pass the user principal in the PrincipalSearcher constructor 
            pS.QueryFilter = uParams;

            // run the query 
            using (PrincipalSearchResult<Principal> results = pS.FindAll())
            {
                foreach (Principal item in results)
                {
                    UserPrincipal u = item as UserPrincipal;
                    list.Add(new MyCustomClass(u.UserPrincipalName)
                    {
                        Cn = u.Name,
                        Email = u.EmailAddress,
                        EmployeeId = u.EmployeeId,
                        NameFirst = u.GivenName,
                        NameLast = u.Surname,
                        ObjectSid = u.Sid.ToString(),
                        DistinguishedName = u.DistinguishedName,
                        SamAccount = u.SamAccountName
                    });
                }
            }
        }

Note that the AD still imposes sometihng like a 1500 item limit on your queries so you will likely need to send your DirectoryEntry top to something like this:

        /// <summary>
    /// group member enumeration, simple and fast for large AD groups
    /// </summary>
    /// <param name="deGroup"></param>
    /// <returns>list if distinguished names</returns>
    public static List<string> GetMemberList(DirectoryEntry deGroup)
    {
        List<string> list = new List<string>();
        DirectoryEntry entry = deGroup;

        uint rangeStep = 1000;
        uint rangeLow = 0;
        uint rangeHigh = rangeLow + (rangeStep - 1);
        bool lastQuery = false;
        bool quitLoop = false;

        do
        {
            string attributeWithRange;
            if (!lastQuery)
            {
                attributeWithRange = String.Format("member;range={0}-{1}", rangeLow, rangeHigh);
            }
            else
            {
                attributeWithRange = String.Format("member;range={0}-*", rangeLow);
            }
            using (DirectorySearcher searcher = new DirectorySearcher(entry))
            {
                searcher.Filter = "(objectClass=*)";
                //searcher.Filter = LdapObjectMgr.filterDisabledUsers;

                searcher.PropertiesToLoad.Clear();
                searcher.PropertiesToLoad.Add(attributeWithRange);
                SearchResult results = searcher.FindOne();
                foreach (string res in results.Properties.PropertyNames)
                {
                    //list the property names
                    System.Diagnostics.Debug.WriteLine(res.ToString());
                }

                if (results.Properties.Contains(attributeWithRange))
                {
                    foreach (object obj in results.Properties[attributeWithRange])
                    {
                        //Console.WriteLine(obj.GetType());
                        if (obj.GetType().Equals(typeof(System.String)))
                        {
                        }
                        else if (obj.GetType().Equals(typeof(System.Int32)))
                        {
                        }
                        //Console.WriteLine(obj.ToString());
                        list.Add(obj.ToString());
                    }
                    if (lastQuery)
                    {
                        quitLoop = true;
                    }
                }
                else
                {
                    if (lastQuery == false)
                    { lastQuery = true; }
                    else
                    { quitLoop = true; }
                }
                if (!lastQuery)
                {
                    rangeLow = rangeHigh + 1;
                    rangeHigh = rangeLow + (rangeStep - 1);
                }
            }
        }
        while (!quitLoop);

        return list;
    }

Upvotes: 1

Ryan Bennett
Ryan Bennett

Reputation: 3432

To connect via C# you will need something like this:

DirectoryEntry child = new DirectoryEntry("LDAP://" + domainControllerName + "/" + 
        objectDn, userName, password);

If you have the domain controller name, the object domain, a user name and a password, you should be good to go.

Just a heads up, you got downvoted because you didn't mention anything that you tried previously.

Upvotes: 0

Related Questions