Friday, 4 January 2013

Searcher.Filter users from Active Directory


Some different types of Searcher. Filter which filters the users from Active Directory according to the search query
//Search all the users from Active Directory
searcher.Filter = "(&(objectCategory=Person)(objectClass=User))";


//Search specific user from Active Directory
searcher.Filter = "(&(objectCategory=Person)(sAMAccountName=userloginname))";

//Get today’s Date
string modifieddatestring = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.UtcNow);

modifieddatestring = modifieddatestring.ToString().Remove(10);
string sDate = modifieddatestring.ToString().Replace("-", "") + "000000.0Z";

//Search only the users which are created in Active Directory on the same day
searcher.Filter = "(&(objectCategory=Person)(objectClass=User)(whenCreated>=" + sDate + "))";

//Search only the users which are updated in Active Directory on the same day
searcher.Filter = "(&(objectCategory=Person)(objectClass=User)(whenChanged>=" + sDate + "))";

//Search only the users which are updated in Active Directory on the same day

string username = currentUser.LoginName.Split('\\')[1].ToString();//Get current user name
searcher.Filter = "samaccountname=" + username.ToString();


//Search & Load only specific properties of current user

searcher.PropertiesToLoad.Add("displayName");
searcher.PropertiesToLoad.Add("mail");
searcher.PropertiesToLoad.Add("employeeNumber");

SearchResult results = searcher.FindOne();
DirectoryEntry directoryEntry = results.GetDirectoryEntry();
//Display these properties in the lable control

lblEmpName.Text = directoryEntry.Properties["displayName"][0].ToString();
lblEmail.Text = directoryEntry.Properties["mail"][0].ToString();
lblEDP.Text = directoryEntry.Properties["employeeNumber"][0].ToString();

No comments:

Post a Comment