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


Практическое руководство. Расширение узла SharePoint в обозревателе сервера

Пользователь может расширить вложенные узлы в узле Подключения SharePoint в обозревателе сервера.Это удобно в случае необходимости добавить в существующий узел новые дочерние узлы, элементы контекстного меню или свойства.Дополнительные сведения см. в разделе Расширение узла подключений SharePoint в обозревателе сервера.

Расширение узла SharePoint в обозревателе сервера

  1. Создайте проект библиотеки классов.

  2. Добавьте ссылки на следующие сборки:

    • Microsoft.VisualStudio.SharePoint

    • Microsoft.VisualStudio.SharePoint.Explorer.Extensions

    • System.ComponentModel.Composition

  3. Создайте класс, реализующий интерфейс IExplorerNodeTypeExtension.

  4. Добавьте в класс атрибут System.ComponentModel.Composition.ExportAttribute.Этот атрибут позволяет Visual Studio находить и загружать пользовательскую реализацию класса IExplorerNodeTypeExtension.Передайте этому конструктору атрибута тип IExplorerNodeTypeExtension;

  5. Добавьте в класс атрибут ExplorerNodeTypeAttribute.Этот атрибут задает идентификатор строки для типа узла, который требуется расширить.

    Чтобы указать предусмотренные в Visual Studio встроенные типы узлов, передайте одно из следующих значений перечисления конструктору атрибута.

    • ExplorerNodeTypes — эти значения позволяют задать узлы подключения сайтов (узлы, отображающие URL-адрес сайта), узлы сайтов и все другие родительские узлы в окне Обозреватель решений.

    • ExtensionNodeTypes – эти значения позволяют задать один из встроенных узлов, представляющих отдельный компонент на сайте SharePoint, например узел, представляющий список, поле или тип содержимого.

  6. В текущей реализации метода IExplorerNodeTypeExtension.Initialize для добавления компонентов в узел используйте члены параметра nodeType.Этот параметр представляет собой объект IExplorerNodeType, который предоставляет доступ к событиям, определенным в интерфейсе IExplorerNodeEvents.Например, можно обработать следующие события.

Пример

В следующем примере кода демонстрируется создание двух различных типов расширений узла.

  • Расширение, добавляющее пункт контекстного меню для узлов сайта SharePoint.При выборе этого пункта меню отображается имя выбранного узла.

  • Расширение, добавляющее настраиваемое свойство с именем ContosoExampleProperty в каждый узел, представляющий поле с именем Основная часть.

Imports System.ComponentModel
Imports System.ComponentModel.Composition
Imports System.Windows.Forms
Imports Microsoft.VisualStudio.SharePoint
Imports Microsoft.VisualStudio.SharePoint.Explorer
Imports Microsoft.VisualStudio.SharePoint.Explorer.Extensions

Namespace Contoso.ServerExplorerExtension
    <Export(GetType(IExplorerNodeTypeExtension))> _
    <ExplorerNodeType(ExplorerNodeTypes.SiteNode)> _
    Friend Class SiteNodeExtensionWithContextMenu
        Implements IExplorerNodeTypeExtension

        Private Sub Initialize(ByVal nodeType As IExplorerNodeType) _
            Implements IExplorerNodeTypeExtension.Initialize
            AddHandler nodeType.NodeMenuItemsRequested, AddressOf NodeMenuItemsRequested
        End Sub

        Private Sub NodeMenuItemsRequested(ByVal Sender As Object, ByVal e As ExplorerNodeMenuItemsRequestedEventArgs)
            Dim menuItem = e.MenuItems.Add("Display Message")
            AddHandler menuItem.Click, AddressOf MenuItemClick
        End Sub

        Private Sub MenuItemClick(ByVal Sender As Object, ByVal e As MenuItemEventArgs)
            Dim node As IExplorerNode = CType(e.Owner, IExplorerNode)
            MessageBox.Show(String.Format("Clicked the menu item for the '{0}' node.", node.Text))
        End Sub
    End Class

    <Export(GetType(IExplorerNodeTypeExtension))> _
    <ExplorerNodeType(ExtensionNodeTypes.FieldNode)> _
    Friend Class FieldNodeExtensionWithProperty
        Implements IExplorerNodeTypeExtension

        Private Sub Initialize(ByVal nodeType As IExplorerNodeType) _
            Implements IExplorerNodeTypeExtension.Initialize
            AddHandler nodeType.NodePropertiesRequested, AddressOf NodePropertiesRequested
        End Sub

        Private Sub NodePropertiesRequested(ByVal Sender As Object, ByVal e As ExplorerNodePropertiesRequestedEventArgs)
            Dim propertyObject As ExampleProperty = Nothing

            ' Only add the property to "Body" fields.
            If e.Node.Text = "Body" Then
                ' If the properties object already exists for this node, get it from the node's annotations.
                If False = e.Node.Annotations.TryGetValue(propertyObject) Then
                    ' Otherwise, create a new properties object and add it to the annotations.
                    propertyObject = New ExampleProperty(e.Node)
                    e.Node.Annotations.Add(propertyObject)
                End If
                e.PropertySources.Add(propertyObject)
            End If
        End Sub
    End Class

    Friend Class ExampleProperty

        Private node As IExplorerNode
        Private Const propertyId As String = "Contoso.CustomActionTestProperty"
        Private Const propertyDefaultValue As String = "This is a test value."

        Friend Sub New(ByVal node As IExplorerNode)
            Me.node = node
        End Sub

        ' Gets or sets a simple string property. 
        <DisplayName("ContosoExampleProperty")> _
        <DescriptionAttribute("This is an example property for field nodes.")> _
        <DefaultValue(propertyDefaultValue)> _
        Public Property TestProperty As String
            Get
                Dim propertyValue As String = Nothing

                ' Get the current property value if it already exists; otherwise, return a default value.
                If False = node.Annotations.TryGetValue(propertyId, propertyValue) Then
                    propertyValue = propertyDefaultValue
                End If
                Return propertyValue
            End Get
            Set(ByVal value As String)
                If value <> propertyDefaultValue Then
                    ' Store the property value in the Annotations property of the node. 
                    ' Data in the Annotations property does not persist when Visual Studio exits.
                    node.Annotations(propertyId) = value
                Else
                    ' Do not save the default value.
                    node.Annotations.Values.Remove(propertyId)
                End If
            End Set
        End Property
    End Class
End Namespace
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Windows.Forms;
using Microsoft.VisualStudio.SharePoint;
using Microsoft.VisualStudio.SharePoint.Explorer;
using Microsoft.VisualStudio.SharePoint.Explorer.Extensions;

namespace Contoso.ServerExplorerExtension
{
    [Export(typeof(IExplorerNodeTypeExtension))]
    [ExplorerNodeType(ExplorerNodeTypes.SiteNode)]
    internal class SiteNodeExtensionWithContextMenu : IExplorerNodeTypeExtension
    {
        public void Initialize(IExplorerNodeType nodeType)
        {
            nodeType.NodeMenuItemsRequested += nodeType_NodeMenuItemsRequested;
        }

        void nodeType_NodeMenuItemsRequested(object sender, ExplorerNodeMenuItemsRequestedEventArgs e)
        {
            IMenuItem menuItem = e.MenuItems.Add("Display Message");
            menuItem.Click += menuItem_Click;
        }

        void menuItem_Click(object sender, MenuItemEventArgs e)
        {
            IExplorerNode node = (IExplorerNode)e.Owner;
            MessageBox.Show(string.Format("Clicked the menu item for the '{0}' node.", node.Text));
        }
    }

    [Export(typeof(IExplorerNodeTypeExtension))]
    [ExplorerNodeType(ExtensionNodeTypes.FieldNode)]
    internal class FieldNodeExtensionWithProperty : IExplorerNodeTypeExtension
    {
        public void Initialize(IExplorerNodeType nodeType)
        {
            nodeType.NodePropertiesRequested += nodeType_NodePropertiesRequested;
        }

        void nodeType_NodePropertiesRequested(object sender, ExplorerNodePropertiesRequestedEventArgs e)
        {
            // Only add the property to "Body" fields.
            if (e.Node.Text == "Body")
            {
                ExampleProperty propertyObject;

                // If the properties object already exists for this node, get it from the node's annotations.
                if (!e.Node.Annotations.TryGetValue(out propertyObject))
                {
                    // Otherwise, create a new properties object and add it to the annotations.
                    propertyObject = new ExampleProperty(e.Node);
                    e.Node.Annotations.Add(propertyObject);
                }

                e.PropertySources.Add(propertyObject);
            }
        }
    }

    internal class ExampleProperty
    {
        private IExplorerNode node;
        private const string propertyId = "Contoso.ExampleProperty";
        private const string propertyDefaultValue = "This is an example property.";

        internal ExampleProperty(IExplorerNode node)
        {
            this.node = node;
        }

        // Gets or sets a simple string property. 
        [DisplayName("ContosoExampleProperty")]
        [DescriptionAttribute("This is an example property for field nodes.")]
        [DefaultValue(propertyDefaultValue)]
        public string TestProperty
        {
            get
            {
                string propertyValue;

                // Get the current property value if it already exists; otherwise, return a default value.
                if (!node.Annotations.TryGetValue(propertyId, out propertyValue))
                {
                    propertyValue = propertyDefaultValue;
                }
                return propertyValue;
            }
            set
            {
                if (value != propertyDefaultValue)
                {
                    // Store the property value in the Annotations property of the node. 
                    // Data in the Annotations property does not persist when Visual Studio exits.
                    node.Annotations[propertyId] = value;
                }
                else
                {
                    // Do not save the default value.
                    node.Annotations.Remove(propertyId);
                }
            }
        }
    }

}

Это расширение добавляет для узлов редактируемое свойство строкового типа.Кроме того, можно создать настраиваемые свойства, отображающие полученные с сервера SharePoint данные, которые доступны только для чтения.Пример, в котором показано, как это сделать, см. в разделе Пошаговое руководство. Расширение обозревателя сервера, чтобы в нем отображались веб-части.

Компиляция кода

Для этого примера требуются ссылки на следующие сборки:

  • Microsoft.VisualStudio.SharePoint

  • Microsoft.VisualStudio.SharePoint.Explorer.Extensions

  • System.ComponentModel.Composition

  • System.Windows.Forms

Развертывание расширения

Чтобы развернуть расширение обозревателя сервера, создайте пакет расширения Visual Studio (VSIX) для сборки и всех остальных файлов, которые предположительно будут распространяться вместе с расширением.Дополнительные сведения см. в разделе Разработка расширений для средств SharePoint в Visual Studio.

См. также

Задачи

Пошаговое руководство. Расширение обозревателя сервера, чтобы в нем отображались веб-части

Основные понятия

Практическое руководство. Добавление в обозреватель сервера пользовательского узла SharePoint

Связь пользовательских данных с расширениями средств SharePoint

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

Расширение узла подключений SharePoint в обозревателе сервера