Question

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.

Was it helpful?

Solution

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;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top