Flexabust Bergson
Flexabust Bergson

Reputation: 762

Active Directory search throws Exception with invalid name being searched

I am making a research of users in Active Directory using an asp.NET MVC5 website. When I make an invalid search (eg. '"éééézztaaz'), an ArgumentException keeps getting thrown, but I do not understand it. Here is my method to search :

public List<ADProperties> SearchUserByName(string name)
{
    //ADProperties is a POCO to store values retrieved
    try
    {

        List<ADProperties> theListIWant = new List<ADProperties>();
        //createDirectoryEntry() is a method to establish a connection to Active Directory
        DirectoryEntry ldapConnection = createDirectoryEntry();
        DirectorySearcher search = new DirectorySearcher(ldapConnection);

        //Search filter to find users
        search.Filter = "(&(objectClass=user)(anr=" + name + "))";

        ///Properties to load
        search.PropertiesToLoad.Add("objectSID");
        search.PropertiesToLoad.Add("displayName");
        search.PropertiesToLoad.Add("distinguishedName");
        resultCollection = search.FindAll();

        //ArgumentException at if statement
        //I put this to AVOID exceptions, then in my controller, if value is null 
        //I return a different view
        if (resultCollection==null ||resultCollection.Count==0)
        {
            return null;
        }

     }
     else
     { //Do stuff and return
          return theListIWant;
    }catch(ActiveDirectoryOperationException e)
    {
        Console.WriteLine("Active Directory Operation Exception caught: " + e.ToString());
    }
    return null;
}

The exact exception is:

The search filter (&(objectClass=user)(anr=)) isn't valid

(Translated from french)

So I don't get it. I added the condition to avoid throwing exceptions but apparently it doesn't help.

Upvotes: 0

Views: 154

Answers (1)

mjwills
mjwills

Reputation: 23984

I would suggest changing:

if (resultCollection==null ||resultCollection.Count==0)
{
    return null;
}

to:

try
{
    if (resultCollection == null || resultCollection.Count == 0)
    {
        return null;
    }
}
catch (ArgumentException)
{
    return null;
}

This will ensure that if ArgumentException is thrown, it will be treated the same way as if resultCollection is null.

Upvotes: 1

Related Questions