title: System.DirectoryServices - The server is not operational
body: <p>I get an error by a website, on which I use Windows Authentication.</p>
  
  <p>Strange things:</p>
  
  <ul>
  <li>Only occurs if user is not yet saved into database (new unknown user)</li>
  <li>Appears only on live system, everything fine on local development environment</li>
  </ul>
  
  <p>This is what I get in a logging mail:</p>
  
  <blockquote>
    <p>Source : System.DirectoryServices</p>
    
    <p>Message: The server is not operational.</p>
    
    <p>Trace:<br>
    at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)<br>
    at System.DirectoryServices.DirectoryEntry.Bind()<br>
    at System.DirectoryServices.DirectoryEntry.get_AdsObject()<br>
    at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne)<br>
    at System.DirectoryServices.DirectorySearcher.FindOne()<br>
    at Smarthouse.Labs.DataAccess.UserListManager.SaveUser(String windowsUserName)  </p>
  </blockquote>
  
  <p>This is how I implement DirectorySearch:</p>
  
  <pre><code>private void SaveUser(string windowsUserName)
  {
      string[] domainAndUser = windowsUserName.Split('\\');
      string domain = domainAndUser[0];
      string username = domainAndUser[1];
  
      DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain);
      DirectorySearcher search = new DirectorySearcher(entry);
  
      try
      {
          // Bind to the native AdsObject to force authentication.
          search.Filter = "(SAMAccountName=" + username + ")";
          search.PropertiesToLoad.Add("cn");
          search.PropertiesToLoad.Add("sn");
          search.PropertiesToLoad.Add("givenName");
          search.PropertiesToLoad.Add("mail");
  
          SearchResult result = search.FindOne();
  
          if (result == null)
          {
              throw new Exception("No results found in Windows authentication.");
          }
  
          User userToSave = new User();
          userToSave.FirstName = (String) result.Properties["givenName"][0];
          userToSave.LastName = (String) result.Properties["sn"][0];
          userToSave.Email = (String) result.Properties["mail"][0];
          userToSave.Username = windowsUserName;
          userToSave.Guid = Guid.NewGuid();
  
          SaveUser(userToSave);
      }
      catch (Exception ex)
      {
          throw new Exception("Error authenticating user. " + ex.Message, ex);
      }
      finally
      {
          //Dispose service and search to prevent leek in memory
          entry.Dispose();
          search.Dispose();
      }
  }
  </code></pre>
  
  <p>If more code examples are needed just tell me.</p>