Retrieve user profile properties by using the .NET client object model in SharePoint

Learn how to retrieve user profile properties programmatically by using the SharePoint .NET client object model.

What are user profile properties in SharePoint?

User properties and user profile properties provide information about SharePoint users, such as display name, email, title, and other business and personal information. In client-side APIs, you access these properties from the PersonProperties object and its UserProfileProperties property. The UserProfileProperties property contains all user profile properties, but the PersonProperties object contains commonly used properties (such as AccountName , DisplayName , and Email ) that are easier to access.

The PeopleManager object includes the following methods that you can use to retrieve user properties and user profile properties by using the .NET client object model:

User profile properties from client APIs are read-only (except the profile picture, which you can change by using the PeopleManager.SetMyProfilePicture method). If you want to change other user profile properties, you must use the server object model.

Note

The client version of the UserProfile object doesn't contain all of the user properties as the server-side version. However, the client-side version does provide the methods for creating a personal site for the current user. To retrieve the client-side UserProfile for the current user, use the ProfileLoader.GetUserProfile method.

For more information about working with profiles, see Work with user profiles in SharePoint.

Prerequisites for setting up your development environment to retrieve user profile properties by using the SharePoint .NET client object model

To create a console application that uses the .NET client object model to retrieve user profile properties, you'll need the following:

  • SharePoint with profiles created for the current user and a target user

  • Visual Studio 2012

  • Full Control connection permissions to access the User Profile service application for the current user.

Note

If you're not developing on the computer that is running SharePoint, get the SharePoint Client Components download that contains SharePoint client assemblies.

Create the console application that retrieves user profile properties by using the SharePoint .NET client object model

  1. On your development computer, open Visual Studio and choose File, New, Project.

  2. In the New Project dialog box, choose .NET Framework 4.5 from the drop-down list at the top of the dialog box.

  3. From the project templates, choose Windows, and then choose Console Application.

  4. Name the project UserProfilesCSOM, and then choose the OK button.

  5. Add references to the following assemblies:

  • Microsoft.SharePoint.Client
  • Microsoft.SharePoint.ClientRuntime
  • Microsoft.SharePoint.Client.UserProfiles
  1. In the Main method, define variables for the server URL and the target user name, as shown in the following code.
const string serverUrl = "http://serverName/";
const string targetUser = "domainName\\userName";

Note: Remember to replace the http://serverName/ and domainName\\\\userName placeholder values before you run the code.

  1. Initialize the SharePoint client context, as shown in the following code.
ClientContext clientContext = new ClientContext(serverUrl);
  1. Get the target user's properties from the PeopleManager object, as shown in the following code.
PeopleManager peopleManager = new PeopleManager(clientContext);
PersonProperties personProperties = peopleManager.GetPropertiesFor(targetUser);

The personProperties object is a client object. Some client objects contain no data until they are initialized. For example, you cannot access the property values of the personProperties object until you initialize it. If you try to access a property before it is initialized, you receive a PropertyOrFieldNotInitializedException exception.

  1. To initialize the personProperties object, register the request that you want to run, and then run the request on the server, as shown in the following code.
clientContext.Load(personProperties, p => p.AccountName, p => p.UserProfileProperties);
clientContext.ExecuteQuery();

When you call the Load method (or the LoadQuery method), you pass in the object that you want to retrieve or change. In this example, the call to the Load method passes in optional parameters to filter the request. The parameters are lambda expressions that request only the AccountName property and UserProfileProperties property of the personProperties object.

Tip: To reduce network traffic, request only the properties that you want to work with when you call the Load method. In addition, if you're working with multiple objects, group multiple calls to the Load method when possible before you call the ExecuteQuery method.

  1. Iterate through the user profile properties and read the name and value of each property, as shown in the following code.
foreach (var property in personProperties.UserProfileProperties)
{
    Console.WriteLine(string.Format("{0}: {1}", 
        property.Key.ToString(), property.Value.ToString()));
}

Code example: Retrieving all user profile properties by using the SharePoint .NET client object model

The following code example shows how to retrieve and iterate through all the user profile properties of a target user, as described in the previous procedure.

Note

Replace the http://serverName/ and domainName\\\\userName placeholder values before you run the code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.UserProfiles;

namespace UserProfilesCSOM
{
    class Program
    {
        static void Main(string[] args)
        {

            // Replace the following placeholder values with the target SharePoint site and
            // target user.
            const string serverUrl = "http://serverName/";  
            const string targetUser = "domainName\\\\userName";  

            // Connect to the client context.
            ClientContext clientContext = new ClientContext(serverUrl);

            // Get the PeopleManager object and then get the target user's properties.
            PeopleManager peopleManager = new PeopleManager(clientContext);
            PersonProperties personProperties = peopleManager.GetPropertiesFor(targetUser);

            // Load the request and run it on the server.
            // This example requests only the AccountName and UserProfileProperties
            // properties of the personProperties object.
            clientContext.Load(personProperties, p => p.AccountName, p => p.UserProfileProperties);
            clientContext.ExecuteQuery();

            foreach (var property in personProperties.UserProfileProperties)
            {
                Console.WriteLine(string.Format("{0}: {1}", 
                    property.Key.ToString(), property.Value.ToString()));
            }
            Console.ReadKey(false);

            // TODO: Add error handling and input validation.
        }
    }
}

Code example: Retrieving user profile properties of people who are following me by using the SharePoint .NET client object model

The following code example shows how to get, in a SharePoint Add-in, the user profile properties of people who are following you.


string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);

if (contextTokenString != null)
{
    Uri sharepointUrl = new Uri(Request.QueryString["SP.Url"]);

    ClientContext clientContext = TokenHelper.GetClientContextWithContextToken(sharepointUrl.ToString(), contextTokenString, Request.Url.Authority);

    PeopleManager peopleManager = new PeopleManager(clientContext);
    ClientObjectList<PersonProperties> peopleFollowedBy = peopleManager.GetMyFollowers();
    clientContext.Load(peopleFollowedBy, people => people.Include(person => person.PictureUrl, person => person.DisplayName));
    clientContext.ExecuteQuery();

    foreach (PersonProperties personFollowedBy in peopleFollowedBy)
    {
        if (!string.IsNullOrEmpty(personFollowedBy.PictureUrl))
        {
        Response.Write("<img src=\\"" + personFollowedBy.PictureUrl + "\\" alt=\\"" + personFollowedBy.DisplayName + "\\"/>");
        }
    }
    clientContext.Dispose();
}

Code example: Retrieving a set of user profile properties by using the SharePoint .NET client object model

The following code example shows how to retrieve a specific set of user profile properties for a target user.

Note

To retrieve the value for only one user profile property, use the GetUserProfilePropertyFor method.

Unlike the previous code example that retrieves a PersonProperties object for the target user, this example calls the PeopleManager.GetUserProfilePropertiesFor method and passes in a UserProfilePropertiesForUser object that specifies the target user and the user profile properties to retrieve. GetUserProfilePropertiesFor returns an IEnumerable<string> collection that contains the values of the properties that you specify.

Note

Replace the http://serverName/ and domainName\\\\userName placeholder values before you run the code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.UserProfiles;

namespace UserProfilesCSOM
{
    class Program
    {
        static void Main(string[] args)
        {

            // Replace the following placeholder values with the target SharePoint site and the
            // target user.
            const string serverUrl = "http://serverName/";  
            const string targetUser = "domainName\\\\userName";  

            // Connect to the client context.
            ClientContext clientContext = new ClientContext(serverUrl);

            // Get the PeopleManager object.
            PeopleManager peopleManager = new PeopleManager(clientContext);

            // Retrieve specific properties by using the GetUserProfilePropertiesFor method. 
            // The returned collection contains only property values.
            string[] profilePropertyNames = new string[] { "PreferredName", "Department", "Title" };
            UserProfilePropertiesForUser profilePropertiesForUser = new UserProfilePropertiesForUser(
                clientContext, targetUser, profilePropertyNames);
            IEnumerable<string> profilePropertyValues = peopleManager.GetUserProfilePropertiesFor(profilePropertiesForUser);

            // Load the request and run it on the server.
            clientContext.Load(profilePropertiesForUser);
            clientContext.ExecuteQuery();

            // Iterate through the property values.
            foreach (var value in profilePropertyValues)
            {
                Console.Write(value + "\\n");
            }
            Console.ReadKey(false);

            // TO DO: Add error handling and input validation.
        }
    }
}

See also