ConsumerConnectionPoint Classe
Definição
Define um objeto de ponto de conexão que permite que um controle de servidor que funciona como consumidor forme uma conexão com um provedor.Defines a connection point object that enables a server control acting as a consumer to form a connection with a provider.
public ref class ConsumerConnectionPoint : System::Web::UI::WebControls::WebParts::ConnectionPoint
public class ConsumerConnectionPoint : System.Web.UI.WebControls.WebParts.ConnectionPoint
type ConsumerConnectionPoint = class
inherit ConnectionPoint
Public Class ConsumerConnectionPoint
Inherits ConnectionPoint
- Herança
Exemplos
O exemplo de código a seguir mostra maneiras simples de criar uma conexão declarativamente, programaticamente ou por meio da interface do usuário, em cada caso, usando um ponto de conexão do consumidor.The following code example shows simple ways to create a connection declaratively, programmatically, or through the UI, in each case making use of a consumer connection point.
O exemplo tem quatro partes:The example has four parts:
Um controle de usuário que permite alterar o modo de exibição de Web Parts em uma página.A user control that enables you to change the Web Parts display mode on a page.
Código-fonte para uma interface e dois WebPart controles atuando como o provedor e o consumidor para uma conexão.Source code for an interface and two WebPart controls acting as the provider and the consumer for a connection.
Uma página da Web para hospedar todos os controles e executar o exemplo de código.A Web page to host all the controls and run the code example.
Uma explicação de como executar a página de exemplo.An explanation of how to run the example page.
A primeira parte deste exemplo de código é o controle de usuário que permite aos usuários alterar modos de exibição em uma página da Web.The first part of this code example is the user control that enables users to change display modes on a Web page. Salve o código-fonte a seguir em um arquivo. ascx, dando a ele o nome de arquivo atribuído ao Src atributo da Register diretiva para esse controle de usuário, que está próximo à parte superior da página da Web de hospedagem.Save the following source code to an .ascx file, giving it the file name that is assigned to the Src attribute of the Register directive for this user control, which is near the top of the hosting Web page. Para obter detalhes sobre modos de exibição e uma descrição do código-fonte neste controle, consulte passo a passos: Alterando modos de exibição em uma página de Web Parts.For details about display modes and a description of the source code in this control, see Walkthrough: Changing Display Modes on a Web Parts Page.
<%@ control language="C#" classname="DisplayModeMenuCS"%>
<script runat="server">
// Use a field to reference the current WebPartManager.
WebPartManager _manager;
void Page_Init(object sender, EventArgs e)
{
Page.InitComplete += new EventHandler(InitComplete);
}
void InitComplete(object sender, System.EventArgs e)
{
_manager = WebPartManager.GetCurrentWebPartManager(Page);
String browseModeName = WebPartManager.BrowseDisplayMode.Name;
// Fill the dropdown with the names of supported display modes.
foreach (WebPartDisplayMode mode in _manager.SupportedDisplayModes)
{
String modeName = mode.Name;
// Make sure a mode is enabled before adding it.
if (mode.IsEnabled(_manager))
{
ListItem item = new ListItem(modeName, modeName);
DisplayModeDropdown.Items.Add(item);
}
}
// If shared scope is allowed for this user, display the scope-switching
// UI and select the appropriate radio button for the current user scope.
if (_manager.Personalization.CanEnterSharedScope)
{
Panel2.Visible = true;
if (_manager.Personalization.Scope == PersonalizationScope.User)
RadioButton1.Checked = true;
else
RadioButton2.Checked = true;
}
}
// Change the page to the selected display mode.
void DisplayModeDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
String selectedMode = DisplayModeDropdown.SelectedValue;
WebPartDisplayMode mode = _manager.SupportedDisplayModes[selectedMode];
if (mode != null)
_manager.DisplayMode = mode;
}
// Set the selected item equal to the current display mode.
void Page_PreRender(object sender, EventArgs e)
{
ListItemCollection items = DisplayModeDropdown.Items;
int selectedIndex =
items.IndexOf(items.FindByText(_manager.DisplayMode.Name));
DisplayModeDropdown.SelectedIndex = selectedIndex;
}
// Reset all of a user's personalization data for the page.
protected void LinkButton1_Click(object sender, EventArgs e)
{
_manager.Personalization.ResetPersonalizationState();
}
// If not in User personalization scope, toggle into it.
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (_manager.Personalization.Scope == PersonalizationScope.Shared)
_manager.Personalization.ToggleScope();
}
// If not in Shared scope, and if user is allowed, toggle the scope.
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
if (_manager.Personalization.CanEnterSharedScope &&
_manager.Personalization.Scope == PersonalizationScope.User)
_manager.Personalization.ToggleScope();
}
</script>
<div>
<asp:Panel ID="Panel1" runat="server"
Borderwidth="1"
Width="230"
BackColor="lightgray"
Font-Names="Verdana, Arial, Sans Serif" >
<asp:Label ID="Label1" runat="server"
Text=" Display Mode"
Font-Bold="true"
Font-Size="8"
Width="120"
AssociatedControlID="DisplayModeDropdown"/>
<asp:DropDownList ID="DisplayModeDropdown" runat="server"
AutoPostBack="true"
Width="120"
OnSelectedIndexChanged="DisplayModeDropdown_SelectedIndexChanged" />
<asp:LinkButton ID="LinkButton1" runat="server"
Text="Reset User State"
ToolTip="Reset the current user's personalization data for the page."
Font-Size="8"
OnClick="LinkButton1_Click" />
<asp:Panel ID="Panel2" runat="server"
GroupingText="Personalization Scope"
Font-Bold="true"
Font-Size="8"
Visible="false" >
<asp:RadioButton ID="RadioButton1" runat="server"
Text="User"
AutoPostBack="true"
GroupName="Scope" OnCheckedChanged="RadioButton1_CheckedChanged" />
<asp:RadioButton ID="RadioButton2" runat="server"
Text="Shared"
AutoPostBack="true"
GroupName="Scope"
OnCheckedChanged="RadioButton2_CheckedChanged" />
</asp:Panel>
</asp:Panel>
</div>
<%@ control language="vb" classname="DisplayModeMenuVB"%>
<script runat="server">
' Use a field to reference the current WebPartManager.
Dim _manager As WebPartManager
Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
AddHandler Page.InitComplete, AddressOf InitComplete
End Sub
Sub InitComplete(ByVal sender As Object, ByVal e As System.EventArgs)
_manager = WebPartManager.GetCurrentWebPartManager(Page)
Dim browseModeName As String = WebPartManager.BrowseDisplayMode.Name
' Fill the dropdown with the names of supported display modes.
Dim mode As WebPartDisplayMode
For Each mode In _manager.SupportedDisplayModes
Dim modeName As String = mode.Name
' Make sure a mode is enabled before adding it.
If mode.IsEnabled(_manager) Then
Dim item As New ListItem(modeName, modeName)
DisplayModeDropdown.Items.Add(item)
End If
Next mode
' If shared scope is allowed for this user, display the scope-switching
' UI and select the appropriate radio button for the current user scope.
If _manager.Personalization.CanEnterSharedScope Then
Panel2.Visible = True
If _manager.Personalization.Scope = PersonalizationScope.User Then
RadioButton1.Checked = True
Else
RadioButton2.Checked = True
End If
End If
End Sub
' Change the page to the selected display mode.
Sub DisplayModeDropdown_SelectedIndexChanged(ByVal sender As Object, _
ByVal e As EventArgs)
Dim selectedMode As String = DisplayModeDropdown.SelectedValue
Dim mode As WebPartDisplayMode = _
_manager.SupportedDisplayModes(selectedMode)
If Not (mode Is Nothing) Then
_manager.DisplayMode = mode
End If
End Sub
' Set the selected item equal to the current display mode.
Sub Page_PreRender(ByVal sender As Object, ByVal e As EventArgs)
Dim items As ListItemCollection = DisplayModeDropdown.Items
Dim selectedIndex As Integer = _
items.IndexOf(items.FindByText(_manager.DisplayMode.Name))
DisplayModeDropdown.SelectedIndex = selectedIndex
End Sub
' Reset all of a user's personalization data for the page.
Protected Sub LinkButton1_Click(ByVal sender As Object, _
ByVal e As EventArgs)
_manager.Personalization.ResetPersonalizationState()
End Sub
' If not in User personalization scope, toggle into it.
Protected Sub RadioButton1_CheckedChanged(ByVal sender As Object, _
ByVal e As EventArgs)
If _manager.Personalization.Scope = PersonalizationScope.Shared Then
_manager.Personalization.ToggleScope()
End If
End Sub
' If not in Shared scope, and if user is allowed, toggle the scope.
Protected Sub RadioButton2_CheckedChanged(ByVal sender As Object, _
ByVal e As EventArgs)
If _manager.Personalization.CanEnterSharedScope AndAlso _
_manager.Personalization.Scope = PersonalizationScope.User Then
_manager.Personalization.ToggleScope()
End If
End Sub
</script>
<div>
<asp:Panel ID="Panel1" runat="server"
Borderwidth="1"
Width="230"
BackColor="lightgray"
Font-Names="Verdana, Arial, Sans Serif" >
<asp:Label ID="Label1" runat="server"
Text=" Display Mode"
Font-Bold="true"
Font-Size="8"
Width="120"
AssociatedControlID="DisplayModeDropdown"/>
<asp:DropDownList ID="DisplayModeDropdown" runat="server"
AutoPostBack="true"
Width="120"
OnSelectedIndexChanged="DisplayModeDropdown_SelectedIndexChanged" />
<asp:LinkButton ID="LinkButton1" runat="server"
Text="Reset User State"
ToolTip="Reset the current user's personalization data for the page."
Font-Size="8"
OnClick="LinkButton1_Click" />
<asp:Panel ID="Panel2" runat="server"
GroupingText="Personalization Scope"
Font-Bold="true"
Font-Size="8"
Visible="false" >
<asp:RadioButton ID="RadioButton1" runat="server"
Text="User"
AutoPostBack="true"
GroupName="Scope" OnCheckedChanged="RadioButton1_CheckedChanged" />
<asp:RadioButton ID="RadioButton2" runat="server"
Text="Shared"
AutoPostBack="true"
GroupName="Scope"
OnCheckedChanged="RadioButton2_CheckedChanged" />
</asp:Panel>
</asp:Panel>
</div>
A segunda parte do exemplo de código é o código-fonte para a interface e os controles.The second part of the code example is the source code for the interface and controls. O arquivo de origem contém uma interface simples chamada IZipCode .The source file contains a simple interface named IZipCode. Há também uma WebPart classe chamada ZipCodeWebPart que implementa a interface e atua como o controle do provedor.There is also a WebPart class named ZipCodeWebPart that implements the interface and acts as the provider control. A outra WebPart classe é nomeada WeatherWebPart e atua como o consumidor da conexão.The other WebPart class is named WeatherWebPart, and it acts as the consumer for the connection. Essa classe tem um método chamado GetZipCode que obtém uma instância da IZipCode interface do controle do provedor.This class has a method named GetZipCode that gets an instance of the IZipCode interface from the provider control. Observe que esse método é marcado como o método de ponto de conexão do consumidor com um ConnectionConsumer atributo em seus metadados.Note that this method is marked as the consumer's connection point method with a ConnectionConsumer attribute in its metadata. Esse é o mecanismo para identificar o método de ponto de conexão no controle de consumidor.This is the mechanism for identifying the connection point method in the consumer control.
Para que o exemplo de código seja executado, você deve compilar esse código-fonte.For the code example to run, you must compile this source code. Você pode compilá-lo explicitamente e colocar o assembly resultante na pasta bin do seu site ou no cache de assembly global.You can compile it explicitly and put the resulting assembly in your Web site's Bin folder or the global assembly cache. Como alternativa, você pode colocar o código-fonte na pasta App_Code do seu site, onde ele será compilado dinamicamente em tempo de execução.Alternatively, you can put the source code in your site's App_Code folder, where it will be dynamically compiled at run time. Este exemplo de código usa compilação dinâmica.This code example uses dynamic compilation. Para obter instruções que demonstram como compilar, consulte passo a passos: desenvolvendo e usando um controle de servidor Web personalizado.For a walkthrough that demonstrates how to compile, see Walkthrough: Developing and Using a Custom Web Server Control.
namespace Samples.AspNet.CS.Controls
{
using System;
using System.Web;
using System.Web.Security;
using System.Security.Permissions;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
[AspNetHostingPermission(SecurityAction.Demand,
Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand,
Level = AspNetHostingPermissionLevel.Minimal)]
public interface IZipCode
{
string ZipCode { get; set;}
}
[AspNetHostingPermission(SecurityAction.Demand,
Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand,
Level = AspNetHostingPermissionLevel.Minimal)]
public class ZipCodeWebPart : WebPart, IZipCode
{
string zipCodeText = String.Empty;
TextBox input;
Button send;
public ZipCodeWebPart()
{
}
// Make the implemented property personalizable to save
// the Zip Code between browser sessions.
[Personalizable()]
public virtual string ZipCode
{
get { return zipCodeText; }
set { zipCodeText = value; }
}
// This is the callback method that returns the provider.
[ConnectionProvider("Zip Code Provider", "ZipCodeProvider")]
public IZipCode ProvideIZipCode()
{
return this;
}
protected override void CreateChildControls()
{
Controls.Clear();
input = new TextBox();
this.Controls.Add(input);
send = new Button();
send.Text = "Enter 5-digit Zip Code";
send.Click += new EventHandler(this.submit_Click);
this.Controls.Add(send);
}
private void submit_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(input.Text))
{
zipCodeText = Page.Server.HtmlEncode(input.Text);
input.Text = String.Empty;
}
}
}
[AspNetHostingPermission(SecurityAction.Demand,
Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand,
Level = AspNetHostingPermissionLevel.Minimal)]
public class WeatherWebPart : WebPart
{
private IZipCode _provider;
string _zipSearch;
Label DisplayContent;
// This method is identified by the ConnectionConsumer
// attribute, and is the mechanism for connecting with
// the provider.
[ConnectionConsumer("Zip Code Consumer", "ZipCodeConsumer")]
public void GetIZipCode(IZipCode Provider)
{
_provider = Provider;
}
protected override void OnPreRender(EventArgs e)
{
EnsureChildControls();
if (this._provider != null)
{
_zipSearch = _provider.ZipCode.Trim();
DisplayContent.Text = "My Zip Code is: " + _zipSearch;
}
}
protected override void CreateChildControls()
{
Controls.Clear();
DisplayContent = new Label();
this.Controls.Add(DisplayContent);
}
}
}
Imports System.Web
Imports System.Web.Security
Imports System.Security.Permissions
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Namespace Samples.AspNet.VB.Controls
<AspNetHostingPermission(SecurityAction.Demand, _
Level:=AspNetHostingPermissionLevel.Minimal)> _
<AspNetHostingPermission(SecurityAction.InheritanceDemand, _
Level:=AspNetHostingPermissionLevel.Minimal)> _
Public Interface IZipCode
Property ZipCode() As String
End Interface
<AspNetHostingPermission(SecurityAction.Demand, _
Level:=AspNetHostingPermissionLevel.Minimal)> _
<AspNetHostingPermission(SecurityAction.InheritanceDemand, _
Level:=AspNetHostingPermissionLevel.Minimal)> _
Public Class ZipCodeWebPart
Inherits WebPart
Implements IZipCode
Private zipCodeText As String = String.Empty
Private input As TextBox
Private send As Button
Public Sub New()
End Sub
' Make the implemented property personalizable to save
' the Zip Code between browser sessions.
<Personalizable()> _
Public Property ZipCode() As String _
Implements IZipCode.ZipCode
Get
Return zipCodeText
End Get
Set(ByVal value As String)
zipCodeText = value
End Set
End Property
' This is the callback method that returns the provider.
<ConnectionProvider("Zip Code Provider", "ZipCodeProvider")> _
Public Function ProvideIZipCode() As IZipCode
Return Me
End Function
Protected Overrides Sub CreateChildControls()
Controls.Clear()
input = New TextBox()
Me.Controls.Add(input)
send = New Button()
send.Text = "Enter 5-digit Zip Code"
AddHandler send.Click, AddressOf Me.submit_Click
Me.Controls.Add(send)
End Sub
Private Sub submit_Click(ByVal sender As Object, _
ByVal e As EventArgs)
If input.Text <> String.Empty Then
zipCodeText = Page.Server.HtmlEncode(input.Text)
input.Text = String.Empty
End If
End Sub
End Class
<AspNetHostingPermission(SecurityAction.Demand, _
Level:=AspNetHostingPermissionLevel.Minimal)> _
<AspNetHostingPermission(SecurityAction.InheritanceDemand, _
Level:=AspNetHostingPermissionLevel.Minimal)> _
Public Class WeatherWebPart
Inherits WebPart
Private _provider As IZipCode
Private _zipSearch As String
Private DisplayContent As Label
' This method is identified by the ConnectionConsumer
' attribute, and is the mechanism for connecting with
' the provider.
<ConnectionConsumer("Zip Code Consumer", "ZipCodeConsumer")> _
Public Sub GetIZipCode(ByVal Provider As IZipCode)
_provider = Provider
End Sub
Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
EnsureChildControls()
If Not (Me._provider Is Nothing) Then
_zipSearch = _provider.ZipCode.Trim()
DisplayContent.Text = "My Zip Code is: " + _zipSearch
End If
End Sub
Protected Overrides Sub CreateChildControls()
Controls.Clear()
DisplayContent = New Label()
Me.Controls.Add(DisplayContent)
End Sub
End Class
End Namespace
A terceira parte do exemplo de código é a página da Web.The third part of the code example is the Web page. Perto da parte superior estão as Register diretivas para registrar os controles personalizados que formam a conexão e o controle de usuário que permite aos usuários alterar modos de exibição na página.Near the top are Register directives to register the custom controls that form the connection, and the user control that enables users to change display modes on the page. A conexão em si é criada declarativamente dentro do <staticconnections> elemento na página.The connection itself is created declaratively within the <staticconnections> element on the page. Isso demonstra uma maneira de criar uma conexão – Observe o ConsumerConnectionPointID atributo no <asp:webpartconnection> elemento.This demonstrates one way of creating a connection--note the ConsumerConnectionPointID attribute in the <asp:webpartconnection> element. Você também pode criar a conexão programaticamente; o código para fazer isso está no Button1_Click método.You can also create the connection programmatically; the code for doing that is in the Button1_Click method. Nesse caso, um ConsumerConnectionPoint objeto é criado e passado para um método que cria a conexão real.In this case, a ConsumerConnectionPoint object is created and then passed to a method that creates the actual connection. Se a conexão é criada de forma declarativa ou programaticamente, os pontos de conexão sempre devem ser especificados para o provedor e para o consumidor.Whether the connection is created declaratively or programmatically, connection points must always be specified for both the provider and the consumer. O Button2_Click método acessa os ConnectionPoint objetos para o provedor e para o consumidor e grava alguns de seus valores de propriedade em um rótulo na página.The Button2_Click method accesses the ConnectionPoint objects for both the provider and the consumer, and writes some of their property values to a label in the page.
<%@ Page Language="C#" %>
<%@ register tagprefix="uc1"
tagname="DisplayModeMenuCS"
src="~/displaymodemenucs.ascx" %>
<%@ Register TagPrefix="aspSample"
Namespace="Samples.AspNet.CS.Controls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
ProviderConnectionPoint provPoint =
mgr.GetProviderConnectionPoints(zip1)["ZipCodeProvider"];
ConsumerConnectionPoint connPoint =
mgr.GetConsumerConnectionPoints(weather1)["ZipCodeConsumer"];
if(mgr.CanConnectWebParts(zip1, provPoint, weather1, connPoint))
mgr.ConnectWebParts(zip1, provPoint, weather1, connPoint);
}
protected void Button2_Click(object sender, EventArgs e)
{
WebPartConnection conn = mgr.Connections[0];
lblConn.Text = "<h2>Connection Point Details</h2>" +
"<h3>Provider Connection Point</h3>" +
" Display name: " + conn.ProviderConnectionPoint.DisplayName +
"<br />" +
" ID: " + conn.ProviderConnectionPoint.ID +
"<br />" +
" Interface type: " +
conn.ProviderConnectionPoint.InterfaceType.ToString() +
"<br />" +
" Control type: " + conn.ProviderConnectionPoint.ControlType.ToString() +
"<br />" +
" Allows multiple connections: " +
conn.ProviderConnectionPoint.AllowsMultipleConnections.ToString() +
"<br />" +
" Enabled: " + conn.ProviderConnectionPoint.GetEnabled(zip1).ToString() +
"<hr />" +
"<h3>Consumer Connection Point</h3>" +
" Display name: " + conn.ConsumerConnectionPoint.DisplayName +
"<br />" +
" ID: " + conn.ConsumerConnectionPoint.ID +
"<br />" +
" Interface type: " + conn.ConsumerConnectionPoint.InterfaceType.ToString() +
"<br />" +
" Control type: " + conn.ConsumerConnectionPoint.ControlType.ToString() +
"<br />" +
" Allows multiple connections: " +
conn.ConsumerConnectionPoint.AllowsMultipleConnections.ToString() +
"<br />" +
" Enabled: " + conn.ConsumerConnectionPoint.GetEnabled(zip1).ToString();
}
protected void Page_Load(object sender, EventArgs e)
{
lblConn.Text = String.Empty;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:WebPartManager ID="mgr" runat="server" >
<StaticConnections>
<asp:WebPartConnection ID="conn1"
ConsumerConnectionPointID="ZipCodeConsumer"
ConsumerID="weather1"
ProviderConnectionPointID="ZipCodeProvider"
ProviderID="zip1" />
</StaticConnections>
</asp:WebPartManager>
<uc1:displaymodemenucs id="menu1" runat="server" />
<asp:WebPartZone ID="WebPartZone1" runat="server">
<ZoneTemplate>
<aspSample:ZipCodeWebPart ID="zip1" runat="server"
Title="Zip Code Provider" />
<aspSample:WeatherWebPart ID="weather1" runat="server"
Title="Zip Code Consumer" />
</ZoneTemplate>
</asp:WebPartZone>
<asp:ConnectionsZone ID="ConnectionsZone1" runat="server">
</asp:ConnectionsZone>
<asp:Button ID="Button1" runat="server"
Text="Dynamic Connection"
OnClick="Button1_Click" />
<br />
<asp:Button ID="Button2" runat="server"
Text="Connection Point Details"
OnClick="Button2_Click" />
<br />
<asp:Label ID="lblConn" runat="server" />
</div>
</form>
</body>
</html>
<%@ Page Language="VB" %>
<%@ register tagprefix="uc1"
tagname="DisplayModeMenuVB"
src="~/displaymodemenuvb.ascx" %>
<%@ Register TagPrefix="aspSample"
Namespace="Samples.AspNet.VB.Controls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Dim provPoint As ProviderConnectionPoint = _
mgr.GetProviderConnectionPoints(zip1)("ZipCodeProvider")
Dim connPoint As ConsumerConnectionPoint = _
mgr.GetConsumerConnectionPoints(weather1)("ZipCodeConsumer")
If mgr.CanConnectWebParts(zip1, provPoint, weather1, connPoint) Then
mgr.ConnectWebParts(zip1, provPoint, weather1, connPoint)
End If
End Sub
Protected Sub Button2_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Dim conn As WebPartConnection = mgr.Connections(0)
lblConn.Text = "<h2>Connection Point Details</h2>" & _
"<h3>Provider Connection Point</h3>" & _
" Display name: " & conn.ProviderConnectionPoint.DisplayName & _
"<br />" & _
" ID: " & conn.ProviderConnectionPoint.ID & _
"<br />" & _
" Interface type: " & conn.ProviderConnectionPoint.InterfaceType.ToString() & _
"<br />" & _
" Control type: " & conn.ProviderConnectionPoint.ControlType.ToString() & _
"<br />" & _
" Allows multiple connections: " & _
conn.ProviderConnectionPoint.AllowsMultipleConnections.ToString() & _
"<br />" & _
" Enabled: " & conn.ProviderConnectionPoint.GetEnabled(zip1).ToString() & _
"<hr />" & _
"<h3>Consumer Connection Point</h3>" & _
" Display name: " & conn.ConsumerConnectionPoint.DisplayName & _
"<br />" & _
" ID: " & conn.ConsumerConnectionPoint.ID & _
"<br />" & _
" Interface type: " & conn.ConsumerConnectionPoint.InterfaceType.ToString() & _
"<br />" & _
" Control type: " & conn.ConsumerConnectionPoint.ControlType.ToString() & _
"<br />" & _
" Allows multiple connections: " & _
conn.ConsumerConnectionPoint.AllowsMultipleConnections.ToString() & _
"<br />" & _
" Enabled: " & conn.ConsumerConnectionPoint.GetEnabled(zip1).ToString()
End Sub
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs)
lblConn.Text = String.Empty
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:WebPartManager ID="mgr" runat="server" >
<StaticConnections>
<asp:WebPartConnection ID="conn1"
ConsumerConnectionPointID="ZipCodeConsumer"
ConsumerID="weather1"
ProviderConnectionPointID="ZipCodeProvider"
ProviderID="zip1" />
</StaticConnections>
</asp:WebPartManager>
<uc1:displaymodemenuvb id="menu1" runat="server" />
<asp:WebPartZone ID="WebPartZone1" runat="server">
<ZoneTemplate>
<aspSample:ZipCodeWebPart ID="zip1" runat="server"
Title="Zip Code Provider" />
<aspSample:WeatherWebPart ID="weather1" runat="server"
Title="Zip Code Consumer" />
</ZoneTemplate>
</asp:WebPartZone>
<asp:ConnectionsZone ID="ConnectionsZone1" runat="server">
</asp:ConnectionsZone>
<asp:Button ID="Button1" runat="server"
Text="Dynamic Connection"
OnClick="Button1_Click" />
<br />
<asp:Button ID="Button2" runat="server"
Text="Connection Point Details"
OnClick="Button2_Click" />
<br />
<asp:Label ID="lblConn" runat="server" />
</div>
</form>
</body>
</html>
Depois de carregar a página em um navegador, clique no botão detalhes do ponto de conexão .After you load the page in a browser, click the Connection Point Details button. São exibidas informações sobre os pontos de conexão do provedor e do consumidor estabelecidos na conexão declarativa.Information about the provider and consumer connection points established in the declarative connection appears. Em seguida, use o controle suspenso modo de exibição para alternar a página para o modo de conexão.Next, use the Display Mode drop-down control to switch the page into connect mode. No menu de verbos do controle do provedor de CEP WebPart (representado por uma seta para baixo na barra de título), clique no verbo conectar.On the verbs menu of the ZIP Code ProviderWebPart control (represented by a downward arrow in the title bar), click the connect verb. A interface do usuário de conexão é exibida, criada automaticamente pelo <asp:connectionszone> controle declarado na página.The connection UI appears, created automatically by the <asp:connectionszone> control declared in the page. Essa é outra maneira de criar uma conexão (por meio da interface do usuário), juntamente com os métodos declarativos e programáticos discutidos anteriormente.This is another way of creating a connection (through the UI), along with the declarative and programmatic methods discussed earlier. Clique no botão Desconectar para encerrar a conexão estática existente.Click the Disconnect button to terminate the existing static connection. Clique no link criar uma conexão com um consumidor .Click the Create a Connection to a Consumer link. A interface do usuário agora exibe um controle suspenso que lista o nome de exibição do ponto de conexão do consumidor.The UI now displays a drop-down control that lists the consumer connection point display name. Selecione o ponto de conexão na lista suspensa e clique em conectar para concluir a conexão.Select the connection point in the drop-down list, and then click Connect to complete the connection. Em seguida, clique em Desconectar novamente.Next, click Disconnect again. Clique no botão conexão dinâmica para criar uma conexão programaticamente.Click the Dynamic Connection button to create a connection programmatically. Use o controle modo de exibição para retornar a página para o modo de procura.Use the Display Mode control to return the page to browse mode. Clique no botão detalhes do ponto de conexão novamente para indicar detalhes sobre o objeto do ponto de conexão do consumidor mais uma vez.Click the Connection Point Details button again, to indicate details about the consumer connection point object once more.
O exemplo demonstrou o estabelecimento de uma conexão e o uso de um ponto de conexão do consumidor de três maneiras: uma conexão estática declarada na marcação da página da Web; uma conexão criada no código que usou um ConsumerConnectionPoint objeto; e uma conexão criada por um usuário por meio da interface do usuário da conexão.The example has demonstrated establishing a connection and using a consumer connection point in three ways: a static connection declared in the Web page markup; a connection created in code that used a ConsumerConnectionPoint object; and a connection created by a user through the connection UI.
Comentários
Em cada conexão de Web Parts entre dois controles de servidor, cada controle deve ter (entre outros requisitos) um objeto de ponto de conexão associado que permite que ele se conecte ao outro controle e forneça ou consuma dados, dependendo se o controle é designado como o provedor ou consumidor para a conexão.In every Web Parts connection between two server controls, each control must have (among other requirements) an associated connection point object that enables it to connect to the other control and to either provide or consume data, depending on whether the control is designated as the provider or consumer for the connection. Um ConnectionPoint objeto em geral contém os detalhes de como um controle pode se conectar a outro controle e o tipo de dados que ele pode compartilhar.A ConnectionPoint object in general contains the details for how a control can connect to another control and the type of data it can share. Para um controle que atua como o consumidor em uma conexão, seu ponto de conexão deve ser um ConsumerConnectionPoint objeto.For a control acting as the consumer in a connection, its connection point must be a ConsumerConnectionPoint object. Para obter detalhes sobre conexões de Web Parts e pontos de conexão, leia os tópicos listados na seção Consulte também abaixo.For details on Web Parts connections and connection points, read the topics listed in the See Also section below.
Para criar um ConsumerConnectionPoint objeto, várias etapas são necessárias:To create a ConsumerConnectionPoint object, several steps are required:
Habilite um controle de consumidor para fazer referência a uma instância de interface.Enable a consumer control to reference an interface instance. Um WebPart ou outro controle de servidor (qualquer tipo de controle de servidor que será adicionado a uma WebPartZoneBase zona pode ser usado) deve ser capaz de consumir dados de uma instância de interface específica.A WebPart or other server control (any type of server control that will be added to a WebPartZoneBase zone can be used) must be able to consume data from a specific interface instance. O controle não precisa implementar a interface; somente o provedor deve implementá-lo.The control need not implement the interface; only the provider must implement it. O consumidor pode trabalhar com o tipo de interface exato servido por um provedor ou, se não tiver, um WebPartTransformer objeto pode ser usado para transformar dados do tipo de interface de um provedor para um tipo compreendido pelo consumidor.The consumer can either work with the exact interface type served by a provider or, if it does not, a WebPartTransformer object can be used to transform data from a provider's interface type to a type understood by the consumer. Uma maneira comum de habilitar um consumidor é declarar um campo particular para conter uma referência ao tipo de interface desejado.A typical way to enable a consumer is to declare a private field to contain a reference to the desired interface type.
Identifique um método de retorno de chamada.Identify a callback method. Um método no consumidor deve ser identificado como o método de retorno de chamada para estabelecer uma conexão com o provedor.A method in the consumer must be identified as the callback method to establish a connection with the provider. Esse método recupera uma instância da interface que o provedor implementa e a atribui para (por exemplo) o campo privado criado na primeira etapa.This method retrieves an instance of the interface that the provider implements, and assigns it to (for example) the private field created in the first step. A abordagem de Web Parts para identificar um método de retorno de chamada no consumidor é adicionar um
ConnectionConsumeratributo de metadados (definido pela ConnectionConsumerAttribute classe) ao método que recebe a instância de interface.The Web Parts approach for identifying a callback method in the consumer is to add aConnectionConsumermetadata attribute (defined by the ConnectionConsumerAttribute class) to the method that receives the interface instance. Quando o atributo é adicionado, o único parâmetro necessário é um nome de exibição a ser usado para o ponto de conexão do consumidor.When the attribute is added, the only required parameter is a display name to use for the consumer connection point. Parâmetros opcionais também podem ser adicionados, como uma ID.Optional parameters can also be added, such as an ID.Processe e gere os dados da instância da interface.Process and output the data from the interface instance. Execute qualquer processamento interno conforme necessário nos dados e, em seguida, um controle de consumidor irá renderizar os dados para a página.Perform any internal processing as needed on the data, and then typically a consumer control will render the data to the page. Uma maneira comum de fazer isso é substituir o método do controle OnPreRender .A common way of doing this is to override the control's OnPreRender method.
Observação
Durante uma solicitação síncrona, um consumidor deve solicitar dados diretamente do provedor durante ou imediatamente após o PreRender evento.During a synchronous request, a consumer should request data directly from the provider during or immediately after the PreRender event. Durante uma solicitação assíncrona, se o método de retorno de chamada do provedor não for chamado em nenhum ponto durante a renderização, o desenvolvedor poderá assumir que nenhum dado foi enviado ao consumidor.During an asynchronous request, if the provider's callback method is not called at any point during rendering, the developer can assume that no data was sent to the consumer.
Depois que um controle tiver sido equipado para atuar como um consumidor, o controle poderá participar de conexões (supondo que um controle de provedor também esteja equipado e disponível).After a control has been equipped to act as a consumer, the control can participate in connections (assuming that a provider control is also equipped and available). Para criar uma conexão estática e declarativa na marcação de uma página da Web, os desenvolvedores podem usar o <asp:webpartconnection> elemento.To create a static, declarative connection in the markup of a Web page, developers can use the <asp:webpartconnection> element. Se o ConnectionConsumer atributo no código-fonte do consumidor que identifica o método de retorno de chamada especificar uma ID para o ponto de conexão, esse valor deverá ser atribuído ao ConsumerConnectionPointID atributo no <asp:webpartconnection> elemento em uma página.If the ConnectionConsumer attribute in the consumer source code that identifies the callback method specifies an ID for the connection point, then that value must be assigned to the ConsumerConnectionPointID attribute in the <asp:webpartconnection> element on a page. Um motivo pelo qual um desenvolvedor pode especificar uma ID para um ponto de conexão do consumidor é se houver vários pontos de conexão definidos no controle de consumidor.A reason that a developer might specify an ID for a consumer connection point is if there are multiple connection points defined in the consumer control. Se uma ID não for especificada para o ponto de conexão do consumidor no controle do consumidor, um valor também não precisará ser atribuído ao ConsumerConnectionPointID atributo na página, pois a conexão será criada usando um valor padrão obtido do DefaultID campo.If an ID is not specified for the consumer connection point in the consumer control, a value does not have to be assigned to the ConsumerConnectionPointID attribute in the page either, because the connection will be created using a default value obtained from the DefaultID field.
Para criar uma conexão no código, os desenvolvedores devem criar um novo ConsumerConnectionPoint objeto chamando o GetConsumerConnectionPoints método e passando a ele a ID do controle do consumidor, junto com a ID ou o índice do ConsumerConnectionPoint objeto definido no controle do consumidor.To create a connection in code, developers must create a new ConsumerConnectionPoint object by calling the GetConsumerConnectionPoints method and passing to it the ID of the consumer control, along with the ID or index of the defined ConsumerConnectionPoint object in the consumer control. O ConsumerConnectionPoint objeto retornado, junto com uma referência ao controle do consumidor, uma referência ao controle do provedor e um objeto correspondente ProviderConnectionPoint , são todos passados para o ConnectWebParts método para criar um novo WebPartConnection objeto.The returned ConsumerConnectionPoint object, along with a reference to the consumer control, a reference to the provider control, and a corresponding ProviderConnectionPoint object, are all passed to the ConnectWebParts method to create a new WebPartConnection object.
Embora os desenvolvedores possam usar pontos de conexão do consumidor como parte do estabelecimento de conexões de forma declarativa ou programática, os usuários também podem interagir com pontos de conexão do consumidor para estabelecer conexões por meio da interface do usuário.Although developers can use consumer connection points as part of establishing connections either declaratively or programmatically, users can also interact with consumer connection points to establish connections through the user interface (UI). Se os desenvolvedores declararem um ConnectionsZone controle em uma página da Web, ele fornecerá uma interface do usuário em tempo de execução para que os usuários criem conexões.If developers declare a ConnectionsZone control on a Web page, it provides a run-time UI for users to create connections. Se os usuários escolherem o controle provedor como o ponto de partida para estabelecer a conexão clicando em seu verbo conectar (eles também podem escolher o consumidor; não há diferença na conexão resultante), na interface do usuário, eles verão um controle de lista suspensa com os nomes de exibição do ponto de conexão do consumidor disponível (ou pontos, se houver vários) para os quais o provedor pode enviar os dadosIf users choose the provider control as the starting point for establishing the connection by clicking its connect verb (they could also choose the consumer; there is no difference in the resulting connection), in the UI they will see a drop-down list control with the display names of the available consumer connection point (or points if there are multiple ones) that the provider can send the data to. Os usuários devem selecionar um ponto de conexão de consumidor para estabelecer uma conexão.Users must select a consumer connection point to establish a connection.
Um ConsumerConnectionPoint objeto associa-se diretamente a um controle de consumidor específico e armazena detalhes sobre uma conexão nas propriedades herdadas da ConnectionPoint classe base.A ConsumerConnectionPoint object associates directly with a specific consumer control, and stores details about a connection in the properties it inherits from the base ConnectionPoint class. Por exemplo, na propriedade Inherited InterfaceType , um ponto de conexão de consumidor mantém o tipo de interface que ele usa.For example, in the inherited InterfaceType property, a consumer connection point keeps the type of interface it uses. Se o provedor e o consumidor em uma conexão entenderem o tipo de interface, os controles serão compatíveis e podem formar uma conexão direta.If the provider and consumer in a connection both understand the interface type, the controls are compatible and capable of forming a direct connection. Se o provedor e o consumidor não puderem funcionar com o mesmo tipo de interface, eles serão incompatíveis e deverão usar um WebPartTransformer objeto para converter a propriedade do ponto de conexão do provedor InterfaceType em um tipo com o qual o consumidor possa trabalhar.If the provider and consumer cannot work with the same interface type, they are incompatible and must use a WebPartTransformer object to translate the provider connection point's InterfaceType property into a type that the consumer can work with. Outra propriedade herdada importante é a DisplayName propriedade, que fornece um nome amigável a ser exibido na interface do usuário para que os usuários escolham um ponto de conexão do consumidor ao criar conexões.Another important inherited property is the DisplayName property, which provides a friendly name to display in the UI for users to choose a consumer connection point when creating connections. O nome de exibição é o parâmetro necessário quando os desenvolvedores adicionam um ConnectionConsumer atributo ao método de retorno de chamada em um controle de consumidor.The display name is the required parameter when developers add a ConnectionConsumer attribute to the callback method in a consumer control. A propriedade herdada ID também é útil, conforme indicado acima, porque ela fornece um identificador exclusivo para um ponto de conexão do consumidor no caso de um consumidor ter vários pontos de conexão.The inherited ID property is also useful, as indicated above, because it provides a unique identifier for a consumer connection point in the event that a consumer has multiple connection points. Um consumidor pode ter vários ConsumerConnectionPoint objetos definidos e, nesse caso, quando os desenvolvedores adicionam o ConnectionConsumer atributo a um método, eles devem especificar um valor de ID para distinguir cada ponto de conexão.A consumer can have multiple ConsumerConnectionPoint objects defined in it, and in this case, when developers add the ConnectionConsumer attribute to a method, they should specify an ID value to distinguish each connection point. Uma outra propriedade herdada notável é a AllowsMultipleConnections propriedade, que indica se um ponto de conexão do consumidor pode se conectar simultaneamente a vários provedores.One other notable inherited property is the AllowsMultipleConnections property, which indicates whether a consumer connection point can connect simultaneously to multiple providers. Esse valor de propriedade é false por padrão para pontos de conexão do consumidor (enquanto ele usa como padrão true para pontos de conexão do provedor).This property value is false by default for consumer connection points (whereas it defaults to true for provider connection points).
A ConsumerConnectionPoint classe adiciona vários métodos exclusivos aos membros herdados da ConnectionPoint classe.The ConsumerConnectionPoint class adds several unique methods to the members it inherits from the ConnectionPoint class. O SetObject método invoca o próprio método de retorno de chamada definido pelo consumidor para recuperar a instância de interface do provedor.The SetObject method invokes the consumer's own defined callback method to retrieve the interface instance from the provider. O SupportsConnection método retorna um valor booliano que indica se o ponto de conexão é capaz de estabelecer conexões, com base no estado atual do controle de consumidor associado.The SupportsConnection method returns a Boolean value that indicates whether the connection point is able to establish connections, based on the current state of the associated consumer control.
Construtores
| ConsumerConnectionPoint(MethodInfo, Type, Type, String, String, Boolean) |
Inicializa uma nova instância da classe ConsumerConnectionPoint.Initializes a new instance of the ConsumerConnectionPoint class. |
Propriedades
| AllowsMultipleConnections |
Obtém um valor que indica se um ponto de conexão é compatível com várias conexões simultâneas.Gets a value that indicates whether a connection point supports multiple simultaneous connections. (Herdado de ConnectionPoint) |
| ControlType |
Obtém o Type do controle do servidor ao qual um ponto de conexão é associado.Gets the Type of the server control with which a connection point is associated. (Herdado de ConnectionPoint) |
| DisplayName |
Obtém uma cadeia de caracteres que funciona como um nome de exibição amigável para representar um ponto de conexão na IU (interface do usuário).Gets a string that serves as a friendly display name to represent a connection point in the user interface (UI). (Herdado de ConnectionPoint) |
| ID |
Obtém uma cadeia de caracteres que contém o identificador para um ponto de conexão.Gets a string that contains the identifier for a connection point. (Herdado de ConnectionPoint) |
| InterfaceType |
Obtém o tipo da interface usada por um ponto de conexão.Gets the type of the interface used by a connection point. (Herdado de ConnectionPoint) |
Métodos
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
| GetEnabled(Control) |
Retorna um valor que indica se um ponto de conexão pode participar de conexões.Returns a value that indicates whether a connection point can participate in connections. (Herdado de ConnectionPoint) |
| GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| SetObject(Control, Object) |
Invoca o método de retorno de chamada em um controle do consumidor e recupera a instância da interface de um controle do provedor.Invokes the callback method in a consumer control and retrieves the interface instance from a provider control. |
| SupportsConnection(Control, ConnectionInterfaceCollection) |
Determina se um ponto de conexão do consumidor é atualmente capaz de estabelecer uma conexão.Determines whether a consumer connection point is currently capable of establishing a connection. |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |