Wednesday, May 4, 2011

Programmatically access user profile object using client object model SharePoint 2010


Here is a Code snippet for retrieving user profile object using Client Object model ECMAScript and Silverlight . I am passing the userId from the front end to get the user profile object.

Code using Silver light

ListItemCollection collList;
string FailedMessage;
private void getUserProfile(int userID)
{
ClientContext clientContext = new ClientContext("PortalURL");
Web oWebsite = clientContext.Web;
oList = clientContext.Web.SiteUserInfoList;
CamlQuery query = new Microsoft.SharePoint.Client.CamlQuery();
string camlQueryXml = "' +'' + userID + '' + 1";
query.ViewXml = camlQueryXml;
collList = oList.GetItems(query);
clientContext.Load(collList);
clientContext.ExecuteQueryAsync(new ClientRequestSucceededEventHandler(onRequestSucceeded), new ClientRequestFailedEventHandler(OnRequestFailed));
}
private void onRequestSucceeded(Object sender, ClientRequestSucceededEventArgs args)
{
try
{
// This is not called on the UI thread.
Dispatcher.BeginInvoke(BindData);

}
catch (Exception ex)
{
MessageBox.Show("Error occured in function onRequestSucceeded() of type " + ex);
}
}
public void OnRequestFailed(Object sender, ClientRequestFailedEventArgs args)
{
FailedMessage = "Request Failed Called with " + args.Message;
Dispatcher.BeginInvoke(ShowFailedMessage);
}
private void ShowFailedMessage()
{
MessageBox.Show(FailedMessage);
}
private void BindData()
{
foreach (ListItem li in collList)
{

//Now U bind the data to collection and use it in all the project.
}
}

Code Using ECMA Script

private void getUserProfile(userID)
{
ClientContext clientContext = new ClientContext('PortalURLl');
Web oWebsite = clientContext.Web;
ListItemCollection collList ;
oList = clientContext.Web.SiteUserInfoList;
CamlQuery query = new Microsoft.SharePoint.Client.CamlQuery();
string camlQueryXml = "' +'' + userID + '' + 1";
query.ViewXml = camlQueryXml;
collList = oList.GetItems(query);
clientContext.Load(collList);
clientContext.ExecuteQueryAsync(new ClientRequestSucceededEventHandler(onRequestSucceeded), new ClientRequestFailedEventHandler(OnRequestFailed));
}

function onRequestSucceeded(sender, args)
{
var item = collListItem.itemAt(0);
var profile = item.get_item(‘Notes’);
var pictureUrl = item.get_item(‘Picture’).get_url();
var Preferedname=item.get_item(‘PreferedName’);
var Loginame=item.get_item(‘LoginName’);
var Firstname=item.get_item(‘FirstName’);

}

function onRequestFailed(sender, args)
{
alert('Request failed with error'+args.message);
}