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


Интерфейс ICellProvider

Примечание. Этот API устарел.

Позволяет веб-части для взаимодействия с веб-частью, реализующий интерфейс ICellConsumer для работы с элементом одиночное значение.

Пространство имен:  Microsoft.SharePoint.WebPartPages.Communication
Сборка:  Microsoft.SharePoint (в Microsoft.SharePoint.dll)

Синтаксис

'Декларация
<ObsoleteAttribute("Use System.Web.UI.WebControls.WebParts.IWebPartField instead")> _
Public Interface ICellProvider
'Применение
Dim instance As ICellProvider
[ObsoleteAttribute("Use System.Web.UI.WebControls.WebParts.IWebPartField instead")]
public interface ICellProvider

Замечания

Интерфейс ICellProvider можно использовать с веб-части, чтобы передать одно значение ICellConsumer веб-части. Его можно использовать в сценариях, где веб-части потребителя был написан для обработки типа данных, передаваемых по веб-части поставщика. Интерфейс ICellProvider поддерживает возможность отправки и получения аргументов инициализации, что позволяет ICellProvider динамически изменять пользовательский интерфейс помогут соблюсти потребности потребителя части веб-части. Интерфейс ICellProvider может подключаться только к ICellConsumer интерфейс. При подключении к ICellConsumer веб-части ICellProvider веб-части, прямого подключения необходимо использовать, будет отображаться диалоговое окно не трансформатор.

Примеры

Который реализует интерфейс ICellProvider и поддерживает выполнение его кода подключения только на сервере (ConnectionRunAt.Server). Эта веб-часть может подключаться к один или несколько веб-части, которые реализуют интерфейс ICellConsumer на сервере. Эта веб-часть пользовательского интерфейса отображает простое текстовое поле и кнопку. При нажатии кнопки веб-частей передает значение «ячейки» в его текстовом поле все веб-части, которые подключены к ней.

Соединяемой веб-части. Эти шаги являются номерами и комментарии в примере кода.

Который реализует интерфейс ICellProvider и поддерживает выполнение его кода подключения только на стороне клиента (ConnectionRunAt.Client). Эта веб-часть может подключаться к один или несколько веб-части, которые реализуют интерфейс ICellConsumer на стороне клиента. Эта веб-часть пользовательского интерфейса отображает простое текстовое поле и кнопку. При нажатии кнопки веб-частей передает значение «ячейки» в его текстовом поле все веб-части, которые подключены к ней.

Соединяемой веб-части. Эти шаги являются номерами и комментарии в примере кода.

Обзор Создание соединяемой веб-части Creating a Connectable Web Partсм.

' Common .NET required namespaces
Imports System
Imports System.ComponentModel
Imports System.Web.UI

' Web Part required namespaces
Imports Microsoft.SharePoint.WebPartPages
Imports System.Xml.Serialization
Imports System.Web.UI.WebControls

' Code Access Security namespaces
Imports System.Security
Imports Microsoft.SharePoint.Utilities

' Step #1: Make a reference to the Communication namespace
Imports Microsoft.SharePoint.WebPartPages.Communication

