0

I have a custom web part which will pull Active directories custom attribute(logged in user). For testing purpose currently I am trying to get "mail" of currently logged in user. But it is not working. Here is my code

DirectoryEntry entry = new DirectoryEntry("LDAP://rp.fs.asdf.org");
            DirectorySearcher mySearcher = new DirectorySearcher(entry, "(sAMAccountName=myuserid1)", new string[] { "mail" });
            mySearcher.PropertiesToLoad.Add("mail");
            SearchResult result = mySearcher.FindOne();
            if (result != null)
            {
                mailID = result.GetDirectoryEntry().Properties["mail"].Value.ToString();
            }
            entry.Close();
            entry.Dispose();
            mySearcher.Dispose();

The same code works perfectly in "Windows form". I have been fighting with this code. Please suggest some ideas. Appreciate your help.

1
  • I have to embed this in SPSecurity.RunWithElevatedPrivileges. Then it worked.
    – Maddy
    Mar 26, 2015 at 17:34

1 Answer 1

0

Using .Net 3.5 System.DirectoryServices.AccountManagement; you can query AD using below code

string userName = SPContext.Current.Web.CurrentUser.UserName;
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, "MyDomain","DC=MyDomain,DC=com");
UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, userName);

Once you have that you can get Email using oUserPrincipal.Email

3
  • I tired this approach also but it didnot work. But when I give username and password it is working. Does it mean I have pass logged in user name and password for this? How can I get user password to pass?
    – Maddy
    Mar 26, 2015 at 17:22
  • Ideally this works when logged in user has correct permissions on AD. Can you confirm the logged in user has enough permission to query AD? Mar 26, 2015 at 17:23
  • I am the logged in user and I am able to query it from "windows forms". It is not working only from web part. I think I solved it. I have to use "SPSecurity.RunWithElevatedPrivileges", now it works.
    – Maddy
    Mar 26, 2015 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.