I have this action method inside my ASP.NET MVC-5 .net 4.6:-
public ActionResult UsersInfo2()
{
List<DomainContext> results = new List<DomainContext>();
try
{
// create LDAP connection object
DirectoryEntry myLdapConnection = createDirectoryEntry();
string ADServerName = System.Web.Configuration.WebConfigurationManager.AppSettings["ADServerName"];
string ADusername = System.Web.Configuration.WebConfigurationManager.AppSettings["ADUserName"];
string ADpassword = System.Web.Configuration.WebConfigurationManager.AppSettings["ADPassword"];
using (var context = new DirectoryEntry("LDAP://mydomain.com:389/DC=mydomain,DC=com", ADusername, ADpassword))
using (var search = new DirectorySearcher(context))
{
SearchResult r = search.FindOne();
ResultPropertyCollection fields = r.Properties;
foreach (String ldapField in fields.PropertyNames)
string temp;
foreach (Object myCollection in fields[ldapField])
temp = String.Format("{0,-20} : {1}",
ldapField, myCollection.ToString());
}
}
using (var context = new PrincipalContext(ContextType.Domain, "mydomain.com", ADusername, ADpassword))
{
bool isvalid = context.ValidateCredentials("*******", "****************");
}
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
return View(results);
}
so after around one day of testing i realize that for the DirectoryEntry I need to pass the server/ldap as follow ("LDAP://mydomain.com:389/DC=mydomain,DC=com", ADusername, ADpassword)) , while for the PrincipalContext we need to pass it as follow:- (ContextType.Domain, "mydomain.com", ADusername, ADpassword)).. so i can not pass the ldap inside the PrincipalContext nor the servrname only inside the DirectoryEntry .. so is this the case? or i am doing things wrongly ?
Thanks
You are correct.
The
System.DirectoryServices.AccountManagementnamespace (PrincipalContext,UserPrincipal, etc.) was created to simplify things. However, it just uses theSystem.DirectoryServicesnamespace (DirectoryEntry, etc.) in the background. (except forValidateCredentials, which usesSystem.DirectoryServices.Protocols.LdapConnection).I prefer to always use
DirectoryEntryand friends because it gives me more control over performance. That's something I wrote an article about: Active Directory: Better performance