Learningsharepoint.com – Server Object model & Client Object Model


Server Object Model –
Here we will look at how to use SharePoint API’s, LINQ, REST and SharePoint web service to extract data from sharepoint server.

Lets Start with using the API’s in Microsoft.SharePoint and Microsoft.SharePoint.Utilities namespaces.

Firstly, to work with SharePoint 2010 components, your code must first establish the site context or site collection context for requests that are made to the server.

Please Note : In SharePoint, the SPsite object also referred to as Site is actually a “Site Collection” object, not a website
and the SPweb object also refered to as “web” is a single site in the site collection.(It can be a top-level site collection site).
also, object of type SPWebApplication is a highest level object which has reference to the web applictaion that contains the site collection.

To get the reference to site context in your code use the recommended Microsoft.SharePoint.SPContext class and its members.

Lets look at how it is used

To get a reference to the site collection –

SPSite oSiteCollection = SPContext.Current.Site;

To get a reference to the current web site or web in the site collection –

SPWeb oWebSite = SPContext.Current.Web;

or

SPWeb oWebSite = SPControl.GetContextWeb(Context);

Note : if your are using Microsoft.SharePoint.SPContext class, you should not dispose any SPSite or SPWeb object obtained by any of the above methods. The SharePoint Foundation runtime will dispose of them after page completion.

To get a reference to all the webs or sites in a site collection –

SPWeb oWebSite = SPContext.Current.Site.AllWebs[“mySite”];

oWebSite.Dispose();

Note : You should explicitly dispose of references to objects that are obtained through the AllWebs() or Openweb() property. You can also use using clause
like below to avoid calling the dispose off method and let sharepoint do this for you.

using can be something like

using (SPWeb oWebSite = SPContext.Current.Site.AllWebs[“mySite”]);
{

}

You can also use the Openweb() as below

using (SPWeb oWebSite = mySiteCollection.OpenWeb(“mySite”))
{

}

Lets look at some other components of the SharePoint farm that you can get using SPContext

To get a reference to the current top-level server farm object –

SPFarm myFarm = SPContext.Current.Site.WebApplication.Farm;

To get a reference to the site collection database –

SPSite oSiteCollection = SPContext.Current.Site.CurrentDatabase

Lets look at some of the general code snippets

To return the collection of site collections in a SharePoint Web application –

SPWebApplication webApplication = SPContext.Current.Site.WebApplication;

using (SPSiteCollection siteCollections = webApplication.Sites)
{

foreach (SPSite siteCollection in siteCollections)
{
Label1.Text += siteCollection.Url + “<BR>”;

siteCollection.Close();
}

}

Note : To run the above code reference the Microsoft.SharePoint.Administration.SPWebApplication assembly in your code.

To return the collection of The all the Webs or sites within a site collection, including the top-level site and all subsites.

SPSite oSiteCollection = SPContext.Current.Site;
using(SPWebCollection collWebsite = oSiteCollection.AllWebs);
{

for (int i = 0; i < collWebsite.Count; i++)
{
using (SPWeb oWebsite = collWebsite[i])
{
SPListCollection collList = oWebsite.Lists;

for (int j = 0; j < collList.Count; j++)
{
Label1.Text += SPEncode.HtmlEncode(collWebsite[i].Title) + ” ”
+ SPEncode.HtmlEncode(collList[j].Title) + “<BR>”;
}
}
}
}

To return the all the subsites and lists of the current site

using (SPWeb oWebSite = mySiteCollection.OpenWeb())
{

using(SPWebCollection subSites = oWebsite.Webs)
{

foreach (SPWeb subSite in subSites)
{
Label1.Text += SPEncode.HtmlEncode(subSite.Title) + “<BR>”;

SPListCollection collList = subSite.Lists;

foreach (SPList oList in collList)
{
Label1.Text += SPEncode.HtmlEncode(oList.Title) + ” ” +
oList.ItemCount.ToString() + “<BR>”;

}subSite.Close();
}
}}

Client Object Model

“The Client Object Model (OM) is a new programming interface for SharePoint 2010 where code runs on a user’s client machine against a local object model and interacts with data on the SharePoint Server. Client OM methods can be called from JavaScript, .NET code or Silverlight code and makes building rich client applications for SharePoint easy.”

To develop rich client side solutions, three set of client-side APIs has been introduced in the Microsoft.SharePoint.Client namespace. The three APIs are targeted for three different types of clients:

1. For .net Managed applications (for example, console applications, window applications, web applications etc, which are not running inside SharePoint Context).

2. For Silverlight applications.

3. For using with JavaScript (called ECMAScript). This API is only available for applications hosted inside SharePoint (for example, web part deployed in SharePoint site can use this JavaScript API for accessing SharePoint from browser using JavaScript).

Before, we go further in explaining these three methods, lets see how this Client object model works ? Here is a good explanation from msdn – When we use SharePoint client API’s to perform a specific task, the SharePoint Foundation 2010 managed client object model bundles up these uses of the API into XML and sends it to the server that runs SharePoint Foundation. Side note -Client OM under the hood uses Client.svc WCF service to communicate with SharePoint foundation. The server receives this request, and makes appropriate calls into the object model on the server, collects the responses, forms them into JavaScript Object Notation (JSON), and sends that JSON back to the SharePoint Foundation 2010 managed client object model. The client object model parses the JSON and presents the results to the application as .NET Framework objects (or ECMAScript objects for ECMAScript).

Lets look at some important notes about the three methods we are going to use –

.NET Managed – The API’s are available to create managed .NET Windows(or client) applications using .NET framework 3.5 and higher.
To communicate with .NET Managed Client OM you need to add Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll in your project. These can be found @ C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI location.

Silverlight – The API’s available is used to create Silverlight applications that use SharePoint data and objects. (Silverlight 2 and newer versions). To communicate with the SharePoint server in Silverlight client context we need to add a reference to Microsoft.SharePoint.Client.Silverlight.dll and Microsoft.SharePoint.Client.Silverlight.Runtime.dll.
The dlls can be found at “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin”.
See the Post Create and deploy silverlight webpart in sharepoint 2010

ECMAScript Client OM – Is a client object model extension for using JavaScript or JScript. This API is only available for applications hosted inside SharePoint (for example, web part deployed in SharePoint site can use this JavaScript API for accessing SharePoint from browser using JavaScript). We will discuss the ECMA script model in detail in next part of the Tutorial.

Lets start with –
.NET Managed – client object model.
This object model was introduced to create console applications, window applications, web applications etc, which are not running inside SharePoint Context. One of the main advantages of using this object model(infact the whole client object model) is that you can execute or line up all the server tasks in one SharePoint server server call. It returns you Json object that you can bind to a client side object.

Lets jump a quick code snippet now.

Add List Items – The example below uses a CAML query to extract list items from “mycustomList” in SPSite site collection.

ClientContext clientContext = new ClientContext(“http://SPSite”);
List list = clientContext.Web.Lists.GetByTitle(“mycustomList”);
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = @”<View><Query><Where>
<Eq><FieldRef Name=’Category’/><Value Type=’Text’>Development</Value>
</Eq></Where></Query><RowLimit>100</RowLimit></View>”;

ListItemCollection listItems = list.GetItems(camlQuery);
clientContext.Load(
listItems,
items => items
.Include(
item => item[“Title”],
item => item[“Category”]));
clientContext.ExecuteQuery();
foreach (ListItem listItem in listItems)
{
Console.WriteLine(“Title: {0}”, listItem[“Title”]);
Console.WriteLine(“Category: {0}”, listItem[“Category”]);
Console.WriteLine();
}
Next we will look at the ECMA Script object model

ECMAScript Client OM – Is a client object model extension for using JavaScript or JScript. This API is only available for applications hosted inside SharePoint (for example, web part deployed in SharePoint site can use this JavaScript API for accessing SharePoint from browser using JavaScript). You can however use this ECMAScript Client OM in web part pages or application pages (aspx pages) by referencing a javascript file (SP.js).

To use ECMAScript Client OM, add an entry for the below in your web part ascx control (the webparts deisgn interface) or to your content editor webpart’s HTML Source.

<script src=”/_layouts/SP.js” type=”text/ecmascript”></script>

Also, if If your code modifies SharePoint content you need to add a FormDigest control inside your page.The formdigest control can be added in master page and then all content pages will get it automatically.
<SharePoint:FormDigest runat=”server” />

For quick start add a Content editor webpart to your site page and modify its HTML source. Now, add the reference to SP.JS specified above and paste in the below code. Make sure you have ‘myCustomlist’ created in your site.

FYI… To get current client context we use SP.ClientContext.get_current() and to get current web we use ctx.get_web(). See the full example below.

Adding a List item – Now lets look at something advanced than above.

<script type=”text/javascript”>

function AddItem()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(‘myCustomlist’);

var listItemCreationInfo = new SP.ListItemCreationInformation();
var newItem = list.addItem(listItemCreationInfo);
newItem.set_item(‘Title’, ‘SPUser’);

newItem.update();
context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success() {
alert(‘Added!’);
}
function failed(sender, args) {
alert(‘failed. Message:’ + args.get_message());
}

Delete an item – and finally how to delete an item.

function deleteItem(ItemId)
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(‘myCustomlist’);
var itemToDelete = list.getItemById(ItemId);
itemToDelete.deleteObject();
context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success() {
alert(‘Deleted!’);
}
function failed(sender, args) {
alert(‘failed. Message:’ + args.get_message());

}</script>

<a href=”#” onclick=”Javascript:AddItem();”>Create Item</a>

<a href=”#” onclick=”Javascript:deleteItem(1);”>Delete Item</a>

Advertisements

About sharepointsriram

9+ Yrs of IT experience
This entry was posted in SharePoint 2010 FAQ. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s