?
Solved

Need help to seach user in AD

Posted on 2011-02-21
8
Medium Priority
?
864 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 2000 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 9

Assisted Solution

by:rawinnlnx9
rawinnlnx9 earned 2000 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

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!

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…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
Suggested Courses
Course of the Month9 days, 14 hours left to enroll

762 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