IWebPartTable Interfaz

Definición

Define una interfaz de proveedor para conectar dos controles de servidor mediante una tabla completa de datos.

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

Ejemplos

En el ejemplo de código siguiente se muestra cómo crear una conexión estática entre dos controles mediante la IWebPartTable interfaz . El ejemplo de código tiene tres partes:

  • Código fuente para dos controles personalizados WebPart que pueden formar una conexión mediante la IWebPartTable interfaz , con un control que actúa como proveedor y el otro que actúa como consumidor.

  • Página web que hospeda los controles y declara la conexión estática en formato de persistencia.

  • Descripción de lo que sucede cuando se ejecuta el código de ejemplo.

La primera parte del ejemplo de código es el código fuente de los dos controles personalizados. En primer lugar, es el código del proveedor, que implementa la IWebPartTable interfaz . Por motivos de simplicidad en el ejemplo, el proveedor crea una tabla con algunos datos en lugar de conectarse a una base de datos. El GetConnectionInterface método actúa como punto de conexión del proveedor, el método de devolución de llamada que devuelve la instancia de interfaz al consumidor. En cuanto al consumidor, recupera la instancia de interfaz del proveedor en su método denominado SetConnectionInterface, que se marca con un ConnectionConsumer atributo . Después de recuperar la instancia de la interfaz, el consumidor, en su OnPreRender método, llama a la implementación del GetTableData método en el proveedor, para recuperar los datos reales y escribirlos en la página.

Para que se ejecute el ejemplo de código, debe compilar este código fuente. Puede compilarlo explícitamente y colocar el ensamblado resultante en la carpeta Bin del sitio web o en la caché global de ensamblados. Como alternativa, puede colocar el código fuente en la carpeta App_Code del sitio, donde se compilará dinámicamente en tiempo de ejecución. En este ejemplo de código se usa la compilación dinámica. Para ver un tutorial que muestra cómo compilar, vea Tutorial: Desarrollo y uso de un control 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

La segunda parte del ejemplo de código es la página web que declara la conexión estática y hospeda los controles. Cerca de la parte superior de la página hay una Register directiva que declara el espacio de nombres del código fuente contenido en el directorio App_Code. La conexión se declara mediante un <asp:webpartconnection> elemento . Los controles de consumidor y proveedor personalizados se declaran en un <zonetemplate> elemento dentro de un <asp:webpartzone> elemento , que es necesario para que puedan conectarse (deben residir dentro de una zona que hereda de la WebPartZoneBase clase ).

<%@ 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>

Cargue la página en un explorador. El control de consumidor muestra los datos proporcionados de la tabla especificada, que el proveedor pone a disposición a través de una instancia de la IWebPartTable interfaz .

Comentarios

Esta interfaz está diseñada para usarse con conexiones elementos web. En una conexión de elementos web, dos controles de servidor que residen en una WebPartZoneBase zona establecen una conexión y comparten datos, con un control que actúa como consumidor y otro que actúa como proveedor. El mecanismo para compartir datos en una conexión de elementos web es una instancia de interfaz, que el proveedor sirve al consumidor mediante un método de devolución de llamada. Para establecer una conexión, el consumidor y el proveedor deben trabajar con el mismo tipo de interfaz para compartir datos. Si el consumidor no reconoce el tipo de interfaz enviado por el proveedor, todavía es posible conectar los controles mediante un transformador (un WebPartTransformer objeto) que traduce la instancia de interfaz enviada por el proveedor a un tipo que reconoce el consumidor. Para obtener más información sobre las conexiones, consulte WebPartConnection y elementos web Connections Overview(Introducción a las conexiones).

La IWebPartTable interfaz es una interfaz de proveedor incluida con el conjunto de controles elementos web como una interfaz estándar para crear conexiones basadas en una tabla de datos. También puede crear interfaces personalizadas para usarlas con conexiones elementos web, pero en muchas aplicaciones web controladas por datos, resulta útil crear conexiones basadas en un campo común (para obtener más información, consulte la IWebPartField interfaz), fila (para obtener más información, ver la IWebPartRow interfaz) o tabla del origen de datos. En una conexión típica, un WebPart control que actúa como proveedor implementaría la IWebPartTable interfaz y proporcionaría una instancia de la interfaz a los consumidores en un método de devolución de llamada especial. Por ejemplo, el proveedor podría implementar una IWebPartTable interfaz para una tabla que contiene datos de rendimiento financiero. Otro WebPart control que actúa como consumidor definiría un método especial para recibir la instancia de interfaz y, a continuación, podría extraer los datos y representar un gráfico para mostrar la información resultante.

La IWebPartTable interfaz tiene dos miembros expuestos. La Schema propiedad devuelve información de esquema sobre la tabla de datos encapsulada en un PropertyDescriptorCollection objeto . El GetTableData método declara un método que un implementador (como un control de proveedor) usa para recuperar los datos de la tabla de la instancia de interfaz cuando se invoca el método de devolución de llamada.

Propiedades

Schema

Obtiene la información del esquema de una tabla de datos que se utiliza para compartir los datos entre dos controles WebPart.

Métodos

GetTableData(TableCallback)

Devuelve los datos de la tabla que la interfaz está utilizando como base de una conexión entre dos controles WebPart.

Se aplica a

Consulte también