ProviderConnectionPoint(MethodInfo, Type, Type, String, String, Boolean) Construtor
Definição
Inicializa uma nova instância da classe ProviderConnectionPoint.Initializes a new instance of the ProviderConnectionPoint class.
public:
ProviderConnectionPoint(System::Reflection::MethodInfo ^ callbackMethod, Type ^ interfaceType, Type ^ controlType, System::String ^ displayName, System::String ^ id, bool allowsMultipleConnections);
public ProviderConnectionPoint (System.Reflection.MethodInfo callbackMethod, Type interfaceType, Type controlType, string displayName, string id, bool allowsMultipleConnections);
new System.Web.UI.WebControls.WebParts.ProviderConnectionPoint : System.Reflection.MethodInfo * Type * Type * string * string * bool -> System.Web.UI.WebControls.WebParts.ProviderConnectionPoint
Public Sub New (callbackMethod As MethodInfo, interfaceType As Type, controlType As Type, displayName As String, id As String, allowsMultipleConnections As Boolean)
Parâmetros
- callbackMethod
- MethodInfo
O método no controle do provedor que retorna uma instância de interface para que os consumidores estabeleçam uma conexão.The method in the provider control that returns an interface instance to consumers to establish a connection.
- interfaceType
- Type
O Type da interface que o provedor serve aos consumidores.The Type of the interface that the provider serves to consumers.
- controlType
- Type
O Type do controle do provedor ao qual o ponto de conexão do provedor está associado.The Type of the provider control with which the provider connection point is associated.
- displayName
- String
Um nome de exibição amigável para o ponto de conexão do provedor que aparece para usuários na IU (interface do usuário) de conexão.A friendly display name for the provider connection point that appears to users in the connection user interface (UI).
- id
- String
Um identificador exclusivo para o ponto de conexão do provedor.A unique identifier for the provider connection point.
- allowsMultipleConnections
- Boolean
Um valor booliano que indica se o ponto de conexão do provedor pode ter várias conexões simultâneas com consumidores.A Boolean value indicating whether the provider connection point can have multiple simultaneous connections with consumers.
Exceções
callbackMethod é null.callbackMethod is null.
- ou --or-
interfaceType é null.interfaceType is null.
- ou --or-
controlType é null.controlType is null.
- ou --or-
displayName é null ou uma cadeia de caracteres vazia ("").displayName is null or an empty string ("").
controlType não é o mesmo tipo que o controle do provedor (ou uma classe válida derivada dele).controlType is not the same type as the provider control (or a valid class derived from it).
Exemplos
O exemplo de código a seguir demonstra como derivar da ProviderConnectionPoint classe para criar um ponto de conexão de provedor personalizado.The following code example demonstrates how to derive from the ProviderConnectionPoint class to create a custom provider connection point.
O exemplo de código tem três partes:The code example has three parts:
Um arquivo de origem que contém um WebPart controle de provedor, um controle de consumidor WebPart e um ProviderConnectionPoint objeto personalizado.A source file that contains a provider WebPart control, a consumer WebPart control, and a custom ProviderConnectionPoint object.
Uma página da Web que hospeda os controles em uma conexão estática.A Web page that hosts the controls in a static connection.
Uma explicação de como executar o código de exemplo.An explanation of how to run the example code.
A primeira parte do exemplo de código é a fonte para os controles do provedor e do consumidor WebPart , e uma ProviderConnectionPoint classe personalizada, denominada TableProviderConnectionPoint .The first part of the code example is the source for the provider and consumer WebPart controls, and a custom ProviderConnectionPoint class, named TableProviderConnectionPoint. Observe que o construtor da TableProviderConnectionPoint classe chama o construtor base, passando-o para os parâmetros necessários, conforme indicado na seção parâmetros.Note that the constructor of the TableProviderConnectionPoint class calls the base constructor, passing it the required parameters as indicated in the Parameters section. Observe também que na TableProviderWebPart classe, o GetConnectionInterface método é especificado como o método de retorno de chamada para conexões e o ConnectionProvider atributo declara o personalizado TableProviderConnectionPoint como um parâmetro.Also note that in the TableProviderWebPart class, the GetConnectionInterface method is specified as the callback method for connections, and the ConnectionProvider attribute declares the custom TableProviderConnectionPoint as a parameter. Isso demonstra como criar um ponto de conexão de provedor personalizado e, em seguida, associá-lo a um controle de provedor.This demonstrates how to create a custom provider connection point and then associate it with a provider control. Este exemplo pressupõe que o código-fonte é compilado dinamicamente, portanto, você deve posicionar o arquivo de código-fonte em uma subpasta App_Code do seu aplicativo Web.This example assumes that the source code is dynamically compiled, so you should place the source code file in an App_Code subfolder of your Web application.
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Security.Permissions;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
//This sample code creates a Web Parts control that acts as a provider of table data.
namespace Samples.AspNet.CS.Controls
{
[AspNetHostingPermission(SecurityAction.Demand,
Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand,
Level = AspNetHostingPermissionLevel.Minimal)]
public sealed class TableProviderWebPart : WebPart, IWebPartTable
{
DataTable _table;
public TableProviderWebPart()
{
_table = new DataTable();
DataColumn col = new DataColumn();
col.DataType = typeof(string);
col.ColumnName = "Name";
_table.Columns.Add(col);
col = new DataColumn();
col.DataType = typeof(string);
col.ColumnName = "Address";
_table.Columns.Add(col);
col = new DataColumn();
col.DataType = typeof(int);
col.ColumnName = "ZIP Code";
_table.Columns.Add(col);
DataRow row = _table.NewRow();
row["Name"] = "John Q. Public";
row["Address"] = "123 Main Street";
row["ZIP Code"] = 98000;
_table.Rows.Add(row);
}
public PropertyDescriptorCollection Schema
{
get
{
return TypeDescriptor.GetProperties(_table.DefaultView[0]);
}
}
public void GetTableData(TableCallback callback)
{
callback(_table.Rows);
}
public bool ConnectionPointEnabled
{
get
{
object o = ViewState["ConnectionPointEnabled"];
return (o != null) ? (bool)o : true;
}
set
{
ViewState["ConnectionPointEnabled"] = value;
}
}
[ConnectionProvider("Table", typeof(TableProviderConnectionPoint), AllowsMultipleConnections = true)]
public IWebPartTable GetConnectionInterface()
{
return new TableProviderWebPart();
}
public class TableProviderConnectionPoint : ProviderConnectionPoint
{
public TableProviderConnectionPoint(MethodInfo callbackMethod, Type interfaceType, Type controlType,
string name, string id, bool allowsMultipleConnections) : base(
callbackMethod, interfaceType, controlType,
name, id, allowsMultipleConnections)
{
}
public override bool GetEnabled(Control control)
{
return ((TableProviderWebPart)control).ConnectionPointEnabled;
}
}
}
// This code sample demonstrates a custom WebPart controls that acts as
// a consumer in a Web Parts connection.
[AspNetHostingPermission(SecurityAction.Demand,
Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand,
Level = AspNetHostingPermissionLevel.Minimal)]
public class TableConsumer : WebPart
{
private IWebPartTable _provider;
private ICollection _tableData;
private void GetTableData(object tableData)
{
_tableData = (ICollection)tableData;
}
protected override void OnPreRender(EventArgs e)
{
if (_provider != null)
{
_provider.GetTableData(new TableCallback(GetTableData));
}
}
protected override void RenderContents(HtmlTextWriter writer)
{
if (_provider != null)
{
PropertyDescriptorCollection props = _provider.Schema;
int count = 0;
if (props != null && props.Count > 0 && _tableData != null)
{
foreach (PropertyDescriptor prop in props)
{
foreach (DataRow o in _tableData)
{
writer.Write(prop.DisplayName + ": " + o[count]);
}
writer.WriteBreak();
writer.WriteLine();
count = count + 1;
}
}
else
{
writer.Write("No data");
}
}
else
{
writer.Write("Not connected");
}
}
[ConnectionConsumer("Table")]
public void SetConnectionInterface(IWebPartTable provider)
{
_provider = provider;
}
public class TableConsumerConnectionPoint : ConsumerConnectionPoint
{
public TableConsumerConnectionPoint(MethodInfo callbackMethod, Type interfaceType, Type controlType,
string name, string id, bool allowsMultipleConnections)
: base(
callbackMethod, interfaceType, controlType,
name, id, allowsMultipleConnections)
{
}
}
}
}
A segunda parte do exemplo de código é a página da Web que hospeda os controles personalizados em uma conexão Web Parts estática.The second part of the code example is the Web page that hosts the custom controls in a static Web Parts connection. Na parte superior da página há uma Register diretiva para declarar um prefixo e o namespace para os controles personalizados.At the top of the page is a Register directive to declare a prefix and the namespace for the custom controls. A conexão é declarada usando um <asp:webpartconnection> elemento, e os controles do provedor e do consumidor são declarados dentro de um <asp:webpartzone> elemento.The connection is declared by using an <asp:webpartconnection> element, and the provider and consumer controls are declared within an <asp:webpartzone> element.
<%@ page language="C#" %>
<%@ 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">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>IField Test Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:webpartmanager id="WebPartManager1" runat="server">
<StaticConnections>
<asp:WebPartConnection id="wp1" ProviderID="provider1" ConsumerID="consumer1">
</asp:WebPartConnection>
</StaticConnections>
</asp:webpartmanager>
<asp:webpartzone id="WebPartZone1" runat="server">
<zoneTemplate>
<aspSample:TableProviderWebPart ID="provider1" runat="server"
ToolTip="Web Parts Table Provider Control" />
<aspSample:TableConsumer ID="consumer1" runat="server"
ToolTip="Web Parts Table Consumer Control"/>
</zoneTemplate>
</asp:webpartzone>
</div>
</form>
</body>
</html>
Carregue a página em um navegador.Load the page in a browser. A conexão entre os controles já existe e o consumidor exibe os dados do provedor, pois a conexão foi declarada como uma conexão estática na página.The connection between the controls already exists, and the consumer displays the data from the provider, because the connection was declared as a static connection in the page.
Comentários
O ProviderConnectionPoint construtor para a ProviderConnectionPoint classe simplesmente chama o construtor base, passando para ele os vários parâmetros e inicializando a classe base.The ProviderConnectionPoint constructor for the ProviderConnectionPoint class simply calls the base constructor, passing to it the various parameters and initializing the base class.
O construtor da classe base verifica um número de parâmetros para um ponto de conexão e pode lançar várias exceções.The base class constructor checks a number of the parameters for a connection point and can throw several exceptions. Para obter uma lista de possíveis exceções, consulte a seção exceções.For a list of possible exceptions, see the Exceptions section.
Você pode chamar o ProviderConnectionPoint construtor para criar sua própria instância da ProviderConnectionPoint classe.You can call the ProviderConnectionPoint constructor to create your own instance of the ProviderConnectionPoint class. No entanto, nos casos em que você está simplesmente estabelecendo uma conexão e não estendendo a classe, você deve chamar o GetProviderConnectionPoints método para retornar um objeto de ponto de conexão existente de um provedor.However, in cases where you are simply establishing a connection and not extending the class, you should call the GetProviderConnectionPoints method to return an existing connection point object from a provider.