Translate

Wednesday, October 3, 2012

Using ClientContext in SharePoint

Using ClientContext in SharePoint

In SharePoint context object provides an entry point into the associated application programming interface (API) that can be used to gain access to other objects.When we have access to the objects, we may interact with the scalar properties like Name, Title, Url of the object.

The ClientContext class can be used in both the managed and Silverlight object models which  inherits from the ClientContextRuntime class. With the help of ClientContext class, we can get a valid run-time context
by passing in the Uniform Resource Locator (URL) of a site.
It also provides several members that are required to access data and invoke methods on the server.
In SharePoint SP.ClientContext class which used in the JavaScript client object model is actually inherits from the SP.Client.ContextRuntime class which provides equivalent functionality to the ClientContext class found in the managed and Silverlight client object models. 

It is possible to get a run-time context in the JavaScript model using the SP.ClientContext class
and  can pass a URL. Which is different in managed and Silverlight models

Sample code shows different ways to access the sharepoint objects in client object model

1.Using Managed Code

//Managed Client Object Model
using (ClientContext context = new ClientContext("http://DemoSite"))
{
Site siteCollections = context.Site;
context.Load(siteCollections);
context.ExecuteQuery();
//access  scalar properties
string url = siteCollection.Url;
}

2.Using Silverlight Client Object Model
using (ClientContext context = new ClientContext("http://DemoSite"))
{
Site siteCollections =context .Site;
context .Load(siteCollections);
context .ExecuteQuery();
}

3.Using JavaScript Client Object Model

var siteCollections;
function getMySiteCollection
{
var context = new SP.ClientContext("/");
siteCollections = context.get_site;
context.load(site);
context.executeQueryAsync(Issuccess, Isfailure);
}
function Issuccess {
string url = siteCollection.get_url;
alert(url);
}
function Isfailure {
alert("It is Failed!");
}

No comments:

Post a Comment