Friday 20 September 2013

SharePoint 2013 Working with User Profiles & JavaScript CSOM

SharePoint 2013 has added a variety of functionality to the Client API. One of them is the ability to fetch User Profile data. Now you can directly query the user profiles and get the required data from the client site. This can be really useful if you are building apps.

If you want to use the REST API to work with user profiles, MSDN has a decent documentation on it here:
http://msdn.microsoft.com/en-us/library/jj163800.aspx
In this post, I will show you how to work with User Profiles using the JavaScript Client Object Model

Before we get started with the code, lets make couple of things sure. First,  you will need a reference to the following JavaScript files in your page:

1234
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.0.min.js"></script>
<script src="/_layouts/15/SP.Runtime.js"></script>
<script src="/_layouts/15/SP.js"></script>
<script src="/_layouts/15/SP.UserProfiles.js"></script>
view rawupScripts.html hosted with ❤ by GitHub

(jQuery is not required but I have added it because we will need it for the $.ajax function when doing REST queries)

Second thing, you will need the domain\username of the user you want to get the user profile data for. This can be easy to get if you are in an On-Prem environment. But if you are working with SharePoint Online, this can be quite tricky. Your username might not always be in the domain\username format. It is stored in the LoginName property if you are querying the Site User Information List:

https://yoursite.sharepoint.com/sites/pubsite/_api/Web/GetUserById(17)

and it is stored in the AccountName property if your querying the User Profile Service:

https://yoursite.sharepoint.com/sites/pubsite/_api/SP.UserProfiles.PeopleManager/GetMyProperties

In SharePoint Online, it will most probably be in the following format:


i:0#.f|membership|vardhaman@yoursite.onmicrosoft.com


Quick Note: If you are using the REST API, you will need to encode the username before you use it in your call. The encodeURIComponent( ) function can be helpful here.

Enough talking. Lets jump into some code right away:


1) Get Multiple User Profile Properties:

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
(function($){
 
$(document).ready(function(){
// Ensure that the SP.UserProfiles.js file is loaded before the custom code runs.
SP.SOD.executeOrDelayUntilScriptLoaded(loadUserData, 'SP.UserProfiles.js');
});
var userProfileProperties = [];
function loadUserData(){
//Get Current Context
var clientContext = new SP.ClientContext.get_current();
//Get Instance of People Manager Class
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
//Properties to fetch from the User Profile
var profilePropertyNames = ["PreferredName","PictureURL"];
//Domain\Username of the user (If you are on SharePoint Online)
var targetUser = "i:0#.f|membership|vardhaman@yoursite.onmicrosoft.com";
//If you are on On-Premise:
//var targetUser = domain\\username
//Create new instance of UserProfilePropertiesForUser
var userProfilePropertiesForUser = new SP.UserProfiles.UserProfilePropertiesForUser(clientContext, targetUser, profilePropertyNames);
userProfileProperties = peopleManager.getUserProfilePropertiesFor(userProfilePropertiesForUser);
//Execute the Query.
clientContext.load(userProfilePropertiesForUser);
clientContext.executeQueryAsync(onSuccess, onFail);
}
function onSuccess() {
var messageText = "\"Preffered Name\" property is " + userProfileProperties[0];
messageText += "\"PictureURL\" property is " + userProfileProperties[1];
alert(messageText);
}
function onFail(sender, args) {
alert("Error: " + args.get_message());
}
})(jQuery);
view rawupMult.js hosted with ❤ by GitHub


2) Get Single User Profile Property:

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
(function($){
 
$(document).ready(function(){
// Ensure that the SP.UserProfiles.js file is loaded before the custom code runs.
SP.SOD.executeOrDelayUntilScriptLoaded(loadUserData, 'SP.UserProfiles.js');
});
var userProfileProperty;
function loadUserData(){
//Get Current Context
var clientContext = new SP.ClientContext.get_current();
//Get Instance of People Manager Class
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
//Property to fetch from the User Profile
var propertyName = "PreferredName";
//Domain\Username of the user (If you are on SharePoint Online)
var targetUser = "i:0#.f|membership|vardhaman@yoursite.onmicrosoft.com";
//If you are on On-Premise:
//var targetUser = domain\\username
//Create new instance of UserProfileProperty
userProfileProperty = peopleManager.getUserProfilePropertyFor(targetUser, propertyName)
//Execute the Query. (No load method necessary)
clientContext.executeQueryAsync(onSuccess, onFail);
}
function onSuccess() {
var messageText = "\"Preferred Name\" property is " + userProfileProperty.get_value();
alert(messageText);
}
function onFail(sender, args) {
alert("Error: " + args.get_message());
}
})(jQuery);
view rawupsing.js hosted with ❤ by GitHub


