IWebPartTable Interface

Definição

Define uma interface de provedor para conectar dois controles de servidor usando uma tabela de dados inteira.

public interface class IWebPartTable
public interface IWebPartTable
type IWebPartTable = interface
Public Interface IWebPartTable

Exemplos

O exemplo de código a seguir demonstra como criar uma conexão estática entre dois controles usando a IWebPartTable interface. O exemplo de código tem três partes:

  • Código-fonte para dois controles personalizados WebPart que podem formar uma conexão usando a IWebPartTable interface, com um controle atuando como provedor e o outro atuando como consumidor.

  • Uma página da Web que hospeda os controles e declara a conexão estática no formato de persistência.

  • Uma descrição do que acontece quando o código de exemplo é executado.

A primeira parte do exemplo de código é o código-fonte dos dois controles personalizados. Primeiro é o código para o provedor, que implementa a IWebPartTable interface. Para simplificar no exemplo, o provedor cria uma tabela com alguns dados em vez de se conectar a um banco de dados. O GetConnectionInterface método serve como ponto de conexão do provedor, o método de retorno de chamada que retorna a instância de interface para o consumidor. Quanto ao consumidor, ele recupera a instância de interface do provedor em seu método nomeado SetConnectionInterface, que é marcado com um ConnectionConsumer atributo. Depois de recuperar a instância da interface, o consumidor, em seu OnPreRender método, chama a implementação do GetTableData método no provedor para recuperar os dados reais e gravá-los na página.

Para que o exemplo de código seja executado, você deve compilar esse código-fonte. Você pode compilá-lo explicitamente e colocar o assembly resultante na pasta Bin do seu site ou no cache de assembly global. 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. Este exemplo de código usa compilação dinâmica. Para obter um passo a passo que demonstra como compilar, consulte Passo a passo: Desenvolvendo e usando um controle de servidor Web personalizado.

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Reflection;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace Samples.AspNet.CS.Controls
{
  // This sample code creates a Web Parts control that acts as a provider 
  // of table data.
  [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 creates a Web Parts control that acts as a consumer 
  // of information provided by the TableProvider.ascx control.
  [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)
      {
      }
    } // TableConsumerConnectionPoint
  } // TableConsumer
} // Samples.AspNet.CS.Controls
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Reflection
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts

Namespace Samples.AspNet.VB.Controls

  ' This sample code creates a Web Parts control that acts as a provider 
  ' of table data.
  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public NotInheritable Class TableProviderWebPart
    Inherits WebPart
    Implements IWebPartTable
    Private _table As DataTable


    Public Sub New()
      _table = New DataTable()

      Dim col As New DataColumn()
      col.DataType = GetType(String)
      col.ColumnName = "Name"
      _table.Columns.Add(col)

      col = New DataColumn()
      col.DataType = GetType(String)
      col.ColumnName = "Address"
      _table.Columns.Add(col)

      col = New DataColumn()
      col.DataType = GetType(Integer)
      col.ColumnName = "ZIP Code"
      _table.Columns.Add(col)

      Dim row As DataRow = _table.NewRow()
      row("Name") = "John Q. Public"
      row("Address") = "123 Main Street"
      row("ZIP Code") = 98000
      _table.Rows.Add(row)

    End Sub


    Public ReadOnly Property Schema() As _
      ComponentModel.PropertyDescriptorCollection Implements IWebPartTable.Schema

      Get
        Return TypeDescriptor.GetProperties(_table.DefaultView(0))
      End Get

    End Property


    Public Sub GetTableData(ByVal callback As TableCallback) _
      Implements IWebPartTable.GetTableData

      callback(_table.Rows)

    End Sub


    Public Property ConnectionPointEnabled() As Boolean
      Get
        Dim o As Object = ViewState("ConnectionPointEnabled")
        Return IIf(Not (o Is Nothing), CBool(o), True)
      End Get
      Set(ByVal value As Boolean)
        ViewState("ConnectionPointEnabled") = value
      End Set
    End Property


    <ConnectionProvider("Table", GetType(TableProviderConnectionPoint), _
      AllowsMultipleConnections:=True)> _
    Public Function GetConnectionInterface() As IWebPartTable

      Return New TableProviderWebPart()

    End Function

  End Class

  ' The connection point for the provider control.
  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class TableProviderConnectionPoint
    Inherits ProviderConnectionPoint

    Public Sub New(ByVal callbackMethod As MethodInfo, _
      ByVal interfaceType As Type, ByVal controlType As Type, _
      ByVal name As String, ByVal id As String, _
      ByVal allowsMultipleConnections As Boolean)
      MyBase.New(callbackMethod, interfaceType, controlType, _
        name, id, allowsMultipleConnections)

    End Sub


    Public Overrides Function GetEnabled(ByVal control _
      As Control) As Boolean

      Return CType(control, TableProviderWebPart).ConnectionPointEnabled

    End Function
  End Class


  ' This code sample creates a Web Parts control that acts as a consumer 
  ' of information provided by the TableProvider.ascx control.
  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class TableConsumer
    Inherits WebPart
    Private _provider As IWebPartTable
    Private _tableData As ICollection


    Private Sub GetTableData(ByVal tableData As ICollection)
      _tableData = CType(tableData, ICollection)

    End Sub


    Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
      If Not (_provider Is Nothing) Then
        _provider.GetTableData(New TableCallback(AddressOf GetTableData))
      End If

    End Sub


    Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)
      If Not (_provider Is Nothing) Then
        Dim props As PropertyDescriptorCollection = _provider.Schema
        Dim count As Integer = 0
        If Not (props Is Nothing) AndAlso props.Count > 0 _
          AndAlso Not (_tableData Is Nothing) Then

          Dim prop As PropertyDescriptor
          For Each prop In props
            Dim o As DataRow
            For Each o In _tableData
              writer.Write(prop.DisplayName & ": " & o(count))
            Next o
            writer.WriteBreak()
            writer.WriteLine()
            count = count + 1
          Next prop
        Else
          writer.Write("No data")
        End If
      Else
        writer.Write("Not connected")
      End If

    End Sub


    <ConnectionConsumer("Table")> _
    Public Sub SetConnectionInterface(ByVal provider As IWebPartTable)
      _provider = provider

    End Sub

  End Class

  ' The connection point for the consumer control.
  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class TableConsumerConnectionPoint
    Inherits ConsumerConnectionPoint

    Public Sub New(ByVal callbackMethod As MethodInfo, _
      ByVal interfaceType As Type, ByVal controlType As Type, _
      ByVal name As String, ByVal id As String, _
      ByVal allowsMultipleConnections As Boolean)
      MyBase.New(callbackMethod, interfaceType, controlType, name, _
        id, allowsMultipleConnections)

    End Sub
  End Class

