none
LDP.exe works but DirectoryServices fails RRS feed

  • Question

  • We have an application which uses DirectoryServices to lookup users on a separate, one-way (external) trusted domain using a bind account from that domain. 

    We are able to use LDP.exe to bind the account and do directory lookups, but when we use DirectoryServices we get the following error:

    "The specified domain does not exist or cannot be contacted"

    We're able to nslookup the external domain name and get the list of DC IPs. I've also tried switching to DirectoryContextType.DirectoryServer and passing in an IP of one of the DCs and get a similar message:

    "Domain controller "#.#.#.#" does not exist or cannot be contacted"

    I have noticed there's also about a 15 second delay when using the program (may be a timeout), which isn't present when I run the same IP through LDP.exe

    Am I comparing apples to oranges with comparing this to LDP.exe, or should I be expecting them to work similarly? What could be the explanation for this difference?

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;
    using System.Diagnostics;
    using System.DirectoryServices;
    using System.DirectoryServices.AccountManagement;
    using System.DirectoryServices.ActiveDirectory;
    using System.Net.Mail;
    using System.Runtime.InteropServices;
    using System.Security.Cryptography;
    using System.Security.Principal;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace UserLookUp
    {
    	class Program
    	{
    		static void Main(string[] args)
    		{
    			string adCredentialUsername;
    			string adCredentialPassword;
    			string userName;
    			string contextName;
    			Console.WriteLine("Press anykey to start or press ESC to cancel ");
    			ConsoleKeyInfo info = Console.ReadKey(true);
    			Domain currentDomain;
    			DirectorySearcher searcher = null;
    			DateTime start = new DateTime();
    			TimeSpan length = new TimeSpan();
    
    			while (info.Key != ConsoleKey.Escape)
    			{
    				Console.WriteLine("Enter BindAccount Domain name: ");
    				contextName = Console.ReadLine();
    				Console.WriteLine("Enter BindAccount Username: ");
    				adCredentialUsername = Console.ReadLine();
    				Console.WriteLine("Enter BindAccount Password: ");
    				adCredentialPassword = Console.ReadLine();
    				Console.WriteLine("Enter the User name you want to search: ");
    				userName = Console.ReadLine();
    
    				Console.WriteLine("......");
    
    
    				try
    				{
    					start = DateTime.Now;
    					DirectoryContext trustContext = new DirectoryContext(DirectoryContextType.Domain, contextName, adCredentialUsername, adCredentialPassword);
    					currentDomain = Domain.GetDomain(trustContext);
    
    					length = DateTime.Now - start;
    					Console.WriteLine("Connected to the domain successfully with {0} milliseconds", length.TotalMilliseconds);
    				}
    				catch (DirectoryServicesCOMException ex)
    				{
    					Console.WriteLine("Domain access encountered AD COM error with message: {0}", ex.Message);
    					continue;
    				}
    				catch (COMException ex)
    				{
    					Console.WriteLine("Domain access encountered COM error with message: {0}", ex.Message);
    					continue;
    				}
    				catch (Exception ex)
    				{
    					Console.WriteLine("Domain access encountered error with message: {0}", ex.Message);
    					continue;
    				}
    
    
    				try
    				{
    					start = DateTime.Now;
    					searcher = new DirectorySearcher(currentDomain.GetDirectoryEntry());
    					length = DateTime.Now - start;
    					Console.WriteLine("Get directory entry successfully with {0} milliseconds", length.TotalMilliseconds);
    				}
    				catch (DirectoryServicesCOMException ex)
    				{
    					Console.WriteLine("Directory entry retrieval encountered AD COM error with message: {0}", ex.Message);
    				}
    				catch (COMException ex)
    				{
    					Console.WriteLine("Directory entry retrieval encountered COM error with message: {0}", ex.Message);
    				}
    				catch (Exception ex)
    				{
    					Console.WriteLine("Directory entry retrieval encountered error with message: {0}", ex.Message);
    				}
    
    
    				StringBuilder filter = new StringBuilder();
    				filter.Append("(samAccountName=" + userName + ")");
    				filter.Append(String.Format("(name={0})", EncodeRfc2254(contextName + "\\" + userName)));
    				//string filterFormat = "(&{0}(|(objectClass=user)(objectClass=group)))";
    				string filterFormat = "(&(|{0})(|(objectClass=user)(objectClass=group)))";
    				
    				searcher.Filter = String.Format(filterFormat, filter.ToString());
    				SearchResult result = searcher.FindOne();
    
    				if (result != null)
    				{
    					Console.WriteLine("Get the user " + userName + " from the domain " + contextName);
    				}
    				else
    				{
    					Console.WriteLine("Didn't get any result!");
    				}
    
    				Console.WriteLine("......");
    				Console.WriteLine("Press anykey to continue or press ESC to cancel ");
    				info = Console.ReadKey(true);
    
    			}
    
    		}
    
    		public static string EncodeRfc2254(string s)
    		{
    			StringBuilder sb = new StringBuilder();
    			for (int i = 0; i < s.Length; i++)
    			{
    				string c;
    				switch (s[i])
    				{
    					case '\0':
    						c = @"\00";
    						break;
    
    					case '*':
    						c = @"\2a";
    						break;
    
    					case '(':
    						c = @"\28";
    						break;
    
    					case ')':
    						c = @"\29";
    						break;
    
    					case '\\':
    						c = @"\5c";
    						break;
    
    					default:
    						c = s[i].ToString();
    						break;
    				}
    				sb.Append(c);
    			}
    
    			return sb.ToString();
    		}
    	}
    }
    



    Thursday, August 16, 2018 5:57 PM

All replies

  • Hi EvanMGray,

    Thank you for posting here.

    For your question, I test the code you provided. It works well for me. I could not reproduce your exception.

    Please check your Domain name, username, password and the user name which you want to search.

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Monday, August 20, 2018 5:29 AM
    Moderator
  • Thanks Wendy - the credentials/domain being used in my LDP.exe and code tests do match (I've been testing extensively). Do you have any additional details on how the two differ?
    Monday, August 20, 2018 1:08 PM
  • UPDATE: I ran a packet trace from the host to the external DC while running the code, and found that it was reaching out on port 445 initially, and not port 389. 445 was blocked in the firewall between our domain and the external domain.
    Thursday, August 23, 2018 6:24 PM