Setting the right DirectoryEntry for DirectorySearcher used for DirectorySynchronization

This week I was asked why one would get the an AccessDenied Error Code when accessing the DirectorySearcher.FindOne Method while the

DirectorySearcher.DirectorySynchronization Property is set and the DirectoryEntry is set to an Organisational Unit (OU) rather.

The following Example explains

   1:  using (DirectoryEntry deRoot = new DirectoryEntry("LDAP://OU=MyOU,DC=yourDomain,DC=com"))
   2:  {
   3:                  using (DirectorySearcher ret = new DirectorySearcher(deRoot))
   4:                  {                  
   5:                      ret.DirectorySynchronization = new DirectorySynchronization();
   6:                      ret.DirectorySynchronization.Option = DirectorySynchronizationOptions.IncrementalValues;
   8:                      foreach (var result in ret.FindAll())
   9:                      {
  10:                          //do
  11:                      }
  12:                  }
  13:  }

While browsing the documentation and talking to an US colleague I realised that underneath the whole managed DirectoryServices infrastructure the DirSync Control is used for Directory Synchronization.

Following the Parameter description I found:

“The base of a DirSync search must be the root of a directory partition, which can be a domain partition, the configuration partition, or the schema partition.”

So the solution to the AccessDenied error is actuall pretty simple: Set the DirectoryEntry to the domain partition, the configuration partition, or the schema Partition when using it in conjunction with DirectorySynchronization and make use of the Filter Property when targeting at specific Sub segments of your Domain such as OUs.

See the correct example:

   1:  using (DirectoryEntry deRoot = new DirectoryEntry("LDAP://DC=yourDomain,DC=com"))
   2:  {
   3:                  using (DirectorySearcher ret = new DirectorySearcher(deRoot))
   4:                  {
   5:                      ret.Filter = "OU=MyOU";
   6:                      ret.DirectorySynchronization = new DirectorySynchronization();
   7:                      ret.DirectorySynchronization.Option = DirectorySynchronizationOptions.IncrementalValues;
   9:                      foreach (var result in ret.FindAll())
  10:                      {
  11:                          //do
  12:                      }
  13:                  }
  14:  }

I hope this works well for you, too. You are welcome to drop me a comment, once succeeded Smile

Comments (1)