SharePoint 2010 Cookbook: Using the Silverlight Client Object Model in SharePoint 2010 to Create a Silverlight Web Part

Introduced with SharePoint 2010, the Client Object Mode helps developers design client applications that access SharePoint content without installing code on the server. The Client Object Model can run directly on client machines without having been installed on the SharePoint server.

An article on MSDN tells us that the SharePoint 2010 Client Object Model supports “three new client APIs for interacting with Sharepoint sites: from a .NET managed application, from a Microsoft Silverlight application, or from ECMAScript (JavaScript, JScript) that executes in the browser.” In this post, we will explore and utilize the Silverlight Client Object Model.

Challenge:

How can I use the Silverlight Client Object Model to create a Silverlight Web Part to retrieve all list items, and display the returned list data in the Silverlight DataGrid?

SharePoint 2010 Silverlight Client Object Model

The  table below lists some Client-side classes and server-side equivalents and, as you can see, it looks like the SharePoint Object Model. As a result, developers find it easy to manage and write code.

Client

Server

ClientContext

SPContext

Site

SPSite

Web

SPWeb

List

SPList

ListItem

SPListItem

Field

SPField

ListItemCollection

SPListItemCollection

View

SPView

 

Solution:

First, we must create a custom list named Profiles in our site collection, structured as shown in the following table:

Column Name

Type

FirstName

Single line of text

LastName

Single line of text

Age

Number (1, 1.0, 100)

Available

Yes/No (check box)

 

Now, we begin creating the solution using the following steps:

1. Start Microsoft Visual Studio 2010.

2. On the File menu, point to New, and then click Project.

3. In the New Project dialog box, in the Installed Template pane, expand Visual C#, and then click Silverlight.

4. In the list of templates, click Silverlight Application.

5. In the Name box, type the name that you want to use for your project, such as SPClientOMDemo.

6. In the Location box, type the location where you want to place the solution, then click OK.

7. The New Silverlight Application dialog box appears as shown in the following illustration:

8. Uncheck the Host the Silverlight application in a new Web site check box.

9. Click the OK button to create the Silverlight Application.

10. Add the reference of SharePoint client object model right-clicking on the SPClientOMDemo project, and then clicking Add Reference… to open the Add Reference dialog box.

11. Select the Browse tab, navigate to the location of the Microsoft.SharePoint.Client.Silverlight.dll and Microsoft.SharePoint.Client.Silverlight.Runtime.dll (They can be found at “C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14TEMPLATELAYOUTSClientBin“). Select both DLLs, and then click OK as shown in the following illustration:

12. After you have added all references, the solution should look like this:

13. Using SharePoint Designer, open the Silverlight page (an XAML file) and drag and drop the DataGrid into the page:

Finally, the MainPage.xaml file will have contents that look like this:

<UserControl x:Class=”SPClientOMDemo.MainPage”


xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”


xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”


xmlns:d=”http://schemas.microsoft.com/expression/blend/2008″


xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006″


mc:Ignorable=”d”


d:DesignHeight=”300″ d:DesignWidth=”400″ xmlns:sdk=”http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk”>



<Grid x:Name=”LayoutRoot” Background=”White”>


<sdk:DataGrid AutoGenerateColumns=”True” Height=”300″ HorizontalAlignment=”Left” Name=”grdData” VerticalAlignment=”Top” Width=”400″ />


</Grid>


</UserControl>


14. Add a class named Profile to our project. This class will represent the SharePoint list that we are going to display in DataGrid. The Profile.cs file has the following contents:

1: namespace SPClientOMDemo


2: {


3: public class Profile


4: {


5: public int ProfileID { get; set; }


6: public string FisrtName { get; set; }


7: public string LastName { get; set; }


8: public int Age { get; set; }


9: public bool Available { get; set; }


10: }


11: }


15. Open the MainPage.xaml.cs file and add the reference.

Using Microsoft.SharePoint.Client, here is the MainPage.Xaml.cs file code:

1: using System;


2: using System.Collections.Generic;


3: using System.Net;


4: using System.Windows;


5: using System.Windows.Controls;


6: using System.Windows.Shapes;


7: using Microsoft.SharePoint.Client;


8:


9: namespace SPClientOMDemo


10: {


11: public partial class MainPage : UserControl


12: {


13: private delegate void DataBindMethod();


14: private ListItemCollection collListItem;


15:


16: public MainPage()


17: {


18: InitializeComponent();


19:


20: ClientContext clientContext = new ClientContext(ApplicationContext.Current.Url);


21: Web web = clientContext.Web;


22: List listProfiles = web.Lists.GetByTitle(“Profiles”);


23:


24: //retrieve the items from the list


25: CamlQuery query = new CamlQuery();


26: query.ViewXml = “<View><RowLimit>100</RowLimit></View>“;


27: collListItem = listProfiles.GetItems(query);


28:


29: //load the returned items of the list in context


30: clientContext.Load(collListItem);


31:


32: //execute the query asynchronously


33: clientContext.ExecuteQueryAsync(onQuerySucceeded, onQueryFailed);


34: }


35: private void onQueryFailed(object sender, ClientRequestFailedEventArgs args)


36: {


37: MessageBox.Show(“Request failed. ” + args.Message + “nStack trace : ” + args.StackTrace);


38: }


39: private void onQuerySucceeded(object sender, ClientRequestSucceededEventArgs args)


40: {


41: DataBindMethod dataBind = DataBind;


42: this.Dispatcher.BeginInvoke(dataBind);


43: }


44: private void DataBind()


45: {


46: List<Profile> profiles = new List<Profile>();


47:


48: foreach (ListItem lstItem in collListItem)


49: {


50: profiles.Add(new Profile()


51: {


52: ProfileID = Convert.ToInt32(lstItem[“ID”].ToString()),


53: FisrtName = lstItem[“FirstName”].ToString(),


54: LastName = lstItem[“LastName”].ToString(),


55: Age = Convert.ToInt32(lstItem[“Age”].ToString()),


56: Available = Convert.ToBoolean(lstItem[“Available”].ToString())


57: });


58: }


59:


60: grdData.ItemsSource = profiles;


61: }


62: }


63: }


Now that we have completed our solution, you can see that it’s very simple, right? In the above code, there’s just one point that we should take an additional interest in, namely:

clientContext.ExecuteQueryAsync(onQuerySucceeded, onQueryFailed);

By way of explanation, I’m going to quote the following text from an MSDN article on Using the Silverlight Object Model:

“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 JavaScript 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 calling BeginInvoke().”

Deploy and Test:

We have two ways to deploy the Silverlight application package file (.xap) to the SharePoint environment:

  • We can use a SharePoint document library and upload the Silverlight aplication package (.xap) file there. Refer to this file’s path location in the document library while adding the Silverlight Web Part; or
  • We can use SharePoint’s default location [TemplatesLayoutsClientBin] and deploy the Silverlight application package (.xap) file there. Refer to this file path from the Silverlight Web Part.

In this post, we will use the second method to deploy and test.

1. Right-click on the project and navigate to the Build tab and set the output path to the following folder:

C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14TEMPLATELAYOUTSClientBin

2. Build the project right-clicking the SPClientOMDemo project in Solution Explore and then selecting Build.

3. On our site collection, select the Page tab, then click Edit Page:

4. Click the Add a Web Part hyperlink:

5. On the Category pane, click Media and Content, select Silverlight Web Part on the Web Parts pane, and then click Add:

:

6. The Silverlight Web Part dialog box will be displayed, and we will input the URL of the Silverlight aplication package file (.xap). In our example, we will input the following url : /_layouts/ClientBin/SPClientOMDemo.xap

7. And finally, we will see the result:

Debugging:

To debug a Silverlight application, you must create a SharePoint project and use it to deploy a Silverlight Web Part. As a reference, see How to: Use a SharePoint Project to Deploy a Silverlight Application.

See also:


SharePoint

Applications

SharePoint apps are stand-alone applications that perform specific tasks on a SharePoint site. Apps can perform functions such as managing a discussion board or knowledge base, performing project management or time tracking tasks, or doing other workflow operations.

SharePoint

Product Suites

Experience greater power and savings by bundling our SharePoint apps and web parts.


Essentials


Essentials Plus


Bamboo Premier


Project Management Suite


Knowledge Management Suite


External User Manager


SharePoint

Web Parts

Extend SharePoint beyond its out-of-the-box capabilities by tailoring it to your requirements with Bamboo Solution’s growing portfolio of Web Parts. Web Parts are the building blocks of pages on a SharePoint site that can be used to customize the user interface and content of a site page. 

SharePoint

Product Suites

Experience greater power and savings by bundling our SharePoint apps and web parts.


Essentials


Essentials Plus


Bamboo Premier


Project Management Suite


Knowledge Management Suite


External User Manager


Office 365

Cloud Parts

Cloud Parts are functional components that extend your SharePoint environment whether it’s hosted, on-premises, or part of Microsoft Office 365. More than mere ports of existing software to the cloud, our Cloud Parts have been built from the ground up to take advantage of the best that the cloud has to offer.

SharePoint

Product Suites

Experience greater power and savings by bundling our SharePoint apps and web parts.


Cloud Parts Suite for O365/SP Onl.


Featured Services

SharePoint Health Check

A SharePoint Health Check will identify the causes of issues and risks associated with your specific environment, and is custom tailored to provide you with the best recommendations to optimize your SharePoint environment.

SQL Health Check

Document recommendations relating to performance, stability, availability, or a specific focus you request of your SQL Server database instances.

My SharePointXperts

The truth is that each SharePoint skill may not be a full time job for many organizations, and it is nearly impossible for one person to do everything you need – so augment your team with SharePointXperts; providing the skill sets you need when you need them!