How to use the Silverlight Client Object Model in SharePoint 2010

As part of the introduction series, I want to present the advantage of the client object model introduced in SharePoint 2010. There are great advantages with this model as it don't require SharePoint needs to be installed on the client machine. We just need to refer the client dlls which Microsoft SharePoint provides and based on them we will write code to communicate with SharePoint server. In this article we will go through Silverlight Client Object Model. If you want to know the other client object model types go here. ECMAScript and Managed client object models.
To communicate with the SharePoint server in Silverlight context we need to give two client SharePoint DLL references to the silver light project.

DLL's Needed: Microsoft.SharePoint.Client.Silverlight.dll and Microsoft.SharePoint.Client.Silverlight.Runtime.dll. They can be found at "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin".
OK, we understand the concept and we will create a project and implement code for better understanding on how it works.

  1. Open Visual Studio 2010.
  2. File -> New -> Project -> Visual C# -> Silverlight -> Select Silverlight Application project template as shown below.

  3. Give some name to the project. In my example, I have given some meaningful name like "SP2010Silverlight_HelloWorld" and create the project.
  4. Now, you see the below screen.

  5. What this meaning is "Do you want to create an ASP.NET web site and host the XAP file generated to the web site". For our example, it's really not needed. But, there is no problem by using that.
  6. Now next step is getting the SharePoint Silverlight Client Dll's reference to our project. So, for this get the SharePoint dll's to the client machine [Where we created project] and paste the DLL's in some safe location. I copied them to C:\SP2010_ClientDLL\.
  7. Now, go to Visual Studio 2010 project right click on project -> select References and browse to location where client dll's copied and select both dll's and hit ok as shown in below figure.

  8. After you added all references the references folder should look like this.
  9. Now we are ready with all prerequisites and part left is with writing code. I will show you simple code on how to write the code for getting web site title and description using Silverlight Client OM.
  10. Before start coding, we need to add reference to the namespace in page by declaring using keyword as shown below.
using Microsoft.SharePoint.Client; 





11. This is the code to get data from a SharePoint server, in this example we are retrieving Title and Description of a web site.



XAML code: MainPage.XAML




<?XML:NAMESPACE PREFIX = [default] http://schemas.microsoft.com/winfx/2006/xaml/presentation NS = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" /><usercontrol xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:datainput="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" x:class="SilverLight_ClientOM_LoadSiteData.MainPage" mc:ignorable="d" d:designwidth="400" d:designheight="197">   
<grid x:name="LayoutRoot" background="White">
<BUTTON name=btnLoadSite content="Load Site" width="75" verticalalignment="Top" margin="25,12,0,0" horizontalalignment="Left" height="23" click="btnLoadSite_Click"></BUTTON>
<canvas name="canvasLabels" visibility="Collapsed">
<DATAINPUT:LABEL content="Site: " name="label1" width="73" verticalalignment="Top" margin="41,55,0,0" horizontalalignment="Left" height="22"></DATAINPUT:LABEL>
<DATAINPUT:LABEL name="label2" width="233" verticalalignment="Top" margin="120,55,0,0" horizontalalignment="Left" height="22"></DATAINPUT:LABEL>
<DATAINPUT:LABEL content="Url:" name="label3" width="73" verticalalignment="Top" margin="41,84,0,0" horizontalalignment="Left" height="24"></DATAINPUT:LABEL>
<DATAINPUT:LABEL name="label4" width="233" verticalalignment="Top" margin="120,84,0,0" horizontalalignment="Left" height="24"></DATAINPUT:LABEL>
<DATAINPUT:LABEL content="Description" name="label5" width="73" verticalalignment="Top" margin="41,116,0,0" horizontalalignment="Left" height="26"></DATAINPUT:LABEL>
<DATAINPUT:LABEL name="label6" width="233" verticalalignment="Top" margin="120,116,0,0" horizontalalignment="Left" height="26">
</DATAINPUT:LABEL></canvas>
</grid>
</usercontrol>







MainPage.Xaml.cs file code:




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 SP2010Silverlight_HelloWorld{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}

private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();

private void btnLoadSite_Click(object sender, RoutedEventArgs e)
{
context = ClientContext.Current;
web = context.Web;
context.Load(web, w => w.Title, w => w.Description, w => w.ServerRelativeUrl);
context.ExecuteQueryAsync(OnSiteLoadSuccess, OnSiteLoadFailure);
}

private void OnSiteLoadSuccess(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = LoadSiteData;
this.Dispatcher.BeginInvoke(updateUI);
}
private void OnSiteLoadFailure(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}

private void LoadSiteData()
{
canvasLabels.Visibility = System.Windows.Visibility.Visible;
label2.Content = web.Title;
label4.Content = web.ServerRelativeUrl;
label6.Content = web.Description;
}
}
}







Place all the code above given in the both files of your project.

Note: Remember to change the web url given in the code "http://nb16" to actual SharePoint server url.


Till now, what we have done is, writing and complete code for loading the site data. But, we need to understand the above code.


In the above code, there is a callback function used. Which is asynchronous and loads data. But, you may confuse at the line delegate UpdateUIMethod(). I copied the below text from MSDN to better understand about the delegate and why it's needed.


"Because query execution is asynchronous when you use the SharePoint Foundation Silverlight object model, you must pass delegates for callback methods as parameters in the ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler) method, similarly to query execution in the ECMAScript object model. However, to run code that makes changes in the user interface (UI) through the Silverlight object model, you must delegate this work to the Dispatcher object of the thread that created the UI by calling BeginInvoke()". So, we should use the delegate to make changes on the UI.


Deploy and Test


We have two ways to deploy the XAP file in SharePoint environment.


One is, We can use SharePoint default location [\Templates\Layouts\ClientBin] and deploy the file there. Refer this location from the Silverlight web part.


Second is, We can use a SharePoint document library and deploy the file there. Refer this document library location file path while adding the silverlight web part. In this post, we will use the default location to deploy and test.




  1. To deploy and test the code in SharePoint 2010 we need to use the SharePoint Silverlight web part [New web part added in this version].


  2. The silverlight web part default location is "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin". So, all the XAP files should be deployed to this location to use them in the silverlight web part.


  3. To make this process easier, we need to do below.


  4. Right click on Silverlight project -> propertiese -> Build -> change the output path to "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin" as shown below.




  5. Build the solution and see the XAP generated in the ClientBin location.


  6. Now, navigate to SharePoint site where you want to see the silverlight data, Edit page.


  7. Add silverlight web part to the page.


  8. It will prompt you for the XAP file location: Type the url: "/_layouts/ClientBin/SP2010Silverlight_HelloWorld.xap".


  9. Now click on OK and you can see the silverlight web part on the page.




Ooh!!! This is it!!! We are done with development, deployment and testing. Hope this won't create any confusion. If you have any issues please let me know. I am always here to help you out...