Monday, March 8, 2010

SharePoint 2010 Silverlight Client Object Model - How to use

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


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()

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


  1. Wow, This is the one of the great and excellent posts I like these days. The way you have written is very explanatory and easily understanding. I appreciate the work you are allocating for writing posts sharing knowledge. With this example, I am also one of the dev who created Silverlight app in SharePoint 2010. Awesome. Happy. :)

  2. Thanks for the Excellent Post. Is Visual Studio 2010 required for developing solutions with Silverlight Client Object Model ? Is Sharepoint Designer of any value for working with Client Object Model ?

  3. Silverlight Client Object Model is nothing but Silverlight programming and accessing objects. So, you can't do that with SharePoint designer. You should need Visual Studio 2010 to get this job done. Any way it's in BETA, I believe no problems to install it.

  4. Hi,

    I cannot seem to get it deployed to the sharepoint site. When i enter the URL /_layouts/ClientBin/TEST.xap
    i get the error "Could not download the Silverlight application or the Silverlight Plugin did not load.

    To re-configure the Web Part or to provide a different Silverlight application (.xap), open the tool pane and then click Configure."

  5. Purna Chander.MMay 9, 2010 at 1:54 PM

    Nice post..

  6. Hi Fzzzz,
    Seems like you have given wrong url in deploying the XAP file from application. Check once the deploy location of the build and test. Let me know, if you need to any help on this.

  7. Hi there... im sort of a noob in this SP COM can you explain to me where should I must change the site url more precisely and how? I know it's a lame question but i have no idea. thanks

  8. Hi Art-Uhr,
    I have changed the code few days back and forgot to update the site url related information. Now the note section in the post is strike out.... So, no url and nothing to be changed. Just copy and paste directly...
    Thanks any way/

  9. Tahnk's to you! I thought I was missing somthing. lol, gorgeous tutorial, btw just added u to gtalk hope it's ok

  10. Hi Guys,

    Great post indeed. I am at client side (meaning out of dev environment) and there is some discussion going at if SP2010 + Silverlight can be used as an application development tool which will be different from typical SharePoint look and feel. Can you please suggest any sites which were developed using above mentioned tools? I just want to give demo about the power of this combo.

    Much obliged.


  11. I am trying to get the Description label to word wrap over more then one line.

    Also how do I use Textbox or other controls instead of just Label. If I try to use a text box or any other control I get "control was not found"


    I've also tried draging and droping the control onto the canvas, but get the same error.

    When using datainput name I only have access to Label, ValidationSummary, DescritionViewer.

  12. Hmm... Very great and awesome article. I really like it. You save my live.. hehe...

    You can go with ASPHostPortal ( This provider offer sharepoint only with $ 9.99/month. I have tried it and until now everyhing works great. Just recommendation

  13. Awesome post. Thanks for all the good work you are doing. It really helps to beginners like me. Keep up the good work. :)

  14. Hi,

    i used your code to generate a silverlight application but i'm facing problem since last three to four days. the problem is that "OnSiteLoadSuccess" and "OnSiteLoadFailed" are never being called. i tried different ways but useless. kindly help..

    Mubeen Iqbal

  15. Hi,

    i used your code to generate a silverlight application but i'm facing problem since last three to four days. the problem is that "OnSiteLoadSuccess" and "OnSiteLoadFailed" are never being called. i tried different ways but useless. kindly help..

    Mubeen Iqbal

  16. Hi Iqbal,
    Please try to debug line by line and see whether the code is getting called at least. Put a break point in btnLoadSite_Click() first line and see the code is getting called.

  17. Hi Praveen,

    yes i checked and event "btnLoadSite_Click()" gets called but "OnSiteLoadSuccess" and "OnSiteLoadFailed" are never being called. what could be the reason for this? any configuration am i missing or any other problem?


  18. .xaml code is not visible. there is some error.

  19. Could you check once your browser settings? I am able to see the XAML code without any issues.


  20. It always goes to OnSiteLoadFailure method . please help

  21. This is the error i got:
    Unhandled Error in Silverlight Application Invalid cross-thread access. at MS.Internal.XcpImports.CheckThread()
    at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value, Boolean allowReadOnlySet)
    at System.Windows.Controls.ContentControl.set_Content(Object value)
    at COMSilverlight.MainPage.OnSiteLoadSuccess(Object sender, ClientRequestSucceededEventArgs e)
    at Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryGetResponseAsyncCallback(IAsyncResult asyncResult)
    at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClassd.b__b(Object state2)
    at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
    at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
    at System.Threading.ThreadPoolWorkQueue.Dispatch()
    at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() default.aspx, line 1 character 1

  22. I beleive you are using the same code as is and you are deploying the code to a SharePoint server and using in a sharepoint site. Please find the full code here:


  23. Why am I getting this error:
    Silverlight Application The query expression is not supported at Microsoft.SharePoint.Client.DataRetrieval.ProcessMemberAccessQueryExpression

    I have deployed my XAP into documents library and approved it. It renders correctly but when I click on button it is giving above error.

  24. Venky,
    The error should not come. This is the first time I am seeing this kind of error. I believe as you are deployed with your credentials, I don't think this is not a permissions issue. And the document library you deployed is also in the same site site as you are using silverlight web part. And please get the complete code here and try:


  25. Hi, I am new in silverlight
    I don't find the .dll files which should be located at Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\LAYOUTS\ClientBin.
    I don't even have this folders. It ends at \14 and then there is nothing
    Can I download those dlls somewhere?
    Thank you in advance

  26. I believe you can download it from here: