Active Directory

From Richard's Wiki
Revision as of 22:36, 2 December 2014 by Rkdrm (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
  • LinqPad C# script to get detail of your own 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 and groups in active directory AD:

//using System.DirectoryServices;
//using System.DirectoryServices.AccountManagement;
void Main()
{
//	const string adSearchContainer = "DC=apac,DC=birchmangroup,DC=com,DC=au";
       const string adSearchContainer = "DC=mrwa,DC=wa,DC=gov,DC=au";
       var users = FetchAllUsersFromActiveDirectory(adSearchContainer);
       var groups = FetchAllGroupsFromActiveDirectory(adSearchContainer);
       users.Dump("Users", true); // to datagrid
       groups.Dump("Groups", true); // to datagrid
}
// 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 searchContainer) {
   return FetchAllFromActiveDirectory(searchContainer, "(&ObjectCategory=user)");
}
private static IEnumerable<User> FetchAllGroupsFromActiveDirectory(string searchContainer) {
   return FetchAllFromActiveDirectory(searchContainer, "(&objectClass=group)");
}
private static IEnumerable<User> FetchAllFromActiveDirectory(string searchContainer, string directorySearcherFilter)
  {
      try
      {
          List<User> result = new List<User>();
          //using (DirectoryEntry searchRoot = new DirectoryEntry()) // Search from root of current domain
          using (DirectoryEntry searchRoot = new DirectoryEntry("LDAP://" + searchContainer))
          {
              DirectorySearcher ser = new DirectorySearcher(searchRoot)
                  {
//                       Filter = "(&ObjectCategory=user)",
//                       Filter = "(&objectClass=group)",
                      Filter = directorySearcherFilter,
                      ReferralChasing = ReferralChasingOption.All,
                      PageSize = 1000,
                  };
              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
                                     });
                  }
              }
              ser.Dispose();
          }
          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;
  }