Here's what happen i am working on login controller where i need to verify user input password with password hash that is in the database. When i'm trying to verify the correct password it is returning NullReferenceException: Object reference not set to an instance of an object. But when i debug it, the line with this code :
var verified = hasher.VerifyHashedPassword(inputModel, resultData.passwordhash, password);
is skipped and does not executed but when i return the value of verified.toString() directly after calling above line of code, it is printing a "Success" string. But when it is failed to verify, the code just work properly. Here's the full code :
public dbSearchResponse dbSearch(string username, string password, ADResponse ldapResult)
{
LoginResponse finalResult = new LoginResponse();
TableSystemUser resultData = new TableSystemUser();
PasswordHasher<OldLoginParamModel> hasher = new PasswordHasher<OldLoginParamModel>(
new OptionsWrapper<PasswordHasherOptions>(
new PasswordHasherOptions()
{
CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2
}));
OldLoginParamModel inputModel = new OldLoginParamModel();
inputModel.grant_type = "password";
inputModel.password = password;
inputModel.username = username;
string hashedPassword = hasher.HashPassword(inputModel, inputModel.password);
using (var connection = new NpgsqlConnection(configuration.GetValue<string>("dbServer:connectionData")))
{
connection.Open();
try
{
var value = connection.Query<TableSystemUser>(
"SELECT id, email, emailconfirmed, passwordhash, phonenumber, username, fullname, dateofbirth, gender, COALESCE(usercredit.saldo, 0) as saldo, pricing.psc, pricing.psm, pricing.plc, pricing.plm, pricing.csc, pricing.csm, pricing.clc, pricing.clm, pricing.ssc, pricing.ssm, pricing.slc, pricing.slm FROM systemuser LEFT OUTER JOIN usercredit ON systemuser.id = usercredit.systemuserid INNER JOIN userpricing ON UUID(systemuser.id) = userpricing.systemuserid INNER JOIN pricing ON userpricing.pricingid = pricing.pricingid WHERE systemuser.email= '" + username + "' and systemuser.emailconfirmed = true;"
);
resultData = value.First();
}
catch (Exception e)
{
//Failed response
dbSearchResponse dbRespNRErr = new dbSearchResponse();
dbRespNRErr.loginResponse = null;
dbRespNRErr.userid = null;
dbRespNRErr.response = "Email not registered.";
return dbRespNRErr;
}
}
var verified = hasher.VerifyHashedPassword(inputModel, resultData.passwordhash, password);
/*But when return the verified.toString() value here, it is returning "Success"
dbSearchResponse dbRespErr = new dbSearchResponse();
dbRespErr.loginResponse = null;
dbRespErr.userid = null;
dbRespErr.response = verified.toString();
return dbRespErr; */
if (verified.toString() == "Success")
{
finalResult.FullName = resultData.fullname;
finalResult.Gender = resultData.gender;
//11/26/1998 12:00:00 AM
finalResult.DateOfBirth = resultData.dateofbirth.ToString("MM/dd/yyyy HH:mm:ss tt");
finalResult.Phone = resultData.phonenumber;
finalResult.Email = resultData.email;
finalResult.UserName = resultData.username;
finalResult.PLC = resultData.plc.ToString();
finalResult.PLM = resultData.plm.ToString();
finalResult.PSC = resultData.psc.ToString();
finalResult.PSM = resultData.psm.ToString();
finalResult.SLC = resultData.slc.ToString();
finalResult.SLM = resultData.slm.ToString();
finalResult.SSC = resultData.ssc.ToString();
finalResult.SSM = resultData.ssm.ToString();
finalResult.CLC = resultData.clc.ToString();
finalResult.CLM = resultData.clm.ToString();
finalResult.CSC = resultData.csc.ToString();
finalResult.CSM = resultData.csm.ToString();
finalResult.PayLater = ldapResult.memberof;
finalResult.Credit = resultData.saldo.ToString();
dbSearchResponse dbResp = new dbSearchResponse();
dbResp.loginResponse = finalResult;
dbResp.userid = resultData.id;
dbResp.response = "success";
return dbResp;
}
//Failed response
dbSearchResponse dbRespErr = new dbSearchResponse();
dbRespErr.loginResponse = null;
dbRespErr.userid = null;
dbRespErr.response = "The user name or password is incorrect.";
return dbRespErr;
}
Anyone know what happen and how to solve it? Thanks
After i do some detailed run check, i notice that the null part of the code is,
finalResult.PayLater = ldapResult.memberof;
But i don't understand why is the error response given suggest that the null was this line of code
var verified = hasher.VerifyHashedPassword(inputModel, resultData.passwordhash, password);
so in that case, i thanks to everyone who have responded to my question.
I have tried yet no answer. I have a table with a calculated column known as ApplicationNo that has prefix 'CHV18' with 000000 and then the identity column values is attached to it form something like CHV180000001, CHV180000002 etc. Now i want to retrieve that value and show it to a user for example after submitting their data it will read thus: "Data submitted successfully! Your Application No is: CHV180000001"
public bool InsertRegistration()
{
// Determine the currently logged on user's UserId
MembershipUser currentUser = Membership.GetUser();
Guid currentUserId = (Guid)currentUser.ProviderUserKey;
//Start of Upload 1
string filename1 = Path.GetFileName(AdmissionUpload.PostedFile.FileName);
string contentType1 = AdmissionUpload.PostedFile.ContentType;
using (Stream fs1 = AdmissionUpload.PostedFile.InputStream)
{
using (BinaryReader br1 = new BinaryReader(fs1))
{
byte[] bytes1 = br1.ReadBytes((Int32)fs1.Length);
string filename2 = Path.GetFileName(StudentIDUpload.PostedFile.FileName);
string contentType2 = StudentIDUpload.PostedFile.ContentType;
using (Stream fs2 = StudentIDUpload.PostedFile.InputStream)
{
using (BinaryReader br2 = new BinaryReader(fs2))
{
byte[] bytes2 = br2.ReadBytes((Int32)fs2.Length);
string filename3 = Path.GetFileName(TranscriptUpload.PostedFile.FileName);
string contentType3 = TranscriptUpload.PostedFile.ContentType;
using (Stream fs3 = TranscriptUpload.PostedFile.InputStream)
{
using (BinaryReader br3 = new BinaryReader(fs3))
{
byte[] bytes3 = br3.ReadBytes((Int32)fs3.Length);
string filename4 = Path.GetFileName(PassportUpload.PostedFile.FileName);
string contentType4 = PassportUpload.PostedFile.ContentType;
using (Stream fs4 = PassportUpload.PostedFile.InputStream)
{
using (BinaryReader br4 = new BinaryReader(fs4))
{
byte[] bytes4 = br4.ReadBytes((Int32)fs4.Length);
//SqlDateTime sqldatenull;
SqlCommand com = new SqlCommand("INSERT INTO Candidates(FirstName, MiddleName, Surname, DateOfBirth, Phone, Email, DateApplied, CurrentLevel, MatricNo, JAMBNo, UTMEScore, YearOfAdmission, ExpectedYearOfGraduation, NIN, StudyMode, EntryMode, NextOfKin, NextOfKinEmail, NextOfKinPhone, RelationToNextOfKin, AcademicReferee, AcademicRefereeMobile, RelationWithAcademicReferee, DirectEntryRegNo, DirectEntryGrade, CurrentGPA, Courseid, Institution, HeadOfDept, HODPhone, HODEmail, RelatedToGovtOfficial, GovtOfficialName, PositionOfGovtOfficial, OnScholarship, ScholarshipName, YearOfScholarship, StateID, LGID, Community, AccountNo, SortCode, UType, AdmissionLetter, AdmissionLetterFileName, AdmissionImageType, StudentID, StudentIDFileName, StudentImageType, Transcript, TranscriptFileName, TranscriptImageType, Passport, PassportFileName, PassportImageType, Maths, Eng, Subject3, Subject4, Subject5, Subject6, Subject7, Address, FacultyID, GradeSubject3, GradeSubject4, GradeSubject5, GradeSubject6, GradeSubject7, Location, UserId, StateOfResidence, Gender, Bank) OUTPUT INSERTED.ApplicationNo VALUES (#FirstName, #MiddleName, #Surname, #DateOfBirth, #Phone, #Email, #DateApplied, #CurrentLevel, #MatricNo, #JAMBNo, #UTMEScore, #YearOfAdmission, #ExpectedYearOfGraduation, #NIN, #StudyMode, #EntryMode, #NextOfKin, #NextOfKinEmail, #NextOfKinPhone, #RelationToNextOfKin, #AcademicReferee, #AcademicRefereeMobile, #RelationWithAcademicReferee, #DirectEntryRegNo, #DirectEntryGrade, #CurrentGPA, #Courseid, #Institution, #HeadOfDept, #HODPhone, #HODEmail, #RelatedToGovtOfficial, #GovtOfficialName, #PositionOfGovtOfficial, #OnScholarship, #ScholarshipName, #YearOfScholarship, #StateID, #LGID, #Community, #AccountNo, #SortCode, #UType, #AdmissionLetter, #AdmissionLetterFileName, #AdmissionImageType, #StudentID, #StudentIDFileName, #StudentImageType, #Transcript, #TranscriptFileName, #TranscriptImageType, #Passport, #PassportFileName, #PassportImageType, #Maths, #Eng, #Subject3, #Subject4, #Subject5, #Subject6, #Subject7, #Address, #FacultyID, #GradeSubject3, #GradeSubject4, #GradeSubject5, #GradeSubject6, #GradeSubject7, #Location, #UserId, #StateOfResidence, #Gender, #Bank)", con);
com.Parameters.AddWithValue("#FirstName", txtFN.Text);
com.Parameters.AddWithValue("#MiddleName", txtMN.Text);
com.Parameters.AddWithValue("#Surname", txtLN.Text);
com.Parameters.AddWithValue("#DateOfBirth", txtdob.Text);
//sqldatenull = SqlDateTime.Null;
// if (txtdob.Text == "")
// {
// com.Parameters["#DateOfBirth"].Value = sqldatenull;
//cmd.Parameters["#Date"].Value = DBNull.Value;
//}
//else
//{
// com.Parameters["#DateOfBirth"].Value = DateTime.Parse(txtdob.Text);
// }
com.Parameters.AddWithValue("#Phone", txtphone.Text);
com.Parameters.AddWithValue("#Email", txtemail.Text);
com.Parameters.AddWithValue("#DateApplied", txtdap.Text);
//sqldatenull = SqlDateTime.Null;
//if (txtdap.Text == "")
//{
//com.Parameters["#DateApplied"].Value = sqldatenull;
//cmd.Parameters["#Date"].Value = DBNull.Value;
//}
//else
//{
//com.Parameters["#DateApplied"].Value = DateTime.Parse(txtdap.Text);
// }
com.Parameters.AddWithValue("#CurrentLevel", ddlclevel.SelectedItem.Text);
com.Parameters.AddWithValue("#MatricNo", txtmatric.Text);
com.Parameters.AddWithValue("#JAMBNo", txtjamb.Text);
com.Parameters.AddWithValue("#UTMEScore", txtutme.Text);
com.Parameters.AddWithValue("#YearOfAdmission", ddlyear.SelectedItem.Text);
com.Parameters.AddWithValue("#ExpectedYearOfGraduation", ddlgraduation.SelectedItem.Text);
com.Parameters.AddWithValue("#NIN", txtnin.Text);
com.Parameters.AddWithValue("#StudyMode", ddlstudytime.SelectedItem.Text);
com.Parameters.AddWithValue("#EntryMode", ddlentrymode.SelectedItem.Text);
com.Parameters.AddWithValue("#NextOfKin", txtkin.Text);
com.Parameters.AddWithValue("#NextOfKinEmail", txtkinemail.Text);
com.Parameters.AddWithValue("#NextOfKinPhone", txtkinphone.Text);
com.Parameters.AddWithValue("#RelationToNextOfKin", txtkinrelation.Text);
com.Parameters.AddWithValue("#AcademicReferee", txtacademicreferee.Text);
com.Parameters.AddWithValue("#AcademicRefereeMobile", txtacadmobile.Text);
com.Parameters.AddWithValue("#RelationWithAcademicReferee", txtacadrelation.Text);
com.Parameters.AddWithValue("#DirectEntryRegNo", txtdirectentry.Text);
com.Parameters.AddWithValue("#DirectEntryGrade", txtentrygrade.Text);
com.Parameters.AddWithValue("#CurrentGPA", txtgpa.Text);
com.Parameters.AddWithValue("#Courseid", ddlcourse.SelectedItem.Value);
com.Parameters["#Courseid"].Value = ddlcourse.SelectedItem.Value;
com.Parameters.AddWithValue("#Institution", ddlUniversity.SelectedItem.Value);
com.Parameters["#Institution"].Value = ddlUniversity.SelectedItem.Value;
com.Parameters.AddWithValue("#HeadOfDept", txthod.Text);
com.Parameters.AddWithValue("#HODPhone", txthodphone.Text);
com.Parameters.AddWithValue("#HODEmail", txthodemail.Text);
com.Parameters.AddWithValue("#RelatedToGovtOfficial", ddlrgovtoff.SelectedItem.Text);
com.Parameters.AddWithValue("#GovtOfficialName", txtgovtofficial.Text);
com.Parameters.AddWithValue("#PositionOfGovtOfficial", txtposgovt.Text);
com.Parameters.AddWithValue("#OnScholarship", ddlsch.SelectedItem.Text);
com.Parameters.AddWithValue("#ScholarshipName", txtschname.Text);
com.Parameters.AddWithValue("#YearOfScholarship", ddlschyear.SelectedItem.Text);
com.Parameters.AddWithValue("#StateID", ddlState.SelectedItem.Value);
com.Parameters["#StateID"].Value = ddlState.SelectedItem.Value;
com.Parameters.AddWithValue("#LGID", ddllga.SelectedItem.Value);
com.Parameters["#LGID"].Value = ddllga.SelectedItem.Value;
com.Parameters.AddWithValue("#Community", txtcommunity.Text);
com.Parameters.AddWithValue("#AccountNo", txtaccno.Text);
com.Parameters.AddWithValue("#SortCode", txtsortcode.Text);
com.Parameters.AddWithValue("#UType", ddlUType.SelectedItem.Value);
com.Parameters["#UType"].Value = ddlUType.SelectedItem.Value;
com.Parameters.AddWithValue("#AdmissionLetter", bytes1);
com.Parameters.AddWithValue("#AdmissionLetterFileName", filename1);
com.Parameters.AddWithValue("#AdmissionImageType", contentType1);
com.Parameters.AddWithValue("#StudentID", bytes2);
com.Parameters.AddWithValue("#StudentIDFileName", filename2);
com.Parameters.AddWithValue("#StudentImageType", contentType2);
//com.Parameters.AddWithValue("#CourtAffidavit", bytes3);
//com.Parameters.AddWithValue("#CourtAffidavitFileName", filename3);
//com.Parameters.AddWithValue("#CourtAffidavitImageType", contentType3);
com.Parameters.AddWithValue("#Transcript", bytes3);
com.Parameters.AddWithValue("#TranscriptFileName", filename3);
com.Parameters.AddWithValue("#TranscriptImageType", contentType2);
com.Parameters.AddWithValue("#Passport", bytes4);
com.Parameters.AddWithValue("#PassportFileName", filename4);
com.Parameters.AddWithValue("#PassportImageType", contentType4);
com.Parameters.AddWithValue("#Maths", ddlgrademaths.SelectedItem.Text);
com.Parameters.AddWithValue("#Eng", ddlgradeeng.SelectedItem.Text);
com.Parameters.AddWithValue("#Subject3", txtsubject3.Text);
com.Parameters.AddWithValue("#Subject4", txtsubject4.Text);
com.Parameters.AddWithValue("#Subject5", txtsubject5.Text);
com.Parameters.AddWithValue("#Subject6", txtsubject6.Text);
com.Parameters.AddWithValue("#Subject7", txtsubject7.Text);
com.Parameters.AddWithValue("#Address", txtaddress.Text);
com.Parameters.AddWithValue("#FacultyID", ddlfaculty.SelectedItem.Value);
com.Parameters["#FacultyID"].Value = ddlfaculty.SelectedItem.Value;
com.Parameters.AddWithValue("#GradeSubject3", ddlgradsub3.SelectedItem.Text);
com.Parameters.AddWithValue("#GradeSubject4", ddlgradesub4.SelectedItem.Text);
com.Parameters.AddWithValue("#GradeSubject5", ddlgradesub5.SelectedItem.Text);
com.Parameters.AddWithValue("#GradeSubject6", ddlgradesub6.SelectedItem.Text);
com.Parameters.AddWithValue("#GradeSubject7", ddlgradesub7.SelectedItem.Text);
com.Parameters.AddWithValue("#Location", ddllocation.SelectedItem.Text);
com.Parameters.AddWithValue("#UserId", currentUserId);
com.Parameters.AddWithValue("#StateOfResidence", ddlstateofresidence.SelectedItem.Text);
com.Parameters.AddWithValue("#Gender", ddlgender.SelectedItem.Text);
com.Parameters.AddWithValue("#Bank", ddlbankname.SelectedItem.Text);
con.Open();
// open connection here, just before executing
// return the true/false for whether a row was inserted
int insertedID = Convert.ToInt32(com.ExecuteScalar());
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
}
}
}
}
}
}
}
}
protected void btnsub_Click(object sender, EventArgs e)
{
//Start of Send Mail Region
//Fetching Email Body Text from EmailTemplate File.
string MailText = string.Empty;
//using streamreader for reading my htmltemplate
using (StreamReader reader = new StreamReader(Server.MapPath("~/Account/RegMessage.html")))
{
MailText = reader.ReadToEnd();
//Repalce [userdetails] = user details
//MailText = MailText.Replace("[ApplicationID]", reg.ApplicationID.ToString());
MailText = MailText.Replace("[FirstName]", txtFN.Text.Trim());
MailText = MailText.Replace("[MiddleName]", txtMN.Text.Trim());
MailText = MailText.Replace("[Surname]", txtLN.Text.Trim());
MailText = MailText.Replace("[MatricNo]", txtmatric.Text.Trim());
MailText = MailText.Replace("[DateApplied]", txtdap.Text.Trim());
MailMessage msg = new MailMessage();
msg.To.Add(txtemail.Text.ToString());
MailAddress from = new MailAddress("scholarships#orm-ng.com", "CHEVRON Scholarships");
msg.From = from;
msg.Subject = "Data submitted successfully! Your Application No is:";
msg.IsBodyHtml = true;
msg.Body = MailText;
SmtpClient smtpClient = new SmtpClient("smtp.1and1.com", 587);
smtpClient.EnableSsl = true;
smtpClient.Credentials = new System.Net.NetworkCredential("scholarships#orm-ng.com", "*****");
if (InsertRegistration())
{
// Only run if inserted correctly
smtpClient.Send(msg);
lblMessage.Text = "Application submitted successfully! Please copy the Application No below and also check your email for confirmation message.";
lblMessage.ForeColor = System.Drawing.Color.Green;
}
else
{
lblMessage.Text = "Error submitting application";
lblMessage.ForeColor = System.Drawing.Color.Red;
}
lblMessage.Visible = true;
}
It doesn't seem that you have any value to be returned. To get the PK of the last inserted record, use Scope_Identity. At the end of Insert statement add a semicolon to indicate the end of the statement then as follows.
#Bank); SELECT SCOPE_IDENTITY();", con);
Now you have a Select statement returning a single value so, com.ExecuteScalar() should work. Don't convert it to an Integer if it is a string. If it is a number you will have to convert to a string, pad the number with zeros and concatenate the CHV18 to the insertedID.
it is the first time I'm working with LDAP and Active Directory. I have to make a web api with .NetCore that have to authenticate with ActiveDirectory (WindowsServer 2008 r2), I'm following the samples in Novell.Directory.Ldap.NETStandard but i can't understand the way that I must set the parameters.
This is the users that I created in ActiveDirectory Server:
In Novell's samples
if (args.Length != 5)
{
System.Console.Out.WriteLine("Usage: mono VerifyPassword <host name>" + " <login dn> <password> <object dn>\n" + " <test password>");
System.Console.Out.WriteLine("Example: mono VerifyPassword Acme.com " + "\"cn=Admin,o=Acme\" secret\n" + " \"cn=JSmith,ou=Sales,o=Acme\" testPassword");
System.Environment.Exit(0);
}
int ldapPort = LdapConnection.DEFAULT_PORT;
int ldapVersion = LdapConnection.Ldap_V3;
System.String ldapHost = args[0];
System.String loginDN = args[1];
System.String password = args[2];
System.String objectDN = args[3];
System.String testPassword = args[4];
LdapConnection conn = new LdapConnection();
try
{
// connect to the server
conn.Connect(ldapHost, ldapPort);
// authenticate to the server
conn.Bind(ldapVersion, loginDN, password);
LdapAttribute attr = new LdapAttribute("userPassword", testPassword);
bool correct = conn.Compare(objectDN, attr);
System.Console.Out.WriteLine(correct?"The password is correct.":"The password is incorrect.\n");
// disconnect with the server
conn.Disconnect();
}
In Novell's samples the "user" parameters looks like this "ou=sales,o=Acme", so I was trying:
int ldapPort = LdapConnection.DEFAULT_PORT;
int ldapVersion = LdapConnection.Ldap_V3;
bool compareResults = false;
String ldapHost = "192.168.58.251";
String loginDN = #"cn=jperez";
String password1 = "Jperez123";
String dn = "mydn";
LdapConnection lc = new LdapConnection();
LdapAttribute attr = null;
try
{
// connect to the server
lc.Connect(ldapHost, ldapPort);
var sdn = lc.GetSchemaDN();
// authenticate to the server
lc.Bind(ldapVersion, loginDN, password1);
...
}
catch (LdapException e)
{
Console.WriteLine("Error: " + e.ToString());
}
But I get this error:
LDAP:
LdapException: Invalid Credentials (49) Invalid Credentials
LdapException: Server Message: 80090308: LdapErr: DSID-0C0903A8,
comment: AcceptSecurityContext error, data 52e, v1db1\u0000
LdapException: Matched DN:
I also get the schemaDn with this funciton: lc.GetSchemaDN(), that return this result: CN=Aggregate,CN=Schema,CN=Configuration,DC=mydn,DC=local
After googling there is no much information with .Netcore than the Novell's samples, please I need your help.
Been working on this as well and ran into the same error. I had to use the Windows domain and username to log in:
String loginDN = "DOMAIN\\jperez";
String password1 = "Jperez123";
lc.Bind(loginDN, password1);
Once I did that, I got in without issue.
I had the same issue and the only way I got it working was by supplying the login like this
lc.Bind("user#domain", "pwd")
I had the same issue until I used this
lc.Bind("uid=" + objUser.UserName + ",ou=SomeValue,dc=SomeValue,dc=SomeValue",password);
also I did not supply a version like in your example
It also works for me:
var ldapVersion = LdapConnection.Ldap_V3;
var loginDN = "CN=victor,CN=Users,DC=example,DC=com";
var password = "123";
conn.Bind(ldapVersion, loginDN, password);
Works on Windows Server 2012r2 with the default domain settings.
If you want to get loginDNs for your domain users, just execute next cmd command on domain controller:
dsquery user
More information here
Yet another variation, I found I had to logon as:
"PartA PartB" of an AD username. (notice the space in the name.)
example being "App Alerts" whereas I normally can login with "AppAlerts"... but this is the Fully Qualified name i found with dsquery user:
"CN=App Alerts,OU=SBSUsers,OU=Users,OU=MyBusiness,DC=myinc,DC=local"
DotNet Version : 6
Novel nuget Package: Novell.Directory.Ldap.NETStandard
Active Directory : 2019 AD server
Step 1 :Add a console Application:
step 2 : Add a class and then put this method in it :
public string Validate(string _username, string _password)
{
string username = _username;
string password = _password;
string domainName = "spenter.com";
string userDn = $"spenterdomain\\{username}";
int ldapVersion = LdapConnection.LdapV3;
// var connection = new LdapConnection { SecureSocketLayer = true };
try
{
using (var ldapConnection = new LdapConnection { SecureSocketLayer = false })
{
ldapConnection.Connect(domainName, LdapConnection.DefaultPort);
ldapConnection.Bind(userDn, password);
if (ldapConnection.Bound)
return $"{username} : has been Authenthicated";
}
}
catch (LdapException ex)
{
Console.WriteLine(ex);
}
return "Credentials Incorrect";
}
Step 3 Main Program Code:
using ldap;
yourclass l1 = new yourclass();
Console.WriteLine("Enter your AD ID");
string uName = Console.ReadLine().ToString();
Console.WriteLine("Enter your AD Pwd");
string Pwd = Console.ReadLine().ToString();
var result = l1.Validate(uName, Pwd);
Console.WriteLine(result);
Console.ReadLine();
I have the following code which is called inside of an ASP.NET application:
public DomainUserInfo GetDomainUserInfoByName(string domain, string firstName, string lastName)
{
string[] domainArray = domain.Split(',');
foreach (string d in domainArray)
{
var principalContext = new PrincipalContext(ContextType.Domain, d);
var userPrincipal = new UserPrincipal(principalContext) {GivenName = firstName, Surname = lastName};
using (var searcher = new PrincipalSearcher(userPrincipal))
{
userPrincipal = (UserPrincipal) searcher.FindOne();
}
if (userPrincipal != null)
{
var domainUserInfo = new DomainUserInfo
{
FirstName = userPrincipal.GivenName,
LastName = userPrincipal.Surname,
Email = userPrincipal.EmailAddress,
LanID = userPrincipal.SamAccountName,
Extension = userPrincipal.VoiceTelephoneNumber,
DomainName = d,
NTAccountName = userPrincipal.Sid.Translate(typeof (NTAccount)).ToString()
};
return domainUserInfo;
}
}
return null;
}
It works when deployed on some servers but not on others, where it throws the exception:
[COMException (0x80005000): Unknown error (0x80005000)]
System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +386081
System.DirectoryServices.DirectoryEntry.Bind() +36
System.DirectoryServices.DirectoryEntry.get_AdsObject() +31
System.DirectoryServices.PropertyValueCollection.PopulateList() +21
System.DirectoryServices.PropertyValueCollection..ctor(DirectoryEntry entry, String propertyName) +49
System.DirectoryServices.PropertyCollection.get_Item(String propertyName) +135
System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInitNoContainer() +288
System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit() +37
System.DirectoryServices.AccountManagement.PrincipalContext.Initialize() +118
System.DirectoryServices.AccountManagement.PrincipalContext.ContextForType(Type t) +34
System.DirectoryServices.AccountManagement.Principal.GetStoreCtxToUse() +37
System.DirectoryServices.AccountManagement.UserPrincipal.set_GivenName(String value) +17
Mfc.Inv.RM.Framework.ActiveDirectory.ActiveDirectoryManager.GetDomainUserInfoByName(String domain, String firstName, String lastName) +167
It looks like this is occurring on the line:
var userPrincipal = new UserPrincipal(principalContext) {GivenName = firstName, Surname = lastName};
when trying to set the GivenName property of the UserPrincipal object.
I'm totally stuck as to what could be causing this, especially since it works on some servers and not others. I already tried writing a console application that calls the same code it works on all of the servers, so I am guessing it has to be something to do with IIS.
here is what I am doing and if you were to hover over userFind or do a QuickWatch on it you will see the following information. also notice the IdentityType.SamAccountName that I am passing
var pc = new PrincipalContext(ContextType.Domain, domainName, null, null);
var userFind = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, username);