Solved

Need help to seach user in AD

Posted on 2011-02-21
8
858 Views
Last Modified: 2012-05-11
Hi Guru's

Wrote C# (console app) to retrieve user info from AD.

CODE :

using System;
using System.Text;
using System.DirectoryServices;

namespace activeDirectoryLdapExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter user: ");
            String username = Console.ReadLine();

            try
            {
                // create LDAP connection object

               // DirectoryEntry myLdapConnection = createDirectoryEntry();
                DirectoryEntry entry = new DirectoryEntry("GC://PFOXINT","aupfoxint\\LdapUser","Ld@pusr1", AuthenticationTypes.Secure);
                //DirectoryEntry entry = new DirectoryEntry("GC://Test", "Test\\Test", "Ld@Test", AuthenticationTypes.Secure);

                // create search object which operates on LDAP connection object
                // and set search object to only find the user specified

               // DirectorySearcher search = new DirectorySearcher(myLdapConnection);
                System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(entry);
                search.Filter = "(cn=" + username + ")";

                // create results objects from search object

                SearchResult result = search.FindOne();

                if (result != null)
                {
                    // user exists, cycle through LDAP fields (cn, telephonenumber etc.)

                    ResultPropertyCollection fields = result.Properties;
                                 
                    foreach (String ldapField in fields.PropertyNames)
                    {
                        // cycle through objects in each field e.g. group membership
                        // (for many fields there will only be one object such as name)

                        foreach (Object myCollection in fields[ldapField])
                        Console.WriteLine(String.Format("{0,-20} : {1}", ldapField, myCollection.ToString()));
                     

                    }
                }

                else
                {
                    // user does not exist
                    Console.WriteLine("User not found!");
                }
            }

            catch (Exception e)
            {
                Console.WriteLine("Exception caught:\n\n" + e.ToString());
            }
        }


    }
}


Now i have a real problem .
every time i use to pass string like "John David" to pulls the info from AD.

But i want to pass string like "John.David" as well as John (space) David,it should return the value.

Please give me some idea,how to deal with it.
0
Comment
Question by:Sha1395
  • 4
  • 4
8 Comments
 
LVL 9

Accepted Solution

by:
rawinnlnx9 earned 500 total points
ID: 34947773
I would write it all out for you but someone else has already done a good job of it: http://www.codeproject.com/KB/system/getuserfrmactdircsharp.aspx

function string setSearchType(string searchTerm)
{
    if (searchTerm.Contains(".")
    {
        searchTerm.Replace(".", " ");
    }
    elseif (searchTerm.Contains(" ")
    {
        //-- Do nothing here. This is how we want it.
    }
    else
    {
       // Neither "John.Doe" or "John Doe" were encountered. Handle this however you want.
    }
    return searchTerm.ToString();
}

Open in new window

0
 

Author Comment

by:Sha1395
ID: 34947796
Thanks a lot for your response,if you seen the code project example, the string is hard coded (like "Richmond") and my case am going to write a class file and use that dll in my windows application to return the value.

so basically my class file will get the string from my windows application. and return the property value for the appropriate users.

where i suppose to call your function in my code ? please
0
 
LVL 9

Expert Comment

by:rawinnlnx9
ID: 34947848
So you might have a public function returnUserProperty as string. This would be called by your windows application. So your windows application instances your class and then:

public string returnUser_givenName(string userName)
{
    string _userName = string.Empty();

    _userName = formatSearchTerm(userName);
 
    //-- From here down add in the code or the call to the function that searches the AD for the requested property. In
    //-- this example the property I'm returning is the "GivenName" property.

    // So you could:
   
    return SearchADForGivenProperty(_userName, "GivenName");
   
    // Then you'd write a function that would take a userName as a string and returned a "GivenName" if that was
    // the passed in property.
}

function string formatSearchTerm(string searchTerm)
{
    if (searchTerm.Contains(".")
    {
        searchTerm.Replace(".", " ");
    }
    elseif (searchTerm.Contains(" ")
    {
        //-- Do nothing here. This is how we want it.
    }
    else
    {
       // Neither "John.Doe" or "John Doe" were encountered. Handle this however you want.
    }
    return searchTerm.ToString();
}
0
 
LVL 9

Assisted Solution

by:rawinnlnx9
rawinnlnx9 earned 500 total points
ID: 34947855
I made a mistake in my formatSearchTerm function. Here is the fixed function.

function string formatSearchTerm(string searchTerm)
{
    if (searchTerm.Contains(".")
    {
        searchTerm = searchTerm.Replace(".", " ");
    }
    elseif (searchTerm.Contains(" ")
    {
        //-- Do nothing here. This is how we want it.
    }
    else
    {
       // Neither "John.Doe" or "John Doe" were encountered. Handle this however you want.
    }
    return searchTerm.ToString();
} 

Open in new window

0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:Sha1395
ID: 34947955
Awesome thank you so much,here am trying to consolidate my code based on your suggestion gotta some problem,please correct me


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;

namespace ClassLibrary4
{
public string returnUser_givenName(string userName)
{
    string _userName = string.Empty();

    _userName = formatSearchTerm(userName);
 
    //-- From here down add in the code or the call to the function that searches the AD for the requested property. In
    //-- this example the property I'm returning is the "GivenName" property.
     DirectoryEntry entry = new DirectoryEntry("GC://PFOXINT","aupfoxint\\LdapUser","Ld@pusr1", AuthenticationTypes.Secure);
     System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(entry);
     search.Filter = "(cn=" + _username + ")";
     if (result != null)
                {
                    // user exists, cycle through LDAP fields (cn, telephonenumber etc.)

                    ResultPropertyCollection fields = result.Properties;
                                 
                    foreach (String ldapField in fields.PropertyNames)
                    {
                        // cycle through objects in each field e.g. group membership
                        // (for many fields there will only be one object such as name)

                        foreach (Object myCollection in fields[ldapField])
                        Console.WriteLine(String.Format("{0,-20} : {1}", ldapField, myCollection.ToString()));
                   
                    }
                }

                else
                {
                    // user does not exist
                    Console.WriteLine("User not found!");
                }
   
    // So you could:
   
   
   
    // Then you'd write a function that would take a userName as a string and returned a "GivenName" if that was
    // the passed in property.
}

function string formatSearchTerm(string searchTerm)
{
    if (searchTerm.Contains(".")
    {
        searchTerm.Replace(".", " ");
    }
    elseif (searchTerm.Contains(" ")
    {
        //-- Do nothing here. This is how we want it.
    }
    else
    {
       // Neither "John.Doe" or "John Doe" were encountered. Handle this however you want.
    }
    return searchTerm.ToString();
}

 }
0
 

Author Comment

by:Sha1395
ID: 34948081
Hi

Please check my code i was trying to write replace inside the main ,rather than calling function.

But i got bunch of errors on that logic.


using System;
using System.Text;
using System.DirectoryServices;

namespace activeDirectoryLdapExamples
{
    class Program
    {
        static void Main(string[] args)
        {
           
            Console.Write("Enter user: ");
            String username = Console.ReadLine();

          if (username.Contains("."))
         {
             username = username.Replace(".", " ");
           }
            elseif (username.Contains(" ")
            {
        //-- Do nothing here. This is how we want it.
             }
          else
          {
       // Neither "John.Doe" or "John Doe" were encountered. Handle this however you want.
          }


            try
            {
                // create LDAP connection object

               // DirectoryEntry myLdapConnection = createDirectoryEntry();
                DirectoryEntry entry = new DirectoryEntry("GC://PFOXINT","aupfoxint\\LdapUser","Ld@pusr1", AuthenticationTypes.Secure);
                //DirectoryEntry entry = new DirectoryEntry("GC://Test", "Test\\Test", "Ld@Test", AuthenticationTypes.Secure);

                // create search object which operates on LDAP connection object
                // and set search object to only find the user specified

               // DirectorySearcher search = new DirectorySearcher(myLdapConnection);
                System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(entry);
                search.Filter = "(cn=" + username + ")";

                // create results objects from search object

                SearchResult result = search.FindOne();

                if (result != null)
                {
                    // user exists, cycle through LDAP fields (cn, telephonenumber etc.)

                    ResultPropertyCollection fields = result.Properties;
                                 
                    foreach (String ldapField in fields.PropertyNames)
                    {
                        // cycle through objects in each field e.g. group membership
                        // (for many fields there will only be one object such as name)

                        foreach (Object myCollection in fields[ldapField])
                        Console.WriteLine(String.Format("{0,-20} : {1}", ldapField, myCollection.ToString()));
                   
                    }
                }

                else
                {
                    // user does not exist
                    Console.WriteLine("User not found!");
                }
            }

            catch (Exception e)
            {
                Console.WriteLine("Exception caught:\n\n" + e.ToString());
            }
        }


    }
}
0
 
LVL 9

Expert Comment

by:rawinnlnx9
ID: 34967324
what is the problem you are having? It looks like what you have should work. Is this a console application? What error are you getting?
0
 

Author Comment

by:Sha1395
ID: 34967624
Its working properly.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
As a trusted technology advisor to your customers you are likely getting the daily question of, ‘should I put this in the cloud?’ As customer demands for cloud services increases, companies will see a shift from traditional buying patterns to new…

911 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now