Using the Silverlight Object Model

Applies to: SharePoint Foundation 2010

Available in SharePoint Online

Microsoft SharePoint Foundation 2010 supports implementation of the Silverlight client object model in two contexts: within a Silverlight Web Part, and within the Silverlight Cross-Domain Data Access system, through which a Silverlight application interacts with Microsoft SharePoint Foundation 2010 data. A third possibility--modifying client access cross-domain policy on the server--opens security risks and is not supported in SharePoint Foundation 2010.

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 by calling BeginInvoke(), as seen in the following examples.

Deploying code through a Silverlight Web Part

To use the SharePoint Foundation Silverlight object model within a Silverlight Web Part, you can create a Silverlight application in Visual Studio, and add your code to the Page class in the default Page.xaml.cs file of your project. After you build your project, upload the project's application package (.xap) file to a document library. Insert a Silverlight Web Part into a Web Parts page and point the URL source of the Web Part to the .xap file in the document library.

The following examples assume the definitions of a Button control and a TextBlock control in the MainPage.xml file of the project.

Retrieving list data

The following example shows how to retrieve SharePoint Foundation data within the context of a Silverlight application. The example involves using event handlers for success or failure of query execution. The onQuerySucceeded method creates a delegate, UpdateUIMethod, to display returned list data in the UI.

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 Microsoft.SDK.SharePointServices.Samples
{
    public partial class MainPage : UserControl
    {
        Web oWebsite;
        ListCollection collList;
        IEnumerable<List> listInfo;
 
        public MainPage()
        {
            InitializeComponent();
        }
 
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ClientContext clientContext = ClientContext.Current;
            oWebsite = clientContext.Web;
            ListCollection collList = oWebsite.Lists;
 
             clientContext.Load(oWebsite,
                website=>website.Title);
 
             listInfo = clientContext.LoadQuery(
                collList.Include(
                    list=>list.Title,
                    list=>list.Fields.Include(
                        field=>field.Title).Where(
                        field=>field.Required  == true
                        && field.Hidden != true)));
 
            clientContext.ExecuteQueryAsync(onQuerySucceeded, onQueryFailed);
        }
 
        private void onQuerySucceeded(object sender, ClientRequestSucceededEventArgs args)
        {
            UpdateUIMethod updateUI = DisplayInfo;
            this.Dispatcher.BeginInvoke(updateUI);
        }
 
        private void onQueryFailed(object sender, ClientRequestFailedEventArgs args)
        {
            MessageBox.Show = "Request failed. " + args.Message + "\n" + args.StackTrace;
        }
 
        private void DisplayInfo()
        {
            MyOutput.Text = "Title: " + oWebsite.Title;
            collList = oWebsite.Lists;
 
            foreach (List oList in listInfo)
            {
                MyOutput.Text += "\n\tList: " + oList.Title;
 
                FieldCollection collField = oList.Fields;
                foreach (Field oField in collField)
                {
                    MyOutput.Text += "\n\t\tField: " + oField.Title;
                }
            }
        }
 
        private delegate void UpdateUIMethod();
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Net
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Shapes
Imports Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Partial Public Class MainPage
        Inherits UserControl
        Private oWebsite As Web
        Private collList As ListCollection
        Private listInfo As IEnumerable(Of List)

        Public Sub New()
            InitializeComponent()
        End Sub

        Private Sub Button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
            Dim clientContext As ClientContext = ClientContext.Current
            oWebsite = clientContext.Web
            Dim collList As ListCollection = oWebsite.Lists

            clientContext.Load(oWebsite, Function(website) website.Title)

            listInfo = clientContext.LoadQuery(collList.Include(Function(list) list.Title, Function(list) list.Fields.Include(Function(field) field.Title).Where(Function(field) field.Required = True AndAlso field.Hidden <> True)))

            clientContext.ExecuteQueryAsync(AddressOf onQuerySucceeded, AddressOf onQueryFailed)
        End Sub

        Private Sub onQuerySucceeded(ByVal sender As Object, ByVal args As ClientRequestSucceededEventArgs)
            Dim updateUI As UpdateUIMethod = AddressOf DisplayInfo
            Me.Dispatcher.BeginInvoke(updateUI)
        End Sub

        Private Sub onQueryFailed(ByVal sender As Object, ByVal args As ClientRequestFailedEventArgs)
            MessageBox.Show = "Request failed. " & args.Message & vbLf & args.StackTrace
        End Sub

        Private Sub DisplayInfo()
            MyOutput.Text = "Title: " & oWebsite.Title
            collList = oWebsite.Lists

            For Each oList As List In listInfo
                MyOutput.Text += vbLf & vbTab & "List: " & oList.Title

                Dim collField As FieldCollection = oList.Fields
                For Each oField As Field In collField
                    MyOutput.Text += vbLf & vbTab & vbTab & "Field: " & oField.Title
                Next oField
            Next oList
        End Sub

        Private Delegate Sub UpdateUIMethod()
    End Class
End Namespace

The previous example uses the Current property to specify the current request context, instead of using the ClientContext(String) constructor and specifying a URL. You can upload, for example, the .xap file to Shared Documents in the root Web site of the site collection, and create a Web Parts page in a child Web site anywhere beneath the root Web site, and add a Silverlight Web Part to this page that points to the .xap file and therefore implements its logic. In other words, your code might live in the root Web site, but its logic becomes available to any Web site in the site collection.

Creating a list item

The following example shows how to create a list item in a specific list. The example uses a delegate to display information about the new item in the UI.

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 Microsoft.SDK.SharePointServices.Samples
{
    public partial class MainPage : UserControl
    {
        private List oList;
        private string siteUrl = "http://MyServer/sites/MySiteCollection/MyWebSite";

        public MainPage()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ClientContext clientContext = new ClientContext(siteUrl);
            Web oWebsite = clientContext.Web;
            ListCollection collList = oWebsite.Lists;

            oList = clientContext.Web.Lists.GetByTitle("Announcements");

            ListItem oListItem = oList.AddItem(new ListItemCreationInformation());
            oListItem["Title"] = "My new item";
            oListItem["Body"] = "This is my new Silverlight item.";
            oListItem.Update();

            clientContext.Load(oList,
                list => list.Title);

            clientContext.ExecuteQueryAsync(onQuerySucceeded, onQueryFailed);
        }

        private void onQuerySucceeded(object sender, ClientRequestSucceededEventArgs args)
        {
            UpdateUIMethod updateUI = DisplayInfo;
            this.Dispatcher.BeginInvoke(updateUI);
        }

        private void DisplayInfo()
        {
            MyOutput.Text = "New item created in " + oList.Title;
        }

        private delegate void UpdateUIMethod(); 
        
        private void onQueryFailed(object sender, ClientRequestFailedEventArgs args)
        {
            MessageBox.Show("Request failed. " + args.Message + "\n" + args.StackTrace);
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Net
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Shapes
Imports Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Partial Public Class MainPage
        Inherits UserControl
        Private oList As List
        Private siteUrl As String = "http://MyServer/sites/MySiteCollection/MyWebSite"

        Public Sub New()
            InitializeComponent()
        End Sub

        Private Sub Button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
            Dim clientContext As New ClientContext(siteUrl)
            Dim oWebsite As Web = clientContext.Web
            Dim collList As ListCollection = oWebsite.Lists

            oList = clientContext.Web.Lists.GetByTitle("Announcements")

            Dim oListItem As ListItem = oList.AddItem(New ListItemCreationInformation())
            oListItem("Title") = "My new item"
            oListItem("Body") = "This is my new Silverlight item."
            oListItem.Update()

            clientContext.Load(oList, Function(list) list.Title)

            clientContext.ExecuteQueryAsync(AddressOf onQuerySucceeded, AddressOf onQueryFailed)
        End Sub

        Private Sub onQuerySucceeded(ByVal sender As Object, ByVal args As ClientRequestSucceededEventArgs)
            Dim updateUI As UpdateUIMethod = AddressOf DisplayInfo
            Me.Dispatcher.BeginInvoke(updateUI)
        End Sub

        Private Sub DisplayInfo()
            MyOutput.Text = "New item created in " & oList.Title
        End Sub

        Private Delegate Sub UpdateUIMethod()

        Private Sub onQueryFailed(ByVal sender As Object, ByVal args As ClientRequestFailedEventArgs)
            MessageBox.Show("Request failed. " & args.Message & vbLf & args.StackTrace)
        End Sub
    End Class
End Namespace

See Also

Concepts

Code Sample: Silverlight List Viewer

Data Retrieval Overview

SharePoint 2010 Client Object Model Guidelines

How to: Retrieve Lists

How to: Create, Update, and Delete List Items

Common Programming Tasks in the Managed Client Object Model

Other Resources

Client Class Library

JavaScript Class Library