Mark DiGiovanni

Sponsors

The Lounge

News

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
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


Posted Sat, Feb 5 2005 7:52 PM by Mark DiGiovanni
Filed under:

[Advertisement]

Comments

L Baudewijns wrote re: How To Retrieve a User's Profile in SharePoint 2003
on Fri, Mar 25 2005 2:49 AM
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?
Nick wrote re: How To Retrieve a User's Profile in SharePoint 2003
on Tue, Jun 14 2005 10:57 AM
How do we update the user profile properties? Neither the web service nor referencing the DLL directly seems to allow this.
Share khan wrote re: How To Retrieve a User's Profile in SharePoint 2003
on Thu, Aug 4 2005 7:05 AM
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??
Nik wrote re: How To Retrieve a User's Profile in SharePoint 2003
on Thu, Aug 4 2005 10:19 AM
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.
Eve wrote re: How To Retrieve a User's Profile in SharePoint 2003
on Wed, Dec 14 2005 1:35 PM
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?
Courtz wrote re: How To Retrieve a User's Profile in SharePoint 2003
on Tue, Jan 31 2006 3:58 AM
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
Asfar Sadewa wrote re: How To Retrieve a User's Profile in SharePoint 2003
on Tue, Jan 31 2006 9:14 PM
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.
Edward wrote re: How To Retrieve a User's Profile in SharePoint 2003
on Wed, Mar 8 2006 8:23 AM
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.
Cameron Seibel wrote re: How To Retrieve a User's Profile in SharePoint 2003
on Mon, Mar 20 2006 5:03 PM
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
Mark wrote re: How To Retrieve a User's Profile in SharePoint 2003
on Fri, May 26 2006 11:03 AM
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?
mourinho wrote re: How To Retrieve a User's Profile in SharePoint 2003
on Thu, Mar 1 2007 4:06 AM

Hi Eva

1. I have the same propblem with you, any suggestion? Thanks

2. I want to learn more about security, for example

<IPermission

class="SecurityPermission"

version="1"                                    

Flags="Execution,UnmanagedCode,ControlPrincipal,ControlAppDomain,ControlEvidence"

/>

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

Taha wrote re: How To Retrieve a User's Profile in SharePoint 2003
on Wed, Mar 21 2007 2:12 PM

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

Taha wrote re: How To Retrieve a User's Profile in SharePoint 2003
on Wed, Mar 21 2007 2:14 PM

some time its:

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

sush wrote re: How To Retrieve a User's Profile in SharePoint 2003
on Tue, May 15 2007 1:50 AM

hi Courtz..

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

Anna wrote re: How To Retrieve a User's Profile in SharePoint 2003
on Wed, May 23 2007 12:47 AM
Can somebody tell me how to search users from the profile database and not from sharepoint which is illustrated in this example.
Christian wrote re: How To Retrieve a User's Profile in SharePoint 2003
on Wed, Jun 13 2007 9:56 AM
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: