0

Scenario: User enters a name (which could be either first name or surname) in the textbox and click the search button. System should return all the usernames (along with Full name) wherever the first or surname matches with existing AD users.

Problem: Input text does not get checked against both the firstname and the surname at the same time.

    List<string> GetUserDetails()
    {
        List<string> allUsers = new List<string>();
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "myDomain",
                                                    "OU=ounit,dc=myDC,dc=com");

        UserPrincipal qbeUser = new UserPrincipal(ctx);

        qbeUser.GivenName = _UITxtUserName.Text;
        qbeUser.Surname = _UITxtUserName.Text;

        PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
            foreach (var found in srch.FindAll())
            {

                allUsers.Add(found.DisplayName +"(" + found.SamAccountName+")");
            }

            allUsers.Sort();

        return allUsers;

    }

I can see the problem is with the _UITxtUserName (text box). But not sure how can it be fixed. Using .Net 3.5.

PineCone
  • 2,193
  • 12
  • 37
  • 78
  • 1
    You cannot do it this way - right now, your code checks for a user that has the **identical** first and last name that both match whatever your user has typed in. It's highly unlikely you'll ever have such a user. You'll need to search for a match on the first name first, and in second search, look for a match on last name, and then join the two resulting lists. – marc_s Oct 14 '13 at 12:18
  • 1
    As said by @marc_s perform the search 2 times by passing different filter criteria to the PrincipalSearcher. Make sure to clear the filter before the 2nd search is called by setting the qbeUser object to null. – Rajesh Oct 14 '13 at 13:42

1 Answers1

4

Working code

List<string> GetUserDetails()
    {
        List<string> allUsers = new List<string>();
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "myDomain",
                                                "OU=ounit,dc=myDC,dc=com");

        UserPrincipal qbeUser = new UserPrincipal(ctx);

        qbeUser.GivenName = _UITxtUserName.Text;

        PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
        foreach (var found in srch.FindAll())
        {

            allUsers.Add(found.DisplayName + "(" + found.SamAccountName + ")");
        }
        qbeUser = null; 
        qbeUser = new UserPrincipal(ctx);

        qbeUser.Surname = _UITxtUserName.Text;

        PrincipalSearcher srch1 = new PrincipalSearcher(qbeUser);
        foreach (var found in srch1.FindAll())
        {

            allUsers.Add(found.DisplayName + "(" + found.SamAccountName + ")");
        }

        allUsers.Sort();

        return allUsers;
    }
PineCone
  • 2,193
  • 12
  • 37
  • 78