Click here to Skip to main content
15,881,173 members
Articles / Properties
Article

How to query Active Directory without hard-coding the domain name

Rate me:
Please Sign up or sign in to vote.
4.67/5 (5 votes)
11 Oct 2013CPOL3 min read 37.4K   8  
It can be useful to be able to write code that can query the current domain without you having to hard-code the domain name.  This article will show

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

It can be useful to be able to write code that can query the current domain without you having to hard-code the domain name.  This article will show you how.

Scenario

Let us imagine that you have two Active Directory forests, one production and one development: they're called prod.com (PROD) and dev.com (DEV).  You're required to develop your code in dev.com before putting it live in prod.com.  You decide that it would be good if you could write code that didn't have hard-coded references to your dev domain because then you wouldn't have to change the code when you put it live. 

Solution

This can be done by using RootDSE. An example distinguishedName from test.com might be  CN=TestGroup1,OU=Groups,DC=test,DC=com.  The latter two 'chunks' (DC=test,DC=com) are also known as a namingContext.  If they happen to be the current domain, then they're known as the defaultNamingContext.

To clarify this, imagine an Active Directory forest with two domains: root.com is the top-level domain and child.root.com is a child domain of root.com.  If you were logged onto a workstation in root.com, your defaultNamingContext would be root.com. If you were logged onto a workstation in child.root.com, your defaultNamingContext would be child.root.com*. 

So, how does this help us?

If we can retrieve the defaultNamingContext from RootDSE, then we can use that instead of part of the distinguishedName.  E.g. "CN=TestGroup1,OU=Groups," + defaultNamingContext.

*In both instances there's also a rootDomainNamingContext which is root.com.

How to get the defaultNamingContext in C#

            string defaultNamingContext;
            using (DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE"))
            {
                defaultNamingContext = rootDSE.Properties["defaultNamingContext"].Value.ToString();
            }
            Console.WriteLine("Accessing domain: {0}", defaultNamingContext);

How to get the defaultNamingContext in VB.Net

        Dim defaultNamingContext As String
        Using rootDSE As New DirectoryEntry("LDAP://RootDSE")
            defaultNamingContext = rootDSE.Properties("defaultNamingContext").Value.ToString()
        End Using
        Console.WriteLine("Accessing domain: {0}", defaultNamingContext)
 

How to get the defaultNamingContext in IronPython

        rootDSE = DirectoryEntry("LDAP://RootDSE")
        defaultNamingContext = rootDSE.Properties["defaultNamingContext"].Value
        Console.WriteLine("Accessing domain: {0}", defaultNamingContext)

 

There are other properties of RootDSE that can be useful.  Here are C# and VB.net snippets that list the properties.  You can see the same by binding to your directory using the LDP tool.

How to list the properties of RootDSE in C#

            using (DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE"))
            {
                Console.WriteLine("\r\nAttributes with a single value:");
                foreach (string propertyName in rootDSE.Properties.PropertyNames)
                {
                    if (rootDSE.Properties[propertyName].Count == 1)
                    {
                        Console.WriteLine("{0,30} = {1}", propertyName,
                            rootDSE.Properties[propertyName].Value);
                        continue;
                    }
                }
                Console.WriteLine("\r\nAttributes with multiple values:");
                foreach (string propertyName in rootDSE.Properties.PropertyNames)
                {
                    if (rootDSE.Properties[propertyName].Count > 1)
                    {
                        Console.WriteLine("    {0}:", propertyName);
                        foreach (object obj in (object[])(rootDSE.Properties[propertyName].Value))
                        {
                            Console.WriteLine("        {0}", obj.ToString());
                        }
                    }
                }
            }
 

How to list the properties of RootDSE in VB.Net

        Using rootDSE As New DirectoryEntry("LDAP://RootDSE")
            Console.WriteLine(vbCrLf + "Attributes with a single value:")
            For Each propertyName As String In rootDSE.Properties.PropertyNames
                If rootDSE.Properties(propertyName).Count = 1 Then
                    Console.WriteLine("{0,30} = {1}", propertyName, _
                            rootDSE.Properties(propertyName).Value.ToString())
                    Continue For
                End If
            Next
            Console.WriteLine(vbCrLf + "Attributes with multiple values:")
            For Each propertyName As String In rootDSE.Properties.PropertyNames
                If rootDSE.Properties(propertyName).Count > 1 Then
                    Console.WriteLine("    {0}:", propertyName)
                    For Each obj As Object In CType(rootDSE.Properties(propertyName).Value, Object())
                        Console.WriteLine("        {0}", obj.ToString())
                    Next
                End If
            Next
        End Using
 

N.B.  I'm a C#er normally so I may not be posting great VB.Net code.  Actually, my C# may not be great either but there you go.  :-)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.

The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.
This is a Collaborative Group

755 members

Comments and Discussions

 
-- There are no messages in this forum --