How To Retrieve a User’s Profile in SharePoint 2003

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

This entry was posted in SharePoint. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

20 Responses to How To Retrieve a User’s Profile in SharePoint 2003

  1. Gayathri says:

    good one

  2. M.V.S.RAVI KUMAR says:

    can you give me some idea how to access user profiles in MOSS?

  3. Christian says:

    Hi

    Im looking for a webpart similar to the built in Contact Details but where one can show more fields than just Picture and Jobtitle. Anyone that can help me with this?

    Attachments:

  4. Anna says:

    Can somebody tell me how to search users from the profile database and not from sharepoint which is illustrated in this example.

  5. sush says:

    hi Courtz..
    can you please tell me how to add users to the profile database…thnx

  6. Taha says:

    some time its:

    File or assembly name spsscheduler_net, or one of its dependencies, was not found.

  7. Taha says:

    I have a problem with defining TopologyManager
    it gives me error of
    File or assembly name Microsoft.SharePoint.Security, or one of its dependencies, was not found.
    any help

  8. mourinho says:

    Hi Eva
    1. I have the same propblem with you, any suggestion? Thanks
    2. I want to learn more about security, for example
    version="1"
    Flags="Execution,UnmanagedCode,ControlPrincipal,ControlAppDomain,ControlEvidence"
    />

    It very hard to understand, please let me know books or references about that, thanks.

  9. Pat says:

    Hey Mark,

    I am doing the exact same thing which you have been looking for. My Profile database is being populated from AD and trying to build a webpart which basically works as a Phone Directory. This article seems to be good but I dont understand if it is pulling the users from the root or actually from the profile DB. If you found some more references for what you have doing please share it with me.

  10. Mark says:

    I’m with the other guy. I’m trying to build an employee database (skills, contact info, resume etc..) and want it to update the Sharepoint profile. I’d rather not even build the database – maybe just extend Active Directory or Outlook contacts (or something). Anyone ever do something similar? How about sharing those webparts on gotdotnet?

  11. Cameron Seibel says:

    Way of doing it without for-eaching through the user database (in VB)

    ‘This webpart will NOT work correctly if the site url is not in the
    ‘alternate url list. This is due to getting the site context. If
    ‘getting the site context or user profile fail, only the user account
    ‘will be displyed.

    Private Function getSPPreferredName(ByVal userAccount As String) As String

    Try
    ‘Some code taken from the SPPT SDK from the UserProfile Class
    ‘Can also be found on the MSDN 2005 Library

    ‘*********** Error Here Requesting Context ***********
    ‘*********** Testing on http://localhost:8080 ***********
    ‘*********** Was not in alternate url so it failed ***********
    ‘*********** getting the site context ***********

    ‘get portal site context from topology
    Dim strUrl As String = Context.Request.Url.GetLeftPart(UriPartial.Authority) & Me.ResolveUrl(Context.Request.ApplicationPath)
    Dim tm As New TopologyManager
    Dim ps As PortalSite = tm.PortalSites(New Uri(strUrl))
    Dim pc As PortalContext = PortalApplication.GetContext(ps)

    ‘initialize user profile config manager object
    Dim upm As New UserProfileManager(pc)
    ‘Check to see if the user exists in the Profile Database
    If upm.UserExists(userAccount) Then
    ‘Create an instance of the user profile with the specified account name
    Dim userProf As UserProfile = upm.GetUserProfile(userAccount)
    ‘Return the preferred name of the user
    context.Trace.Warn(userProf(“PreferredName”).ToString())
    Return userProf(“PreferredName”).ToString()
    Else
    ‘If the user doesn’t exist just return the user account
    Return userAccount
    End If

    Catch ex As Exception
    ‘Write stacktrace for troubleshooting to tracing info if Try
    ‘block fails
    context.Trace.Warn(ex.StackTrace)
    ‘Just return the userAccount if the GetContext or GetUserProfile
    ‘fail.
    Return userAccount
    End Try
    End Function

  12. Edward says:

    U DA MAN!!!!

    Just wanted to say thanks. I am doing something very similiar. Building Employee directory application and wanted to use the SharePoint profile database to get path to photos etc. Just saved me some time. Thanks.

  13. Asfar Sadewa says:

    I got an error on this line.

    SPUserCollection allUsers = rootSite.RootWeb.AllUsers;

    the error was:
    The referenced virtual server is not on the config database.

    how come??? can you diagnose my problem?? because i am sure that the value of the uri’s absolute path is correct and point to my portal address.

  14. Courtz says:

    In this example you only search the users already added to sharepoint not the profile database, but do bring up user info for the existing (added) users from the profile database

  15. Eve says:

    I’m trying what you suggested, but I’m getting the following error:

    System.Security.SecurityException: Request failed. at Microsoft.SharePoint.Portal.Topology.TopologyManager.g() at Microsoft.SharePoint.Portal.Topology.TopologyManager..ctor() at WebPartLibrary.PhoneBook.CreateChildControls() in y:\webpartlibrary\webpartlibrary\phonebook.cs:line 129

    I am using a custom trust file, but it doesn’t work with WSS_MediumTrust either. It will only work when I set it to full trust, which I would rather not do. Any suggestions?

  16. Nik says:

    I’m sure that no one wants to share the web part that they have created right? I’ve been trying to find something to do this for a while now, but I am not a developer, and VS.Net scares me.

  17. Share khan says:

    I have created a webpart based on your code.
    It works fine with the portal.
    My portal also has a host header name.
    When I access th site with this host header name the web part is not rendered

    There is no hard coding of site name in the code.
    Any Idea??

  18. Nick says:

    How do we update the user profile properties? Neither the web service nor referencing the DLL directly seems to allow this.

  19. L Baudewijns says:

    On the inside of my network, it works correctly (http://sharepoint). But when i view the portal from the internet (eg. http://portal.sharepoint.nl) then, the site url stays empty.

    Any suggestions?

Leave a Reply