title: How to pass a UserPrincipal with PrincipalContext inside ASP.NET MVC
body: <p>I have the following code to connect to our AD :-</p>
  
  <pre><code>List&lt;DomainContext&gt; results = new List&lt;DomainContext&gt;();
  string ADServerName = System.Web.Configuration.WebConfigurationManager.AppSettings["ADServerName"];
  
  using (var context = new PrincipalContext(ContextType.Domain, ADServerName))
  using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
  {
  </code></pre>
  
  <p>The above worked on our Dev machine as the AD and the asp.net mvc were on the same machine. currently I need to connect to our staging AD which is on different machine. so I need to pass the AD service account (username &amp; password) to the <code>PrincipalContext</code>. Can anyone advice? I read online that I need to use <code>UserPrincipal</code> as follow:-</p>
  
  <pre><code>public UserPrincipal(
      PrincipalContext context,
      string samAccountName,
      string password,
      bool enabled
  )
  </code></pre>
  
  <p>but I am not sure how I can modify my code accordingly ?</p>
  
  <p>Thanks</p>
  
  <p><strong>EDIT</strong>
  I tried this to display only user that have brancjA or brachB inside their distinguished accounts:-</p>
  
  <pre><code>public List&lt;DomainContext&gt; GetADUsers(string term=null)
          {
              string[] types = new string[] { "BranchA", "BranchB" };
              List&lt;DomainContext&gt; results = new List&lt;DomainContext&gt;();
              string ADServerName = System.Web.Configuration.WebConfigurationManager.AppSettings["ADServerName"];
              using (var context = new PrincipalContext(ContextType.Domain, ADServerName, "username", "password"))
              using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
              {
                  var searchResults = searcher.FindAll();
  
  
  
                  foreach (Principal p in searchResults)
                  {
                     if ((term == null || p.SamAccountName.ToString().ToUpper().StartsWith(term.ToUpper())) &amp;&amp; (types.Contains(p.DistinguishedName)))
  </code></pre>
  
  <p>but the result was that no users were returned. can you advice please ?</p>