Simple SharePoint 2010 + Silverlight + Client Object Model Example

NOTE: I updated this post today (Feb 7, 2011) to make the code snippets easier to work with. I tried very hard not to introduce any new typos as I did this, but if you see anything wonky, let me know (if somehthing is not working – think about typos FIRST!)!

This post will take you through a very simple example of using a Silverlight application in SharePoint 2010, using the new SharePoint 2010 Client Object Model. I will also show how to use the new SharePoint 2010 tools in Visual Studio 2010 to package the Silverlight application for deployment. Note that I will not be getting into the details of creating a flashy (no pun intended) UI in Silverlight – i will just create a very simple UI with a list box and a text box.

The Example is broken into 2 parts. The first will describe how to create a SharePoint 2010 solution which will deploy a Silverlight XAP file to SharePoint. The second part will introduce a simple Client Object Model solution in Silverlight.

Part 1 – Creating a SharePoint 2010 Solution to Deploy a Silverlight Application

1) Start with a Team Site in SharePoint 2010 (I am sure any other site type would work just as well).

2) Create a document library to store your Silverlight XAP file (I called mine Silverlight).

3) On the home page of the team site, add a SharePoint Silverlight web part as shown below:

Silverlight Web Part

Next, we will create the Visual Studio 2010 solution.

4) Create a new Visual Studio project, selecting the Empty SharePoint Project template (Visual C# | SharePoint | 2010 | Empty SharePoint Project). Name your solution SharePointSolutionDeployment. This will also add an empty SharePoint project in the solution. Make sure you point to the site you just set up for debugging. In addition, you have the option of creating a Sandbox or Farm solution – in general you should create a Sandbox solution unless you find you really need to do otherwise.

5) Next, add a Silverlight Application project (Visual C# | Silverlight | Silverlight Application) to the solution.  I named mine Simple Silverlight Application.

6) Change the background colour of the layout grid in the MainPage.xaml file. Double click MainPage.xaml to open it in design mode. and change the background colour of the grid to slate gray (or what ever you like – this is just to make it obvious when it shows up in SharePoint).

Now we will add the Module to the SharePointSolutionDeployment project, which will deploy our Silverlight XAP file to SharePoint.

7) Right click the SharePointSolutionDeployment and select Add | New Item…then select Visual C# | SharePoint 2010 | 2010 | Module. Name it Simple Silverlight Application Module

8) In the Solution Explorer, right click the Sample.txt file, and select Delete (note that it is also automatically deleted from the Elements.xml file).

9) Click on the Simple Silverlight Application Module, and observe the Properties display, as shown below:

Module 1

10) Click on the ellipses to edit the Project Output References collection, and click Add:

Module 2

11) Click the dropdown next to Project Name, and select Simple Silverlight Application. Then change the Deployment Type to ElementFile, and click OK:

Module 3

12) Now, open the Elements.xml from your Simple Silverlight Application Module and make the following changes:

13) In the Module element, add the attribute Url=”name of your document library” (use the name of the document library you created in Step 3).

14) Add the following File element inside the Module element:

<File Path="Simple Silverlight Application Module\Simple Silverlight Application.xap"
      URL="Simple Silverlight Application.xap"
      Type="GhostableInLibrary" />

15) Your Element.xml file should now look like:

<?xml version=1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
   <Module Name="Simple Silverlight Application Module" Url="Silverlight">
      <File Path="Simple Silverlight Application Module\Simple Silverlight Application.xap"
            URL="Simple Silverlight Application.xap"
            Type="GhostableInLibrary" />
   </Module>
</Elements>

 

16) You should now be able to build and deploy your solution (under the Build menu).

17) Once you have deployed the solution, check your SharePoint site to verify that the XAP file was deployed to the Silverlight library.

18) Go to your site home page (or the page where you created your Silverlight web part), and configure the Silverlight web part to point to your XAP file. After saving the settings and saving the page, your Silverlight web part should look something like below (note that the rectangle is slate gray, as we set in step 3):

Part 1 Complete

Part 2 – Using the Client Object Model in the Simple Silverlight Application

In this step, we will modify the Simple Silverlight Application to use the SharePoint 2010 Client Object Model to access information regarding the lists on the site.

19) In the Simple Silverlight Application, add references to Microsoft.SharePoint.Client.Silverlight and Microsoft.SharePoint.Client.Silverlight.Runtime. You will have to browse to find these in the Add Reference dialog. They are located at C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin

20) Right-click App.xaml and select View Code.

21) Add the following using statements:

using Microsoft.SharePoint.Client;
using System.Threading;

 

22) Next add the following statement to the start of the Application_Startup method:

private void Application_Startup(object sender, StartupEventArgs e)
{
      ApplicationContext.Init(e.InitParams, SynchronizationContext.Current);
      this.RootVisual = new MainPage();
}

 

23) Now modify the MainPage.xaml design, adding a List Box and a Text Box as shown below. The List Box will be used to display a list of the lists on the site, and the Text Box will display some details regarding the list selected in the List Box.

<Grid x:Name="LayoutRoot" Background="SlateGray">
   <StackPanel Orientation="Horizontal" >
      <ListBox Name="lbLists" Width="300" Height="400" ScrollViewer.VerticalScrollBarVisibility="Auto" Margin="20,20,20,20" />
      <TextBox Name="txtDetails" Width="200" Height="400" TextWrapping="Wrap" />
   </StackPanel>
</Grid>

24) Right click MainPage.xaml and select View Code. the following using statement to MainPage.xaml.cs:

using Microsoft.SharePoint.Client;

25) Add two member variables as shown below:

private Microsoft.SharePoint.Client.Web _web;
private Microsoft.SharePoint.Client.List _list;

26) Add the following code to the MainPage constructor, below the InitializeComponent() call. Note the call to ExecuteQueryAsync – as this is Silverlight, the queries back tot he server need to be asynchronous.

ClientContext context = new ClientContext(ApplicationContext.Current.Url);

_web = context.Web;

context.Load(_web);
context.Load(_web.Lists);

context.ExecuteQueryAsync(new ClientRequestSucceededEventHandler(OnRequestSucceeded), new ClientRequestFailedEventHandler(OnRequestFailed));

27) Next, add the two callback routines from ExecuteQueryAsync, as shown below. In OnRequestSucceeded, the call to FillList is called on a separate thread. The OnRequestFailed method is just a stub.

private void OnRequestSucceeded(Object sender, ClientRequestSucceededEventArgs args)
{ // this is not called on the UI thread
      Dispatcher.BeginInvoke(FillList);
}

private void OnRequestFailed(Object sender, ClientRequestFailedEventArgs args)
{
}

28) Now, implement the FillList method:

private void FillList()
{
   lbLists.Items.Clear();
   lbLists.ItemsSource = _web.Lists;
   lbLists.DisplayMemberPath = "Title";
}

29) Build and deploy the solution. Refresh your page with the Silverlight web part. The List Box should now display a list of the Lists on your site, as shown below:

Lists

30) Next, we will add an event handler for the List Box selection changed, and to then retrieve the details for the selected list.

31) In the design view for MainPage.xaml, double click the list box to create a handler for the selection changed event. Add the following code to the event handler (again note the asynchronous call):

private void lbLists_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   using (ClientContext context = new ClientContext(ApplicationContext.Current.Url))
   {
      _list = context.Web.Lists.GetByTitle(((Microsoft.SharePoint.Client.List)lbLists.SelectedItem).Title);
      context.Load(_list);
      context.ExecuteQueryAsync(new ClientRequestSucceededEventHandler(OnListDetailsRequestSucceeded), null);
   }
}

32) Add the callback routine for the asynchronous query:

private void OnListDetailsRequestSucceeded(Object sender, ClientRequestSucceededEventArgs args)
{ // this is not called on the UI thread
   Dispatcher.BeginInvoke(ShowListDetails);
}

33) Finally, add the routine to display the list details in the Text Box:

private void ShowListDetails()
{
   string infoAboutList =
      string.Format("List Details:" + Environment.NewLine +
                         "Title: {0}" +
                         "Description: {1}" +
                         "Item Count: {2}" +
                         "Base Template: {3}" +
                         "Base Type: {4}" +
                         "Content Types Enabled?: {5}" +
                         "Hidden?: {6}",
                         _list.Title + Environment.NewLine,
                         _list.Description + Environment.NewLine,
                         _list.ItemCount + Environment.NewLine,
                         _list.BaseTemplate + Environment.NewLine,
                         _list.BaseType + Environment.NewLine,
                         _list.ContentTypesEnabled + Environment.NewLine,
                         _list.Hidden + Environment.NewLine);

   txtDetails.Text = infoAboutList;
}

34) Build and deploy the solution. Refresh your page with the Silverlight web part. As before, the List Box should now display a list of the Lists on your site. Select one of the lists, and the details for the list should be displayed in the Text Box, as shown below:

List Details

This has been a very simple introduction to creating and deploying a Silverlight application into SharePoint 2010, and then using the SharePoint 2010 Client Object Model to access list information and display it in Silverlight. This could be extended to query more information on the Lists, or information on other collections on the site, such as Content Types, or Workflow Templates. The Silverlight UI could also obviously be enhanced as well.