Solved

Need help to seach user in AD

Posted on 2011-02-21
8
859 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
Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

 
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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.

832 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