?
Solved

Extracting Users from Active directory

Posted on 2010-11-10
9
Medium Priority
?
1,091 Views
Last Modified: 2013-12-24
I need to extract user information from Active Directory...

I am not to familiar with the current Active directory structure.. So I was wondering how can I go about querying the active directory for user info...

I am able to log into the active directory using the DirectoryEntry object in C# and set the search criteria filter to "(&(objectCategory=user)(objectClass=person))" but this does not give me much info...

I have also attached my current code in the code section

Any help in this regard will be highly appreciated..

public DataTable GetData(Entities.Config.EtlConfig config)
        {
            var s = new SqlLoader();
            var dt = s.GetTableSchema(config.SqlTableToLoad);
            string setdate = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss");
            try
            {
                var de = GetDirectoryEntry();
                var ds = new DirectorySearcher(de) { Filter = "(&(objectCategory=user)(objectClass=person))" };
                var results = ds.FindAll();
                //var results = ds.FindOne();

                    foreach (SearchResult result in results)
                    {
                        if (results != null)
                        {
                            DataRow dr = dt.NewRow();

                            dr["Employee_Key"] = GetProperty(result, "title") ?? string.Empty;
                            dr["Employee_Name"] = GetProperty(result, "cn") ?? string.Empty;


                            dr["Employee_Full_Name"] = GetProperty(result, "distinguishedName") ?? string.Empty;
                            dr["Employee_Phone_Number"] = GetProperty(result, "telephoneNumber") ?? string.Empty;

                            dr["Email_Address"] = GetProperty(result, "mail") ?? string.Empty;
                            dr["Business_Unit"] = GetProperty(result, "department") ?? string.Empty;

                            dr["Supervisor_Full_Name"] = GetProperty(result, "manager") ?? string.Empty;
                            dr["Row_Update_Date"] = setdate;
                            dr["Source"] = config.Source;

                            dt.Rows.Add(dr);
                        }
                        de.Close();

                    }
                return dt;

            }
            catch (Exception e)
            {
                _log.Error(e.Message);
                throw new CustomException(e, ErrorType.DataImporter, e.Message);
            }
        }
        /// <summary>
        /// Method used to create an entry to the AD.
        /// Replace the path, username, and password.
        /// </summary>
        /// <returns>DirectoryEntry</returns>
        public static DirectoryEntry GetDirectoryEntry()
        {
            var de = new DirectoryEntry
                         {
                             //Path = "LDAP://DC=a,DC=b,DC=c,DC=Com",
                             Path = "LDAP://a.b.c.Com",
                             Username = @"a\SomeUser",
                             Password = "SomePwd"
                         };
            return de;
        }

        public static string GetProperty(SearchResult searchResult, string propertyName)
        {
            return searchResult.Properties.Contains(propertyName) ? searchResult.Properties[propertyName][0].ToString() : string.Empty;
        }

Open in new window

0
Comment
Question by:2ooth
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 2
9 Comments
 
LVL 15

Expert Comment

by:angus_young_acdc
ID: 34101469
So what information is it you are trying to extract?  Is there anything specific?  
0
 
LVL 4

Accepted Solution

by:
incerc earned 2000 total points
ID: 34101531
Please try :

Filter = "(&(objectCategory=person)(objectClass=user))"

(switch values in your filter)

0
 
LVL 4

Expert Comment

by:incerc
ID: 34101566
0
Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
LVL 4

Expert Comment

by:incerc
ID: 34101593
For a code sample of retrieving all the active directory user’s attributes, configured and not configured, please take a look in here:
http://codeleacher.wordpress.com/2008/08/07/how-to-get-all-users-active-directory-schema-properties/

There, hope it helps!
0
 
LVL 4

Expert Comment

by:incerc
ID: 34101715
Hum, back again .. I just noticed in your code that you close the DirectoryEntry object after the first result is processed :

  foreach (SearchResult result in results)
                    {
                        if (results != null) --> typo? (should check result in here)
                        {
                            ...
                        }
                        de.Close();  ---> problem! should close after foreach ended
                    }

Also,  if (results != null) should be before the foreach method, or it should read like this :
if (result != null)
0
 

Author Comment

by:2ooth
ID: 34103096
HI,

Thank you for all your Comments...

I really really appreciate your help

I basically need to search for all users within Active directory..

I am currently unable to set the filter to extract only users.. even though i have set the filter to (&(objectCategory=person)(objectClass=user))

@incerc - Thanks for pointing out the bug with regards to my code.. however the situation is still hopeless

i did go thought the link about "Searching Active Directory for User Accounts " However it did not provide me with much information as to how this could be achieved.

Please Helpp!!!
0
 
LVL 4

Expert Comment

by:incerc
ID: 34103916
Hi,

What do you obtain using the filter above?

Can you run your code into debug mode and check the values? Or maybe put some debug messages in order to have more info?

Is it an exception thrown?
0
 

Author Comment

by:2ooth
ID: 34104230
I finaly cracked it.....

Its all working now...

You guys are the best!!!!

Thank you all for your help
0
 
LVL 4

Expert Comment

by:incerc
ID: 34110111
Nice to hear that, what was the problem?

I'd suggest that you close then this question, and select an answer that helped you in your debugging. :)
0

Featured Post

Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this blog post, we’ll look at how using thread_statistics can cause high memory usage.
In the absence of a fully-fledged GPO Management product like AGPM, the script in this article will provide you with a simple way to watch the domain (or a select OU) for GPOs changes and automatically take backups when policies are added, removed o…
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
Suggested Courses

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question