3) Get User Profile Properties of the Current User:

1234567891011121314151617181920212223242526272829303132333435363738
(function($){
$(document).ready(function(){
// Ensure that the SP.UserProfiles.js file is loaded before the custom code runs.
SP.SOD.executeOrDelayUntilScriptLoaded(loadUserData, 'SP.UserProfiles.js');
});
var userProfileProperties;
function loadUserData(){
//Get Current Context
var clientContext = new SP.ClientContext.get_current();
//Get Instance of People Manager Class
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
//Get properties of the current user
userProfileProperties = peopleManager.getMyProperties()
clientContext.load(userProfileProperties);
//Execute the Query.
clientContext.executeQueryAsync(onSuccess, onFail);
}
function onSuccess() {
alert(userProfileProperties.get_displayName());
}
function onFail(sender, args) {
alert("Error: " + args.get_message());
}
})(jQuery);
view rawsp15_up_current.js hosted with ❤ by GitHub


4) Get Properties of Multiple Users in Single Request:

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
(function($){
 
$(document).ready(function(){
// Ensure that the SP.UserProfiles.js file is loaded before the custom code runs.
SP.SOD.executeOrDelayUntilScriptLoaded(loadUserData, 'SP.UserProfiles.js');
});
 
var userProfileProperties = [];
//Array containing domain\usernames of multiple users. You can get the usersnames any way you want.
var targerUsers = ["i:0#.f|membership|vardhaman@yoursite.onmicrosoft.com","i:0#.f|membership|demouser1@yoursite.onmicrosoft.com"];
//If you are on On-Premise:
//var targerUsers = ["domain\\username","domain\\demouser1"];
function loadUserData(){
//Get Current Context
var clientContext = new SP.ClientContext.get_current();
//Get Instance of People Manager Class
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
//Property to fetch from the User Profile
var propertyName = "PreferredName";
for(var i=0;i<targerUsers.length;i++){
//Create new instance of UserProfileProperty
userProfileProperties[i] = peopleManager.getUserProfilePropertyFor(targerUsers[i], propertyName);
}
//Execute the Query. (No load method necessary)
clientContext.executeQueryAsync(onSuccess, onFail);
}
function onSuccess() {
var messageText = "";
for(var i=0;i<userProfileProperties.length;i++){
messageText += "\"Preffered Name\" property is " + userProfileProperties[i].get_value();
}
alert(messageText);
}
function onFail(sender, args) {
alert("Error: " + args.get_message());
}
 
})(jQuery);
view rawuponecall.js hosted with ❤ by GitHub


For this last example, Let's observe the XML which is sent to the server:

1234567891011121314151617181920
<Request xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009" SchemaVersion="15.0.0.0" LibraryVersion="15.0.0.0" ApplicationName="Javascript Library">
<Actions>
<ObjectPath Id="1" ObjectPathId="0"></ObjectPath>
<Method Name="GetUserProfilePropertyFor" Id="2" ObjectPathId="0">
<Parameters>
<Parameter Type="String">i:0#.f|membership|vardhaman@yoursite.onmicrosoft.com</Parameter>
<Parameter Type="String">PreferredName</Parameter>
</Parameters>
</Method>
<Method Name="GetUserProfilePropertyFor" Id="3" ObjectPathId="0">
<Parameters>
<Parameter Type="String">i:0#.f|membership|demouser1@yoursite.onmicrosoft.com</Parameter>
<Parameter Type="String">PreferredName</Parameter>
</Parameters>
</Method>
</Actions>
<ObjectPaths>
<Constructor Id="0" TypeId="{cf560d69-0fdb-4489-a216-b6b47adf8ef8}"></Constructor>
</ObjectPaths>
</Request>
view rawup.xml hosted with ❤ by GitHub


With this, we can confirm that only one call was made to the server to retrieve the properties of multiple users. This way, you can even retrieve multiple properties of multiple users in one call.

Share This!


1 comment:

Translate

Total Pageviews

Powered By Blogger · Designed By Seo Blogger Templates