Active Directory
From Richard's Wiki
- LinqPad C# script to get detail of your won identity in AD:
// using System.DirectoryServices; // using System.DirectoryServices.AccountManagement; using(PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "apac")) using(UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "kurzejar")) usr.Dump();
- LinqPad C# script to get all users in active directory AD:
//using System.DirectoryServices; //using System.DirectoryServices.AccountManagement; void Main() { const string allAdUsersSearchContainer = "OU=UsersMarch 2005,OU=Users,OU=Beacon,DC=beacon,DC=com,DC=au"; var users = FetchAllUsersFromActiveDirectory(allAdUsersSearchContainer); users.Dump(); } // Define other methods and classes here public class User { public string Name { get; set; } public string Login { get; set; } public string DistinguishedName { get; set; } } private static IEnumerable<User> FetchAllUsersFromActiveDirectory(string allUsersSearchContainer) { try { List<User> result = new List<User>(); //using (DirectoryEntry searchRoot = new DirectoryEntry()) // Search from root of current domain using (DirectoryEntry searchRoot = new DirectoryEntry("LDAP://" + allUsersSearchContainer)) { DirectorySearcher ser = new DirectorySearcher(searchRoot) { Filter = "(&ObjectCategory=user)", ReferralChasing = ReferralChasingOption.All }; ser.PropertiesToLoad.Add("Name"); ser.PropertiesToLoad.Add("distinguishedName"); ser.PropertiesToLoad.Add("sAMAccountName"); //ser.PropertiesToLoad.Add("mail"); //ser.PropertiesToLoad.Add("description"); using (SearchResultCollection searchResults = ser.FindAll()) { int count = searchResults.Count; for (int i = 0; i < count; i++) { SearchResult searchResult = searchResults[i]; string name = GetSearchResultProperty(searchResult, "Name"); string distinguishedName = GetSearchResultProperty(searchResult, "distinguishedName"); string samAccount = GetSearchResultProperty(searchResult, "sAMAccountName"); //var email = GetSearchResultProperty(searchResult, "mail"); //var description = GetSearchResultProperty(searchResult, "description"); result.Add(new User { Name = name, Login = samAccount, DistinguishedName = distinguishedName, //Email = email, //Role = description }); } } } return result; } catch (Exception ex) { string message = string.Format("FetchAllUsersFromActiveDirectory() failed"); // Log.Error(message, ex); throw; } } private static string GetSearchResultProperty(SearchResult result, string name) { if (result.Properties.Contains(name)) { var propertyCollection = result.Properties[name]; if (propertyCollection.Count == 1 && propertyCollection[0] != null) { return propertyCollection[0].ToString(); } } return string.Empty; }