0

We are using the foll. code to retrieve the AD users and their details:-

We get error at line: SearchResultCollection resultCol = search.FindAll();

Exception is: DirectoryServiceCOMException: An operations error occurred. at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_AdsObject() at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne) at SharePointProject20.VisualWebPart1.VisualWebPart1.GetADUsers()

public List<Users> GetADUsers()
        {
            try
            {
                List<Users> lstADUsers = new List<Users>();
                string DomainPath = "LDAP://DC=SYSDOM,DC=local";
                DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
                DirectorySearcher search = new DirectorySearcher(searchRoot);
                search.Filter = "(&(objectClass=user)(objectCategory=person))";
                search.PropertiesToLoad.Add("samaccountname");
                search.PropertiesToLoad.Add("mail");
                search.PropertiesToLoad.Add("usergroup");
                search.PropertiesToLoad.Add("displayname");//first name
                SearchResult result;
                SearchResultCollection resultCol = search.FindAll();
                if (resultCol != null)
                {
                    for (int counter = 0; counter < resultCol.Count; counter++)
                    {
                        string UserNameEmailString = string.Empty;
                        result = resultCol[counter];
                        if (result.Properties.Contains("samaccountname") &&
                                 result.Properties.Contains("mail") &&
                            result.Properties.Contains("displayname"))
                        {
                            Users objSurveyUsers = new Users();
                            objSurveyUsers.Email = (String)result.Properties["mail"][0] +
                              "^" + (String)result.Properties["displayname"][0];
                            objSurveyUsers.UserName = (String)result.Properties["samaccountname"][0];
                            objSurveyUsers.DisplayName = (String)result.Properties["displayname"][0];
                            lstADUsers.Add(objSurveyUsers);
                        }
                    }
                }
                return lstADUsers;
            }
            catch (Exception ex)
            {
                return null;
            }
        }


    public class Users
    {
        public string Email { get; set; }
        public string UserName { get; set; }
        public string DisplayName { get; set; }
        public bool isMapped { get; set; }
    }

What could be the issue?

Our domain name is SYSDOM.local

Could it be related to permissions (how do I verify this with network admin guys?), or do I need to explicitly pass username/password?

Code reference: http://www.codeproject.com/Tips/599697/Get-list-of-Active-Directory-users-in-Csharp

4
  • Are you sure that "usergroup" is a valid attribute? Commented Mar 20, 2014 at 13:11
  • I am not very sure I got the source from the reference url. Is it not correct? Commented Mar 20, 2014 at 16:50
  • It is sure not a default one. In the reference url,he doesn't even use the property afterward. Try remove that line. I'm not saying this will fix your error, but I found it a bit ankward. Commented Mar 21, 2014 at 2:50
  • Also, according to this post stackoverflow.com/questions/7285503/… , this looks indeed like a authentification issue. Try passing privileged credentials to the directoryEntry. Commented Mar 21, 2014 at 2:54

2 Answers 2

1

If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. You can use a PrincipalSearcher and a "query-by-example" principal to do your searching:

// create your domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
   // define a "query-by-example" principal - here, we search for a UserPrincipal 
   UserPrincipal qbeUser = new UserPrincipal(ctx);

   // create your principal searcher passing in the QBE principal    
   PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

   // find all matches
   foreach(var found in srch.FindAll())
   {
       // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....          
   }
}

If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement. Or see the MSDN documentation on the System.DirectoryServices.AccountManagement namespace.

Of course, depending on your need, you might want to specify other properties on that "query-by-example" user principal you create:

  • DisplayName (typically: first name + space + last name)
  • SAM Account Name - your Windows/AD account name
  • User Principal Name - your "[email protected]" style name

You can specify any of the properties on the UserPrincipal and use those as "query-by-example" for your PrincipalSearcher.

Constructing the PrincipalContext like shown in the sample will automatically connect to the current AD domain with the current user credentials. If you need to, you can specify other containers or domains to bind to, or you can also supply alternative credentials by using other overloads of the PrincipalContext constructor

Sign up to request clarification or add additional context in comments.

6 Comments

I am on ASP.NET 4.5, it there any reference code available?
System.DirectoryServices.AccountManagement is available for .net 3.5 and up. The code above will work for you.
If I use the code it gives "Exception Details: System.DirectoryServices.DirectoryServicesCOMException: An operations error occurred." at line "PrincipalSearcher srch = new PrincipalSearcher(qbeUser);"
@NachiketKamat: is there an .InnerEXception with a more useful message? If so: what is it? Also: is that computer part of the AD domain?
@NachiketKamat: as atconway explained - this error would happen if the user account the app is running under doesn't have the privileges necessary to connect to and query Active Directory
|
0

The issue was resolved after using the HostingEnvironment.Impersonate() in PageLoad:-

Example:

using (HostingEnvironment.Impersonate()) {
GetADUsers();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.