Reputation: 227
I have a requirement to retrieve all the user related information from the Active Directory.
My code retrieves username,useremail, Full Name
of the user but when I try to retrieve the name of the manager, the code throws an exception.
The following is my code :
DataTable table = new DataTable();
table = dt;
DirectoryEntry dEntry = new DirectoryEntry("LDAP://" + domain);
DirectorySearcher dSearch = new DirectorySearcher(dEntry);
SearchResultCollection sResultcol;
try
{
dSearch.Filter = "(objectCategory=organizationalUnit)";
sResultcol = dSearch.FindAll();
foreach (SearchResult sResult in sResultcol)
{
DirectoryEntry dUserEntry = new DirectoryEntry();
DirectorySearcher dSearchUsers = new DirectorySearcher(dEntry);
SearchResultCollection sUserResults;
dSearchUsers.Filter = "(objectClass=User)";
dSearchUsers.SearchScope = SearchScope.Subtree;
sUserResults = dSearchUsers.FindAll();
foreach (SearchResult sUserResult in sUserResults)
{
DataRow dr = table.NewRow();
string empCode = sResult.Properties["pager"].ToString();
if (empCode.Length != 0)
{
dr["empcode"] = empCode;
string namee = sUserResult.Properties["samaccountname"][0].ToString();
dr["name"] = namee;
string disname = sResult.Properties["distinguishedName"][0].ToString();
dr["ou"] = disname;
string manager = sUserResult.Properties["manager"].Value.ToString();
dr["manager"] = manager;
dt.Rows.Add(dr);
}
}
dUserEntry.Close();
}
return dt;
}
catch (Exception ex)
{
throw new Exception("Error at retrieveUsers() : " + ex.Message.ToString());
}
I get the exception
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
when I try to get the manager name.
As per the structure of the Active Directory, the manager's name is located in another tab.
Does anyone have any idea of retrieving the data from the tabs other than General from the Active Directory?
Please help me.
Thanks in advance.
Upvotes: 0
Views: 4811
Reputation: 754983
Well, the manager's content could be empty on a given user - and if a property doesn't have a value assigned to it, in Active Directory, it's .Properties[...]
will be NULL - so you must check for that before accessing that non-existing property:
if(sUserResult.Properties["manager"] != null)
{
string manager = sUserResult.Properties["manager"].Value.ToString();
}
Also: this entry is just the DN (distinguished name) of the manager - something like
CN=Joe Blow,OU=Sales,OU=Europe,DC=yourcompany,DC=com
it doesn't contain the "nice" display name of the manager, or something like that.... to get that information, you'd have to use the DN to bind to the manager's user object and get that data, too.
Also: have you actually set up your data table?? In the code you're showing, you're just creating the DataTable
- but you're not setting up any columns inside it - so any assignment like
dr["empcode"] = empCode;
is bound to fail since there is no column empcode
in that DataTable
yet ...
Upvotes: 0