serving the solutions day and night

Pages

Monday, July 30, 2012

LDAP (Active Directory) Programming with C#

  1. .NET Support 2 sets of classes of Active Directory(AD) operations.
  2. System.DirectoryServices
    Older class, supports from .net 1.0. Supports all AD operations (setting password, enable/disable account, reterive AD objects).
  3. System.DirectoryServices.AccountManagement
    Newer version (>=3.5), easier to manage AD operations. Usign UserPrincipal object to access LDAP object.
  4. createDirectoryEntry Function
    static DirectoryEntry GetDirectoryEntryObject()
    {
      DirectoryEntry deObj = new DirectoryEntry("SERVER_NAME"); //SVR-MAK.DNS.local
      deObj.Path = "LDAP://SVR-MAK.DNS.local:389/DC=DNS,DC=local";
      deObj.AuthenticationType = AuthenticationTypes.Secure;
      //deConn.Username = "username";
      //deConn.Password = "password";
      return deObj;
    }
    username and password - no need to specify if you logged into a system as a domain admin
  5. Search Filter to get all user's record.
    SearchFilter("Mo A. Ka");
    private void SearchFilter(String username)
    {
      try
      {
        DirectoryEntry deObj = GetDirectoryEntryObject();

        DirectorySearcher deSearch = new DirectorySearcher(deObj);
        deSearch.Filter = "(cn=" + username + ")";
        //search.Filter = "(&(objectClass=user)(objectCategory=person))";
    User Exist
        SearchResultCollection srResultsCol = deSearch.FindAll();
        Response.Write(srResultsCol.Count + "<br>");
    Find One User
        SearchResult srResults = deSearch.FindOne();
        if (srResults != null)
        {
          Response.Write(String.Format(srResults.Path) + "<br>");
    Get selected information from a user's record
          Response.Write(srResults.Properties["displayname"][0].ToString());
          Response.Write(srResults.Properties["mail"][0].ToString());

          ResultPropertyCollection rpcCol = srResults.Properties;
    Get all information from a user's record
          foreach (String field in rpcCol.PropertyNames)
          {
            foreach (Object objCol in rpcCol[field])
              Response.Write(String.Format("{0,-20} : {1} <br>", field, objCol.ToString()));
            }
          }
          else
          {
            // user does not exist
            Response.Write("User not found!");
          }
        }
        catch (Exception e)
        {
          Response.Write("Exception caught:\n\n" + e.ToString());
        }
    }
    Output
    LDAP://DNS-FPS01.DNS.local:389/CN=Mo A. Ka,CN=Users,DC=DNS,DC=local
    cn : Mo A. Ka
    mailnickname : mKa
    memberof : CN=DNS-SPUser,CN=Users,DC=DNS,DC=local
    displayname : Mo Ka
    sn : Ka
    samaccountname : mKa
    givenname : Mo
    mail : mKa@DNSsolutions.com
    adspath : LDAP://DNS-SVR01.DNS.local:389/CN=Mo A. Ka,CN=Users,DC=DNS,DC=local
    lockouttime : 0
    proxyaddresDNS : SMTP:mKa@DNS.com
    userprincipalname : mKa@DNS.local
    countrycode : 0
    lastlogontimestamp : 129579115667725093
    ...more...
  6. Get All user's record information.
    DirectoryEntry deObj = GetDirectoryEntryObject();
    DirectorySearcher deSearch = new DirectorySearcher(deObj);
    deSearch.PropertiesToLoad.Add("cn");
    deSearch.PropertiesToLoad.Add("displayname");

    SearchResultCollection srResultsCol = deSearch.FindAll();

    foreach (SearchResult srResults in srResultsCol)
    {
      if (srResults.Properties["cn"].Count > 0 && srResults.Properties["displayname"].Count > 0)
      {
        String cn = srResults.Properties["cn"][0].ToString();
        String displayname= srResults.Properties["displayname"][0].ToString();
        Response.Write(String.Format("{0,-20} : {1}
    ", cn,displayname);
      }
    }

  7. Modify user information
    ModifyUser("Mo A. Ka", "displayname");
    private void ModifyUser(String username, String property)
    {
      DirectoryEntry deObj = GetDirectoryEntryObject();
      DirectorySearcher deSearch = new DirectorySearcher(deObj);
      deSearch.Filter = "(cn=" + username + ")";
      deSearch.PropertiesToLoad.Add(property);

      SearchResult srResults = deSearch.FindOne();
      if (srResults != null)
      {
        DirectoryEntry entryToUpdate = srResults.GetDirectoryEntry();
        Response.Write(srResults.Properties[property][0].ToString());
        entryToUpdate.Properties[property].Value = "Mohideen A Kader";
        entryToUpdate.CommitChanges();
      }
    }

No comments: