Επεξεργασία

Κοινή χρήση μέσω


IWebPartField Interface

Definition

Defines a provider interface for connecting two server controls using a single field of data.

public interface class IWebPartField
public interface IWebPartField
type IWebPartField = interface
Public Interface IWebPartField
Derived

Examples

The following code example demonstrates how to create a static connection between two controls using the IWebPartField interface. The code example has three parts:

  • Source code for two custom WebPart controls that can form a connection using the IWebPartField interface, with one control acting as the provider, the other acting as the consumer.

  • A Web page that hosts the controls and declares the static connection in persistence format.

  • A description of what happens when the example code runs.

The first part of the code example is the source code for the two custom controls. First is the code for the provider, which implements the IWebPartField interface. For simplicity in the example, the provider creates a table with some data rather than connecting to a database. The GetConnectionInterface method serves as the provider's connection point, the callback method that returns the interface instance to the consumer. As for the consumer, it retrieves the interface instance from the provider in its method named SetConnectionInterface, which is marked with a ConnectionConsumer attribute. After retrieving the instance of the interface, the consumer, in its OnPreRender method, calls the implementation of the GetFieldValue method in the provider, to retrieve the actual data.

For the code example to run, you must compile this source code. You can compile it explicitly and put the resulting assembly in your Web site's Bin folder or the global assembly cache. Alternatively, you can put the source code in your site's App_Code folder, where it will be dynamically compiled at run time. This code example uses dynamic compilation. For a walkthrough that demonstrates how to compile, see Walkthrough: Developing and Using a Custom Web Server Control.

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 field data.
  [AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  public sealed class FieldProviderWebPart : WebPart, IWebPartField
  {
    private DataTable _table;

    public FieldProviderWebPart() 
    {
        _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);
    }

      [ConnectionProvider("FieldProvider")]
      public IWebPartField GetConnectionInterface()
    {
        return new FieldProviderWebPart();
    }

    public PropertyDescriptor Schema 
    {
        get 
        {
            /* The two parameters are row and field. Zero is the first record. 
                0,2 returns the zip code field value.   */ 
            return TypeDescriptor.GetProperties(_table.DefaultView[0])[2];
        }
    }

      void IWebPartField.GetFieldValue(FieldCallback callback) 
    {
        callback(Schema.GetValue(_table.DefaultView[0]));
    }
  } // end FieldProviderWebPart

  // This sample code creates a Web Parts control that acts as a consumer 
  // of an IWebPartField interface.
  [AspNetHostingPermission(SecurityAction.Demand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  [AspNetHostingPermission(SecurityAction.InheritanceDemand,
    Level = AspNetHostingPermissionLevel.Minimal)]
  public class FieldConsumerWebPart : WebPart
  {

    private IWebPartField _provider;
    private object _fieldValue;

    private void GetFieldValue(object fieldValue)
    {
      _fieldValue = fieldValue;
    }

    public bool ConnectionPointEnabled
    {
      get
      {
        object o = ViewState["ConnectionPointEnabled"];
        return (o != null) ? (bool)o : true;
      }
      set
      {
        ViewState["ConnectionPointEnabled"] = value;
      }
    }

    protected override void OnPreRender(EventArgs e)
    {
      if (_provider != null)
      {
        _provider.GetFieldValue(new FieldCallback(GetFieldValue));
      }
      base.OnPreRender(e);
    }

    protected override void RenderContents(HtmlTextWriter writer)
    {

      if (_provider != null)
      {
        PropertyDescriptor prop = _provider.Schema;

        if (prop != null && _fieldValue != null)
        {
          writer.Write(prop.DisplayName + ": " + _fieldValue);
        }
        else
        {
          writer.Write("No data");
        }
      }
      else
      {
        writer.Write("Not connected");
      }
    }

    [ConnectionConsumer("FieldConsumer", "Connpoint1", 
      typeof(FieldConsumerConnectionPoint), AllowsMultipleConnections = true)]
    public void SetConnectionInterface(IWebPartField provider)
    {
      _provider = provider;
    }

    public class FieldConsumerConnectionPoint : ConsumerConnectionPoint
    {
      public FieldConsumerConnectionPoint(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 ((FieldConsumerWebPart)control).ConnectionPointEnabled;
      }
    } // end FieldConsumerConnectionPoint
  } // end FieldConsumerWebPart
} // end namespace 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 field data.
  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public NotInheritable Class FieldProviderWebPart
    Inherits WebPart
    Implements IWebPartField
    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


    <ConnectionProvider("FieldProvider")> _
    Public Function GetConnectionInterface() As IWebPartField
      Return New FieldProviderWebPart()

    End Function


    Public ReadOnly Property Schema() As ComponentModel.PropertyDescriptor _
      Implements IWebPartField.Schema
      Get
        ' The two parameters are row and field. Zero is the first record. 
        ' 0,2 returns the zip code field value.   
        Return TypeDescriptor.GetProperties(_table.DefaultView(0))(2)
      End Get
    End Property


    Sub GetFieldValue(ByVal callback As FieldCallback) _
      Implements IWebPartField.GetFieldValue

      callback(Schema.GetValue(_table.DefaultView(0)))

    End Sub

  End Class


  ' This sample code creates a Web Parts control that acts as a 
  ' consumer of an IWebPartField interface.
  <AspNetHostingPermission(SecurityAction.Demand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  <AspNetHostingPermission(SecurityAction.InheritanceDemand, _
    Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class FieldConsumerWebPart
    Inherits WebPart

    Private _provider As IWebPartField
    Private _fieldValue As Object


    Private Sub GetFieldValue(ByVal fieldValue As Object)
      _fieldValue = fieldValue

    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


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

    End Sub


    Protected Overrides Sub RenderContents(ByVal writer As _
      HtmlTextWriter)

      If Not (_provider Is Nothing) Then
        Dim prop As PropertyDescriptor = _provider.Schema

        If Not (prop Is Nothing) AndAlso Not (_fieldValue Is Nothing) Then
          writer.Write(prop.DisplayName & ": " & _fieldValue)
        Else
          writer.Write("No data")
        End If
      Else
        writer.Write("Not connected")
      End If

    End Sub

    <ConnectionConsumer("FieldConsumer", "Connpoint1", _
      GetType(FieldConsumerConnectionPoint), AllowsMultipleConnections:=True)> _
    Public Sub SetConnectionInterface(ByVal provider As IWebPartField)
      _provider = provider

    End Sub

  End Class

  Public Class FieldConsumerConnectionPoint
    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


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

      Return CType(control, FieldConsumerWebPart).ConnectionPointEnabled

    End Function

  End Class

End Namespace  ' Samples.AspNet.VB.Controls

The second part of the code example is the Web page that declares the static connection and hosts the controls. Near the top of the page is a Register directive that declares the namespace of the source code contained in the App_Code directory. The connection is declared using an <asp:webpartconnection> element. The custom consumer and provider controls are declared in a <zonetemplate> element within an <asp:webpartzone> element, which is required for them to be able to connect (they must reside within a zone that inherits from the WebPartZoneBase class).

<%@ page language="C#" %>
<%@ Register tagprefix="IField" 
    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">

<!-- This code sample creates a page with two Web Parts controls 
and establishes a connection between the controls. -->
<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>IWebPartField Test Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:webpartmanager id="WebPartManager1" runat="server">
            <StaticConnections>
                <asp:WebPartConnection id="con1" ProviderID="provider1" 
                  ConsumerID="consumer1" 
                  ConsumerConnectionPointID="Connpoint1">
                </asp:WebPartConnection>
            </StaticConnections>
        </asp:webpartmanager>
        <asp:webpartzone id="WebPartZone1" runat="server">
            <zoneTemplate>
              <ifield:fieldproviderwebpart runat="Server" 
                ID="provider1" Title="Provider" />
              <ifield:fieldconsumerwebpart runat="Server" 
                ID="consumer1" Title="Consumer"/>
            </zoneTemplate>
        </asp:webpartzone>
    
    </div>
    </form>
</body>
</html>
<%@ page language="VB" debug="true" %>
<%@ Register tagprefix="IField" 
    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">

<!-- This code sample creates a page with two Web Parts controls 
and establishes a connection between the controls. -->
<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>IWebPartField Test Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:webpartmanager id="WebPartManager1" runat="server">
            <StaticConnections>
                <asp:WebPartConnection id="con1" ProviderID="provider1" 
                  ConsumerID="consumer1" 
                  ConsumerConnectionPointID="Connpoint1">
                </asp:WebPartConnection>
            </StaticConnections>
        </asp:webpartmanager>
        <asp:webpartzone id="WebPartZone1" runat="server">
            <zoneTemplate>
              <ifield:fieldproviderwebpart runat="Server" 
                ID="provider1" Title="Provider" />
              <ifield:fieldconsumerwebpart runat="Server" 
                ID="consumer1" Title="Consumer"/>
            </zoneTemplate>
        </asp:webpartzone>
    </div>
    </form>
</body>
</html>

Load the page in a browser. The consumer control displays the data provided from the specified field, which the provider makes available through an instance of the IWebPartField interface.

Remarks

This interface is designed to be used with Web Parts connections. In a Web Parts connection, two server controls that reside in a WebPartZoneBase zone establish a connection and share data, with one control acting as the consumer and the other control acting as a provider. The mechanism for sharing data in a Web Parts connection is an interface instance, which the provider serves to the consumer by means of a callback method. To establish a connection, the consumer and provider must both work with the same interface type for sharing data. If the consumer does not recognize the interface type sent by the provider, it is still possible to connect the controls by means of a transformer (a WebPartTransformer object) that translates the interface instance sent by the provider into a type that the consumer recognizes. For details on connections, see WebPartConnection and Web Parts Connections Overview.

The IWebPartField interface is a provider interface included with the Web Parts control set as a standard interface for creating connections based on a data field. You can also create custom interfaces to use with Web Parts connections, but in many data-driven Web applications, it is useful to create connections based on a common row (for details, see the IWebPartRow interface), table (for details, see the IWebPartTable interface), or field from the data source, using the IWebPartField interface. In a typical connection, a WebPart control acting as a provider would implement the IWebPartField interface and provide an instance of the interface to consumers in a special callback method. For example, the provider might implement an IWebPartField interface for a field in your user information table that contains a Web user's postal code data. Another WebPart control acting as a consumer would define a special method to receive the interface instance, and could then extract the postal code data, and look up and display weather information based on the postal code.

The IWebPartField interface has two exposed members. The Schema property returns schema information about the data field encapsulated in a PropertyDescriptor object. The GetFieldValue method declares a method that an implementer (such as a provider control) uses to retrieve the interface instance's field data when the callback method is invoked.

Properties

Schema

Gets the schema information for a data field that is used to share data between two WebPart controls.

Methods

GetFieldValue(FieldCallback)

Returns the value of the field that is being used by the interface as the basis of a connection between two WebPart controls.

Applies to

See also