Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

ProviderConnectionPoint Class

Defines a connection point object that enables a server control acting as a provider to form a connection with a consumer.

System.Object
  System.Web.UI.WebControls.WebParts.ConnectionPoint
    System.Web.UI.WebControls.WebParts.ProviderConnectionPoint

Namespace:  System.Web.UI.WebControls.WebParts
Assembly:  System.Web (in System.Web.dll)
public class ProviderConnectionPoint : ConnectionPoint

The ProviderConnectionPoint type exposes the following members.

  NameDescription
Public methodProviderConnectionPointInitializes a new instance of the ProviderConnectionPoint class.
Top
  NameDescription
Public propertyAllowsMultipleConnectionsGets a value that indicates whether a connection point supports multiple simultaneous connections. (Inherited from ConnectionPoint.)
Public propertyControlTypeGets the Type of the server control with which a connection point is associated. (Inherited from ConnectionPoint.)
Public propertyDisplayNameGets a string that serves as a friendly display name to represent a connection point in the user interface (UI). (Inherited from ConnectionPoint.)
Public propertyIDGets a string that contains the identifier for a connection point. (Inherited from ConnectionPoint.)
Public propertyInterfaceTypeGets the type of the interface used by a connection point. (Inherited from ConnectionPoint.)
Top
  NameDescription
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetEnabledReturns a value that indicates whether a connection point can participate in connections. (Inherited from ConnectionPoint.)
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetObjectInvokes the callback method in a provider control that gets an interface instance to return to consumers.
Public methodGetSecondaryInterfacesGets an optional collection of secondary interfaces that can be supported by a provider connection point.
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

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. 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. For a control acting as the provider in a connection, its connection point must be a ProviderConnectionPoint object. For details on Web Parts connections and connection points, see the topics listed in the See Also section below.

To create a ProviderConnectionPoint object, several steps are required:

  1. Create an interface. When a provider shares data with a consumer, it does so by getting an instance of an interface, and returning that instance to a consumer.

  2. Implement the interface in a provider. A WebPart or other server control (any type of server control in a WebPartZoneBase zone can be used) that will be the provider must implement the interface created in the first step.

  3. Identify a callback method. A method in the provider must be identified as the callback method to establish a connection. This method returns an instance of the implemented interface to a consumer. The Web Parts approach for identifying a callback method in the provider is to add a ConnectionProvider metadata attribute (defined by the ConnectionProviderAttribute class) to the method that returns the interface instance. When the attribute is added, the only required parameter is a display name to use for the provider connection point. Optional parameters can also be added, such as an ID for the connection point.

After a control has been equipped to act as a provider, the control can participate in connections (assuming that a consumer control is similarly equipped and available). To create a static, declarative connection in the markup of a Web page, developers can use the <asp:webpartconnection> element. If the ConnectionProvider attribute in the provider source code that identifies the callback method specifies an ID for the connection point, then that value must be assigned to the ProviderConnectionPointID attribute in the <asp:webpartconnection> element on a page. One reason that a developer might specify an ID for a provider connection point is if there are multiple connection points in the provider control. If an ID is not specified for the provider connection point in the provider control, a value does not have to be assigned to the ProviderConnectionPointID attribute in the page either, because the connection will be created using a default value obtained from the DefaultID field.

To create a connection in code, developers must create a new ProviderConnectionPoint object by calling the GetProviderConnectionPoints method and passing to it the ID of the provider control, along with the ID or index of the defined ProviderConnectionPoint object in the provider control. The returned ProviderConnectionPoint object, along with a reference to the provider control, a reference to the consumer control, and a corresponding ConsumerConnectionPoint object, are all passed to the ConnectWebParts method to create a new WebPartConnection object.

Although developers can use provider connection points as part of establishing connections either declaratively or programmatically, users can also interact with provider connection points to establish connections through the user interface (UI). If developers declare a ConnectionsZone control on a Web page, it provides a run-time UI for users to create connections. If users choose the consumer control as the starting point for establishing the connection by clicking its connect verb (they could also choose the provider; there is no difference in the resulting connection), in the UI they will see a drop-down list control with the display name of the available provider connection point (or points if there are multiple ones). Users must select a provider connection point to create a connection.

