Solved

Need help to seach user in AD

Posted on 2011-02-21
8
857 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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Bit flags and bit flag manipulation is perhaps one of the most underrated strategies in programming, likely because most programmers developing in high-level languages rely too much on the high-level features, and forget about the low-level ones. Th…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

708 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

12 Experts available now in Live!

Get 1:1 Help Now