I need to get the emailid's from outlook in my C# application to send mail. I have userId or FirstName and LastName. Please suggest me a suitable method.
Thanks
public string GetEmaiId(string userId)
{
string email = string.Empty;
DirectorySearcher objsearch = new DirectorySearcher();
string strrootdse = objsearch.SearchRoot.Path;
DirectoryEntry objdirentry = new DirectoryEntry(strrootdse);
objsearch.Filter = "(& (cn=" + userId + ")(objectClass=user))";
objsearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;
objsearch.PropertiesToLoad.Add("cn");
objsearch.PropertyNamesOnly = true;
objsearch.Sort.Direction = System.DirectoryServices.SortDirection.Ascending;
objsearch.Sort.PropertyName = "cn";
SearchResultCollection colresults = objsearch.FindAll();
foreach (SearchResult objresult in colresults)
{
email = objresult.GetDirectoryEntry().Properties["mail"].Value.ToString();
}
objsearch.Dispose();
return email;
}
Related
Am currently working on a Webforms Webapplication in C# and need to import the value of email address of the altRecipient attribute in Active Directory. I've been struggling with this for days now and can't seem to get it right.
The 'altRecipient' attribute returns a path//: that leads to the DistinguishedName. So i get something like this CN=edward-audi,OU=AUe,OU=daimler Mail,DC=diamler,DC=net.The returned value is the CN and the email address i need, is within the CN specifically where OU=daimler Mail. Am not sure if am doing the right thing. Maybe my approach is totally wrong.
SearchResultCollection result;
DirectorySearcher search = new DirectorySearcher("LDAP://DC=mycompany,DC=net")
{
SearchScope = SearchScope.Subtree,
Filter = "(&(objectCategory=user)(sAMAccountName=*" + UserName + "*))"
};
result = search.FindAll();
foreach (SearchResult sr in result)
{
dr = table.NewRow();
DirectoryEntry de = sr.GetDirectoryEntry();
if (de.Properties["altRecipient"].Value != null && de.Properties["altRecipient"].Value.ToString() != string.Empty)
{
string userID = de.Properties["sAMAccountName"].Value.ToString();
string Domain = "domain.net";
PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain);
UserPrincipal up = UserPrincipal.FindByIdentity(pc, userID);
if (up != null)
{
string userPrincipal = up.ToString();
de = up.GetUnderlyingObject() as DirectoryEntry;
string altRecepientCN = de.Properties["altRecipient"].Value.ToString();
UserPrincipal altRecepientValue = UserPrincipal.FindByIdentity(pc, altRecepientCN);
}
}
}
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 am trying create Activity record in Dynamics 2011 with owner name set as "test_user". Instead below code is taking credential which is used to access Dynamics API. Is there any way to impersonate "test_user" user without passing his password? Thank you.
string TargetCrmService = ConfigurationManager.AppSettings["TargetCrmService"];
string UserName = ConfigurationManager.AppSettings["UserName"];
string Domain = ConfigurationManager.AppSettings["Domain"];
string Password = ConfigurationManager.AppSettings["Password"];
Uri organizationUri = new Uri("http://CRMDEV/XRMServices/2011/Organization.svc");
Uri homeRealmUri = null;
ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = Domain + "\\" + UserName;
credentials.UserName.Password = Password;
OrganizationServiceProxy orgProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);
var _userId = (from u in orgProxy.CreateQuery<SystemUser>()
where u.FullName == "Kevin Cook"
select u.SystemUserId.Value).FirstOrDefault();
IOrganizationService _service = (IOrganizationService)orgProxy;
_service.CallerId = _userId;
try
{
//Entity activity = new Entity("activitypointer");
Entity activity = new Entity("appointment");
activity["subject"] = "Test Meeting 1";
activity["description"] = "Test Description";
activity["scheduledstart"] = DateTime.Now;
activity["scheduledend"] = DateTime.Now.AddMinutes(30);
activity["createdbyname"] = "test_user";
activity["modifiedbyname"] = "test_user";
activity["createdbyname"] = "test_user";
activity["owneridname"] = "test_user";
Guid id = _service.Create(activity);
Console.WriteLine("id: " + id);
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
Modified Code
Based on example on http://msdn.microsoft.com/en-us/library/gg309629.aspx
var _userId = (from u in orgProxy.CreateQuery<SystemUser>()
where u.FullName == "Kevin Cook"
select u.SystemUserId.Value).FirstOrDefault();
You have two methods of setting the owenr id of an entity in CRM.
Use the AssignRequest to update the record after it is created.
Use impersonation with the OrganizationServiceProxy, CallerId to use the particular user you'd like to be the owner when it's created. You don't need their password to do impersonation, just their CRM SystemUserId
How to get user manager email id from active directory? I have written code with which I can get user's firstname, lastname, email id and his manager name based on userid, but I want to get manager email id along with his manager name.
Can somebody please help me how to get this? Here is my code:
protected void ddlAdsuser_SelectedIndexChanged(object sender, EventArgs e)
{
DirectoryEntry root = new DirectoryEntry("LDAP://RootDSE");
string myDomain = root.Properties["defaultNamingContext"].Value.ToString();
DirectoryEntry domain = new DirectoryEntry("LDAP://" + myDomain);
DirectorySearcher dsUsers = new DirectorySearcher(domain);
dsUsers.Filter = "(userPrincipalName=" + ddlAdsuser.Text + ")";
foreach (SearchResult sResultSet in dsUsers.FindAll())
{
lblfname.Text = GetProperty(sResultSet, "givenName");
lbllname.Text = GetProperty(sResultSet, "sn");
lblemail.Text = GetProperty(sResultSet, "mail");
string Manager = string.Empty;
Manager = GetProperty(sResultSet, "manager");
if (Manager != "")
{
if (Manager.Contains("CN="))
{
int Length = Manager.IndexOf(',');
Manager = Manager.Substring(3, Length - 3);
}
else
{
Manager = string.Empty;
}
}
lblManagerID.Text = Manager; //Here displaying the manager name.
}
}
public static string GetProperty(SearchResult searchResult, string PropertyName)
{
if (searchResult.Properties.Contains(PropertyName))
{
return searchResult.Properties[PropertyName][0].ToString();
}
else
{
return string.Empty;
}
}
DirectorySearcher objDirSearch = new DirectorySearcher(SearchRoot);
DirectoryEntry dentUser = null;
string pstrFieldName, pstrValue;
pstrFieldName = "company";
pstrValue = "12345"; //Employee number
/*setting the filter as per the employee number*/
objDirSearch.Filter = "(&(objectClass=user)(" + pstrFieldName + "=" + pstrValue + "))";
SearchResult objResults = objDirectorySearch.FindOne();
dentUser = new DirectoryEntry(objResults.Path);}
string strManager = dentUser.Properties["manager"].Value.ToString();
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.DistinguishedName, strManager);
string strManagerMailID = user.EmailAddress;
Simple code and working great:
public static string GetEmail(string userId)
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userId);
return user.EmailAddress;
}
You must add assembly System.DirectoryServices.AccountManagement.dll.
If you have any troubles with connection to AD, you can try to add AD server name in PrincipalContext constructor.
Just do a second search for the manager.
Note that you way of building the query filter is buggy, you need to escape some characters (Especially the " quote) in order to avoid broken queries depending on user input.
I'm writing a web application which uses windows authentication and I can happily get the user's login name using something like:
string login = User.Identity.Name.ToString();
But I don't need their login name I want their DisplayName. I've been banging my head for a couple hours now...
Can I access my organisation's AD via a web application?
How about this:
private static string GetFullName()
{
try
{
DirectoryEntry de = new DirectoryEntry("WinNT://" + Environment.UserDomainName + "/" + Environment.UserName);
return de.Properties["displayName"].Value.ToString();
}
catch { return null; }
}
See related question: Active Directory: Retrieve User information
See also: Howto: (Almost) Everything In Active Directory via C# and more specifically section "Enumerate an object's properties".
If you have a path to connect to a group in a domain, the following snippet may be helpful:
GetUserProperty("<myaccount>", "DisplayName");
public static string GetUserProperty(string accountName, string propertyName)
{
DirectoryEntry entry = new DirectoryEntry();
// "LDAP://CN=<group name>, CN =<Users>, DC=<domain component>, DC=<domain component>,..."
entry.Path = "LDAP://...";
entry.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + accountName + ")";
search.PropertiesToLoad.Add(propertyName);
SearchResultCollection results = search.FindAll();
if (results != null && results.Count > 0)
{
return results[0].Properties[propertyName][0].ToString();
}
else
{
return "Unknown User";
}
}
Use this:
string displayName = UserPrincipal.Current.DisplayName;
In case anyone cares I managed to crack this one:
/// This is some imaginary code to show you how to use it
Session["USER"] = User.Identity.Name.ToString();
Session["LOGIN"] = RemoveDomainPrefix(User.Identity.Name.ToString()); // not a real function :D
string ldappath = "LDAP://your_ldap_path";
// "LDAP://CN=<group name>, CN =<Users>, DC=<domain component>, DC=<domain component>,..."
Session["cn"] = GetAttribute(ldappath, (string)Session["LOGIN"], "cn");
Session["displayName"] = GetAttribute(ldappath, (string)Session["LOGIN"], "displayName");
Session["mail"] = GetAttribute(ldappath, (string)Session["LOGIN"], "mail");
Session["givenName"] = GetAttribute(ldappath, (string)Session["LOGIN"], "givenName");
Session["sn"] = GetAttribute(ldappath, (string)Session["LOGIN"], "sn");
/// working code
public static string GetAttribute(string ldappath, string sAMAccountName, string attribute)
{
string OUT = string.Empty;
try
{
DirectoryEntry de = new DirectoryEntry(ldappath);
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=" + sAMAccountName + "))";
SearchResultCollection results = ds.FindAll();
foreach (SearchResult result in results)
{
OUT = GetProperty(result, attribute);
}
}
catch (Exception t)
{
// System.Diagnostics.Debug.WriteLine(t.Message);
}
return (OUT != null) ? OUT : string.Empty;
}
public static string GetProperty(SearchResult searchResult, string PropertyName)
{
if (searchResult.Properties.Contains(PropertyName))
{
return searchResult.Properties[PropertyName][0].ToString();
}
else
{
return string.Empty;
}
}
There is a CodePlex project for Linq to AD, if you're interested.
It's also covered in the book LINQ Unleashed for C# by Paul Kimmel - he uses the above project as his starting point.
not affiliated with either source - I just read the book recently