How can i Pull Profile image from sharepoint

1k Views Asked by At

I'am new in API's & trying to pull user profile from sharepoint i use following code but don't know about servername? domainname? and username?

const string serverUrl = "http://sharepoint.com/";
            const string targetUser = "ttgdev-my.sharepoint.com\\[email protected]";

            // 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);

Please guide me it will give me the error in {"The property or field 'UserProfileProperties' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested."} in the following line

 clientContext.ExecuteQuery();
1

There are 1 best solutions below

0
On BEST ANSWER

Most likely it is related with the format of targetUser variable. PeopleManager.GetPropertiesFor method expects accountName parameter to be specified in the proper format, in case of SharePoint Online it should be specified in claims format, for example:

i:0#.f|membership|[email protected]

For more details about Claims format follow this article.

So, in your case targetUser value should be replaced from ttgdev-my.sharepoint.com\\[email protected] to i:0#.f|membership|[email protected]


The following example demonstrates how to retrieve user profile picture via CSOM API:

using (var ctx = TokenHelper.GetClientContextWithAccessToken(webUri.ToString(), accessToken))
{

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

   //Retrieve picture property
   var result = peopleManager.GetUserProfilePropertyFor(accountName, "PictureURL");
   ctx.ExecuteQuery();
   Console.WriteLine("Picture Url: {0}",result.Value);
}