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="">
   <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" />


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" />

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.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

private void OnRequestFailed(Object sender, ClientRequestFailedEventArgs args)

28) Now, implement the FillList method:

private void FillList()
   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:


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.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

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.


I have been working in the world of technology for 25-odd years. I am an entrepreneur and consultant, focused on software solutions, social networking, and innovation processes. Currently, I am a Principal Consultant with T4G Limited, specializing in Portal Technologies (including SharePoint), software/systems development, service oriented architectures, and many other things which I will probably not remember until I need to use them. Prior to that, I was VP of Technology at Whitehill Technologies, Inc., where I spent almost 9 years helping to grow the company from a start-up to one of the most successful private software companies in Canada. Prior to that I worked on internet conferencing using early VoIP, and on large military communications projects. Before even that, I worked in satellite control, and remote sensing. Going way back to university, my focus was on theoretical physics and astrophysics. Currently my interests revolve around most aspects of software development, from technologies to management, and in the area of defining sustainable, repeatable processes for innovation within technology organizations. I also have a particular interest in Tablet PC technologies – I have been using one for several years, and I love it. On the personal side, I still have a strong interest in all aspects of science, especially physical sciences, as well as philosophy and comparative religion. In addition, I am into music, playing guitar (badly, I am sorry to say), and reading almost anything I can lay my hands on. I am also a member of the IEEE/IEEE Computer Society, and of the Association for Computing Machinery.

Tagged with: , , , , ,
Posted in SharePoint, SharePoint 2010, Silverlight
20 comments on “Simple SharePoint 2010 + Silverlight + Client Object Model Example
  1. I have used your code, it throws invalid cross thread acess error

  2. […] Sharepoint – Silverlight – Client OM Share this:TwitterFacebookLike this:LikeBe the first to like this […]

  3. sticnivan says:

    “Note the call to ExecuteQueryAsync – as this is Silverlight, the queries back tot he server need to be asynchronous.”
    Where else can I read about it?

  4. Linkstheman says:

    This was a great tutorial. The only issue I ran into was the error that Cameron got. I just recreated the project, shortening the names I used for each of the added items (SharePointSolutionDeployment became SPSD, etc). This fixed the issue, and the rest of the tutorial went smoothly.

    I was looking for just such a tutorial like this, being completely new to Silverlight myself. Thanks!

    • Fred says:

      THanks for the feedback, and the info about the file name length issue. I kind of thought this might be the issue, but had not had time to check it out. I tend to do most of my work close to the root of the drive (usually in C:\Development) because I have run into problems in the past (as I am sure most of us have) with paths being too long, and with issues due to spaces in the path.

      Thanks again!

  5. Flo says:

    great tutorial! now, i want to show just one list on the right. the Titles of my ListItems and on the right i want to show all other columns. a problem is: i have two look-up-Columns. can you give me some tips? i don`t get it…


  6. Cameron says:

    When I deploy the solution (point 16 in part1), the vs 2010 give a error:
    Error 1 The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters. C:\Users\cameron.ling\documents\visual studio 2010\Projects\SharePointSolutionDeployment\SharePointSolutionDeployment\Features\Feature1\Feature1.feature SharePointSolutionDeployment

  7. Matvey says:

    Hi, i have problem with deploy website. When i deploy website, i get error “Error occurred in deployment step ‘Activate Features’: ….”

  8. Selena Glenn says:

    Thanks Fred, your example was very helpful to me.

    I am early bird to sharepoint, do you have any Sharepoint 2010 Ebooks

  9. Shri says:

    Hi,thank u for this post,
    Can i access Silverlight Application(.xap) that is hosted on external domain from silvelight webpart. this .xap is a simple silverlight application that is not accessing any sharepoint data. Do we need to for Fuild application Model for this.

    thank U

  10. Praveen says:

    Excellent post.
    Check the SharePoint 2010 series of articles here.

  11. RogueIV says:

    Thanks for the post – this is the best sample code I have seen so far. I did not even follow the entire solution you described – I simply built the XAP, copied it to _layouts, and added it to a silverlight web part on a page to test. No problems.

  12. matveich says:

    thank for the post.

  13. Rajanikanth says:

    how do u verify wether ur xap file is deployed in ur sharepoint? (point 17 in part 1 example). when i followed ur steps it shows error that “your silverlight application could not be loaded”

    • Fred says:

      In Step 2, you created a Document Library in which to store the XAP file. You can just go look in that Document Library and see if your XAP file is there.

      Note that the URL on the element in Step 13 must match the name you gave to your Document Library.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Obligatory Disclaimer
Please keep in mind that any opinions, points-of-view, comments, or other content which I post to this site are mine and mine alone. They in no way reflect the views of my employer, my country, my dog, my cat, or anyone else you can think of. To paraphrase Monty Python, "That is the theory that I have and which is mine, and what it is, too."

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 623 other followers

%d bloggers like this: