0

I have the following code :

        DirectoryEntry directoryEntry = default(DirectoryEntry);
        // Binding object. 
        DirectoryEntry objGroupEntry = default(DirectoryEntry);
        // Group Results. 
        DirectorySearcher objSearchADAM = default(DirectorySearcher);
        // Search object. 
        SearchResultCollection objSearchResults = default(SearchResultCollection);
        // Binding path. 
        ActiveDirectory result = new ActiveDirectory();
        ActiveDirectoryItem treeNode;

    string adServer = ADTestProject.Properties.Settings.Default.Server;
    string adDomain = ADTestProject.Properties.Settings.Default.Domain;
    string adUsername = ADTestProject.Properties.Settings.Default.AdiminUsername;
    string password = ADTestProject.Properties.Settings.Default.Password;

    string[] dc = adDomain.Split('.');

    string dcAdDomain = string.Empty;

    foreach (string item in dc)
    {
        if (dc[dc.Length - 1].Equals(item))
            dcAdDomain = dcAdDomain + "DC=" + item;
        else
            dcAdDomain = dcAdDomain + "DC=" + item + ",";
    }

    // Get the AD LDS object. 

        if (pathToAD.Length > 0)
            directoryEntry = new DirectoryEntry("LDAP://" + adServer + "/CN=Users," + dcAdDomain, adUsername, password);
        else
            directoryEntry = new DirectoryEntry();

        DirectorySearcher ds = new DirectorySearcher(directoryEntry);
        ds.SearchScope = SearchScope.Subtree;
        ds.Filter = "(&(objectClass=group))";

        objSearchResults = ds.FindAll();

And then this :

if (objSearchResults.Count != 0)
{
    foreach (SearchResult objResult in objSearchResults)
    {
        objGroupEntry = objResult.GetDirectoryEntry();
        result.ActiveDirectoryTree.Add(new ActiveDirectoryItem() 
        { Id = objGroupEntry.Guid, 
            ParentId = objGroupEntry.Parent.Guid, 
            AccountName = objGroupEntry.Name, 
            Type = ActiveDirectoryType.Group, 
            PickableNode = false 
        });

        foreach (object child in objGroupEntry.Properties["member"])
        {
            treeNode = new ActiveDirectoryItem();
            var path = child.ToString().Replace;
            using (var memberEntry = new DirectoryEntry(path))
            {

                if (memberEntry.Username != null && memberEntry.SchemaEntry.Name.CompareTo("group") != 0 
                    && memberEntry.Properties.Contains("sAMAccountName") && memberEntry.Properties.Contains("objectSid"))
                {
                    treeNode.Id = Guid.NewGuid();
                    treeNode.ParentId = objGroupEntry.Guid;
                    treeNode.AccountName = memberEntry.Properties["sAMAccountName"][0].ToString();
                    treeNode.Type = ActiveDirectoryType.User;
                    treeNode.PickableNode = true;
                    treeNode.FullName = memberEntry.Properties["Name"][0].ToString();

                    byte[] sidBytes = (byte[])memberEntry.Properties["objectSid"][0];
                    treeNode.ObjectSid = new System.Security.Principal.SecurityIdentifier(sidBytes, 0).ToString();

                    result.ActiveDirectoryTree.Add(treeNode);
                }
            }
        }
    }
}

The Child.ToString could look like this :

CN=S-1-5-18,CN=ForeignSecurityPrincipals,DC=MyDomain,DC=local

The problem is that memberEntry get a lot of exceptions on its properties? Why?

The exception is this :

'memberEntry.Name' threw an exception of type 'System.Runtime.InteropServices.COMException' string {System.Runtime.InteropServices.COMException} - Unspecified error -2147467259

Stacktrace : at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind() at System.DirectoryServices.DirectoryEntry.get_Name()

nickytonline
  • 6,855
  • 6
  • 42
  • 76
Banshee
  • 15,376
  • 38
  • 128
  • 219
  • `catch (Exception e) { throw e; }` - a bit pointless, you're loosing whole call stack. Use `throw;` instead or get rid of whole try \ catch block. – Jakub Konecki Jun 12 '12 at 09:58
  • Yes you are correct, haven cleaned the code yet. Thanks – Banshee Jun 12 '12 at 09:59
  • Since you haven't mentioned the exact exception you're getting, we can only guess here but perhaps the `Name` attribute isn't defined on all the objects? You're getting it unconditionally and that would might the issue. – Maverik Jun 12 '12 at 10:03
  • I have updated with the exception. I get this(exception) on all 30 items? – Banshee Jun 12 '12 at 10:08
  • Thats COM error 0x80004005: Lookup failed. So Name attribute isn't found on any of them (or you can't read it because of permissions) - Have you tried checking with ADSI for the existence of the attribute? – Maverik Jun 12 '12 at 10:14
  • Im not sure what you mean? Im fetching all items from the AD and then I try to get extra information about them like name, accountName and so on. When getting that far we know that the item is existing, the question is only to get extra data about the item to be able to display it in nice way. – Banshee Jun 12 '12 at 10:22
  • I just spotted something else. I don't see you specifying PropertiesToLoad anywhere in your code. Are you doing that somewhere before querying for value? Be default only a limited properties are pulled from AD – Maverik Jun 12 '12 at 10:22
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/12432/discussion-between-maverik-and-snowjim) – Maverik Jun 12 '12 at 10:23

2 Answers2

4

After a chat with OP, we determined the problem to be in the path variable being used in DirectoryEntry and explicit authentication needed within OP's environment.

relevant change was:

using (var memberEntry = new DirectoryEntry(path))

to

using (var memberEntry = new DirectoryEntry("LDAP://" + adServer + "/" + path, adUsername, password))

For details: Full transcript

Community
  • 1
  • 1
Maverik
  • 5,619
  • 35
  • 48
0

This could be a duplicate of get a list of user from the AD

But, despite that, there is an article that describes lots of useful queries on the AD on CodeProject: Querying MS AD using dot Net

Community
  • 1
  • 1
Mare Infinitus
  • 8,024
  • 8
  • 64
  • 113
  • I don't think the two are similar. The question in link was asking how to pull the users. Problem here is a lookup failure and OP has to figure out why. – Maverik Jun 12 '12 at 10:20