Tuesday, July 17, 2012

Client Object Model - Part 1 To Part 12

Client Object Model - Part 1

From this post, we are going to start new series for client object model. If you have not gone through previous post Client Object Model which describes you what client object model is all about, I would strongly encourage you to read that first and then come back and continue reading here.

We are going to star with managed client object model. Managed client object model works on the .Net CLR. That means any normal application that runs on the .Net CLR installed platform.

I am going to show you by taking windows application as an example and look into some of the very basic stuff to get the web properties.

First create a windows application project and take a reference of two DLLs that are needed to work with.

They are Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll and you can find them 14/ISAPI folder.

public void LoadData()
{
string webUrl = "{site URL}"; //replace this with your site URL

ClientContext context = new ClientContext(webUrl);

Web web = context.Web;

context.Load(web);

context.ExecuteQuery();

this.lblWebTitle.Text = web.Title;

this.lblWebDescription.Text = web.Description;


}

private void button1_Click(object sender, EventArgs e)
{
LoadData();

}

As you can see there is very little difference between server object model and COM as far as classes are concern. SPWeb becomes Web, SPContext becomes ClientContext.

Do remember one thing, until and unless we call executequery method, nothing happens. As soon as executequery method is invoked, then managed client object model bundles up all requests together and then pass it to the server. There is no network traffic till then.



Overall approach with client object model is you bundle up all requests that you want to query to server (web properties, lists properties etc) and then call them at once by invoking executequery method.

We are going to see more and more examples with different approaches. Next is doing same with the help of Silverlight Client.

Client Object Model – Part 2

In this post, we are going to see how we can use Silverlight client object model for SharePoint. If you have not gone through Part – 1 - managed client object model, I recommend you reading them first and then continue reading here.

We are going to create Silverlight project this time. So go ahead and add Silverlight application. You will see two projects loaded in solution. One is the web project which will generate the .xap file and the other is the client project that we need for our SharePoint.

A Silverlight application run on the browser that means it runs on the client side and whenever requires it interacts with serve with the help of WCF calls as far as database connectivity is concern. But in this model with SharePoint, we do not need to write anything extra with WCF. It has already been taken care of.

You need to add two DLL to the client project as shown in image below.

Microsoft.SharePoint.Client.Silverlight.dll and Microsoft.SharePoint.Client.Silverlight.Runtime.dll

They are located at C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin



Create a simple UI in mainpage.xaml file



We need to understand that Silverlight application works on asynchronous model which means that once the process is started, we cannot block the UI. It works on the call back function for success and failure. So if you try to write down same line of code which we did in our previous part 1 post, it will not work at all.

We need to change the code this time due to Silverlight asynchronous model.

Write down following code to your xaml cs file.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.SharePoint.Client;


namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();


public MainPage()
{
InitializeComponent();
}

private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
LoadData();
}

private void LoadData()
{

context = ClientContext.Current;

web = context.Web;

context.Load(web);

context.ExecuteQueryAsync(LoadSucces, LoadFailed);


}

private void DisplayData()
{
this.lblWebTitle.Text = web.Title;

this.lblWebDescription.Text = web.Description;
}

private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}

private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}


}
}




Because we will host this application inside SharePoint, we are not passing any URL for SharePoint site as we did in previous post. We will take reference of current SharePoint site.

When we click the button, we call function with two parameters which are method delegates. Respective method triggers based on the response we get from server. If we get success, then our first method will trigger or else the second. Observe that we call it asynchronously so that it does not block UI.

Build the solution.

Now to deploy this application in SharePoint we have two different options. One is we can deploy the generated .XAP file in ClientBin folder to some document library which has proper permission for users or we can deploy this XAP file to 14\TEMPLATE\LAYOUTS\ClientBin folder.

Now we are set with the deployment. All we have to do is open a page where you want to view this Silverlight application which accesses SharePoint data with client object model.

Edit the page, add Silverlight web part.

Once you add Silverlight web part, you will be prompt to give path of XAP file. If you have deployed in document library, give path of document library/file name.xap or else give path of 14\TEMPLATE\LAYOUTS\ClientBin\file name.xap.

Once done, save your changes on the page and see the simple magic happening on the page.


Client Object Model – Part 3

In this post, we are going to see how we can work with SharePoint using JavaScript as our scripting language. This is called ECMA script. All functions that relates to SharePoint JavaScript are located in the files starting with SP in layouts folder.

One of very important files is SP.js. This is one of the file that we have to use in every script that we write while writing ECMA script for SharePoint.

We are going to do the same thing that we did in post 1 and post 2. So if you have not gone through post 1 and post 2, I would recommend you reading them first and then continue reading from here.

Now there are two ways we can write this ECMA script. It can be either on the content editor web part on a page or it can be on any aspx page developed in visual studio and used it in SharePoint.

If we use content editor web part, then we have to write following line as the first line in the script.

ExecuteOrDelayUntilScriptLoaded(initialize, "sp.js");

Now initialize is the name of the function. So if you have a different function name, then you need to mention that name instead of initialize.

All JavaScript files actually loads randomly. We can never say with guarantee that this file will be loaded after this file. So we never know when the functions are available to call. Hence this method waits for SP.js to load and then only call our initialize function. This ensures that after sp.js is loaded, we can use all its methods in the JavaScript code.

