Monday, June 16, 2008

Method to search a user in Active Directory and get all the user information

The following method is used for searching a user in Active directory of an organization and fetch the user details like user name, email, phone number, department , manager etc.

Import following two web services,

using System.DirectoryServices;
using System.Collections.Generic;

public List SerachUserInDomain(string UserName)
{

string Name, Email, Manager, Extension, Department;

NDAUserInfo UserInfo;

const string MCHP_DIRECTORY_PATH = LDAP://microsoft.com/DC=microsoft,DC=com; //Provide the Active directory path from where user details to be fetched

List SearchResult = new List();

DirectorySearcher MchpDirSearch = new DirectorySearcher(); //Create an object of DirectorySearcher

MchpDirSearch.Filter = "(&(objectCategory=person)(objectClass=user)(cn=*" + UserName + "*))"; //Add the filter condition

try
{
SearchResultCollection DirectorySearchResult = MchpDirSearch.FindAll(); // Searches AD for the filter condition and returns the result

int SearchResultCount = DirectorySearchResult.Count;

//AD may contain multiple users with the same name, it will return mutliple rows
for (int i = 1; i <= SearchResultCount; i++)
{
//get user name
Name = DirectorySearchResult[i - 1].Properties["cn"][0].ToString();

//get user email
Email = DirectorySearchResult[i - 1].Properties["mail"][0].ToString();

//get user manager name
Manager = DirectorySearchResult[i - 1].Properties["manager"][0].ToString();
if (Manager != "")
{
if (Manager.Contains("CN="))
{
int Length = Manager.IndexOf(',');
Manager = Manager.Substring(3, Length - 3);
}
else
{
Manager = string.Empty;
}
}

//get user Department name
Department = DirectorySearchResult[i - 1].Properties["department"][0].ToString();

//get user extension
Extension = DirectorySearchResult[i - 1].Properties["telephonenumber"][0].ToString();

//add the results into an userinfo object
UserInfo = new NDAUserInfo();
UserInfo.UserName = Name;
UserInfo.UserEmail = Email;
UserInfo.UserManager = Manager;
UserInfo.UserExtension = Extension;
UserInfo.UserDepartment = Department;

SearchResult.Add(UserInfo);

//To sort user names if it contains multiple users
if (DirectorySearchResult[i - 1].Properties["samaccountname"][0].ToString() == UserName)
{
for (int c = SearchResult.Count - 1; c > 0; c--)
{
SearchResult[c] = SearchResult[c - 1];
}
SearchResult[0] = UserInfo;
}
return SearchResult;
}

For the above method, NDAUserInfo is a class with properties UserName, UserEmail, UserDepartment, UserExtension, UserManager

No comments: