Использование объектной модели Silverlight

Дата последнего изменения: 1 июля 2010 г.

Применимо к: SharePoint Foundation 2010

Доступно на сайте SharePoint Online

Microsoft SharePoint Foundation 2010 поддерживает реализацию объектной модели клиента Silverlight в двух контекстах — внутри веб-части Silverlight и внутри системы междоменного доступа к данным Silverlight — с помощью которых приложение Silverlight взаимодействует с данными Microsoft SharePoint Foundation 2010. Третья возможность — изменение клиентской политики междоменного доступа — связана с рисками безопасности и не поддерживается в SharePoint Foundation 2010.

Поскольку при использовании объектной модели SharePoint Foundation Silverlight запросы выполняются асинхронно, необходимо передать делегаты для методов обратного вызова в качестве параметров в метод ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler), что похоже на выполнение запросов в объектной модели JavaScript. Однако для запуска кода, вносящего изменения в пользовательский интерфейс посредством объектной модели Silverlight, необходимо делегировать эту работу объекту Dispatcher потока, который создал пользовательский интерфейс с помощью вызова BeginInvoke(), как видно в следующих примерах.

Развертывание кода с помощью веб-части Silverlight

Чтобы использовать объектную модель SharePoint Foundation Silverlight внутри веб-части Silverlight, можно создать в Visual Studio приложение Silverlight и добавить свой код в класс Page в файле по умолчанию Page.xaml.cs проекта. После построения проекта отправьте файл пакета приложения проекта (XAP) в библиотеку документов. Вставьте веб-часть Silverlight на страницу веб-частей, а затем выберите исходный URL-адрес этой веб-части в файле XAP в библиотеке документов.

В следующих примерах предполагается наличие определений элементов управления Button и TextBlock в файле MainPage.xml проекта.

Извлечение данных списков

В следующем примере показано, как извлечь данные SharePoint Foundation в контексте приложения Silverlight. Использование обработчиков событий в примере позволяет определить, был ли запрос успешно выполнен или произошел сбой. Метод onQuerySucceeded создает делегат UpdateUIMethod для отображения возвращенных данных списков в пользовательском интерфейсе.

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

В предыдущем примере вместо использования конструктора ClientContext(String) и задания URL-адреса используется свойство Current для указания текущего контекста запроса. Можно отправить, например, файл XAP в Общие документы в корневом веб-сайте семейства веб-сайтов, создать страницу веб-частей на дочернем веб-сайте в любом месте ниже по уровню, чем корневой веб-сайт, и добавить на эту страницу веб-часть Silverlight, которая указывает на файл XAP и таким образом реализует его логическую схему. Другими словами, код может находиться на корневом веб-сайте, но его логическая схема становится доступной любому веб-сайту в семействе веб-сайтов.

Создание элемента списка

В следующем примере показано, как создать элемент в определенном списке. В примере используется делегат для отображения сведений о новом элементе в пользовательском интерфейсе.

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

См. также

Концепции

Пример кода: средство просмотра списков Silverlight

Обзор извлечения данных

Инструкции по использованию клиентской объектной модели

Практическое руководство. Получение списков

Практическое руководство. Создание, обновление и удаление элементов списка

Общие задачи программирования

Другие ресурсы

Библиотека классов для клиента

Библиотека классов ECMAScript