If you use ASPX page and want to refer JavaScript functions for SharePoint, then this should be used in ASPX.

<SHAREPOINT:SCRIPTLINK name="SP.js" runat="server" ondemand="true" localizable="false"></SHAREPOINT:SCRIPTLINK>

We are going to add content editor web part and then we will write a simple script which will prompt web title and description for us.

Do remember one very important thing. Via ECMA script you cannot access object from any other site. It works only on the current context. All operations can be done only on the current site.

Add one content editor web part in the page where you want. Now let’s write down a simple script in editor web part.


<script type="text/javascript">
var currentcontext = null;
var currentweb = null;

ExecuteOrDelayUntilScriptLoaded(LoadCurrentSite, "sp.js");


function LoadCurrentSite()

{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();
currentcontext.load(currentweb);
currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));

}

function ExecuteOnSuccess(sender, args) {
alert('web title:' + currentweb.get_title() + '\n Description:' + currentweb.get_description());
}

function ExecuteOnFailure(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}

</script>


Now here what we have done is we have written a simple line of code which says wait till sp.js load and once it is loaded, we call LoadCurrentSite function which we have defined.

ExecuteOrDelayUntilScriptLoaded(LoadCurrentSite, "sp.js");

This function gets the current context and then loads the web and at the end we call it two functions asynchronously. If succeed then one function and if fails then the other function. If succeed, we would be able to get the title and description with the help of currentweb.get_title() and currentweb.get_description() function.

Remember that it has to be in lower case, otherwise you will face a problem and it might take a lot of time just to detect what went wrong when actually this could be the problem with letter cases. All method should have get_ and then the name.

We are going to see how to get all properties because here we do not have intellisense with us to support.

One very useful tip is whenever we call a load method for web; it actually loads all properties for the web creating unnecessary traffic between server and client. We can reduce this with the help of calling only those properties which we need.


In our case, we needed title and description. We could have changed our code little to create much more efficient. So let’s do that. All we need to do is change one line.

currentcontext.load(currentweb);
to
currentcontext.load(currentweb,'Title','Description');

Final output

 

Client Object Model – Part 4

We are going to see more about client object model with respect to ECMA script for SharePoint. If you have not gone through part 1 to part 3, I would recommend you reading them first and then continue reading from here.

This post is continuation to last part 3. As I have mentioned in the last post, that because we do not get intellisense for methods for ECMA script, we need to know what are the methods available for us. We used get_title() and get_description()as an example in last post. There are many more methods available not only for web also for lists, views and for every object that exist in SharePoint just like we have all of them for server side API.

The main problem is where to get it from? How to know names of those methods? Other problem is they are case sensitive, so we have to be extra careful.

To get all properties available for specified object, open a SharePoint site and then navigate to your page where you have added a code to get title and description of current web in content editor web part in internet explorer.

Now I have Internet Explorer 9 so I pressed Alt key, clicked on Tools menu and click on F12 Developer tools or simply press F12 key to get developer tools.



If you have IE7 or IE8, then also there should be an option for tools menu and then go to developer tools option.

After getting developer tools, you should be able to view source code in the developer pane. There are different tabs in the window as well. We are interested in scripts tab. This tab shows you all the scripts in the page. If you have loaded any of the JavaScript files instead of writing a code in content editor then you should be able to locate those functions in the file here in this tab.

Check out the code written by us and locate it.



We want to see all properties related to web, so right click the line and select insert breakpoint.

currentweb = currentcontext.get_web();



Hit start debugging



You will find breakpoint comes and waits so that we can step through each line.

Hover the mouse on it and check out all properties by scrolling down the entire list.





Same way you can get all properties of site, list, views, groups etc. objects of SharePoint and then you know what to use while you code in script.


Client Object Model – Part 5

We are going to continue with ECMA script examples and going to see how to perform
various operations sing ECMA script.

If you have not gone through Part 1 to Part 4, I would recommend reading them first before continue this.

Let’s expand our example and explore how we can create lists, list items, delete list etc. These operations are easy to perform. Once you get to know how to call list and list items, then it’s really easy to play around with them.

1) Create List


<script type="text/javascript">

var currentcontext = null;
var currentweb = null;

ExecuteOrDelayUntilScriptLoaded(CreateList, "sp.js");


function CreateList()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext .get_web();


var ListInfo = new SP.ListCreationInformation();
var ItemInfo = new SP.ListItemCreationInformation();

ListInfo.set_title('List Created From ECMA Script');
ListInfo.set_templateType(SP.ListTemplateType.genericList);

this.createdList = currentweb.get_lists().add(ListInfo);


currentcontext.load(createdList, 'Title','Id');

currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));

}

function ExecuteOnSuccess(sender, args) {
alert('list title:' + createdList .get_title() + '\n ID' + createdList .get_id());
}

function ExecuteOnFailure(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}

</script>


2) Delete List


<script type="text/javascript">

var currentcontext = null;
var currentweb = null;

ExecuteOrDelayUntilScriptLoaded(DeleteList, "sp.js");


function DeleteList()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();

this.list = currentweb.get_lists().getByTitle('List Created From ECMA Script');
this.list.deleteObject();


currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));

}

function ExecuteOnSuccess(sender, args) {
alert('list deleted successfully');
}

function ExecuteOnFailure(sender, args) {
alert('list could not be deleted');
}

</script>



3) Update List


<script type="text/javascript">

var currentcontext = null;
var currentweb = null;

ExecuteOrDelayUntilScriptLoaded(UpdateList, "sp.js");


function UpdateList()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();

this.list = currentweb.get_lists().getByTitle('List Created From ECMA Script');
this.list.set_description('Description set from ECMA script');

list.update();
currentcontext.load(list, 'Description');

currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));

}

function ExecuteOnSuccess(sender, args) {
alert('list description :' + this.list.get_description());
}

function ExecuteOnFailure(sender, args) {
alert('Description cannot be set');
}

</script>



4) Create List Item


<script type="text/javascript">

var currentcontext = null;
var currentweb = null;

ExecuteOrDelayUntilScriptLoaded(CreateListItem, "sp.js");


function CreateListItem ()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();

this.list = currentweb.get_lists().getByTitle('List Created From ECMA Script');
var ItemInfo = new SP.ListItemCreationInformation();
this.ListItem = list.addItem(ItemInfo);


ListItem.set_item('Title', 'Item created from ECMA script');

ListItem.update();

currentcontext.load(ListItem);

currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));

}

function ExecuteOnSuccess(sender, args) {
alert('list item id:' + this.ListItem.get_id());
}

function ExecuteOnFailure(sender, args) {
alert('List Item cannot be created');
}

</script>



5) Update List Item


<script type="text/javascript">


var currentcontext = null;
var currentweb = null;

ExecuteOrDelayUntilScriptLoaded(UpdateListItem, "sp.js");

function UpdateListItem()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();

this.list = currentweb.get_lists().getByTitle('List Created From ECMA Script');

this.ListItem = list.getItemById(1);
ListItem.set_item('Title', 'Item ID 1 update using ECMA script');
ListItem.update();


currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));

}

function ExecuteOnSuccess(sender, args) {
alert('list item updated successfully');
}

function ExecuteOnFailure(sender, args) {
alert('List Item cannot be updated');
}

</script>


6) Delete List Item


<script type="text/javascript">


var currentcontext = null;
var currentweb = null;

ExecuteOrDelayUntilScriptLoaded(DeleteListItem, "sp.js");

function DeleteListItem()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();

this.list = currentweb.get_lists().getByTitle('List Created From ECMA Script');
this.ListItem = list.getItemById(1);
ListItem.deleteObject();


currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));

}

function ExecuteOnSuccess(sender, args) {
alert('list item deleted successfully');
}

function ExecuteOnFailure(sender, args) {
alert('List Item cannot be deleted');
}

</script>

Client Object Model – Part 6

If you have not gone through Part 1 to Part 5, I would recommend you reading them first and then continue reading from here.

We are going to see more examples of ECMA script here.


1) Create Site

<script type="text/javascript">


var currentcontext = null;
var currentweb = null;

ExecuteOrDelayUntilScriptLoaded(CreateSite, "sp.js");

function CreateSite()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();

var webCreateInfo = new SP.WebCreationInformation();
webCreateInfo.set_description("This site created from ECMA script");
webCreateInfo.set_language(1033);
webCreateInfo.set_title("ECMA Script created site");
webCreateInfo.set_url("ECMAScriptSite");
webCreateInfo.set_useSamePermissionsAsParentSite(true);
webCreateInfo.set_webTemplate("STS#0");

this.NewWebsite = this.currentweb.get_webs().add(webCreateInfo);

currentcontext.load(this.NewWebsite, 'ServerRelativeUrl', 'Created');


currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));

}

function ExecuteOnSuccess(sender, args) {
alert("Web site url : " + this.NewWebsite.get_serverRelativeUrl());
}

function ExecuteOnFailure(sender, args) {
alert('Site cannot be created');
}

</script>






2) Iterate through sub sites
<script type="text/javascript">

var currentcontext = null;
var currentweb = null;

ExecuteOrDelayUntilScriptLoaded(EnumerateThroughSite, "sp.js");

function EnumerateThroughSite()
{
currentcontext = new SP.ClientContext.get_current();

currentweb = currentcontext.get_web();

this.subsites = currentweb.get_webs();

//this.sitecoll = currentcontext.get_site(); //to get top level site - just for information

currentcontext.load(this.subsites);

currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));

}

function ExecuteOnSuccess(sender, args) {
var subsites = '';

var groupEnumerator = this.subsites.getEnumerator();
while (groupEnumerator.moveNext()) {
var Site = groupEnumerator.get_current();
subsites += '\nID: ' + Site.get_id() +
'\nTitle: ' + Site.get_title();

}
alert(subsites);
}

function ExecuteOnFailure(sender, args) {
alert("Cannot enumerate");
}
</script>



3) Load List properties
<script type="text/javascript">


var currentcontext = null;
var currentweb = null;

ExecuteOrDelayUntilScriptLoaded(LoadListProp, "sp.js");

function LoadListProp()
{
currentcontext = new SP.ClientContext.get_current();

currentweb = currentcontext.get_web();

this.list = currentweb.get_lists().getByTitle("Employees");

currentcontext.load(list, 'Title', 'Id');

currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));

}


