SharePoint の .NET クライアント オブジェクト モデルを使用してユーザー プロファイル プロパティを取得する

SharePoint の .NET クライアント オブジェクト モデルを使用して、ユーザー プロファイル プロパティをプログラムによって取得する方法を説明します。

SharePointのユーザー プロファイル プロパティとは

ユーザー プロパティとユーザー プロファイル プロパティは、表示名、電子メール、肩書き、その他のビジネス情報や個人情報など、SharePoint ユーザーに関する情報を提供します。 クライアント側 API では、 PersonProperties オブジェクトとその UserProfileProperties プロパティからこれらのプロパティにアクセスします。 UserProfileProperties プロパティにはすべてのユーザー プロファイル プロパティが含まれていますが、PersonProperties オブジェクトには、アクセスしやすい一般的に使用されるプロパティ (AccountNameDisplayNameEmail など) が含まれています。

PeopleManager オブジェクトには、.NET クライアント オブジェクト モデルを使用してユーザー プロパティとユーザー プロファイル プロパティを取得するために使用できる次のメソッドが含まれています。

クライアント API のユーザー プロファイル プロパティは読み取り専用です ( PeopleManager.SetMyProfilePicture メソッドを使用して変更できるプロファイル画像を除きます)。 その他のユーザー プロファイル プロパティを変更する場合は、サーバー オブジェクト モデルを使用する必要があります。

注:

UserProfile オブジェクトのクライアント バージョンには、サーバー側のバージョンとしてすべてのユーザー プロパティが含まれているわけではありません。 ただし、クライアント側のバージョンでは、現在のユーザーの個人用サイトを作成するメソッドを提供しています。 現在のユーザーの、クライアント側の UserProfile を取得するには、ProfileLoader.GetUserProfile メソッドを使用します。

プロファイルの操作の詳細については、「 SharePoint でのユーザー プロファイルの操作」を参照してください。

SharePointの .NET クライアント オブジェクト モデルを使用してユーザー プロファイル プロパティを取得できる開発環境をセットアップするための前提条件

.NET クライアント オブジェクト モデルを使用してユーザー プロファイルのプロパティを取得するコンソール アプリケーションを作成するには、次のものが必要です。

  • 現在のユーザーと対象のユーザー用に作成されたプロファイルがある SharePoint

  • Visual Studio 2012

  • 現在のユーザーの User Profile Service アプリケーションに対するフル コントロール接続のアクセス許可

注:

SharePoint を実行しているコンピューターで開発していない場合は、SharePoint クライアント アセンブリを含む SharePoint クライアント コンポーネント のダウンロードを取得します。

SharePoint .NETクライアント オブジェクト モデルを使用してユーザー プロファイルのプロパティを取得するコンソールアプリケーションの作成

  1. 開発用のコンピューターで、Visual Studio を開き、[ ファイル]、[ 新規作成]、[ プロジェクト] の順に選択します。

  2. [ 新しいプロジェクト] ダイアログ ボックスで、上部のドロップダウン リストから [ .NET Framework 4.5] を選択します。

  3. プロジェクト テンプレートから [ Windows]、[ コンソール アプリケーション] の順に選択します。

  4. プロジェクトの名前を UserProfilesCSOM とし、[ OK] をクリックします。

  5. 次のアセンブリへの参照を追加します。

  • Microsoft.SharePoint.Client
  • Microsoft.SharePoint.ClientRuntime
  • Microsoft.SharePoint.Client.UserProfiles
  1. 次のコードに示すように、Main メソッドで、サーバー URL と対象のユーザー名の変数を定義します。
const string serverUrl = "http://serverName/";
const string targetUser = "domainName\\userName";

注: コードを実行する前に、 と domainName\\\\userName プレースホルダーのhttp://serverName/値を置き換えてください。

  1. 次のコードに示すように、SharePoint のクライアント コンテキストを初期化します。
ClientContext clientContext = new ClientContext(serverUrl);
  1. 対象ユーザーのプロパティを PeopleManager オブジェクトから取得します。
PeopleManager peopleManager = new PeopleManager(clientContext);
PersonProperties personProperties = peopleManager.GetPropertiesFor(targetUser);

personProperties オブジェクトは、クライアント オブジェクトです。 一部のクライアント オブジェクトには、初期化されるまでデータが一切含まれていません。 たとえば、 personProperties オブジェクトのプロパティ値は、初期化されるまでアクセスできません。 初期化される前にプロパティへのアクセスを試みると、 PropertyOrFieldNotInitializedException という例外が発生します。

  1. personProperties オブジェクトを初期化するには、実行するリクエストを登録し、そのリクエストをサーバー上で実行します (次のコードを参照)。
clientContext.Load(personProperties, p => p.AccountName, p => p.UserProfileProperties);
clientContext.ExecuteQuery();

Load メソッド (または LoadQuery メソッド) の呼び出し時には、取得または変更するオブジェクトを渡します。 この例では、 Load メソッドの呼び出しにより、リクエストをフィルターするためのオプション パラメーターが渡されています。 このパラメーター群は、 personProperties オブジェクトの AccountName プロパティと UserProfileProperties プロパティのみを要求するラムダ式です。

ヒント: ネットワーク トラフィックを削減するには、Load メソッドを呼び出す際に、操作するプロパティのみを要求します。 さらに、複数のオブジェクトを操作する場合は、Load メソッドへの複数の呼び出しをグループ化してから ExecuteQuery メソッドを呼び出します (可能な場合)。

  1. 次のコードに示すように、ユーザープロファイルのプロパティを反復処理し、各プロパティの名前と値を読み取ります。
foreach (var property in personProperties.UserProfileProperties)
{
    Console.WriteLine(string.Format("{0}: {1}", 
        property.Key.ToString(), property.Value.ToString()));
}

コード例: SharePointの .NET クライアント オブジェクト モデルを使用したすべてのユーザー プロファイル プロパティの取得

次のコード例では、前の手順で説明した、対象ユーザーのすべてのユーザー プロファイル プロパティを取得して反復処理を行う方法を示します。

注:

コードを実行する前に http://serverName/ 、 と domainName\\\\userName プレースホルダーの値を置き換えます。


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.
        }
    }
}

コード例: SharePoint .NET クライアント オブジェクト モデルを使用して自分をフォローしている他のユーザーのユーザー プロファイル プロパティを取得する

次のコード例は、SharePoint アドイン で、自分をフォローしている人のユーザー プロファイルのプロパティを取得する方法を示しています。


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();
}

コード例: SharePointの .NET クライアント オブジェクト モデルを使用した一連のユーザー プロファイル プロパティの取得

次のコード例は、対象ユーザーのユーザー プロファイル プロパティの特定のセットを取得する方法を示しています。

注:

1 つのユーザー プロファイル プロパティの値のみを取得するには、 GetUserProfilePropertyFor メソッドを使用します。

ターゲット ユーザーの PersonProperties オブジェクトを取得する前のコード例とは異なり、この例では PeopleManager.GetUserProfilePropertiesFor メソッドを呼び出し、取得するターゲット ユーザーとユーザー プロファイルプロパティを指定する UserProfilePropertiesForUser オブジェクトを渡します。 GetUserProfilePropertiesFor は、指定したプロパティの値を含む IEnumerable<文字列> コレクションを返します。

注:

コードを実行する前に http://serverName/ 、 と domainName\\\\userName プレースホルダーの値を置き換えます。


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.
        }
    }
}

関連項目