I'd like to know how can I do to access to Active Directory information (eg: Department) of an User starting from an SPUser... I've User Profile Service configured and I see in Sharepoint those fields..
Thank you!
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It only takes a minute to sign up.
Sign up to join this communityI'd like to know how can I do to access to Active Directory information (eg: Department) of an User starting from an SPUser... I've User Profile Service configured and I see in Sharepoint those fields..
Thank you!
You also can use the SPUser
and SPUserCollection
Object to iterate through all user profiles
using Microsoft.SharePoint;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.Server;
using System.Web;
here is the code:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite siteCollection = new SPSite("http://testssite:1130"))
{
using (SPWeb site = siteCollection.OpenWeb())
{
ServerContext serverContext = ServerContext.GetContext(siteCollection);
UserProfileManager userProfileMangager = new UserProfileManager(serverContext);
SPUserCollection userCollection = site.AllUsers;
foreach (SPUser spUser in userCollection)
{
UserProfile profile = userProfileMangager.GetUserProfile(spUser.LoginName);
Console.WriteLine(profile["department"].Value);
}
}
});
RunWithElevatedPrivileges
call will works only of the system account is declared as administrator on the profile service application. Don't forget to grant this role, if you don't want to get obscure NullReferenceException
– Steve B
Jun 18 '12 at 14:37
You will need to load it from the User Profiles and not the SPUser object.
SPServiceContext svcContext = SPServiceContext.GetContext(site);
UserProfileManager profileManager = new UserProfileManager(svcContext);
UserProfile profile = profileManager.GetUserProfile(accountname);
string department = profile["department"].Value;
RunWithElevatedPermission
won't be enough.
– Steve B
Jun 18 '12 at 14:36
The other answers are effective and accurate. Though, I'm interested in another method, that does not require code that runs ElevatedPrivileges code N times whenever this information is requested.
I would consider building a list (or SQL table) with the AD Users, and necessary fields, which is updated on a scheduled basis.
The info can be loaded into a SQL data via t-sql nightly or weekly: http://blog.tech-cats.com/2007/09/querying-active-directory-through-sql.html or into a SharePoint list via c# using various methods.
The advantage here is that, every time the information required, AD does not need to be accessed via Elevated permissions.