I am currently building a Web Part for our internal SharePoint 2003
portal site that will return the employee directory complete with
photo, email address, and home, work, and cell phone numbers. To do
this, the web part needs to access to the users profile. Here is the C#
code needed to get the user profiles.
*The below code does not represent a complete web part*
First, make sure that your web part has the appropriate code access
security settings such as the SharePointPermission with the following
setting: ObjectModel=True. For more information on Code Access Security
and SharePoint, click here.
Add the following using statements after the assemblies are referenced.
using Microsoft.SharePoint.Portal;
using Microsoft.SharePoint.Portal.Topology;
using Microsoft.SharePoint.Portal.UserProfiles;
The root site will have to be retrieved to get the collection of users. Use the following method to get the base URL.
private string GetRootUrl()
{
string url = Context.Request.Url.GetLeftPart(UriPartial.Authority) + this.ResolveUrl( Context.Request.ApplicationPath);
return url;
}
*NOTE* If you are accessing the portal site via http://localhost/, you must add http://localhost/ as an alias for the site.
//Get the root URL and the PortalContext.
string url = GetRootUrl();
SPSite rootSite = SPControl.GetContextSite(Context);
PortalContext portalContext = null;
Uri uri = new Uri(url);
//Get the collection of portal sites by the URL.
TopologyManager topologyManager = new TopologyManager();
PortalSiteCollection sites = topologyManager.PortalSites;
portalContext = PortalApplication.GetContext(sites[uri]);
//Get all the users that have access.
SPUserCollection allUsers = rootSite.RootWeb.AllUsers;
UserProfileManager upm = new UserProfileManager(portalContext);
//Loop through the users to get their profile.
foreach (SPUser user in allUsers)
{
//Do whatever needs to be done with the following properties.
UserProfile up = upm.GetUserProfile(user.LoginName);
string fullName = up["PreferredName"].ToString();
string emailAddress = up["WorkEmail"].ToString();
string homePhone = up["HomePhone"].ToString();
string cellPhone = up["MobilePhone"].ToString();
}
To see a list of property names available to you, navigate here:
Site Settings > Manage profile Database > View profile
properties.
For additional resources on SharePoint, visit the following sites:
SharePoint and Code Access Security
Lamont Harrington's SharePoint 2003 Resource Center
SharePoint University
Push the Limits of SharePoint Customization
--Mark
Posted
Sat, Feb 5 2005 7:52 PM
by
Mark DiGiovanni