A ProviderConnectionPoint object associates directly with a specific provider control, and stores details about a connection in the properties it inherits from the base ConnectionPoint class. For example, in the inherited InterfaceType property, a provider connection point keeps the type of interface returned by the provider. If the provider and consumer in a connection both work with the same interface type, the controls are compatible and capable of forming a direct connection. 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 value into a type that the consumer can work with. Another important inherited property is the DisplayName property, which provides a friendly name to display in the UI for users to choose a provider connection point when creating connections. The display name is the required parameter when developers add a ConnectionProvider attribute to the callback method in a provider control. The inherited ID property is also useful, as indicated above, because it provides a unique identifier for a provider connection point in the event that a provider has multiple connection points. A provider can have multiple ProviderConnectionPoint objects defined in it, and in this case, when developers add the ConnectionProvider attribute to a method, they should specify an ID value to distinguish each connection point. One other notable inherited property is the AllowsMultipleConnections property, which indicates whether a provider connection point can connect simultaneously to multiple consumers. This property value is true by default for provider connection points (whereas it defaults to false for consumer connection points).

The ProviderConnectionPoint class adds several unique methods to the members it inherits from the ConnectionPoint class. The GetObject method retrieves an instance of the interface that the callback method will return to consumers. The GetSecondaryInterfaces method retrieves additional consumer interfaces that are part of an existing connection, but are not the interfaces used to establish the connection.

The following code example shows simple ways to create a connection declaratively, programmatically, or through the UI, in each case making use of a provider connection point.

The example has four parts:

  • A user control that enables you to change the Web Parts display mode on a page.

  • Source code for an interface and two WebPart controls acting as the provider and the consumer for a connection.

  • A Web page to host all the controls and run the code example.

  • An explanation of how to run the example page.

The first part of this code example is the user control that enables users to change display modes on a Web page. 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. 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="&nbsp;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>

The second part of the code example is the source code for the interface and controls. The source file contains a simple interface named IZipCode. There is also a WebPart class named ZipCodeWebPart that implements the interface and acts as the provider control. Its ProvideIZipCode method is the callback method that implements the interface's only member. The method simply returns an instance of the interface. Note that the method is marked with a ConnectionProvider attribute in its metadata. This is the mechanism for identifying the method as the callback method for the provider's connection point. The other WebPart class is named WeatherWebPart, and it acts as the consumer for the connection. This class has a method named GetZipCode that gets an instance of the IZipCode interface from the provider control. Note that this method is marked as the consumer's connection point method with a ConnectionConsumer attribute in its metadata. This is the mechanism for identifying the connection point method in the consumer control.

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.

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 (input.Text != String.Empty)
      {
        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);
    }

  }
}

The third part of the code example is the Web page. 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. The connection itself is created declaratively within the <staticconnections> element on the page. This demonstrates one way of creating a connection--note the ProviderConnectionPointID attribute in the <asp:webpartconnection> element. You can also create the connection programmatically; the code for doing that is in the Button1_Click method. In this case, a ProviderConnectionPoint object is created and then passed to a method that creates the actual connection. Whether the connection is created declaratively or programmatically, connection points must always be specified for both the provider and the consumer. 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>

After you load the page in a browser, click the Connection Point Details button. Information about the provider and consumer connection points established in the declarative connection appears. Next, use the Display Mode drop-down control to switch the page into connect mode. On the verbs menu of the ZIP Code Consumer WebPart control (represented by a downward arrow in the title bar), click the connect verb. The connection UI appears, created automatically by the <asp:connectionszone> control declared in the page. This is another way of creating a connection (through the UI), along with the declarative and programmatic methods discussed earlier. Click the Disconnect button to terminate the existing static connection. Click the Create a Connection to a Provider link. The UI now displays a drop-down control that lists the provider connection point display name. Select the connection point in the drop-down list, and then click Connect to complete the connection. Next, click Disconnect again. Then, click the Dynamic Connection button to create a connection programmatically. Use the Display Mode control to return the page to browse mode. Click the Connection Point Details button again, to once more indicate details about the provider connection point object.

The example has demonstrated establishing a connection and using a provider connection point in three ways: a static connection declared in the Web page markup; a connection created in code that used a ProviderConnectionPoint object; and a connection created by a user through the connection UI.

.NET Framework

Supported in: 4.5.1, 4.5, 4, 3.5, 3.0, 2.0

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft. All rights reserved.