End Namespace  ' Samples.AspNet.CS.Controls

A segunda parte do exemplo de código é a página da Web que declara a conexão estática e hospeda os controles. Perto da parte superior da página há uma Register diretiva que declara o namespace do código-fonte contido no diretório App_Code. A conexão é declarada usando um <asp:webpartconnection> elemento. Os controles personalizados do consumidor e do provedor são declarados em um <zonetemplate> elemento dentro de um <asp:webpartzone> elemento, o que é necessário para que eles possam se conectar (eles devem residir dentro de uma zona que herda da WebPartZoneBase classe).

<%@ page language="C#" %>
<%@ Register tagprefix="IRow" 
    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>IRow 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>
            <irow:RowProviderWebPart ID="provider1" runat="server" 
              Title="Row Provider Control" />
            <irow:RowConsumerWebPart ID="consumer1" runat="server" 
              Title="Row Consumer Control" />
          </ZoneTemplate>
        </asp:webpartzone>
    </div>
    </form>
</body>
</html>
<%@ page language="VB" %>
<%@ Register tagprefix="IRow" 
    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">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>IRow 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>
            <irow:RowProviderWebPart ID="provider1" runat="server" 
              Title="Row Provider Control" />
            <irow:RowConsumerWebPart ID="consumer1" runat="server" 
              Title="Row Consumer Control" />
          </ZoneTemplate>
        </asp:webpartzone>
    </div>
    </form>
</body>
</html>

Carregue a página em um navegador. O controle do consumidor exibe os dados fornecidos da tabela especificada, que o provedor disponibiliza por meio de uma instância da IWebPartTable interface.

Comentários

Essa interface foi projetada para ser usada com conexões Web Parts. Em uma conexão Web Parts, dois controles de servidor que residem em uma WebPartZoneBase zona estabelecem uma conexão e compartilham dados, com um controle atuando como consumidor e o outro atuando como um provedor. O mecanismo para compartilhar dados em uma conexão Web Parts é uma instância de interface, que o provedor atende ao consumidor por meio de um método de retorno de chamada. Para estabelecer uma conexão, o consumidor e o provedor devem trabalhar com o mesmo tipo de interface para compartilhar dados. Se o consumidor não reconhecer o tipo de interface enviado pelo provedor, ainda será possível conectar os controles por meio de um transformador (um WebPartTransformer objeto) que traduza a instância de interface enviada pelo provedor em um tipo que o consumidor reconhece. Para obter detalhes sobre conexões, consulte WebPartConnection e Web Parts Visão geral de conexões.

A IWebPartTable interface é uma interface do provedor incluída no conjunto de controle Web Parts como uma interface padrão para criar conexões com base em uma tabela de dados. Você também pode criar interfaces personalizadas para usar com conexões Web Parts, mas em muitos aplicativos Web controlados por dados, é útil criar conexões com base em um campo comum (para obter detalhes, ver a IWebPartField interface), linha (para obter detalhes, ver a IWebPartRow interface) ou tabela da fonte de dados. Em uma conexão típica, um WebPart controle que atua como provedor implementaria a IWebPartTable interface e forneceria uma instância da interface aos consumidores em um método de retorno de chamada especial. Por exemplo, o provedor pode implementar uma IWebPartTable interface para uma tabela que contém dados de desempenho financeiro. Outro WebPart controle que atua como consumidor definiria um método especial para receber a instância de interface e, em seguida, poderia extrair os dados e renderizar um gráfico para exibir as informações resultantes.

A IWebPartTable interface tem dois membros expostos. A Schema propriedade retorna informações de esquema sobre a tabela de dados encapsulada em um PropertyDescriptorCollection objeto. O GetTableData método declara um método que um implementador (como um controle de provedor) usa para recuperar os dados da tabela da instância de interface quando o método de retorno de chamada é invocado.

Propriedades

Schema

Obtém as informações de esquema para uma tabela de dados que é usada para compartilhar dados entre dois controles de WebPart.

Métodos

GetTableData(TableCallback)

Retorna os dados para a tabela que está sendo usada pela interface como a base de uma conexão entre dois controles WebPart.

Aplica-se a

Confira também