Solved

If condition in search filter

Posted on 2011-02-21
5
1,084 Views
Last Modified: 2012-05-11
Hi ,

I wrote a below 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();

            if (username.Contains("."))
            {
               
                string[] splitString = username.Split(new char[] { '.' });
                username = splitString[splitString.Length - 1];
                Console.WriteLine(username);


            }


            try
            {
                // create LDAP connection object

                // DirectoryEntry myLdapConnection = createDirectoryEntry();

                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 + ")";

                search.Filter = "(sn=" + 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());
            }
        }


    }
}

Am passing the string (eg:will.smith) in that case am using IF statement to get the last name (eg:smith) and using search.Filter = "(sn=" + username + ")";

Now i have a problem,if the string comes like (eg: Will(space )Smith) then i will take the whole string and use the  search.Filter = "(cn=" + username + ")";

i was trying to put if statement,it doesn't work,some one please give me an idea.



0
Comment
Question by:Sha1395
  • 2
  • 2
5 Comments
 
LVL 53

Accepted Solution

by:
Dhaest earned 500 total points
ID: 34949201
You can search for the space location....

// DirectorySearcher search = new DirectorySearcher(myLdapConnection);

System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(entry);

if (username.IndexOf(" ") > 0)
     search.Filter = "(cn=" + username + ")";
else
      search.Filter = "(sn=" + username + ")";
               
 // create results objects from search object

0
 
LVL 8

Expert Comment

by:crysallus
ID: 34949268
Probably easiest if you create the whole filter search string in the if statement eg.

string searchFilter = "";
if (username.Contains("."))
{
    string[] splitString = username.Split(new char[] { '.' });
    searchFilter = "(sn=" + splitString[splitString.Length - 1] + ")";
}
else if (username.Contains(' '))
{
    string[] splitString = username.Split(new char[] { ' ' });
    searchFilter = "(sn=" + splitString[splitString.Length - 1] + ")";
}
else
    searchFilter = "(cn=" + username + ")";

try
{
    ... (your code as is here)
    search.Filter = searchFilter;
etc.

Open in new window

As long as that matches what you want to search on i.e. surname if username contains it, otherwise the whole username.
0
 

Author Comment

by:Sha1395
ID: 34950193
Thanks Dhaest and crysallus for your great reply,i just modified my code based on Dhaet (feel very simple and very less to change in my code)

Anyway thanks a lot guys
0
 

Author Comment

by:Sha1395
ID: 34950235
i have one more question the whole code was written in C# console application ,i just want to convert this file in to DLL class library and i will create windows application and pass the string from there.

Please help me or suggest me a simple way to convert the whole file in to DLL class library then i will call this dll from my win application and pass the string from there.

Thanks in Advance
0
 
LVL 8

Expert Comment

by:crysallus
ID: 34950253
That question you've just added probably needs to be a separate question so you can assign more points to whoever answers it.
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

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…
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!
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

785 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