Tuesday, July 2, 2013

SharePoint client Object model

SharePoint client Object model has the JavaScript and managed client object model which will be used in different scenarios.

* JavaScript client object which will be used in Jquery or Jscript and the custom js file will be hosted in SharePoint server or SharePoint document library.

* Managed client object model which will be used with Rich internet application like Silverlight app (can be used with in SharePoint using Silverlight web parts) and can also be used outside SharePoint using console/ windows application executed from client machine or MVC application hosted outside SharePoint.


Sample code to query a SharePoint list using Javascript based SharePoint client OM

function clientOMSample() {
var cCtxt = new SP.ClientContext.get_current();
// get the site and web.
var site = cCtxt.get_site();
var web = site.get_rootWeb();

// get the list by name
var lstColl = web.get_lists();
var thisList = lstColl.getByTitle(“customlist”);
var cQry = new SP.CamlQuery();
var query = "";
cQry.set_viewXml(query);
var listItemColl = thisList.getItems(cQry);
cCtxt.load(listItemColl);


var asyncCallback = function (s, a, data) { data.func(s, a, data); };
// Call the executeQueryAsync method to execute the pending requests in the server cCtxt.executeQueryAsync(
Function.createCallback(asyncCallback, {func: onGetItemsQuerySucceeded, listItemColl: listItemColl}),
Function.createCallback(asyncCallback, { func: onGetItemsQueryFailed, listItemColl: listItemColl }));
}

function onGetItemsQuerySucceeded (s, a, data) {
var listItems = data.listItemColl.getEnumerator();
// Additional process goes here
}
function onGetItemsQueryFailed (s, a, data) {
// Handle error.
}

$(document).ready(function () {
// Call the function only when the sp.js is completely loaded
ExecuteOrDelayUntilScriptLoaded(clientOMSample, "sp.js");
});


Sample code to Updaye a SharePoint list item using Managed client OM

ClientContext clientContext = new ClientContext("http://spSiteUrl");
Site site = clientContext.Site;
// Get the current user and update the modified by information
User userInfo = site.RootWeb.EnsureUser(HttpContext.Request.LogonUserIdentity.Name);

// Get the File (Page from pages library) using the Url
Microsoft.SharePoint.Client.Web web = site.OpenWeb("/subsite");
Microsoft.SharePoint.Client.File filePage = web.GetFileByServerRelativeUrl("/subsite/Pages/default.aspx");

clientContext.Load(userInfo);
clientContext.ExecuteQuery();
Microsoft.SharePoint.Client.ListItem fileitem = filePage.ListItemAllFields;

// Update the file properties
fileitem["FieldName"] = "Test Contact Name";
// Update Modified by Information IF REQUIRED
fileitem["Editor"] = userInfo;

fileitem.Update();  
clientContext.ExecuteQuery();

                       

No comments: