Поделиться через


Пошаговое руководство. Создание объекта службы контента

Дата последнего изменения: 30 сентября 2009 г.

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

В этой статье
Файл класса ContentService
Файл класса ContentLocationCollection
Файл класса ContentLocation
Добавление настраиваемого действия и ASPX-страниц

В этом пошаговом руководстве показан процесс определения логики настраиваемой службы для управления контентом сайта в развертывании SharePoint Foundation. Данный пример показывает, как создавать классы, производные от классов в пространстве имен Microsoft.SharePoint.Administration, чтобы сохранить пользовательские административные настройки в базе данных. Пример содержит файлы классов, реализующие структуры данных, которые содержат метаданные для списка расположений. Каждое расположение контента определяет URL-адрес, который должен быть сохранен.

Этот пример содержит файлы кода для следующих классов:

  • ContentService.   Определяет объект верхнего уровня, производный от класса SPService, и содержит логику управления расположениями контента в развертывании. Этот класс содержит конструкторы для инициализации объекта ContentService, а также члены для возвращения службы контента и ее коллекции расположений контента.

  • ContentLocationCollection.   Определяет класс коллекции, наследуемый от класса SPPerisistedChildCollection и предоставляющий объект для хранения расположений контента. Этот класс содержит конструктор и метод Add.

  • ContentLocation.   Наследуется от SPPersistedObject и определяет расположение контента. Этот класс содержит конструкторы и члены для значений пользовательских свойств.

Помимо создания сборки с предыдущими файлами кода, в этом примере демонстрируется использование пользовательского компонента действий для добавления страницы Операции, предоставляющей администраторам доступ к службам. В примере также описывается, как использовать пользовательские ASPX-страницы, чтобы предоставить пользовательский интерфейс, необходимый для управления службой контента и элементами расположений контента. Сведения о создании проекта SharePoint Foundation в Microsoft Visual Studio 2005 см. в разделе Getting Started with Programmatically Customizing a SharePoint Web Site in Visual Studio.

Файл класса ContentService

Следующий пример кода определяет перечисление FormatType и класс верхнего уровня ContentService, содержащий конструкторы и следующие члены:

  • Local.   Статическое свойство для возвращения текущей службы расположений контента.

  • Locations.   Статическое свойство для доступа к коллекции расположений контента.

  • GetAllContentLocations.   Метод, возвращающий все расположения контента, предоставленные службой.

  • Format.   Свойство для получения или задания типа формата для службы контента.

В начале каждого представленного ниже файла кода следует добавить директиву для импорта пространства имен Microsoft.SharePoint.Administration, как показано в следующем примере. Чтобы сохранять значения свойств в базе данных, используйте атрибут Persisted. Пользовательским пространством имен, содержащим объекты в примере, является MS.Samples.SharePoint.ContentManager.

Imports System
Imports System.Collections.Generic
Imports System.Text
Imports Microsoft.SharePoint.Administration

Namespace MS.Samples.SharePoint.ContentManager

    Public Enum FormatType
        HTML
        XML
    End Enum 'ContentLocationType

    <System.Runtime.InteropServices.Guid("BB69A6EB-3230-43ca-B4F5-752EAC39C74A")>  _
    Public Class ContentService
        Inherits SPService

        <Persisted()>  _
        Private formatType As FormatType

        Private Shared locations As ContentLocationCollection
        Private Shared local As ContentService = Nothing
      
        ' A static property that retrieves the content service. 
        Public Shared ReadOnly Property Local() As ContentService
            Get
                If ContentService.local Is Nothing Then
                    ContentService.local = _
                      SPFarm.Local.Services.GetValue < ContentService > "ContentService"
                End If

                Return ContentService.local
            End Get
        End Property

        ' A static property for accessing the location collection. 
        Public Shared ReadOnly Property Locations() As ContentLocationCollection
            Get
                If Me.locations Is Nothing Then
                    Me.locations = New ContentLocationCollection(Me)
                End If

                Return Me.locations
            End Get
        End Property

        ' An empty public constructor required for serialization. 
        Public Sub New()
        End Sub 'New

        Public Sub New(farm As SPFarm)
            MyBase.New("ContentService", farm)
            ' Add code to initialize as needed. 
        End Sub 'New

        ' A method to retrieve the content location collection. 
        Public Function GetAllContentLocations() As ContentLocationCollection
            Dim service As ContentService = ContentService.Local
            If service Is Nothing Then
                Return Nothing
            End If

            Return service.Locations
        End Function 'GetAllContentLocations

        Public Property Format () As FormatType
            Get
                Return Me.formatType
            End Get
            Set
                Me.formatType = value
            End Set
        End Property 
    End Class 'ContentService
End Namespace 'MS.Samples.SharePoint.ContentManager
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Administration;

namespace MS.Samples.SharePoint.ContentManager
{
    public enum FormatType
    {
        HTML,
        XML
    }
    [System.Runtime.InteropServices.Guid("BB69A6EB-3230-43ca-B4F5-752EAC39C74A")]
    public class ContentService : SPService
    {
        [Persisted]
        private FormatType formatType;

        private static ContentLocationCollection locations;
        private static ContentService local = null;

        /* A static property that retrieves the content service. */
        public static ContentService Local
        {
            get
            {
                if (ContentService.local == null)
                {
                    ContentService.local = 
                      SPFarm.Local.Services.GetValue<ContentService>("ContentService");
                }

                return ContentService.local;
            }
        }

        /* A static property for accessing the location collection. */
        public static ContentLocationCollection Locations
        {
            get
            {
                if (this.locations == null)
                {
                    this.locations = new ContentLocationCollection(this);
                }

                return this.locations;
            }
        }

        /* An empty public constructor required for serialization. */
        public ContentService()
        {;}

        public ContentService(SPFarm farm)
            : base("ContentService", farm)
        {/* Add code to initialize as needed. */}

        /* A method to retrieve the content location collection. */
        public ContentLocationCollection GetAllContentLocations()
        {
            ContentService service = ContentService.Local;

            if (service == null)
            {
                return null;
            }

            return service.Locations;
        }

        public FormatType Format
        {
            get 
            {
                return this.formatType; 
            }
            set 
            { 
                this.formatType = value; 
            }
        }
    }
}

Определите настраиваемый метод Provision, чтобы добавить в базу данных объект ContentService, как в следующем примере. Этот метод может содержаться в предыдущем классе ContentService или может размещаться отдельно, что позволит повысить модульность и обеспечит доступ из различных контекстов (например, из установщика компонентов, который можно создать для установки службы) или при запуске из командной строки. Метод Provision добавляет объект ContentService в базу данных без указания сборки и класса.

ПримечаниеПримечание

Определенный настраиваемый метод Provision не является методом Provision базового класса SPPersistedObject.

Public Sub Provision()
  ' Add the ContentService administration object to the database.
  Dim contentService As ContentService = ContentService.Local
  
  If contentService Is Nothing Then
    contentService = New ContentService(SPFarm.Local)
    contentService.Update()
  End If
End Sub
public void Provision()
{
    /* Add the ContentService administration object to the database. */
    ContentService contentService = ContentService.Local;

    if (contentService == null)
    {
        contentService = new ContentService(SPFarm.Local);
        contentService.Update();
    }
}

Файл класса ContentLocationCollection

В следующем примере определяется класс ContentLocationCollection, содержащий конструкторы и метод Add для добавления в коллекцию новых расположений контента.

Public Class ContentLocationCollection

  Public Sub New(parent As SPPersistedObject)
    MyBase.New(parent)
  End Sub
  
  Public Sub Add(url As String)
    Dim location As New ContentLocation(String.Empty, Me.Parent)
    
    location.Url = url
    
    location.Update()
  End Sub
End Class
public class ContentLocationCollection : SPPersistedChildCollection<ContentLocation>
{
    public ContentLocationCollection(SPPersistedObject parent) : base(parent)
    {;}

    public void Add(String url)
    {
        ContentLocation location = new ContentLocation(String.Empty, this.Parent);

        location.Url = url;

        location.Update();
    }
}

Файл класса ContentLocation

В следующем примере определяется перечисление ContentLocationType, которое описывает тип расположения контента, а также класс ContentLocation, описывающий свойства расположения контента, в том числе его отображаемое имя, тип, URL-адрес и путь вывода. Задание атрибута Persisted позволяет сохранить значение свойства в базе данных.

Класс ContentLocation содержит следующие члены:

  • DisplayName.   Свойство, позволяющее получить отображаемое имя расположения.

  • Url.   Свойство, позволяющее получить или задать URL-адрес расположения контента.

  • LocationType.   Свойство, позволяющее получить или задать тип расположения.

  • ContentOutputPath.   Свойство, позволяющее получить или задать путь вывода.

Public Enum ContentLocationType
    Web
    List
End Enum 'ContentLocationType

Public Class ContentLocation
  Inherits SPPersistedObject
    <Persisted()>  _
    Private locationType As ContentLocationType

    <Persisted()>  _
    Private contentOutputPath As String

    <Persisted()>  _
    Private url As String

    Public Sub New()
    End Sub 'New

    Public Sub New(name As String, parent As SPPersistedObject)
        MyBase.New(name, parent)
    End Sub 'New

    Public Overrides ReadOnly Property DisplayName() As String
        Get
            Return Me.url
        End Get
    End Property

    Public Property Url() As String
        Get
            Return Me.url
        End Get
        Set
            If Me.url = value Then
                Return
            End If

        Me.url = value

        ' The Name property must be unique among multiple children in a 
        ' collection.  Use the URL to ensure uniqueness. 
         Me.Name = Me.url
        End Set
    End Property
      
    Public Property LocationType() As ContentLocationType
        Get
            Return Me.locationType
        End Get
        Set
            Me.locationType = value
        End Set
    End Property 
      
    Public Property ContentOutputPath() As String
        Get
            Return Me.contentOutputPath
        End Get
        Set
            Me.contentOutputPath = value
        End Set
    End Property
End Class 'ContentLocation
public enum ContentLocationType
{
    Web,
    List
}

public class ContentLocation : SPPersistedObject
{
    [Persisted]
    private ContentLocationType locationType;

    [Persisted]
    private String contentOutputPath;

    [Persisted]
    private String url;

    public ContentLocation()
    {}

    public ContentLocation(string name, SPPersistedObject parent)
      : base(name, parent)
    {;}

    public override string DisplayName
    {
        get
        {
            return this.url;
        }
    }

    public String Url
    {
        get { return this.url; }
        set 
        {
            if (this.url == value)
            {
                return;
            }

            this.url = value;
            /* The Name property must be unique among multiple children in a collection.  Use the URL to ensure uniqueness. */
            this.Name = this.url; 
        }
    }

    public ContentLocationType LocationType
    {
        get { return this.locationType; }
        set { this.locationType = value; }
    }

    public String ContentOutputPath
    {
        get { return this.contentOutputPath; }
        set { this.contentOutputPath = value; }
    }
}

Добавление настраиваемого действия и ASPX-страниц

Добавьте ASPX-страницы в папку \Admin и определите фоновый код в сборке. Сведения об административных ASPX-страницах см. в разделе Страницы центра администрирования. Для добавления настраиваемого действия на страницу центра администрирования используйте компонент. Сведения о добавлении настраиваемого действия см. в разделе Практическое руководство. Изменение пользовательского интерфейса с помощью настраиваемых действий.

В следующем файле Elements.xml в раздел Глобальная конфигурация страницы Операции для управления расположениями контента добавляется настраиваемое действие Экспорт контента, ссылающееся на страницу contentman.aspx.

<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="https://schemas.microsoft.com/sharepoint/">
  <CustomAction
    Id="ContentManagement"
    GroupId="GlobalConfiguration"
    Location="Microsoft.SharePoint.Administration.Operations"
    Sequence="31"
    Title="Content export">
    <UrlAction Url="/_admin/contentman.aspx" />
  </CustomAction>
</Elements>

Файл contentman.aspx, на который указывает настраиваемое действие, может содержать ссылки на страницы форм для создания, отображения или изменения элементов расположения контента. Например, код страницы Создать элемент может содержать указанную ниже логику, которая добавляет элементы расположений для URL-адресов, введенных в поле urlImportExport на этой странице, и выполняет перенаправление на страницу contentman.aspx:

Imports System
Imports System.Collections.Generic
Imports System.Text
Imports Microsoft.SharePoint.WebControls
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace MS.Samples.SharePoint.ContentManager

    Public Class NewContentImportExportPage
        Inherits Page
        Protected urlImportExport As InputFormTextBox

        Protected Sub SaveNewImportExport(sender As Object, eventArgs As EventArgs)
            Dim service As ContentService = ContentService.Local

            service.Locations.Add(Me.urlImportExport.Text)

            Response.Redirect("/_admin/contentman.aspx", True)
        End Sub 'SaveNewImportExport
    End Class 'NewContentImportExportPage
End Namespace 'MS.Samples.SharePoint.ContentManager
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.WebControls;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MS.Samples.SharePoint.ContentManager
{
    public class NewContentImportExportPage : Page
    {
        protected InputFormTextBox urlImportExport;

        protected void SaveNewImportExport(object sender, EventArgs eventArgs)
        {
            ContentService service = ContentService.Local;

            service.Locations.Add(this.urlImportExport.Text);

            Response.Redirect("/_admin/contentman.aspx", true);
        }
    }
}

После реализации настраиваемой службы можно получить доступ к ее данным путем создания экземпляра службы и вызова его членов. Кроме того, можно также создать другие настраиваемые объекты, наследуемые от других сохраненных объектов в пространстве имен Microsoft.SharePoint.Administration. Например, разработчик может создать класс, производный от класса SPJobDefinition, чтобы реализовать задание таймера и выполнить из настраиваемой службы синхронизированные по времени операции, или наследовать от класса SPFeatureReceiver, чтобы определить обработку события регистрации службы при ее установке или настройке в качестве компонента.

Сохраненные объекты позволяют добавить пользовательские объекты администрирования в базу данных конфигурации, чтобы сохранить логику и данные веб-приложения, построенного на платформе SharePoint Foundation.