Monday, May 21, 2012

Code to retrieve the manager of the user from Active Directory throws an Exception

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.





No comments:

Post a Comment