function ExecuteOnSuccess(sender, args) {

alert('List title : ' + this.list.get_title() + '; List ID : '+ this.list.get_id());

//alert('success');

}



function ExecuteOnFailure(sender, args) {
alert("Cannot enumerate");
}
</script>




4) Load List Data

<script type="text/javascript">


var currentcontext = null;
var currentweb = null;

ExecuteOrDelayUntilScriptLoaded(LoadListData, "sp.js");

function LoadListData()
{
currentcontext = new SP.ClientContext.get_current();

currentweb = currentcontext.get_web();

this.list = currentweb.get_lists().getByTitle("Employees");

var camlQuery = new SP.CamlQuery();
var query = '<View><RowLimit>3</RowLimit></View>';
camlQuery.set_viewXml(query);

this.listItems = list.getItems(camlQuery);
currentcontext.load(listItems, 'Include(DisplayName,Id)');


currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));

}


function ExecuteOnSuccess(sender, args) {

var listEnumerator = this.listItems.getEnumerator();
//iterate though all of the items
while (listEnumerator.moveNext()) {
var item = listEnumerator.get_current();
var title = item.get_displayName();
var id = item.get_id();
alert("Item title : " + title + "; Item ID : "+ id);
}

}



function ExecuteOnFailure(sender, args) {
alert("Cannot load list data");
}
</script>

Client Object Model – Part 7

We are going to continue exploring more ECMA script. If you have not gone through part 1 to part 6, I would recommend you reading them first and then continue exploring this part onwards.

1) Query List


<script type="text/javascript">

var currentcontext = null;
var currentweb = null;

ExecuteOrDelayUntilScriptLoaded(QueryListData, "sp.js");

function QueryListData()
{
currentcontext = new SP.ClientContext.get_current();

currentweb = currentcontext.get_web();

this.list = currentweb.get_lists().getByTitle("Employees");

var camlQuery = new SP.CamlQuery();

camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name="First_x0020_Name"/><Value Type="Text">Andre</Value></Eq></Where></Query><ViewFields><FieldRef Name="Title" /></ViewFields></View>');


this.listItems = this.list.getItems(camlQuery);


currentcontext.load(listItems);


currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));

}


function ExecuteOnSuccess(sender, args) {


var listEnumerator = this.listItems.getEnumerator();
//iterate though all of the items
while (listEnumerator.moveNext()) {
var item = listEnumerator.get_current();

var title = item.get_item('Title');

alert(title);

}

}



function ExecuteOnFailure(sender, args) {
alert("Cannot enumerate");
}
</script>


2) Getting version and other info from list item. Also check out how to get lookup field value in case of created by and modified by.


<script type="text/javascript">

var currentcontext = null;
var currentweb = null;

ExecuteOrDelayUntilScriptLoaded(QueryListData, "sp.js");

function QueryListData()
{
currentcontext = new SP.ClientContext.get_current();

currentweb = currentcontext.get_web();

this.list = currentweb.get_lists().getByTitle("Employees");

var camlQuery = new SP.CamlQuery();

camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name="First_x0020_Name"/><Value Type="Text">Andre</Value></Eq></Where></Query></View>');


this.listItems = this.list.getItems(camlQuery);

currentcontext.load(listItems);


currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));

}


function ExecuteOnSuccess(sender, args) {


var listEnumerator = this.listItems.getEnumerator();
//iterate though all of the items
while (listEnumerator.moveNext()) {
var item = listEnumerator.get_current();

var title = item.get_item('Title');

var vInformation = item.get_item('_UIVersionString');

var Created = item.get_item('Created');

var Modified = item.get_item('Modified');

var CreatedBy = item.get_item('Author').get_lookupValue();

var ModifiedBy = item.get_item('Editor').get_lookupValue();

var totalsctring = "Title:" + title + "\n" + "Version:" + vInformation + "\n" + "Created:" + Created +"\n" +
"Modified:" + Modified +"\n" +
"CreatedBy:" + CreatedBy +"\n" +
"ModifiedBy :" + ModifiedBy +"\n" ;


alert(totalsctring);

}
}

function ExecuteOnFailure(sender, args) {
alert("Cannot enumerate");
}
</script>



3) Iterate through Site Groups


<script type="text/javascript">

var currentcontext = null;
var currentweb = null;

ExecuteOrDelayUntilScriptLoaded(IteratethroughGroup, "sp.js");

function IteratethroughGroup()
{
currentcontext = new SP.ClientContext.get_current();

currentweb = currentcontext.get_web();

this.groupCollection = currentweb.get_siteGroups();

currentcontext.load(this.groupCollection);

currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));

}


function ExecuteOnSuccess(sender, args) {

var listEnumerator = this.groupCollection.getEnumerator();
//iterate though all of the items
while (listEnumerator.moveNext()) {
var item = listEnumerator.get_current();


groupName = item.get_title();

alert(groupName);

}
}

function ExecuteOnFailure(sender, args) {
alert("Cannot enumerate");
}
</script>


4) Iterate through recycle bin

Remember, this is for the site collection recycle bin because we have taken site as a reference. If you want to take individual web recycle bin into consideration then use ge_web istead of get_site option. Rest everything need not to be changed.


<script type="text/javascript">


var currentcontext = null;
var currentsite = null;

ExecuteOrDelayUntilScriptLoaded(IteratethroughRecycleBin, "sp.js");

function IteratethroughRecycleBin()
{
currentcontext = new SP.ClientContext.get_current();

currentsite = currentcontext.get_site();

this.rbincoll = currentsite.get_recycleBin();

currentcontext.load(this.rbincoll);

currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));

}


function ExecuteOnSuccess(sender, args) {

if(this.rbincoll.get_count() > 0)
{
var listEnumerator = this.rbincoll.getEnumerator();
//iterate though all of the items
while (listEnumerator.moveNext()) {
var item = listEnumerator.get_current();

var title = item.get_title();
var id = item.get_id();

alert("ID: " + id+ "\nTitle:" + title);
}

}
else
{
alert('There is no item in recycle bin');
}
}

function ExecuteOnFailure(sender, args) {
alert("Cannot enumerate");
}
</script>

Client Object Model – Part 8

Let us continue exploring client object model. From this post we will explore Silverlight client object model and explore different examples. I would recommend reading part 1 to part 7 first to get to know about client object model and then continue reading from here.

1) Iterating through list items



namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
ListItemCollection listItems;
private delegate void UpdateUIMethod();


public MainPage()
{
InitializeComponent();
}

private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
LoadData();
}

private void LoadData()
{

context = ClientContext.Current;

web = context.Web;

List lstEmployees = web.Lists.GetByTitle("Employees");

CamlQuery Query = new CamlQuery();
Query.ViewXml = "<View/>";

listItems = lstEmployees.GetItems(Query);

context.Load(lstEmployees);
context.Load(listItems);

context.ExecuteQueryAsync(LoadSucces, LoadFailed);

}

private void DisplayData()
{
foreach (ListItem listItem in listItems)
{
lblOutputLabel.Text += Environment.NewLine + "\n" +
"ID: " + listItem.Id + " Title:" + listItem["Title"] + " First Name : " + listItem["First_x0020_Name"]
+ " Last Name" + listItem["Last_x0020_Name"];
}
}

private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}

private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}


}
}


2) Getting only specific properties

Instead of getting all properties of any specific object, if we want to get only specific properties that we are interested in, we can use lambda expression in query. This will result in less network traffic.


namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
ListItemCollection listItems;
private delegate void UpdateUIMethod();


public MainPage()
{
InitializeComponent();
}

private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
LoadData();
}

private void LoadData()
{

context = ClientContext.Current;

web = context.Web;

context.Load(web,
s => s.Title,
s => s.Description);


context.ExecuteQueryAsync(LoadSucces, LoadFailed);

}

private void DisplayData()
{

lblOutputLabel.Text += "Web Title : " + web.Title + Environment.NewLine + "\n" + " Description:" + web.Description ;


}

private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}

private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}


}
}


3) Create a list and list items


namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();


public MainPage()
{
InitializeComponent();
}

private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
LoadData();
}

private void LoadData()
{

context = ClientContext.Current;

web = context.Web;

ListCreationInformation lstCreationListFromSL =
new ListCreationInformation();
lstCreationListFromSL.Title = "List created from silverlight";
lstCreationListFromSL.TemplateType = (int)ListTemplateType.GenericList;
List lstFromSL = web.Lists.Add(lstCreationListFromSL);

Field fldFirstName = lstFromSL.Fields.AddFieldAsXml(@"<Field Type='Text' DisplayName='First Name'/>", true, AddFieldOptions.DefaultValue);
Field fldLastName = lstFromSL.Fields.AddFieldAsXml(@"<Field Type='Text' DisplayName='Last Name'/>", true, AddFieldOptions.DefaultValue);
Field fldAge = lstFromSL.Fields.AddFieldAsXml(@"<Field Type='Number' DisplayName='Age'/>", true, AddFieldOptions.DefaultValue);


ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();

ListItem listItem = lstFromSL.AddItem(itemCreateInfo);
listItem["Title"] = "1 Item created From SL";
listItem["First_x0020_Name"] = "John";
listItem["Last_x0020_Name"] = "Desilva";
listItem["Age"] = "25";
listItem.Update();

listItem = lstFromSL.AddItem(itemCreateInfo);
listItem["Title"] = "2 Item created From SL";
listItem["First_x0020_Name"] = "Michelle";
listItem["Last_x0020_Name"] = "Alberto";
listItem["Age"] = "24";
listItem.Update();


context.ExecuteQueryAsync(LoadSucces, LoadFailed);

}

private void DisplayData()
{

lblOutputLabel.Text += "List Created successfully and items are also created successfully";


}

private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}

private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}


}
}

Client Object Model – Part 9

Let us continue our series of client object model and explore more on Silverlight client object model. Silverlight client object model and managed client object model is almost similar. It’s just that managed client object model works on a .net framework installed on machine where it runs and does not require by default asynchronous processing which is mandatory for Silverlight client object model.

If you have not gone through Part 1 to Part 8, I would recommend you reading them first and then continue reading.

Let’s explore more examples


1) Querying a list and return selected fields only. Here I am retrieving only three fields that I want to show.



namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();
ListItemCollection listItems ;


public MainPage()
{
InitializeComponent();
}

private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
LoadData();
}

private void LoadData()
{

context = ClientContext.Current;

web = context.Web;

List lstEmployees = web.Lists.GetByTitle("Employees");

CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml =
@"<View>
<Query>
<Where>
<Eq>
<FieldRef Name='Title'/>
<Value Type='Text'>Andre Pal</Value>
</Eq>
</Where>
</Query>
<RowLimit>100</RowLimit>
</View>";

listItems = lstEmployees.GetItems(camlQuery);


context.Load(
listItems,
items => items
.Include(
item => item["Title"],
item => item["Last_x0020_Name"],
item => item["EmployeeID"]));


context.ExecuteQueryAsync(LoadSucces, LoadFailed);

}

private void DisplayData()
{
foreach (ListItem listItem in listItems)
{
lblOutputLabel.Text += "Title:" + listItem["Title"] + " Last Name : " + listItem["Last_x0020_Name"] + " Employee ID : " + listItem["EmployeeID"] + Environment.NewLine;
}


}

private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}

private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}


}
}


2) Update items in a list. Here I have used the same above code. We need to take care what when we are dealing with Silverlight, we cannot block UI and hence for every operation that we perform, we need to pass on asynchronous callback functions. Hence when we are updating the record, we have passed on another function which updates and then call appropriate method once succeeded or failed.



namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();
ListItemCollection listItems ;


public MainPage()
{
InitializeComponent();
}

private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
LoadData();
}

private void LoadData()
{

context = ClientContext.Current;

web = context.Web;

List lstEmployees = web.Lists.GetByTitle("Employees");

CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml =
@"<View>
<Query>
<Where>
<Eq>
<FieldRef Name='Title'/>
<Value Type='Text'>Andre Pal</Value>
</Eq>
</Where>
</Query>
<RowLimit>100</RowLimit>
</View>";

listItems = lstEmployees.GetItems(camlQuery);


context.Load(
listItems,
items => items
.Include(
item => item["Title"],
item => item["Last_x0020_Name"],
item => item["EmployeeID"]));


context.ExecuteQueryAsync(LoadSucces, LoadFailed);

}

private void DisplayData()
{
foreach (ListItem listItem in listItems)
{
listItem["Title"] = listItem["Title"] + " Updated From Code";
listItem.Update();

}

context.ExecuteQueryAsync(LoadSuccesAfterUpdate, LoadFailed);

}

private void UpdateSuccess()
{
MessageBox.Show("All records updated");
}

private void LoadSuccesAfterUpdate(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUISuccess = UpdateSuccess;
this.Dispatcher.BeginInvoke(updateUISuccess);

}

private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}

private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}


}
}




3) Delete items from list

Deleting list items is pretty easy stuff. However there is one very important thing that we need to take care of. When we get the list items object and when we loop through items to delete them one by one, then collection keep losing one element from it and then we end up having exception thrown from it or finishes without removing certain items. Hence we need to change list items collection with the help of ToList method like shown below.




namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();
ListItemCollection listItems ;


public MainPage()
{
InitializeComponent();
}

private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
LoadData();
}

private void LoadData()
{

context = ClientContext.Current;

web = context.Web;

List lstEmployees = web.Lists.GetByTitle("Employees");

CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml =
@"<View>
<Query>
<Where>
<Eq>
<FieldRef Name='Title'/>
<Value Type='Text'>Andre Pal</Value>
</Eq>
</Where>
</Query>
<RowLimit>100</RowLimit>
</View>";

listItems = lstEmployees.GetItems(camlQuery);


context.Load(
listItems,
items => items
.Include(
item => item["Title"],
item => item["Last_x0020_Name"],
item => item["EmployeeID"]));


context.ExecuteQueryAsync(LoadSucces, LoadFailed);

}

private void DisplayData()
{
foreach (ListItem listItem in listItems.ToList())
{
listItem.DeleteObject();

}

context.ExecuteQueryAsync(LoadSuccesAfterUpdate, LoadFailed);

}

private void UpdateSuccess()
{
MessageBox.Show("All records deleted");
}

private void LoadSuccesAfterUpdate(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUISuccess = UpdateSuccess;
this.Dispatcher.BeginInvoke(updateUISuccess);

}

private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}

private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}

}
}

Client Object Model – Part 10

We are going to continue to dive in for further exploration in Silverlight Client object model. If you have not gone through Part 1 to Part 9, I would recommend you reading them first and the continue reading from here.

Some more examples of Silverlight Client object model

1) Iterating through groups and users



namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();

GroupCollection collGroup;


public MainPage()
{
InitializeComponent();
}

private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
LoadData();
}

private void LoadData()
{
context = ClientContext.Current;

web = context.Web;

collGroup = context.Web.SiteGroups;

context.Load(collGroup);

context.Load(collGroup,
groups => groups.Include(
group => group.Users));

context.ExecuteQueryAsync(LoadSucces, LoadFailed);

}

private void DisplayData()
{
foreach (Group groupItem in collGroup)
{
lblOutputLabel.Text += "Group Name: " + groupItem.Title + Environment.NewLine + "________________" + Environment.NewLine;

UserCollection userColl = groupItem.Users;

foreach (User user in userColl)
{
lblOutputLabel.Text += " User Name : " + user.Title + Environment.NewLine;
}

}

}


private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}

private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}


}
}



2) Iterating through groups and users by including only specific properties

Same as above example, only thing to change is instead of


context.Load(collGroup);

context.Load(collGroup,
groups => groups.Include(
group => group.Users));

We can write something like this:

context.Load(collGroup,
groups => groups.Include(
group => group.Title,
group => group.Id,
group => group.Users.Include(
user => user.Title )));

Here what we have done is we have only included groups ID and Title as well as users Title only. It becomes faster than the previous example due to less network traffic.

3) Creating Group



namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();

GroupCollection collGroup;


public MainPage()
{
InitializeComponent();
}

private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
LoadData();
}

private void LoadData()
{
context = ClientContext.Current;

web = context.Web;

GroupCreationInformation FinanceGroup = new GroupCreationInformation();

FinanceGroup.Title = "Finance Group";

FinanceGroup.Description = "This group has been added through SCOM";

web.SiteGroups.Add(FinanceGroup);

context.ExecuteQueryAsync(LoadSucces, LoadFailed);

}

private void DisplayData()
{
lblOutputLabel.Text = "Group has been created successfully";
}


private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}

private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}


}
}




4) Adding users to a group


namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();

GroupCollection collGroup;


public MainPage()
{
InitializeComponent();
}

private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
LoadData();
}

private void LoadData()
{
context = ClientContext.Current;

web = context.Web;

GroupCollection collGroup = context.Web.SiteGroups;

Group FinanceGroup = collGroup.GetById(3);

UserCreationInformation userCreationInfo = new UserCreationInformation();
userCreationInfo.Email = "name@domain.com";
userCreationInfo.LoginName = @"DOMAIN\name";
userCreationInfo.Title = "Michael";

User User = FinanceGroup.Users.Add(userCreationInfo);


context.ExecuteQueryAsync(LoadSucces, LoadFailed);

}

private void DisplayData()
{
lblOutputLabel.Text = "Group has been created successfully";
}


private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}

private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}


}
}

Client Object Model – Part 11

We are going to continue exploring more Silverlight Client Object model examples. Again, same examples can be used for managed client object model as well. It’s just that Silverlight works on delegate methods for asynchronous methods. While working with managed object model is quite simpler.

If you have not gone through Part 1 to Part 10, I would recommend you reading them first and then continue exploring from here. There is a lot of stuff to learn in those parts.

1) Break Role Inheritance

If you want to break role inheritance for a list or any list item or library or document or a sub site, we can use BreakRoleInheritance(Boolean, Boolean) method to break it. Breaking inheritance means stopping permission inheriting from its parent and then assigning unique permissions for specific object.



If first Boolean parameter which is CopyRoleAssignments is false then it even does not copy any permission from parent and user becomes an owner of that object under whom the code is running. Second parameter which is clearSubScopes means that do we need to clear the unique permission on child object and then subsequently inherit permission from its parent or not.




namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();


public MainPage()
{
InitializeComponent();
}

private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
BreakInheritance();
}

private void BreakInheritance()
{
context = ClientContext.Current;

web = context.Web;

List lstEmployee = web.Lists.GetByTitle("Employees");

lstEmployee.BreakRoleInheritance(true, true);

context.ExecuteQueryAsync(LoadSucces, LoadFailed);

}

private void DisplayData()
{
lblOutputLabel.Text = "Inheritance has been broken successfully from its parent site";
}


private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}

private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}


}
}


2) Custom User Actions



Custom user actions mean any action that is added to the default options given in the SharePoint. We can add edit control block as custom action which reflects an option while we select the list item or document item in list or library. We can define custom action to be in the menu options of site actions menu. We can also define custom actions options for modify all site settings sub menu options.


UserCustomActions returns the collection of all custom actions defined in an object. If your object is list, then it returns all custom actions defined in that list. If your object is site, then it returns all custom actions defined at site level.

We can add, remove and update custom actions through client object model. Whatever we can do with one client object model method can be achieved with other client object model methods.

Adding custom user actions to a list edit control block


context = ClientContext.Current;

web = context.Web;

List lstEmployee = web.Lists.GetByTitle("Employees");

UserCustomActionCollection collCustomAction = lstEmployee.UserCustomActions;

UserCustomAction UserCustomAction = collCustomAction.Add();
UserCustomAction.Location = "EditControlBlock";
UserCustomAction.Sequence = 100;
UserCustomAction.Title = "SPKings User Custom Action";
UserCustomAction.Url = context.Url + @"/_layouts/SPKingsPage.aspx";
UserCustomAction.Update();


context.ExecuteQueryAsync(LoadSucces, LoadFailed);


Update custom user actions to a list edit control block


namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();

UserCustomActionCollection collCustomAction;

public MainPage()
{
InitializeComponent();
}

private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
AddCustomAction();
}


private void AddCustomAction()
{
context = ClientContext.Current;

web = context.Web;

List lstEmployee = web.Lists.GetByTitle("Employees");

collCustomAction = lstEmployee.UserCustomActions;

context.Load(collCustomAction,
userCustomActions => userCustomActions.Include(
userCustomAction => userCustomAction.Title));

context.ExecuteQueryAsync(LoadSucces, LoadFailed);

}

private void DisplayData()
{

foreach (UserCustomAction oUserCustomAction in collCustomAction)
{
if (oUserCustomAction.Title == "SPKings User Custom Action")
{
oUserCustomAction.ImageUrl = context.Url + "/_layouts/images/SomeImage.jpeg";
oUserCustomAction.Update();

context.ExecuteQueryAsync(LoadSuccesAfterUpdate, LoadFailed);
}
}

}