Namespace ConnectionCodeSamples
   ' Step #2: Inherit from the WebPart base class and implement 
   ' the ICellProvider interface.
   
   Public Class ServerSideCellProvider
      Inherits WebPart
      Implements ICellProvider
      
      ' Step #3: Declare the ICellProvider events.
      ' Because this class implements the ICellProvider interface, 
      ' it must 
      ' implement the interface member events CellProviderInit and 
      ' CellReady.
      Public Event CellProviderInit As CellProviderInitEventHandler 
         Implements ICellProvider.CellProviderInit
      Public Event CellReady As CellReadyEventHandler Implements 
         ICellProvider.CellReady
      
      ' Declare variables for keeping track of the connection state.
      Private _connected As Boolean = False
      Private _connectedWebPartTitle As String = String.Empty
      Private _connectedField As String = String.Empty
      Private _registrationErrorMsg As String = "An error has occurred 
         trying to register your connection interfaces."
      Private _registrationErrorOccurred As Boolean = False
      Private _notConnectedMsg As String = "NOT CONNECTED. To use this 
         Web Part, connect it to a server-side Cell Consumer Web Part."
      
      ' Declare variables for cell field names.
      Private _cellName As String = "ProvideCell"
      Private _cellDisplayName As String = "Provide Cell"
      
      ' Declare variables for the Web Part user interface.
      Private _cellButton As Button
      Private _cellInput As TextBox
      Private _connectedWebPartLabel As String = "Connected to Web 
         Part"
      Private _connectedFieldLabel As String = "Send to Field"
      Private _cellClicked As Boolean = False
       'Keep track of whether button is clicked
 
     ' Step #4: Override the EnsureInterfaces() method and call the 
     ' RegisterInterface method.
      Public Overrides Sub EnsureInterfaces()
         ' If your Web Part is installed in the bin directory and the 
         ' Code Access Security (CAS) setting doesn't 
         ' allow Web Part Connections, an exception will be thrown. To 
         ' allow your Web Part to behave 
         ' well and continue working, a try/catch block should be used 
         ' when attempting to register interfaces.
         ' Web Part Connections will only work if the level attribute 
         ' of the <trust> tag in the web.config file is set to 
         ' WSS_Minimal, WSS_Medium, or Full. By default a new 
         ' SharePoint site is installed with the trust level set to 
         ' WSS_Minimal.
         Try
            ' Register the ICellProvider Interface
            ' <param name="interfaceName">Friendly name of the 
            ' interface that is being implemented.
            ' It must be unique on the client so the _WPQ_ token is 
            ' used.</param>
            ' <param name="interfaceType">Specifies which interface is 
            ' being implemented.</param>
            ' <param name="maxConnections">Defines how many times this 
            ' interface can be connected.</param>
            ' <param name="runAtOptions">Determines where the interface 
            ' can run.</param>
            ' <param name="interfaceObject">Reference to the object 
            ' that is implementing this interface.</param>
            ' <param name="interfaceClientReference">Name used to 
            ' reference the interface on the client. 
            ' It must be unique on the client so the _WPQ_ token is 
            ' used.</param>
            ' <param name="menuLabel">Label for the interface that 
            ' appears in the UI</param>
            ' <param name="description">Description of the interface 
            ' that appears in the UI</param>
            ' <param name="allowCrossPageConnection">Specifies if the 
            ' interface can connect to a Web Part on a different page. 
            ' This is an optional parameter with a default of false. 
            ' Note that only some server side interfaces are allowed to 
            ' connect across pages by the Web Part Infrastructure. 
            ' The ICellProvider interface is not allowed to connect 
            ' across pages.</param>
            RegisterInterface("MyCellProviderInterface_WPQ_", 
               InterfaceTypes.ICellProvider, WebPart.UnlimitedConnections, 
               ConnectionRunAt.Server, Me, "CellProviderInterface_WPQ_", 
               "Provide Cell To", "Provides a single value to a cell 
               consumer Web Part.") 

         Catch se As SecurityException
            _registrationErrorOccurred = True
         End Try
      End Sub
      
      ' Step #6: Override the CanRunAt() method.
      ' The CanRunAt method is called by the Web Part infrastructure 
      ' during the ASP.NET PreRender event to determine where the Web 
      ' Part can run based on its current configuration.
      Public Overrides Function CanRunAt() As ConnectionRunAt
         'This Web Part can run on the server.
         Return ConnectionRunAt.Server
      End Function
      
      ' Step #7: Override the PartCommunicationConnect() method.
      ' The PartCommunicationConnect method is called by the Web Part 
      ' infrastructure to notify the Web Part that it
      ' is connected during the ASP.NET PreRender event. Relevant 
      ' information is passed to the part such as 
      ' the interface it is connected over, the Web Part it is being 
      ' connected to, and where the part will be running, 
      ' either client or server side. 
      ' <param name="interfaceName">Friendly name of the interface that 
      ' is being connected</param>
      ' <param name="connectedPart">Reference to the other Web Part 
      ' that is being connected to</param>
      ' <param name="connectedInterfaceName">Friendly name of the 
      ' interface on the other Web Part</param>
      ' <param name="runAt">Where the interface should execute</param>
      Public Overrides Sub PartCommunicationConnect(interfaceName As 
         String, connectedPart As WebPart, connectedInterfaceName As 
         String, runAt As ConnectionRunAt)
         ' Keep track of whether the Web Part is connected or not.
         If interfaceName = "MyCellProviderInterface_WPQ_" Then
            _connected = True
            _connectedWebPartTitle = SPEncode.HtmlEncode(connectedPart.Title)
         End If
      End Sub
      
      ' Step #8: Implement the CellConsumerInit event handler.
      ' The connected consumer part(s) will call this method during its 
      ' PartCommunicationInit phase
      ' to pass initialization information to this provider Web Part.
      ' <param name="sender">Reference to the Consumer Web Part</param>
      ' <param name="cellConsumerInitEventArgs">The argument data 
      ' structure passed by the Consumer Web Part</param>
      Public Sub CellConsumerInit(sender As Object, 
         cellConsumerInitEventArgs As CellConsumerInitEventArgs) 
         Implements ICellProvider.CellConsumerInit
         'Encode and store the field display name.
         _connectedField = SPEncode.HtmlEncode(cellConsumerInitEventArgs.FieldDisplayName)
      End Sub
      
      ' Step #9: Override the PartCommunicationInit() method
      ' PartCommunicationInit() is called by the Web Part 
      ' infrastructure during the ASP.NET PreRender 
      ' event to allow the part to pass initialization information to 
      ' the other connected parts.
      ' It is important to always pass initialization information as 
      ' some parts may not behave properly if this initialization 
      ' information is not received.
      Public Overrides Sub PartCommunicationInit()
        ' Check if connected
         If _connected Then 
           ' Create the InitEventArgs structure for the 
           ' CellProviderInit event.
            Dim cellProviderInitArgs As New CellProviderInitEventArgs()

            ' Set the FieldName and FieldDisplay values.
             cellProviderInitArgs.FieldName = _cellName
             cellProviderInitArgs.FieldDisplayName = _cellDisplayName

            ' Fire the CellProviderInit event. 
            RaiseEvent CellProviderInit(Me, cellProviderInitArgs)

          End If
      End Sub
      
      ' Step #10: Override the PartCommunicationMain() method.
      ' The PartCommunicationMain method is called by the Web Part 
      ' infrastructure on the client during 
      ' the ASP.NET PreRender event to allow the part to pass its 
      ' primary data to the other connected parts.
      ' It is important to always fire the CellReady event. Some parts
      ' may not behave properly if they are left waiting for this 
      ' information.
      Public Overrides Sub PartCommunicationMain()
            ' Check if connected.
            If _connected Then
                ' Create the CellReadyEventArgs data structure for the 
                ' CellProviderInit event.
                Dim cellReadyArgs As New CellReadyEventArgs()

                ' If the user clicked the button, then send the value.
                If _cellClicked Then
                    ' Set the cell to the value of the TextBox text
                    ' This is the value that will be sent to the 
                    ' Consumer
                    cellReadyArgs.Cell = _cellInput.Text
                Else
                    ' The user didn't actually click the button
                    ' so just send an empty string to the consumer.
                    cellReadyArgs.Cell = ""
                End If

                ' Fire the CellReady event.
                ' The Consumer will receive the cell value in its 
                ' CellReady event handler
                RaiseEvent CellReady(Me, cellReadyArgs)
            End If
        End Sub
      
      Protected Overrides Sub RenderWebPart(output As HtmlTextWriter)
         
         ' Check for connection interface registration error.
         If _registrationErrorOccurred Then
            output.Write(_registrationErrorMsg)
            Return
         End If
         
         ' Ensure that all of the Web Part's controls are created
         EnsureChildControls()
         
         ' Render HTML and controls if connected
         If _connected Then
            ' Render the cell label.
            output.RenderBeginTag(HtmlTextWriterTag.B)
            output.Write((_cellDisplayName + ": "))
            output.RenderEndTag()
            
            ' Render the TextBox control.
            _cellInput.RenderControl(output)
            
            ' Render the Button control.
            _cellButton.RenderControl(output)
            
            ' Line Break
            output.RenderBeginTag(HtmlTextWriterTag.Br)
            output.RenderEndTag()
            
            ' Render the connected Web Part's title.
            output.Write((_connectedWebPartLabel + ": "))
            output.RenderBeginTag(HtmlTextWriterTag.I)
            output.Write(_connectedWebPartTitle)
            output.RenderEndTag()
            output.Write("<br>")
            
            ' Render the connected Web Part's field name.
            output.Write((_connectedFieldLabel + ": "))
            output.RenderBeginTag(HtmlTextWriterTag.I)
            output.Write(_connectedField)
            output.RenderEndTag()
         
         Else
            ' The Web Part isn't connected
            output.Write(_notConnectedMsg)
         End If
      End Sub
      
      ' Override the CreateChildControls method to create the
      ' Web Part's user interface controls.
      Protected Overrides Sub CreateChildControls()
         ' Create the Button.
         _cellButton = New Button()
         _cellButton.ID = "CellButton"
         _cellButton.Text = "Fire CellReady"
         Controls.Add(_cellButton)
         
         ' Create the TextBox.
         _cellInput = New TextBox()
         _cellInput.ID = "CellInput"
         Controls.Add(_cellInput)
         
         ' Initialize to false -- user hasn't clicked the button yet
         _cellClicked = False
         
         ' Listen for the cell button's Click event.
         AddHandler _cellButton.Click, AddressOf CellButtonClicked
      End Sub
      
      
      ' Handle the cell button's Click event.
      Private Sub CellButtonClicked(sender As Object, e As EventArgs)
         ' User clicked button, set to true
         _cellClicked = True
      End Sub
   End Class
End Namespace
// Common .NET required namespaces
using System;
using System.ComponentModel;
using System.Web.UI;

// Web Part required namespaces
using Microsoft.SharePoint.WebPartPages;
using System.Xml.Serialization;
using System.Web.UI.WebControls;

// Code Access Security namespaces
using System.Security;
using Microsoft.SharePoint.Utilities;

// Step #1: Make a reference to the Communication namespace
using Microsoft.SharePoint.WebPartPages.Communication;

namespace ConnectionCodeSamples
{
    // Step #2: Inherit from the WebPart base class and implement 
    // the ICellProvider interface.
    public class ServerSideCellProvider : WebPart, ICellProvider
    {    
        
        // Step #3: Declare the ICellProvider events.
        // Because this class implements the ICellProvider interface, 
        // it must 
        // implement the interface member events CellProviderInit and 
        // CellReady.
        public event CellProviderInitEventHandler CellProviderInit;    
        public event CellReadyEventHandler CellReady;                

        // Declare variables for keeping track of the connection state.
        private bool _connected = false;
        private string _connectedWebPartTitle = string.Empty;
        private string _connectedField = string.Empty;
        private string _registrationErrorMsg = "An error has occurred 
           trying to register your connection interfaces.";
        private bool _registrationErrorOccurred = false;
        private string _notConnectedMsg = "NOT CONNECTED. To use this 
           Web Part, connect it to a server-side Cell Consumer Web 
           Part.";

        // Declare variables for cell field names.
        private string _cellName = "ProvideCell";
        private string _cellDisplayName = "Provide Cell";

        // Declare variables for the Web Part user interface.
        private Button _cellButton;    
        private TextBox _cellInput;
        private string _connectedWebPartLabel = "Connected to Web 
           Part";
        private string _connectedFieldLabel = "Send to Field";
        private bool _cellClicked = false;  //keep track of whether button is clicked
        
        // Step #4: Override the EnsureInterfaces() method and call the 
        // RegisterInterface method.
        public override void EnsureInterfaces()
        {
            // If your Web Part is installed in the bin directory and 
            // the Code Access Security (CAS) setting doesn't 
            // allow Web Part Connections, an exception will be thrown. 
            // To allow your Web Part to behave 
            // well and continue working, a try/catch block should be 
            // used when attempting to register interfaces.
            // Web Part Connections will only work if the level 
            // attribute of the <trust> tag in the 
            // web.config file is set to WSS_Minimal, WSS_Medium, or 
            // Full. By default a new SharePoint site
            // is installed with the trust level set to WSS_Minimal.
            try
            {
                // Register the ICellProvider Interface
                // <param name="interfaceName">Friendly name of the 
                // interface that is being implemented.
                // It must be unique on the client so the _WPQ_ token 
                // is used.</param>
                // <param name="interfaceType">Specifies which 
                // interface is being implemented.</param>
                // <param name="maxConnections">Defines how many times 
                // this interface can be connected.</param>
                // <param name="runAtOptions">Determines where the 
                // interface can run.</param>
                // <param name="interfaceObject">Reference to the 
                // object that is implementing this interface.</param>
                // <param name="interfaceClientReference">Name used to 
                // reference the interface on the client. 
                // It must be unique on the client so the _WPQ_ token 
                // is used.</param>
                // <param name="menuLabel">Label for the interface 
                // that appears in the UI</param>
                // <param name="description">Description of the 
                // interface that appears in the UI</param>
                // <param name="allowCrossPageConnection">Specifies if 
                // the interface can connect to a Web Part
                // on a different page. This is an optional parameter 
                // with a default of false. Note that only some 
                // server side interfaces are allowed to connect across 
                // pages by the Web Part Infrastructure. 
                // The ICellProvider interface is not allowed to 
                // connect across pages.</param>
                RegisterInterface("MyCellProviderInterface_WPQ_",            //InterfaceName    
                    InterfaceTypes.ICellProvider,                            //InterfaceType
                    WebPart.UnlimitedConnections,                            //MaxConnections
                    ConnectionRunAt.Server,                                  //RunAtOptions
                    this,                                                    //InterfaceObject
                    "CellProviderInterface_WPQ_",                            //InterfaceClientReference
                    "Provide Cell To",                                       //MenuLabel
                    "Provides a single value to a cell consumer Web Part."); //Description
            }
            catch(SecurityException se)
            {
                _registrationErrorOccurred = true;
            }
        }

        // Step #6: Override the CanRunAt() method.
        // The CanRunAt method is called by the Web Part infrastructure 
        // during the ASP.NET PreRender event
        // to determine where the Web Part can run based on its current 
        // configuration.
        public override ConnectionRunAt CanRunAt()
        {
            //This Web Part can run on the server.
            return ConnectionRunAt.Server;
        }

        // Step #7: Override the PartCommunicationConnect() method.
        // The PartCommunicationConnect method is called by the Web 
        // Part infrastructure to notify the Web Part that it
        // is connected during the ASP.NET PreRender event. Relevant 
        // information is passed to the part such as 
        // the interface it is connected over, the Web Part it is being 
        // connected to, and where the part will be running, 
        // either client or server side. 
        // <param name="interfaceName">Friendly name of the interface 
        // that is being connected</param>
        // <param name="connectedPart">Reference to the other Web Part 
        // that is being connected to</param>
        // <param name="connectedInterfaceName">Friendly name of the 
        // interface on the other Web Part</param>
        // <param name="runAt">Where the interface should 
        // execute</param>
        public override void PartCommunicationConnect(
            string interfaceName,
            WebPart connectedPart,
            string connectedInterfaceName,
            ConnectionRunAt runAt)
        {
            // Keep track of whether the Web Part is connected or not.
            if (interfaceName == "MyCellProviderInterface_WPQ_")
            {
                _connected = true;
                _connectedWebPartTitle = 
                   SPEncode.HtmlEncode(connectedPart.Title);
            }
        }

        // Step #8: Implement the CellConsumerInit event handler.
        // The connected consumer part(s) will call this method during 
        // its PartCommunicationInit phase
        // to pass initialization information to this provider Web 
        // Part.
        // <param name="sender">Reference to the Consumer Web 
        // Part</param>
        // <param name="cellConsumerInitEventArgs">The argument data 
        // structure passed by the Consumer Web Part</param>
        public void CellConsumerInit(object sender, 
           CellConsumerInitEventArgs cellConsumerInitEventArgs)
        {
            //Encode and store the field display name.
            _connectedField = SPEncode.HtmlEncode(cellConsumerInitEventArgs.FieldDisplayName);

        }

        // Step #9: Override the PartCommunicationInit() method
        // PartCommunicationInit() is called by the Web Part 
        // infrastructure during the ASP.NET PreRender 
        // event to allow the part to pass initialization information 
        // to the other connected parts.
        // It is important to always pass initialization information as 
        // some parts
        // may not behave properly if this initialization information 
        // is not received.
        public override void PartCommunicationInit()
        {
            // Check if connected
            if(_connected)
            {
                // If there is a listener, fire the CellProviderInit 
                // event.
                if (CellProviderInit != null)
                {
                    // Create the InitEventArgs structure for the 
                    // CellProviderInit event.
                    CellProviderInitEventArgs cellProviderInitArgs = 
                       new CellProviderInitEventArgs();
                    
                    // Set the FieldName and FieldDisplay values.
                    cellProviderInitArgs.FieldName = _cellName;
                    cellProviderInitArgs.FieldDisplayName = 
                      _cellDisplayName;
                    
                    // Fire the CellProviderInit event.
                    CellProviderInit(this, cellProviderInitArgs);
                }
            }
        }

        // Step #10: Override the PartCommunicationMain() method.
        // The PartCommunicationMain method is called by the Web Part 
        // infrastructure on the client during 
        // the ASP.NET PreRender event to allow the part to pass its 
        // primary data to the other connected parts.
        // It is important to always fire the CellReady event. Some 
        // parts may not behave properly if they are left waiting for 
        // this information.
        public override void PartCommunicationMain()
        {
            // Check if connected.
            if(_connected)
            {
                // If there is a listener, fire the CellReady event.
                if (CellReady != null)
                {
                    // Create the CellReadyEventArgs data structure for 
                    // the CellProviderInit event.
                    CellReadyEventArgs cellReadyArgs = new 
                       CellReadyEventArgs();

                    // If the user clicked the button, then send the 
                    // value.
                    if (_cellClicked)
                    {
                        // Set the cell to the value of the TextBox 
                        // text.
                        // This is the value that will be sent to the 
                        // Consumer
                        cellReadyArgs.Cell = _cellInput.Text;
                    }
                    else
                    {
                        // The user didn't actually click the button
                        // so just send an empty string to the 
                        // consumer.
                        cellReadyArgs.Cell = "";
                    }

                    // Fire the CellReady event.
                    // The Consumer will receive the cell value in its 
                    // CellReady event handler
                    CellReady(this, cellReadyArgs);
                }
            }
        }

        protected override void RenderWebPart(HtmlTextWriter output)
        {
        
            // Check for connection interface registration error.
            if (_registrationErrorOccurred)
            {
                output.Write(_registrationErrorMsg);
                return;
            }

            // Ensure that all of the Web Part's controls are created
            EnsureChildControls();

            // Render HTML and controls if connected
            if(_connected)
            {
                // Render the cell label.
                output.RenderBeginTag(HtmlTextWriterTag.B);
                output.Write(_cellDisplayName + ": ");
                output.RenderEndTag();

                // Render the TextBox control.
                _cellInput.RenderControl(output);

                // Render the Button control.
                _cellButton.RenderControl(output);
                
                // Line Break
                output.RenderBeginTag(HtmlTextWriterTag.Br);
                output.RenderEndTag();

                // Render the connected Web Part's title.
                output.Write(_connectedWebPartLabel + ": ");
                output.RenderBeginTag(HtmlTextWriterTag.I);
                output.Write(_connectedWebPartTitle);
                output.RenderEndTag();
                output.Write("<br>");

                // Render the connected Web Part's field name.
                output.Write(_connectedFieldLabel + ": ");
                output.RenderBeginTag(HtmlTextWriterTag.I);
                output.Write(_connectedField);
                output.RenderEndTag();

            }
            else
            {
                // The Web Part isn't connected
                output.Write(_notConnectedMsg);
            }
        }

        // Override the CreateChildControls method to create the
        // Web Part's user interface controls.
        protected override void CreateChildControls()
        {
            // Create the Button.
            _cellButton = new Button();
            _cellButton.ID = "CellButton";
            _cellButton.Text = "Fire CellReady";
            Controls.Add(_cellButton);
        
            // Create the TextBox.
            _cellInput = new TextBox();
            _cellInput.ID = "CellInput";
            Controls.Add(_cellInput);

            // Initialize to false -- user hasn't clicked the 
            // button yet
            _cellClicked = false; 

            // Listen for the cell button's Click event.
            _cellButton.Click += new EventHandler(CellButtonClicked);
        }

        // Handle the cell button's Click event.
        private void CellButtonClicked(object sender, EventArgs e)
        {
            // User clicked button, set to true
            _cellClicked = true; 
        }
    }
}
' Common .NET required namespaces.
Imports System
Imports System.ComponentModel
Imports System.Web.UI

' WebPart Required namespaces.
Imports Microsoft.SharePoint.WebPartPages
Imports System.Xml.Serialization
Imports System.Web.UI.WebControls

' Code Access Security namespaces.
Imports System.Security
Imports Microsoft.SharePoint.Utilities

'Step #1: Make a Reference to the Communication Namespace
Imports Microsoft.SharePoint.WebPartPages.Communication

Namespace ConnectionCodeSamples
   ' Step #2: Inherit from the WebPart base class and implement the 
   ' ICellProvider interface.
   
   Public Class ClientSideCellProvider
      Inherits WebPart
      Implements ICellProvider
      ' Step #3: Declare the ICellProvider events.
      ' Because this class implements the ICellProvider interface, it 
      ' must declare the interface member events CellProviderInit and 
      ' CellReady. However, because this is a client side Web Part the 
      ' actual code for these events will be implemented 
      ' on the client. See the myInit() and myMain() functions in 
      ' the JavaScript rendered to the client
      ' in the RenderWebPart method.
      Public Event CellProviderInit As CellProviderInitEventHandler 
         Implements ICellProvider.CellProviderInit
      Public Event CellReady As CellReadyEventHandler Implements 
         ICellProvider.CellReady
      
      ' Declare variables for keeping track of the connection state.
      Private _connected As Boolean = False
      Private _connectedWebPartTitle As String = String.Empty
      Private _registrationErrorMsg As String = "An error has occurred 
         trying to register your connection interfaces."
      Private _registrationErrorOccurred As Boolean = False
      Private _notConnectedMsg As String = "NOT CONNECTED. To use this 
         Web Part, connect it to a client-side Cell Consumer Web Part."
      
      ' Step #4: Override the EnsureInterfaces() method and call the 
      ' RegisterInterface method.
      Public Overrides Sub EnsureInterfaces()
         ' If your Web Part is installed in the bin directory and the 
         ' Code Access Security (CAS) setting doesn't 
         ' allow Web Part Connections, an exception will be thrown. To 
         ' allow your Web Part to behave 
         ' well and continue working, a try/catch block should be used 
         ' when attempting to register interfaces.
         ' Web Part Connections will only work if the level attribute 
         ' of the <trust> tag in the web.config file is set to 
         ' WSS_Minimal, WSS_Medium, or Full. By default a new 
         ' SharePoint site
         ' is installed with the trust level set to WSS_Minimal.
         Try
            ' Register the ICellProvider Interface
            ' <param name="interfaceName">Friendly name of the 
            ' interface that is being implemented.
            '    It must be unique on the client so the _WPQ_ token is 
            ' used.</param>
            ' <param name="interfaceType">Specifies which interface is 
            ' being implemented.</param>
            ' <param name="maxConnections">Defines how many times this 
            ' interface can be connected.</param>
            ' <param name="runAtOptions">Determines where the interface 
            ' can run.</param>
            ' <param name="interfaceObject">Reference to the object 
            ' that is implementing this interface.</param>
            ' <param name="interfaceClientReference">Name used to 
            ' reference the interface on the client. 
            ' It must be unique on the client so the _WPQ_ token is 
            ' used.</param>
            ' <param name="menuLabel">Label for the interface that 
            ' appears in the UI</param>
            ' <param name="description">Description of the interface 
            ' that appears in the UI</param>
            ' <param name="allowCrossPageConnection">Specifies if the 
            ' interface can connect to a Web Part
            ' on a different page. This is an optional parameter with a 
            ' default of false. Note that only some 
            ' server side interfaces are allowed to go cross page by 
            ' the Web Part Infrastructure. 
            ' The ICellProvider interface is not allowed to go cross 
            ' page.</param>
            RegisterInterface("MyCellProviderInterface_WPQ_", 
               InterfaceTypes.ICellProvider, 
               WebPart.UnlimitedConnections, ConnectionRunAt.Client, 
               Me, "CellProviderInterface_WPQ_", "Provide Cell To", 
               "Provides a single value to a cell consumer Web Part.")
         Catch se As SecurityException
            _registrationErrorOccurred = True
         End Try
      End Sub
      
      ' Step #6: Override the CanRunAt() method.
      ' The CanRunAt method is called by the Web Part infrastructure 
      ' during the ASP.NET PreRender event
      ' to determine where the Web Part can run based on its current 
      ' configuration.
      Public Overrides Function CanRunAt() As ConnectionRunAt
         ' This Web Part can run on the client.
         Return ConnectionRunAt.Client
      End Function
      
      ' Step #7: Override the PartCommunicationConnect() method.
      ' The PartCommunicationConnect method is called by the Web Part 
      ' infrastructure to notify the Web Part that it
      ' is connected during the ASP.NET PreRender event. Relevant 
      ' information is passed to the part such as 
      ' the interface it is connected over, the Web Part it is being 
      ' conected to, and where the part will be running, 
      ' either client or server side. 
      ' <param name="interfaceName">Friendly name of the interface that 
      ' is being connected</param>
      ' <param name="connectedPart">Reference to the other Web Part 
      ' that is being connected to</param>
      ' <param name="connectedInterfaceName">Friendly name of the 
      ' interface on the other Web Part</param>
      ' <param name="runAt">Where the interface should execute</param>
      Public Overrides Sub PartCommunicationConnect(interfaceName As 
         String, connectedPart As WebPart, connectedInterfaceName As 
         String, runAt As ConnectionRunAt)
         ' Keep track of whether the Web Part is connected or not.
         If interfaceName = "MyCellProviderInterface_WPQ_" Then
            _connected = True
            _connectedWebPartTitle = SPEncode.HtmlEncode(connectedPart.Title)
         End If
      End Sub
      
      ' Step #8: Implement the CellConsumerInit event handler.
      ' The connected consumer part(s) will call this method during its 
      ' PartCommunicationInit phase
      ' to pass initialization information to the provider Web Part.
      ' <param name="sender">Reference to the Consumer Web Part</param>
      ' <param name="cellConsumerInitEventArgs">The args passed by the 
      ' Consumer Web Part</param>
      Public Sub CellConsumerInit(sender As Object, 
         cellConsumerInitEventArgs As CellConsumerInitEventArgs) 
         Implements ICellProvider.CellConsumerInit
      End Sub
      
      ' Because this class implements the ICellProvider interface, it 
      ' must implement the interface member CellConsumerInit. However, 
      ' because this is a client-side Web Part, the actual code for 
      ' this method will be implemented on the client. See the 
      ' myCellConsumerInit() function in the JavaScript rendered to the 
      ' client in the RenderWebPart method.
      
      Protected Overrides Sub RenderWebPart(output As HtmlTextWriter)
         ' Check for connection interface registration error
         If _registrationErrorOccurred Then
            output.Write(_registrationErrorMsg)
            Return
         End If
         
         ' ************* CLIENT-SIDE CONNECTION CODE ***************
         ' Steps 9-11 are implemented in the following client code
         ' 
         ' Step #9: Implement PartCommunicationInit Function (see 
         ' myInit JavaScript Function)
         ' PartCommunicationInit() is called by the Web Part 
         ' infrastructure on the client
         ' to allow the part to pass initialization information to the other connected parts.
         ' It is important to always pass initialization information. 
         ' Some parts
         ' may not behave properly if this initialization information 
         ' is not received.
         ' 
         ' Step #10: Implement PartCommunicationMain Function (see 
         ' myMain JavaScript Function)
         ' PartCommunicationMain() is called by the Web Part 
         ' infrastructure on the client
         ' to allow the part to pass its primary data to the other 
         ' connected parts.
         ' It is important to always fire the CellReady event. Some 
         ' parts may not behave properly if they are left waiting for 
         ' this information.
          
         ' Step #11: Implement CellConsumerInit Function (see 
         ' myCellConsumerInit JavaScript Function)
         ' This is the client-side implementation of step #8.
         ' Render script if connected
         If _connected Then
            output.Write(ReplaceTokens( _
                "<P>" + ControlChars.Lf _
                + "   <B>Provide Cell: </B>" + ControlChars.Lf _
                + "   <INPUT TYPE=""text"" ID=""CellInput_WPQ_""/>" + 
                   ControlChars.Lf _
                + "   <INPUT TYPE=""button"" ID=""CellButton_WPQ_"" 
                   onclick=""CellButtonClick_WPQ_()"" VALUE=""Fire 
                   CellReady""/><br><br>" + ControlChars.Lf _
                + "   Connected to Web Part: <I>" + 
                _connectedWebPartTitle + "</I><br>" + ControlChars.Lf _
                + "   Send to Field: <I><span 
                   ID=""ConnectedField_WPQ_""></span></I>" + 
                   ControlChars.Lf _
                + "</P>" + ControlChars.Lf _
                + "<SCRIPT LANGUAGE=""JavaScript"">" + ControlChars.Lf _
                + "<!-- " + ControlChars.Lf _
                + "   var CellProviderInterface_WPQ_ = new 
                   Provider_WPQ_();" + ControlChars.Lf _
                + "   function Provider_WPQ_()" + ControlChars.Lf _
                + "   {" + ControlChars.Lf _
                + "      this.PartCommunicationInit = myInit;" + 
                   ControlChars.Lf _
                + "      this.PartCommunicationMain = myMain;" + 
                   ControlChars.Lf _
                + "      this.CellConsumerInit = myCellConsumerInit;" + 
                   ControlChars.Lf _
                + "      function myInit()" + ControlChars.Lf _
                + "      {" + ControlChars.Lf _
                + "         var cellProviderInitEventArgs = new 
                   Object();" + ControlChars.Lf _
                + "         cellProviderInitEventArgs.FieldName = 
                   ""ProvideCell"";" + ControlChars.Lf _
                + "         cellProviderInitEventArgs.FieldDisplayName 
                   = ""Provide Cell"";" + ControlChars.Lf _
                + "         WPSC.RaiseConnectionEvent(""MyCellProviderInterface_WPQ_"", 
   ""CellProviderInit"", cellProviderInitEventArgs);" + ControlChars.Lf _
                + "      }" + ControlChars.Lf _
                + "      function myMain()" + ControlChars.Lf _
                + "      {" + ControlChars.Lf _
                + "         var cellReadyEventArgs = new Object();" + 
                   ControlChars.Lf _
                + "         cellReadyEventArgs.Cell = null;" + 
                   ControlChars.Lf _
                + "         WPSC.RaiseConnectionEvent(""MyCellProviderInterface_WPQ_"", 
   ""CellReady"", cellReadyEventArgs);" + ControlChars.Lf _
                + "      }" + ControlChars.Lf _
                + "      function myCellConsumerInit(sender, 
                   cellConsumerInitEventArgs)" + ControlChars.Lf _
                + "      {" + ControlChars.Lf _
                + "         document.all(""ConnectedField_WPQ_"").innerText = cellConsumerInitEventArgs.FieldDisplayName;" + ControlChars.Lf _
                + "      }" + ControlChars.Lf _
                + "   }" + ControlChars.Lf _
                + "   function CellButtonClick_WPQ_()" + 
                   ControlChars.Lf _
                + "   {" + ControlChars.Lf _
                + "      var cellReadyEventArgs = new Object();" + 
                   ControlChars.Lf _
                + "      cellReadyEventArgs.Cell = 
                   document.all(""CellInput_WPQ_"").value;" + 
                   ControlChars.Lf _
                + "     WPSC.RaiseConnectionEvent(""MyCellProviderInterface_WPQ_"", ""CellReady"", cellReadyEventArgs);" _
                + ControlChars.Lf + "   }" + ControlChars.Lf _
                + "//-->" + ControlChars.Lf _
                + "</SCRIPT>" + ControlChars.Lf))
        
         Else
            ' The Web Part isn't connected.
            output.Write(_notConnectedMsg)
         End If
      End Sub
   End Class
End Namespace
// Common .NET required namespaces.
using System;
using System.ComponentModel;
using System.Web.UI;

// WebPart Required namespaces.
using Microsoft.SharePoint.WebPartPages;
using System.Xml.Serialization;
using System.Web.UI.WebControls;

// Code Access Security namespaces.
using System.Security;
using Microsoft.SharePoint.Utilities;

//Step #1: Make a Reference to the Communication Namespace
using Microsoft.SharePoint.WebPartPages.Communication;

namespace ConnectionCodeSamples
{
    // Step #2: Inherit from the WebPart base class and implement the 
    // ICellProvider interface.
    public class ClientSideCellProvider : WebPart, ICellProvider
    {    
        // Step #3: Declare the ICellProvider events.
        // Because this class implements the ICellProvider interface, 
        // it must declare the interface member events CellProviderInit 
        // and CellReady. However, because this is a client side Web 
        // Part the actual code for these events will be implemented 
        // on the client. See the myInit() and myMain() functions in 
        // the JavaScript rendered to the client
        // in the RenderWebPart method.
        public event CellProviderInitEventHandler CellProviderInit;
        public event CellReadyEventHandler CellReady;                

        // Declare variables for keeping track of the connection state.
        private bool _connected = false;
        private string _connectedWebPartTitle = string.Empty;
        private string _registrationErrorMsg = "An error has occurred 
           trying to register your connection interfaces.";
        private bool _registrationErrorOccurred = false;
        private string _notConnectedMsg = "NOT CONNECTED. To use this 
           Web Part, connect it to a client-side Cell Consumer Web 
           Part.";
        
        // Step #4: Override the EnsureInterfaces() method and call the 
        // RegisterInterface method.
        public override void EnsureInterfaces()
        {
            // If your Web Part is installed in the bin directory and 
            // the Code Access Security (CAS) setting doesn't 
            // allow Web Part Connections, an exception will be thrown. 
            // To allow your Web Part to behave 
            // well and continue working, a try/catch block should be 
            // used when attempting to register interfaces.
            // Web Part Connections will only work if the level 
            // attribute of the <trust> tag in the 
            // web.config file is set to WSS_Minimal, WSS_Medium, or 
            // Full. By default a new SharePoint site
            // is installed with the trust level set to WSS_Minimal.
            try
            {
                // Register the ICellProvider Interface
                // <param name="interfaceName">Friendly name of the 
                // interface that is being implemented.
                //    It must be unique on the client so the _WPQ_ 
                // token is used.</param>
                // <param name="interfaceType">Specifies which 
                // interface is being implemented.</param>
                // <param name="maxConnections">Defines how many times 
                // this interface can be connected.</param>
                // <param name="runAtOptions">Determines where the 
                // interface can run.</param>
                // <param name="interfaceObject">Reference to the 
                // object that is implementing this interface.</param>
                // <param name="interfaceClientReference">Name used to 
                // reference the interface on the client. 
                // It must be unique on the client so the _WPQ_ token 
                // is used.</param>
                // <param name="menuLabel">Label for the interface 
                // that appears in the UI</param>
                // <param name="description">Description of the 
                // interface that appears in the UI</param>
                // <param name="allowCrossPageConnection">Specifies if 
                // the interface can connect to a Web Part
                // on a different page. This is an optional parameter 
                // with a default of false. Note that only some 
                // server side interfaces are allowed to go cross page 
                // by the Web Part Infrastructure. 
                // The ICellProvider interface is not allowed to go 
                // cross page.</param>
                RegisterInterface("MyCellProviderInterface_WPQ_",            //InterfaceName    
                    InterfaceTypes.ICellProvider,                            //InterfaceType
                    WebPart.UnlimitedConnections,                            //MaxConnections
                    ConnectionRunAt.Client,                                  //RunAtOptions
                    this,                                                    //InterfaceObject
                    "CellProviderInterface_WPQ_",                            //InterfaceClientReference
                    "Provide Cell To",                                       //MenuLabel
                    "Provides a single value to a cell consumer Web Part."); //Description
            }
            catch(SecurityException se)
            {
                _registrationErrorOccurred = true;
            }
        }

        // Step #6: Override the CanRunAt() method.
        // The CanRunAt method is called by the Web Part infrastructure 
        // during the ASP.NET PreRender event
        // to determine where the Web Part can run based on its current 
        // configuration.
        public override ConnectionRunAt CanRunAt()
        {
            // This Web Part can run on the client.
            return ConnectionRunAt.Client;
        }

        // Step #7: Override the PartCommunicationConnect() method.
        // The PartCommunicationConnect method is called by the Web 
        // Part infrastructure to notify the Web Part that it
        // is connected during the ASP.NET PreRender event. Relevant 
        // information is passed to the part such as 
        // the interface it is connected over, the Web Part it is being 
        // conected to, and where the part will be running, 
        // either client or server side. 
        // <param name="interfaceName">Friendly name of the interface 
        // that is being connected</param>
        // <param name="connectedPart">Reference to the other Web Part 
        // that is being connected to</param>
        // <param name="connectedInterfaceName">Friendly name of the 
        // interface on the other Web Part</param>
        // <param name="runAt">Where the interface should 
        // execute</param>
        public override void PartCommunicationConnect(
            string interfaceName,
            WebPart connectedPart,
            string connectedInterfaceName,
            ConnectionRunAt runAt)
        {
            // Keep track of whether the Web Part is connected or not.
            if (interfaceName == "MyCellProviderInterface_WPQ_")
            {
                _connected = true;
                _connectedWebPartTitle = SPEncode.HtmlEncode(connectedPart.Title);
            }
        }

        // Step #8: Implement the CellConsumerInit event handler.
        // The connected consumer part(s) will call this method during 
        // its PartCommunicationInit phase
        // to pass initialization information to the provider Web Part.
        // <param name="sender">Reference to the Consumer Web 
        // Part</param>
        // <param name="cellConsumerInitEventArgs">The args passed by 
        // the Consumer Web Part</param>
        public void CellConsumerInit(object sender, CellConsumerInitEventArgs cellConsumerInitEventArgs)
        {
            // Because this class implements the ICellProvider 
            // interface, it must 
            // implement the interface member CellConsumerInit. 
            // However, because this is a client-side 
            // Web Part, the actual code for this method will be 
            // implemented on the client. See the 
            // myCellConsumerInit() function in the JavaScript rendered 
            // to the client in the RenderWebPart method.
        }

        protected override void RenderWebPart(HtmlTextWriter output)
        {
            // Check for connection interface registration error
            if (_registrationErrorOccurred)
            {
                output.Write(_registrationErrorMsg);
                return;
            }

            // ************* CLIENT-SIDE CONNECTION CODE 
            // ***************
            // Steps 9-11 are implemented in the following client code
            // 
            // Step #9: Implement PartCommunicationInit Function (see 
            // myInit JavaScript Function)
            // PartCommunicationInit() is called by the Web Part 
            // infrastructure on the client
            // to allow the part to pass initialization information to 
            // the other connected parts.
            // It is important to always pass initialization 
            // information. Some parts
            // may not behave properly if this initialization 
            // information is not received.
            // 
            // Step #10: Implement PartCommunicationMain Function (see 
            // myMain JavaScript Function)
            // PartCommunicationMain() is called by the Web Part 
            // infrastructure on the client
            // to allow the part to pass its primary data to the other 
            // connected parts.
            // It is important to always fire the CellReady event. Some 
            // parts may not behave properly if they are left waiting 
            // for this information.
            // 
            // Step #11: Implement CellConsumerInit Function (see 
            // myCellConsumerInit JavaScript Function)
            // This is the client-side implementation of step #8.

            // Render script if connected
            if(_connected)
            {
                output.Write(ReplaceTokens(
                    "<P>\n"
                    + "   <B>Provide Cell: </B>\n"
                    + "   <INPUT TYPE=\"text\" ID=\"CellInput_WPQ_\"/>\n"
                    + "   <INPUT TYPE=\"button\" ID=\"CellButton_WPQ_\" 
                       onclick=\"CellButtonClick_WPQ_()\" VALUE=\"Fire 
                       CellReady\"/><br><br>\n"
                    + "   Connected to Web Part: <I>" + 
                        _connectedWebPartTitle + "</I><br>\n"
                    + "   Send to Field: <I><span 
                       ID=\"ConnectedField_WPQ_\"></span></I>\n"
                    + "</P>\n"

                    + "<SCRIPT LANGUAGE=\"JavaScript\">\n"
                    + "<!-- \n"
                    + "   var CellProviderInterface_WPQ_ = new 
                       Provider_WPQ_();\n"

                    + "   function Provider_WPQ_()\n"
                    + "   {\n"                    
                    + "      this.PartCommunicationInit = myInit;\n"
                    + "      this.PartCommunicationMain = myMain;\n"
                    + "      this.CellConsumerInit = 
                       myCellConsumerInit;\n"

                    + "      function myInit()\n"
                    + "      {\n"
                    + "         var cellProviderInitEventArgs = new 
                       Object();\n"
                    + "         cellProviderInitEventArgs.FieldName = 
                       \"ProvideCell\";\n"
                    + "         
                       cellProviderInitEventArgs.FieldDisplayName = 
                       \"Provide Cell\";\n"

                    + "         WPSC.RaiseConnectionEvent(\"MyCellProviderInterface_WPQ_\", \"CellProviderInit\", cellProviderInitEventArgs);\n"
                    + "      }\n"

                    + "      function myMain()\n"
                    + "      {\n"
                    + "         var cellReadyEventArgs = new 
                       Object();\n"
                    + "         cellReadyEventArgs.Cell = null;\n"

                    + "         WPSC.RaiseConnectionEvent(\"MyCellProviderInterface_WPQ_\", \"CellReady\", cellReadyEventArgs);\n"
                    + "      }\n"

                    + "      function myCellConsumerInit(sender, cellConsumerInitEventArgs)\n"
                    + "      {\n"
                    + "         document.all(\"ConnectedField_WPQ_\").innerText = 
   cellConsumerInitEventArgs.FieldDisplayName;\n"
                    + "      }\n"
                    + "   }\n"

                    + "   function CellButtonClick_WPQ_()\n"
                    + "   {\n"
                    + "      var cellReadyEventArgs = new Object();\n"
                    + "      cellReadyEventArgs.Cell = 
                       document.all(\"CellInput_WPQ_\").value;\n"

                    + "     WPSC.RaiseConnectionEvent(\"MyCellProviderInterface_WPQ_\", \"CellReady\", cellReadyEventArgs);\n"
                    + "   }\n"
                    + "//-->\n"
                    + "</SCRIPT>\n"));
            }
            else
            {
                // The Web Part isn't connected.
                output.Write(_notConnectedMsg);
            }

        }
    }
}

См. также

Справочные материалы

Элементы ICellProvider

Пространство имен Microsoft.SharePoint.WebPartPages.Communication