Showing posts with label User Profiles. Show all posts
Showing posts with label User Profiles. Show all posts

Friday, 20 September 2013

Get Multiple User Properties in SharePoint 2013

var users=["domain\\kalpeshp", "domain\\sachinka", "domain\\nikhils"];

function GetUserProperties(clientContext, peopleManager, targetUser, profilePropertyNames){
 var userProfilePropertiesForUser = new SP.UserProfiles.UserProfilePropertiesForUser(
  clientContext,
  targetUser,
  profilePropertyNames);
 var userProfileProps = peopleManager.getUserProfilePropertiesFor(userProfilePropertiesForUser);

 clientContext.load(userProfilePropertiesForUser);
 clientContext.executeQueryAsync(
  function () { console.log(userProfileProps[0] + " works in " + userProfileProps[1] + " as a " + userProfileProps[2]); },
  function () { console.log("Failure") });
 }


function GetAllUserProperties(){
 var targetUser = "domain\\kalpeshp";

 // Create the client context and get the PeopleManager instance.
 var clientContext = new SP.ClientContext.get_current();
 var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);

 // Get user profile properties for the target user.
 // Specify the properties to retrieve and create the UserProfilePropertiesForUser object.
 // Then get the requested properties by using the getUserProfilePropertiesFor method.
 var profilePropertyNames = ["PreferredName", "Department", "Title"];

 for(var i=0; i<users.length;i++){
     GetUserProperties(clientContext, peopleManager, users[i], profilePropertyNames);
 }
}
Read More

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.
Read More

SharePoint SP Services Get User Profile Properties

'GetUserData':function(loginName){
        $().SPServices({
            operation: "GetUserProfileByName",
            AccountName: loginName, // replace adLogin with your string expression
            completefunc:function(data,status) {
                var profile = {};
                $(data.responseText).find("PropertyData").each(function(idx, val) {
                    var $val = $(val);
                    var name = $val.find("Name").text();
                    var value = $val.find("Value").text();
                    profile[name] = value;
                });
                ////////////debugger;
                // At this point the profile object has all profile properties:
                User.id = _spPageContextInfo.userId;
                User.title = profile.Title;
                User.userCountry = profile.UCBCountry;
                User.loginName = profile.AccountName;

            }
        });
    }
Read More

Monday, 3 December 2012

Sharepoint Object Model User Profiles



Introduction
In this article I am going to explain you that How to use User Profiles and profile properties in Sharepoint Object model.
In SharePoint 2007, a userid is uniquely identified by his/her username. The username is Tied to the membershipprovider that the site is configured to authenticate against. A user can also have other information like phone number, email etc.
Even if business require then they can add custom property like Origin, Race etc.
Detail:-
First, your code must have references to the Microsoft.SharePoint, Microsoft.Office.Server, and System.Web Assemblies. With those references available, you can use the SPSite class and the UserProfileManager class as entry points into the user profile subsystem within MOSS.
As per my opinion; there are few below important points while using user profiles programmatically:
1. Retrieving User Profiles
2. Read Profile Property
3. Modify User Profile
4. Create a User Profile
5. Create a User Profile property
The Code:-
Main class I am going to explain in only 1st point. In rest other point I will only highlight code block which is related to respective point.
1. Retrieving User Profiles
We can get user profile object by using GetUserProfile method of UserProfileManager.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Server;
using Microsoft.Office.Server.Administration;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;
using System.Web;
 
namespace UserProfilesConsoleApp
{
 class Program
 {
   static void Main(string[] args)
   {
     using ( SPSite site = new SPSite("site url"))
     {
 ServerContext context = ServerContext.GetContext(site);
 UserProfileManager profileManager = new UserProfileManager(context);
 // you can also get current user from web object.
        // syntex: SPWeb.CurrentUser
 UserProfile profile = profileManager.GetUserProfile(@"domainuser");
 Console.WriteLine("Profile {0}", profile.MultiloginAccounts[0]);
        // you got user profile object. now you can use any property of it.
        // like profile.ID, profile.PersonalSite.RootWeb.Titl e, profile.PersonalSite.Url etc..
 
     }
   }
 }
}


2. Read Profile Property
We can read property using UserProfileManager.Properties
foreach (Property prop in profileManager.Properties)
{
  Console.WriteLine("t{0} : {1}",
  prop.DisplayName, profile[prop.Name].Value);
}

3. Modify User Profile
profile["Origin"] = "India";
//Make sure that you call the Commit method 
//when you are finished making changes to the profile
profile.Commit();

4. Create a User Profile
UserProfileManager profileManager = new
UserProfileManager(context);
string acId = @"domainavinash";
if (!profileManager.UserExists(acId))
{
  UserProfile profile = profileManager.CreateUserProfile(acId);
  if (profile == null)
 Console.WriteLine("ould not create user profile, an error occurred.");
  else
 Console.WriteLine("User profile has been created.");
}
else
 Console.WriteLine("User profile for this account " + acId + " already exists.");

5. Create user Profile Property
PropertyCollection pc = profileManager.Properties;
Property p = pc.Create(false);
p.Name = "TestProperty";
p.DisplayName = "Test Property";
p.Type = "String";
p.Length = 50;
p.PrivacyPolicy = PrivacyPolicy.OptIn;
p.DefaultPrivacy = Privacy.Organization;
pc.Add(p);

Reference:-

Thanks
Nikhil S.

Read More

Translate

Total Pageviews

Powered By Blogger · Designed By Seo Blogger Templates