Solved

Need help to seach user in AD

Posted on 2011-02-21
8
861 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
[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
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 

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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

735 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