private void DisplayMessage()
{
lblOutputLabel.Text = "Custom Action - ECB has been update successfully";
}

private void LoadSuccesAfterUpdate(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUIAfterUpdate = DisplayMessage;
this.Dispatcher.BeginInvoke(updateUIAfterUpdate);
}

private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}

private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}


}
}



3) Working with Web Parts on a page

We can get all the web parts residing on a page with the help of client object model and re arrange them as well as change their properties like title. We can also remove them or add new one as well.

Change title of the web part


namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();
LimitedWebPartManager limitedWebPartManager = null;

public MainPage()
{
InitializeComponent();
}

private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
AddCustomAction();
}


private void AddCustomAction()
{
context = ClientContext.Current;

string URL = ClientContext.Current.Url;

web = context.Web;

File HomePage = web.GetFileByServerRelativeUrl("/sites/SP2010/Shared%20Documents/Default.aspx");


limitedWebPartManager = HomePage.GetLimitedWebPartManager(PersonalizationScope.Shared);

context.Load(limitedWebPartManager.WebParts,
webparts => webparts.Include(
webpart => webpart.WebPart.Title));


context.ExecuteQueryAsync(LoadSucces, LoadFailed);

}

private void DisplayData()
{

WebPartDefinition oWebPartDefinition = limitedWebPartManager.WebParts[1];
WebPart oWebPart = oWebPartDefinition.WebPart;
oWebPart.Title = "SPKings Title Changed again";

oWebPartDefinition.SaveWebPartChanges();

context.ExecuteQueryAsync(LoadSuccesAfterUpdate, LoadFailed);


}

private void DisplayMessage()
{
lblOutputLabel.Text = "WebPart title has been changed successfully";
}

private void LoadSuccesAfterUpdate(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUIAfterUpdate = DisplayMessage;
this.Dispatcher.BeginInvoke(updateUIAfterUpdate);
}

private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}

private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);

}


}
}



Deleting a web part


namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();
LimitedWebPartManager limitedWebPartManager = null;

public MainPage()
{
InitializeComponent();
}

private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
AddCustomAction();
}


private void AddCustomAction()
{
context = ClientContext.Current;

string URL = ClientContext.Current.Url;

web = context.Web;

File HomePage = web.GetFileByServerRelativeUrl("/sites/SP2010/Shared%20Documents/Default.aspx");

limitedWebPartManager = HomePage.GetLimitedWebPartManager(PersonalizationScope.Shared);

context.Load(limitedWebPartManager.WebParts);

context.ExecuteQueryAsync(LoadSucces, LoadFailed);

}

private void DisplayData()
{

WebPartDefinition webPartDefinition = limitedWebPartManager.WebParts[1];
webPartDefinition.DeleteWebPart();
context.ExecuteQueryAsync(LoadSuccesAfterUpdate, LoadFailed);

}

private void DisplayMessage()
{
lblOutputLabel.Text = "WebPart has been deleted successfully";
}

private void LoadSuccesAfterUpdate(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUIAfterUpdate = DisplayMessage;
this.Dispatcher.BeginInvoke(updateUIAfterUpdate);
}

private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}

private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
//MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);

lblOutputLabel.Text = "Request Failed: " + e.Message; // +"Stack Trace:" + e.StackTrace;
}


}
}

Client Object Model – Part 12

We are going to end this series of client object model with this post. There are so many things that we can do with the help of any of the three client object model methods. It is the matter of experience and doing practices only. Keep trying more things on your own and do let us know if you get stuck somewhere.

In this post, we are going to discuss on one very important aspect of client object model. But before that if you have not gone through Part 1 to Part 11, I would recommend reading them first and then continue reading from here.

You must have thought that in none of the series we talked about authentication. How does a client object model connects with the respective objects on the server like lists, sites, libraries, workflows etc.?


There are three methods.
1) Default authentication
2) Forms authentication
3) Anonymous authentication


And we have managed client object model, Silverlight client object model and ECMA script object model.


Managed COM – Windows authentication is default authentication.
So we do not need to explicitly specify anything. When we do not specify anything, it connects with our windows credentials and then checks our access on objects that we access through object model.

So we need to be very careful while writing a code that when the code runs, user should have a sufficient privilege on objects.

We can use anonymous or forms authentication with managed COM.

Silverlight COM – Same as Managed COM.

ECMA COM - Do not need any authentication. It runs inside the browser page and hence by default it has passed the parent authentication method.
Setting the Forms bases authentication on COM
If we use Forms authentication, then we need to set one more property which is AuthenticationMode on clientcontext object.
Plus we also need to make an instance of FormsAuthenticationLoginInfo class and assign the username and password before accessing or performing any operation on any SharePoint object and then set that authentication object to client context object.
FormsAuthenticationLoginInfo objformsAuth = new
FormsAuthenticationLoginInfo("UserName", "Password");

clientContext.FormsAuthenticationLoginInfo = objformsAuth;

Setting the Anonymous authentication on COM
ClientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
Do remember that when using this method, object which you are trying to access in code should have anonymous permission assigned.




 

No comments:

Post a Comment