Интерфейс IParametersOutConsumer
Примечание. Этот API устарел.
Реализует интерфейс IParametersOutProvider для связи свой список параметров для реализации этого интерфейса веб-части потребителя. Эти интерфейсы позволяют также передача через другие сведения, например выбранной строки.
Пространство имен: Microsoft.SharePoint.WebPartPages.Communication
Сборка: Microsoft.SharePoint (в Microsoft.SharePoint.dll)
Синтаксис
'Декларация
<ObsoleteAttribute("Use System.Web.UI.WebControls.WebParts.IWebPartParameters instead")> _
Public Interface IParametersOutConsumer
'Применение
Dim instance As IParametersOutConsumer
[ObsoleteAttribute("Use System.Web.UI.WebControls.WebParts.IWebPartParameters instead")]
public interface IParametersOutConsumer
Замечания
Должен быть реализован интерфейс IParametersOutConsumer для веб-части, необходимо использовать общие коллекции параметров. Его можно использовать в сценариях, где часть потребителя разработана осознавая отправляемых поставщиком данных. Кроме того веб-частей, который реализует интерфейс IParametersOutConsumer имеет возможность получения аргументов инициализации из части поставщика. Интерфейс IParametersOutConsumer может подключаться только с помощью интерфейса IParametersOutProvider . Это прямое подключение не трансформатор диалоговое окно отображается при подключении этих интерфейсов. Таким образом часть потребителя необходимо правильно сопоставить входящие параметры из части поставщика.
Интерфейсы IParametersOutConsumer и IParametersOutProvider позволяют передать дополнительную информацию, например выбранной строки. Например когда пользователь щелкает строку в списке, данные строки, а также параметры могут передаваться через эти интерфейсы.
Примеры
В следующем примере кода показан простой серверных IParametersOutConsumer веб-части. Он может быть подключен другой веб-части, который реализует интерфейс IParametersOutProvider на сервере. Эта веб-часть отображает абзац текста. Можно задать атрибуты стиля текста, например шрифт, цвет, вес и размер с помощью веб-частей, который реализует интерфейс IParametersOutProvider .
8 действия относятся к тому, что данная соединяемой веб-части. Эти шаги будут пронумерованы и комментария в следующем примере кода.
Обзор шагов в создании соединяемой веб-части 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: Reference the Communication namespace.
Imports Microsoft.SharePoint.WebPartPages.Communication
Namespace ConnectionCodeSamples
'Step #2: Inherit from the WebPart base class and implement the
'IParametersOutConsumer interface.
Public Class ServerSideParametersOutConsumer
Inherits WebPart
Implements IParametersOutConsumer
' Declare variables for keeping track of 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 set the text style of this Web Part connect it to an appropriate Parameters Out Provider Web Part."
' Declare variables for Web Part user interface.
Private _connectedWebPartLabel As String = "Connected to Web Part"
Private _webPartDescription As String
Private _fontFamily As String = String.Empty
Private _fontColor As String = String.Empty
Private _fontWeight As String = String.Empty
Private _fontSize As String = String.Empty
Private _parametersOutProviderInitEventArgs As ParametersOutProviderInitEventArgs
Private _parametersOutReadyFlag As Boolean = False
Private _noParametersOutFlag As Boolean = False
' Constructor
Public Sub New()
' Set Web Part Description
_webPartDescription = "This is an example of a IParametersOutConsumer Web Part. The following "
_webPartDescription += "text style attributes can be set when passed as parameters via a Web Part Connection: "
_webPartDescription += "font color, weight, size, and family. This Web Part can only be connected to "
_webPartDescription += "another part which implements the IParametersOutProvider interface."
End Sub
' Step #3: Override the EnsureInterfaces method and call
' RegisterInterface method.
' The EnsureInterfaces method is called by the Web Part
' infrastructure during the ASP.Net PreRender event
' and allows the part to register all of its connection
' interfaces.
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 IParametersOutConsumer Interface
' <param name="interfaceName">Friendly name of the
' interface that is being implemented.</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.
' This is a server side example so the value is set to
' empty string.</param>
' <param name="menuLabel">Label for the interface that
' appears in the UI</param>
' <param name="description">Description of the interface
' which 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 IParametersOutConsumer interface is not allowed to
' connect across pages.</param>
RegisterInterface("MyParametersOutConsumerInterface", InterfaceTypes.IParametersOutConsumer, WebPart.LimitOneConnection, ConnectionRunAt.Server, Me, "", "Consume Font Parameters From", "Consumes font parameters from another Web Part.") 'InterfaceName
'InterfaceType
'MaxConnections
'RunAtOptions
'InterfaceObject
'InterfaceClientReference
'MenuLabel
'Description
Catch se As SecurityException
_registrationErrorOccurred = True
End Try
End Sub
' Step #4: 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 #5: 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)
' Check if this is my particular Row interface
If interfaceName = "MyParametersOutConsumerInterface" Then
'Keep track of the Connection
_connected = True
_connectedWebPartTitle = SPEncode.HtmlEncode(connectedPart.Title)
End If
End Sub
' Step #6: Implement the ParametersOutProviderInit event handler.
' The connected provider part will call this method during its
' PartCommunicationInit phase
' to pass initialization information to the consumer Web Part.
' <param name="sender">Reference to the Consumer Web Part</param>
' <param name="parametersOutProviderInitEventArgs">The args
' passed by the provider Web Part</param>
Public Sub ParametersOutProviderInit(sender As Object, parametersOutProviderInitEventArgs As ParametersOutProviderInitEventArgs) _
Implements IParametersOutConsumer.ParametersOutProviderInit
' Store the provider part properties.
_parametersOutProviderInitEventArgs = parametersOutProviderInitEventArgs
End Sub
' Step #7: Implement the ParametersOutReady event handler.
' The connected provider part may call this method during its
' PartCommunicationMain phase
' to pass its primary data to the consumer Web Part.
' <param name="sender">Provider Web Part</param>
' <param name="parametersOutReadyEventArgs">The args passed by
' the Provider</param>
Public Sub ParametersOutReady(sender As Object, parametersOutReadyEventArgs As ParametersOutReadyEventArgs) _
Implements IParametersOutConsumer.ParametersOutReady
_parametersOutReadyFlag = True
' Set the text box values to the values of the Parameters.
If Not (parametersOutReadyEventArgs.ParameterValues Is Nothing) Then
_fontFamily = parametersOutReadyEventArgs.ParameterValues(0)
_fontColor = parametersOutReadyEventArgs.ParameterValues(1)
_fontWeight = parametersOutReadyEventArgs.ParameterValues(2)
_fontSize = parametersOutReadyEventArgs.ParameterValues(3)
' Store font attributes in a State Bag for use by the
' NoParametersOut event handler.
ViewState("FontFamily") = _fontFamily
ViewState("FontColor") = _fontColor
ViewState("FontWeight") = _fontWeight
ViewState("FontSize") = _fontSize
End If
End Sub
' Step #8: Implement the NoParametersOut event handler.
' The connected provider part may call this method during its
' PartCommunicationMain phase
' to indicate there is no change in the parameter values. This
' allows the consumer part to
' display its cached data instead of potentially hitting a
' database again or recalculating values.
' <param name="sender">Provider Web Part</param>
' <param name="eventArgs">The Event Argumentsr</param>
Public Sub NoParametersOut(sender As Object, eventArgs As EventArgs) Implements IParametersOutConsumer.NoParametersOut
_noParametersOutFlag = True
' Set font attributes based on cached values.
_fontFamily = CStr(ViewState("FontFamily"))
_fontColor = CStr(ViewState("FontColor"))
_fontWeight = CStr(ViewState("FontWeight"))
_fontSize = CStr(ViewState("FontSize"))
End Sub
Protected Overrides Sub RenderWebPart(output As HtmlTextWriter)
' Check for connection interface registration error.
If _registrationErrorOccurred Then
output.Write(_registrationErrorMsg)
Return
End If
' Set text style attributes.
output.AddStyleAttribute(HtmlTextWriterStyle.FontFamily, _fontFamily)
output.AddStyleAttribute(HtmlTextWriterStyle.Color, _fontColor)
output.AddStyleAttribute(HtmlTextWriterStyle.FontWeight, _fontWeight)
output.AddStyleAttribute(HtmlTextWriterStyle.FontSize, _fontSize)
' Output Web Part description.
output.RenderBeginTag(HtmlTextWriterTag.Div)
output.Write("<br>")
output.Write(_webPartDescription)
output.RenderEndTag()
' Line break.
output.RenderBeginTag(HtmlTextWriterTag.Br)
output.RenderEndTag()
' Check if connected.
If _connected Then
' Render font attributes if they have been set.
If Not (_fontFamily Is Nothing) Then
' Specify source of font attributes.
output.RenderBeginTag(HtmlTextWriterTag.B)
If _parametersOutReadyFlag Then
output.Write("Provided Font Parameters <br>")
ElseIf _noParametersOutFlag Then
output.Write("<font color=blue>Cached</font> Font Parameters <br>")
End If
output.RenderEndTag()
' Render parameters send by provider part.
If _parametersOutProviderInitEventArgs.ParameterOutProperties.Length <> 0 Then
Dim ParamOutProps As ParameterOutProperty() = _parametersOutProviderInitEventArgs.ParameterOutProperties
output.Write((ParamOutProps(0).ParameterDisplayName + ": " + _fontFamily + "<br>"))
output.Write((ParamOutProps(1).ParameterDisplayName + ": " + _fontColor + "<br>"))
output.Write((ParamOutProps(2).ParameterDisplayName + ": " + _fontWeight + "<br>"))
output.Write((ParamOutProps(3).ParameterDisplayName + ": " + _fontSize + "<br>"))
End If
End If
' Line break.
output.RenderBeginTag(HtmlTextWriterTag.Br)
output.RenderEndTag()
' Render connected Web Part title.
output.Write((_connectedWebPartLabel + ": "))
output.RenderBeginTag(HtmlTextWriterTag.I)
output.Write(_connectedWebPartTitle)
output.RenderEndTag()
output.Write("<br>")
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;
// 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: Reference the Communication namespace.
using Microsoft.SharePoint.WebPartPages.Communication;
namespace ConnectionCodeSamples
{
//Step #2: Inherit from the WebPart base class and implement the
//IParametersOutConsumer interface.
public class ServerSideParametersOutConsumer : WebPart, IParametersOutConsumer
{
// Declare variables for keeping track of 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 set the text style of this Web Part connect it to an appropriate Parameters Out Provider Web Part.";
// Declare variables for Web Part user interface.
private string _connectedWebPartLabel = "Connected to Web Part";
private string _webPartDescription;
string _fontFamily = string.Empty;
string _fontColor = string.Empty;
string _fontWeight = string.Empty;
string _fontSize = string.Empty;
ParametersOutProviderInitEventArgs _parametersOutProviderInitEventArgs;
bool _parametersOutReadyFlag = false;
bool _noParametersOutFlag = false;
// Constructor
public ServerSideParametersOutConsumer()
{
// Set Web Part Description
_webPartDescription = "This is an example of a IParametersOutConsumer Web Part. The following ";
_webPartDescription += "text style attributes can be set when passed as parameters via a Web Part Connection: ";
_webPartDescription += "font color, weight, size, and family. This Web Part can only be connected to ";
_webPartDescription += "another part which implements the IParametersOutProvider interface.";
}
// Step #3: Override the EnsureInterfaces method and call
// RegisterInterface method.
// The EnsureInterfaces method is called by the Web Part
// infrastructure during the ASP.Net PreRender event
// and allows the part to register all of its connection
// interfaces.
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 IParametersOutConsumer Interface
// <param name="interfaceName">Friendly name of the
// interface that is being implemented.</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.
// This is a server side example so the value is set to
// empty string.</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 IParametersOutConsumer interface is not allowed
// to connect across pages.</param>
RegisterInterface("MyParametersOutConsumerInterface", //InterfaceName
InterfaceTypes.IParametersOutConsumer, //InterfaceType
WebPart.LimitOneConnection, //MaxConnections
ConnectionRunAt.Server, //RunAtOptions
this, //InterfaceObject
"", //InterfaceClientReference
"Consume Font Parameters From", //MenuLabel
"Consumes font parameters from another Web Part."); //Description
}
catch(SecurityException se)
{
_registrationErrorOccurred = true;
}
}
// Step #4: 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 #5: 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)
{
// Check if this is my particular Row interface
if (interfaceName == "MyParametersOutConsumerInterface")
{
//Keep track of the Connection
_connected = true;
_connectedWebPartTitle = SPEncode.HtmlEncode(connectedPart.Title);
}
}
// Step #6: Implement the ParametersOutProviderInit event
// handler.
// The connected provider part will call this method during its
// PartCommunicationInit phase
// to pass initialization information to the consumer Web Part.
// <param name="sender">Reference to the Consumer Web
// Part</param>
// <param name="parametersOutProviderInitEventArgs">The args
// passed by the provider Web Part</param>
public void ParametersOutProviderInit(object sender, ParametersOutProviderInitEventArgs parametersOutProviderInitEventArgs)
{
// Store the provider part properties.
_parametersOutProviderInitEventArgs = parametersOutProviderInitEventArgs;
}
// Step #7: Implement the ParametersOutReady event handler.
// The connected provider part may call this method during its
// PartCommunicationMain phase
// to pass its primary data to the consumer Web Part.
// <param name="sender">Provider Web Part</param>
// <param name="parametersOutReadyEventArgs">The args passed by
// the Provider</param>
public void ParametersOutReady(object sender, ParametersOutReadyEventArgs parametersOutReadyEventArgs)
{
_parametersOutReadyFlag = true;
// Set the text box values to the values of the Parameters.
if(parametersOutReadyEventArgs.ParameterValues != null)
{
_fontFamily = parametersOutReadyEventArgs.ParameterValues[0];
_fontColor = parametersOutReadyEventArgs.ParameterValues[1];
_fontWeight = parametersOutReadyEventArgs.ParameterValues[2];
_fontSize = parametersOutReadyEventArgs.ParameterValues[3];
// Store font attributes in a State Bag for use by the
// NoParametersOut event handler.
ViewState["FontFamily"] = _fontFamily;
ViewState["FontColor"] = _fontColor;
ViewState["FontWeight"] = _fontWeight;
ViewState["FontSize"] = _fontSize;
}
}
// Step #8: Implement the NoParametersOut event handler.
// The connected provider part may call this method during its
// PartCommunicationMain phase
// to indicate there is no change in the parameter values. This
// allows the consumer part to
// display its cached data instead of potentially hitting a
// database again or recalculating values.
// <param name="sender">Provider Web Part</param>
// <param name="eventArgs">The Event Argumentsr</param>
public void NoParametersOut(object sender, EventArgs eventArgs)
{
_noParametersOutFlag = true;
// Set font attributes based on cached values.
_fontFamily = (string)ViewState["FontFamily"];
_fontColor = (string)ViewState["FontColor"];
_fontWeight = (string)ViewState["FontWeight"];
_fontSize = (string)ViewState["FontSize"];
}
protected override void RenderWebPart(HtmlTextWriter output)
{
// Check for connection interface registration error.
if (_registrationErrorOccurred)
{
output.Write(_registrationErrorMsg);
return;
}
// Set text style attributes.
output.AddStyleAttribute(HtmlTextWriterStyle.FontFamily, _fontFamily);
output.AddStyleAttribute(HtmlTextWriterStyle.Color, _fontColor);
output.AddStyleAttribute(HtmlTextWriterStyle.FontWeight, _fontWeight);
output.AddStyleAttribute(HtmlTextWriterStyle.FontSize, _fontSize);
// Output Web Part description.
output.RenderBeginTag(HtmlTextWriterTag.Div);
output.Write("<br>");
output.Write(_webPartDescription);
output.RenderEndTag();
// Line break.
output.RenderBeginTag(HtmlTextWriterTag.Br);
output.RenderEndTag();
// Check if connected.
if(_connected)
{
// Render font attributes if they have been set.
if (_fontFamily != null)
{
// Specify source of font attributes.
output.RenderBeginTag(HtmlTextWriterTag.B);
if (_parametersOutReadyFlag)
output.Write("Provided Font Parameters <br>");
else if (_noParametersOutFlag)
output.Write("<font color=blue>Cached</font> Font Parameters <br>");
output.RenderEndTag();
// Render parameters send by provider part.
if (_parametersOutProviderInitEventArgs.ParameterOutProperties.Length != 0)
{
ParameterOutProperty[] ParamOutProps = _parametersOutProviderInitEventArgs.ParameterOutProperties;
output.Write(ParamOutProps[0].ParameterDisplayName + ": " + _fontFamily + "<br>");
output.Write(ParamOutProps[1].ParameterDisplayName + ": " + _fontColor + "<br>");
output.Write(ParamOutProps[2].ParameterDisplayName + ": " + _fontWeight + "<br>");
output.Write(ParamOutProps[3].ParameterDisplayName + ": " + _fontSize + "<br>");
}
}
// Line break.
output.RenderBeginTag(HtmlTextWriterTag.Br);
output.RenderEndTag();
// Render connected Web Part title.
output.Write(_connectedWebPartLabel + ": ");
output.RenderBeginTag(HtmlTextWriterTag.I);
output.Write(_connectedWebPartTitle);
output.RenderEndTag();
output.Write("<br>");
}
else
{
// The Web Part isn't connected.
output.Write(_notConnectedMsg);
}
}
}
}
См. также
Справочные материалы
Элементы IParametersOutConsumer
Пространство имен Microsoft.SharePoint.WebPartPages.Communication