次の方法で共有


接続可能な SharePoint Foundation の Web パーツを作成する

最終更新日: 2011年9月29日

適用対象: SharePoint Foundation 2010

この記事の内容
接続可能な Web パーツについて
ICellProvider インターフェイスを実装する Web パーツを作成する
ステップ 1 : インターフェイス クラスを作成する
ステップ 2 : イベントを宣言する
ステップ 3 : EnsureInterfaces メソッドを無効にし、次に RegisterInterface メソッドを呼び出す
ステップ 4 : CanRunAt メソッドを無効にする
ステップ 5 : PartCommunicationConnect メソッドを無効にする
ステップ 6 : PartCommunicationInit メソッドを無効にする
ステップ 7 : PartCommunicationMain メソッドを無効にする
ステップ 8 : GetInitEventArgs メソッドを無効にする
ステップ 9 : インターフェイス イベント ハンドラを実装する
ステップ 10 : RenderWebPart メソッドを無効にする
ステップ 11 : 関連するメソッドを実装する
ICellProvider インターフェイスと ICellConsumer インターフェイスを実装する一組のサンプル Web パーツ

このプログラミング作業では、2 つの接続可能な SharePoint Web パーツの作成方法について説明します。作成するのは、1 つのセルの値を使用できる Web パーツと、1 つのセルの値を提供できる Web パーツです。

重要重要

Microsoft SharePoint Foundation の Web パーツ インフラストラクチャは Microsoft ASP.NET Web パーツ インフラストラクチャに基づいて構築されており、ASP.NET の WebPart クラスから派生する Web パーツは、ASP.NET 接続モデルを含め、SharePoint で完全にサポートされています。可能な限り ASP.NET Web パーツを作成し、ASP.NET 接続モデルを使用して Web パーツに接続するようにします。

派生元として最適な WebPart 基本クラスの選択の詳細については、「Creating Web Parts in Windows SharePoint Services」を参照してください。ASP.NET Web パーツとその接続モデルの詳細については、ASP.NET のドキュメントの「Web パーツ接続の概要」を参照してください。

接続可能な Web パーツについて

SharePoint Web パーツ インフラストラクチャは、Web パーツが実行時に相互に情報をやり取りできる、接続インターフェイスと呼ばれる標準化されたインターフェイス セットを提供します。たとえば、SharePoint Foundation に組み込まれているリスト Web パーツは、1 行のデータを、行を表示するフォームを実装する Web パーツなど、その行を使用 (受信) する任意の Web パーツに提供 (送信) できます。

Web パーツ インフラストラクチャによって標準の接続インターフェイス セットが提供されるので、接続可能な Web パーツはさまざまな開発者や会社によって開発されることが可能で、相互に通信できます。接続インターフェイスをサポートする Web パーツは、エンド ユーザーが Microsoft SharePoint Designer または Web ブラウザーを使用して接続できます。これによりエンド ユーザーは、メニュー主導の簡単なインターフェイスから Web パーツの高度な組み合わせを構築できます。

SharePoint Foundation の接続クラスと接続インターフェイスは、Microsoft.SharePoint.WebPartPages.Communication 名前空間で実装されます。

接続インターフェイス

接続インターフェイスは、リスト内の行など特定のアイテムに関連するペアのイベントです。ペアのインターフェイスは、それぞれを実装する Web パーツの間に通信バスを形成します。接続可能な Web パーツは、1 つ以上の接続されたパーツに対してインターフェイス イベントを発生し、アクションを実行させます。ペアのインターフェイスは、一方がプロバイダ、他方がコンシューマと呼ばれます。プロバイダからのイベントはコンシューマで処理され、コンシューマからのイベントはプロバイダで処理されます。次の表は、ペアの接続インターフェイスについて簡単にまとめたものです。

接続インターフェイス ペア

説明

ICellProvider, ICellConsumer

セルまたはフィールドなど、1 つの値のアイテムを提供または使用する接続インターフェイスです。

IRowProvider, IRowConsumer

1 行 (または複数行) の値を提供または使用する接続インターフェイスです。

IListProvider, IListConsumer

リスト全体を提供または使用する接続インターフェイスです。

IFilterProvider, IFilterConsumer

フィルタ値を提供または使用する接続インターフェイスです。たとえば、SharePoint のリスト Web パーツは、IListProviderIRowProvider、および IFilterConsumer をサポートします。IRowProviderIFilterConsumer に接続できるので、2 つの異なる SharePoint リストが相互に接続できます。これにより、一方のリストが接続したもう一方のリストにフィルタを適用できます。

IParametersInProvider, IParametersInConsumer

Web パーツ間で任意のパラメータ セットを送受信できる IParameterIn インターフェイスです。これらのインターフェイスは、コンシューマ Web パーツがパラメータ リストを所有し、これを別の Web パーツと通信する必要がある状況で使用されます。

IParametersOutProvider, IParametersOutConsumer

Web パーツ間で任意のパラメータ セットを送受信できる IParameterOut インターフェイスです。これらのインターフェイスは、プロバイダ Web パーツがパラメータ リストを所有し、これを別の Web パーツと通信する必要がある状況で使用されます。

互換性規則

Web パーツを接続できるのは、互換性がある場合のみです。Web パーツ インフラストラクチャでは、2 つの Web パーツを接続できるかどうかを判断するときに、以下の互換性規則が評価されます。Web パーツの互換性がないと判明した場合、ブラウザーの [接続] メニューは無効になり、ツール ヒントには互換性がないという理由が表示されます。

対のペア

接続インターフェイスは、互換性のある他のインターフェイスとのみ接続できます。最も基本的な互換性規則は、対のペアとして、またはトランスフォーマを介して接続する必要があるということです。対のペアとして接続するというのは、IRowProvider インターフェイスを実装する Web パーツは、IRowConsumer インターフェイスを実装するもう 1 つの Web パーツと接続できるという意味です。

トランスフォーマ

Web パーツが、同じインターフェイスを持たない別の Web パーツと接続する必要がある場合、Web パーツ インフラストラクチャは、インターフェイス トランスフォーマを提供します。これにより、2 つの異なるインターフェイスを自然で透明な方法で接続できます。

たとえば、連絡先リストを画像ビューアに接続するとします。ただし、連絡先リストには IRowProvider インターフェイスしかなく、画像ビューアには ICellConsumer インターフェイスしかありません。この問題を解決するために、これら 2 つのインターフェイスを相互に接続できるインターフェイス トランスフォーマを使用します。

次の表は、トランスフォーマーを介して相互に接続できるインターフェイスのペアと、接続に Microsoft SharePoint Designer 2010 が必要かどうかを示します。

トランスフォーマ

ブラウザでの

接続

SharePoint Designer 2010 での接続

IRowProvider から ICellConsumer

はい

はい

IRowProvider から IFilterConsumer

はい

はい

IParametersOutProvider から IParametersInConsumer

いいえ

はい

IRowProvider から IParametersInConsumer

いいえ

はい

ページ間接続

一部のインターフェイスでは、別のページ上の Web パーツに接続できます。動作はハイパーリンクとほぼ同じです。

ページ間接続について、以下のことを理解する必要があります。

  • ページ間接続を作成するには、SharePoint Designer 2010 などの SharePoint Foundation 互換の Web ページ エディターが必要です。ただし、ページ間接続がいったん形成されたら、サポートされる任意の Web ブラウザーで実行時に利用できます。

  • ページ間接続を確立できるのは、サーバーで実行されるように設計された実装を持つ、接続可能な Web パーツのみです (CanRunAt メソッドで取得する ConnectionRunAt の値が Server または ServerAndClient であること)。クライアント側で形成される接続は、複数の Web ページにまたがることはできません。

次の表は、ページ間接続が可能なインターフェイスです。

接続元のページ インターフェイス

接続先のページ インターフェイス

IRowProvider

IFilterConsumer

IRowProvider

IParametersInConsumer

IFilterProvider

IFilterConsumer

IParametersOutProvider

IParametersInConsumer

IParametersInProvider

IParametersInConsumer

ページ間の Web パーツ接続を操作するときは、以下のことを実行する必要があります。

  • ConnectionRunAt.Server または ConnectionRunAt.ServerAndClient を RegisterInterface メソッドの runAtOptions パラメーターに渡します。

  • true を RegisterInterface メソッドの allowCrossPageConnection パラメータに渡します。

  • 接続インターフェイスから渡されるデータに関する情報を提供するために、GetInitEventArgs メソッドを実装します。

クライアントとサーバーの接続

Web パーツは、いつでもクライアントやサーバーで実行できます。稼働環境を検出し、クライアントでの実行とサーバーでの実行を動的に切り替えることができるように設計された Web パーツもあります。Web パーツは、同じ場所で稼働している別の Web パーツにのみ接続できます。たとえば、サーバー側のパーツが接続できるのは、サーバー側の別のパーツのみです。サーバー側のパーツは、クライアント側のパーツとは接続できません。接続チェーンに、種類の違う接続を含めることはできません。パーツがクライアントまたはサーバーの接続を動的に切り替えることができる場合、Web パーツ インフラストラクチャでは、その Web パーツが現在接続している Web パーツ チェーンに応じて、クライアント側またはサーバー側のパーツとして自動的に固定します。

接続の最大数

インターフェイスを登録すると、他の Web パーツへの接続の最大数を RegisterInterface メソッドの maxConnections パラメータに指定できます。1 つの Web パーツで接続の上限を超えると、他のパーツには接続できません。

オプションは、1 または無制限です。

  • WebPart.UnlimitedConnections は、接続可能な Web パーツが別の Web パーツとの接続数を制限しないことを指定します。

  • WebPart.LimitOneConnection は、接続可能な Web パーツが 1 つだけ接続を受け付けることを指定します。

循環接続の禁止

Web パーツは直接または接続チェーンを介して、それ自体に接続できません。

共有 Web パーツと個人用 Web パーツの接続

個人用 Web パーツがコンシューマで、共有 Web パーツが無制限数の接続をサポートしている場合、共有 Web パーツは個人用 Web パーツと接続できます。

プログラム フロー

接続した Web パーツは、特定のインターフェイス イベントを開始することで、相互に情報を渡します。Web パーツが ICellProvider などのインターフェイスを実装している場合、多数のメソッドを無効にする必要があります。インターフェイス イベントの開始は、無効にされたメソッドを指定したタイミングで Web パーツ インフラストラクチャが呼び出すことで実行されます。接続可能な Web パーツを作成する以下のステップは、無効にする必要があるメソッドと、そのために Web パーツ作成者が使用する典型的なコードを定義します。

ICellProvider インターフェイスを実装する Web パーツを作成する

このプログラミング作業では、ICellProvider インターフェイスを使用する接続インターフェイスに必要なメソッドとイベントをすべて実装するクラスを作成するプロセスを定義します。完全なコード例については、これらのステップの最後にある ICellProviderICellConsumer のサンプルを参照してください。

Web パーツの接続インターフェイスを実装するには、以下の 11 の高レベルのステップを実行する必要があります。

  1. インターフェイス クラスを作成します。

  2. イベントを宣言します。

  3. EnsureInterfaces メソッドをオーバーライドし、次に RegisterInterface メソッドを呼び出します。

  4. CanRunAt メソッドをオーバーライドします。

  5. PartCommunicationConnect メソッドをオーバーライドします。

  6. PartCommunicationInit メソッドをオーバーライドします。

  7. PartCommunicationMain メソッドをオーバーライドします。

  8. GetInitEventArgs メソッドをオーバーライドします。

  9. インターフェイス イベント ハンドラを実装します。

  10. RenderWebPart メソッドをオーバーライドします。

  11. 関連するメソッドを実装します。

ステップ 1 : インターフェイス クラスを作成する

定義済みの接続インターフェイスのいずれかを実装するクラスを作成します。この例では、ICellProvider インターフェイスを実装します。残りのステップ (2 ~ 11) で、すべてのコードはこのクラス内に記述します。

public class CellProvider : WebPart, ICellProvider

{
       // Much code goes here. See steps 2 – 11.
}
Public Class CellProvider
    Inherits WebPart
    Implements ICellProvider

    ' Much code goes here. See steps 2 – 11.
End Class

ステップ 2 : イベントを宣言する

接続インターフェイスに関連するすべてのイベントを宣言します。ここでは、Web パーツで使用される他の変数も宣言します。ICellProvider インターフェイスを操作しているので、以下の例では CellProviderInit イベントと CellReady イベント用の変数を宣言します。

// CellProviderInit Event

public event CellProviderInitEventHandler CellProviderInit;

// CellReady Event

public event CellReadyEventHandler CellReady;
' CellProviderInit Event

Public Event CellProviderInit As CellProviderInitEventHandler

' CellReady Event

Public Event CellReady As CellReadyEventHandler

ステップ 3 : EnsureInterfaces メソッドを無効にし、次に RegisterInterface メソッドを呼び出す

EnsureInterfaces メソッドを無効にします。このメソッドは、Web パーツのレンダリング前に Web パーツ インフラストラクチャによって呼び出されます。この時点で、2 つの RegisterInterface メソッドのいずれかを呼び出すことで、Web パーツのすべてのインターフェイスを登録します。

public override void EnsureInterfaces()
{
   // Register Interfaces      (See following section) 

}
Public Overrides Sub EnsureInterfaces()
   ' Register Interfaces      (See following section) 

End Sub

オーバーライドされた EnsureInterfaces メソッドの中で、RegisterInterface メソッドを呼び出すことで使用されるインターフェイスについて Web パーツ インフラストラクチャに通知します。ステップ 3 で説明するように、RegisterInterface メソッドは EnsureInterfaces メソッドの中で実行します。RegisterInterface メソッドは複数のパラメーターをとるので、次にそれらを定義します。

メソッド定義

protected InterfaceProperties RegisterInterface(string interfaceName,
                     string interfaceType,
                     int maxConnections,
                     ConnectionRunAt runAtOptions,
                     object interfaceObject,
                     string interfaceClientReference,
                     string menuLabel,
                     string description)
 Protected Function RegisterInterface(ByVal interfaceName As String,
                                         ByVal interfaceType As String,
                                         ByVal maxConnections As Integer,
                                          ByVal runAtOptions As ConnectionRunAt,
                                          ByVal interfaceObject As Object,
                                          ByVal interfaceClientReference As String,
                                          ByVal menuLabel As String,
                                          ByVal description As String) As InterfaceProperties

End Function

注意

2 番目の RegisterInterface メソッドを利用して、インターフェイスがページ間接続をサポートするかどうかを明示的に指定する allowCrossPageConnection パラメータを追加できます。このパラメータを含まない RegisterInterface メソッドは、Web パーツ インフラストラクチャによって定義された接続互換性規則でサポートされるすべての接続インターフェイスについて allowCrossPageConnection パラメータの設定を true にハードコーディングします (前述の「ページ間接続」を参照)。他のすべての接続インターフェイスは false にハードコーディングされます。

メソッド パラメータ

パラメータ

説明

interfaceName

インターフェイスのフレンドリ名を表す文字列プロパティ。フレンドリ名は、パーツに一意である必要があります。このプロパティには、特殊文字 (<、>、&、二重引用符、単一引用符、カンマ、またはセミコロン) を含めることはできません。

interfaceType

インターフェイスのタイプを表すプロパティ (IRowProviderICellConsumer など)。

maxConnections

1 つのインターフェイスに接続をいくつ形成できるかを決定するために Web パーツ インフラストラクチャが問い合わせることができるプロパティ。maxConnections は int です。WebPart.LimitOneConnection または WebPart.UnlimitedConnections を指定できます。

runAtOptions

インターフェイスが実行可能な場所を定義します (Client、Server、ClientAndServer、None)。

interfaceObject

このインターフェイスを実装する実際のオブジェクトへの参照。

interfaceClientReference

クライアント側接続の場合、interfaceClientReference は、インターフェイスを実装するクライアント側オブジェクトの識別子として使用される文字列です。名前の一意性を保証するために、この識別子には _WPQ_ が含まれ、() などの特殊文字を含めることができます。パーツがクライアント側接続をサポートしない場合は、空の文字列を使用できます。Web パーツ インフラストラクチャにより、二重引用符は単一引用符としてエンコードされます。

注意

WPQ_ は、パーツのレンダリング時に Web パーツ インフラストラクチャによって一意な識別子に置き換えられるトークンです。

menuLabel

汎用のラベルまたはインターフェイスの説明。これは、接続メニュー ユーザー インターフェイスに表示されます。接続を作成するユーザーがデータ フローの方向を理解できるように、メニュー ラベルの先頭には "Provide" や "Consume" などの動詞を使用することをお勧めします。

description

インターフェイスの詳しい説明。

InterfaceProperties myCellProviderInterface = RegisterInterface(
   "MyCellProviderInterface_WPQ_",   //InterfaceName 
   "ICellProvider",         //InterfaceType 
   WebPart.UnlimitedConnections,   //MaxConnections 
   ConnectionRunAt.ServerAndClient,   //RunAtOptions 
   this,               //InterfaceObject 
   "CellProviderInterface_WPQ_",   //InterfaceClientReference 
   "Provide Value From Text Box",         //MenuLabel 
   "Provides the value entered into the text box.");   //Description
Dim myCellProviderInterface As InterfaceProperties = RegisterInterface("MyCellProviderInterface_WPQ_", "ICellProvider", WebPart.UnlimitedConnections, ConnectionRunAt.ServerAndClient, Me, "CellProviderInterface_WPQ_", "Provide Value From Text Box", "Provides the value entered into the text box.") 'Description

注意

コード アクセス セキュリティ アクセス許可の例外をキャッチするには、RegisterInterface 呼び出しを try/catch ブロックで囲みます。これを行う方法の例については、RegisterInterface メソッドのトピックを参照してください。

ステップ 4 : CanRunAt メソッドを無効にする

接続可能なすべての Web パーツは CanRunAt メソッドを無効にする必要があります。このメソッドは、Web パーツが実行可能な場所はサーバーか、クライアントか、またはその両方かを知るために、Web パーツ インフラストラクチャによって呼び出されます。Web パーツは、ユーザーのクライアントの現在構成と接続先の Web パーツに基づいて、どこで実行できるかを決定する必要があります。返される値は、ConnectionRunAt 列挙値の Client、Server、ClientAndServer、および None です。たとえば、Web パーツにリッチとダウンレベルという 2 種類のレンダリングがあるとします。リッチ レンダリングを行うには、ActiveX コンポーネントがインストールされている必要があるとします。この場合、CanRunAt メソッドは、ActiveX コンポーネントがインストールされている場合は Client、インストールされていない場合は Server を返します。

public override ConnectionRunAt CanRunAt()
{
   // This Web Part can run on both the client and the server
   return ConnectionRunAt.ServerAndClient;
}
public override ConnectionRunAt CanRunAt()
{
   // This Web Part can run on both the client and the server
   return ConnectionRunAt.ServerAndClient;
}

ステップ 5 : PartCommunicationConnect メソッドを無効にする

接続可能なすべての Web パーツは PartCommunicationConnect メソッドを無効にする必要があります。このメソッドは、接続が完了したことを Web パーツに通知し、どのパーツに接続したかなどの関連情報を渡すために、Web パーツ インフラストラクチャによって呼び出されます。これは、接続したことを示すイベントに Web パーツ インフラストラクチャがリンクした直後に発生します。このメソッドでは、Web パーツ作成者がインターフェイスを実行できる場所を追跡し、必要な UI コントロールを作成し、接続が適切に形成されたことを確認します。このメソッドはいくつかのパラメータをとるので、次にそれらを定義します。

メソッド定義

public override void PartCommunicationConnect (string interfaceName, 
                  WebPart connectedPart, 
                  string connectedInterfaceName, 
                  ConnectionRunAt runAt)
Public Overrides Sub PartCommunicationConnect(ByVal interfaceName As String, ByVal connectedPart As WebPart, ByVal connectedInterfaceName As String, ByVal runAt As ConnectionRunAt)

End Sub

メソッド パラメータ

パラメータ

説明

interfaceName

接続中のインターフェイスのフレンドリ名。

connectedPart

現在の接続先である Web パーツへの参照。connectedPart パラメータと connectedInterfaceName パラメータの両方により、接続元のパーツが現在の接続先であるパーツのタイプを特定できます。これにより、Web パーツは詳細な情報を得た上で相手パーツとの通信を確立できます。たとえば、接続元パーツが接続先パーツに関する詳細な情報を持っている場合、接続元パーツは接続先パーツのパブリック オブジェクト モデルを利用できます。ただし、適切に機能するには、これらのパーツの両方がこの意図に沿って設計されている必要があります。たとえば、チャート パーツとピボット パーツは、両者が接続された場合に、共通のデータ ソースの同じレイアウトを共有するように設計できます。

connectedInterfaceName

接続先 Web パーツのインターフェイスのフレンドリ名。

runAt

インターフェイスが実行可能な場所。これはクライアントまたはサーバーのどちらかです。いくつかの要因に基づいて Web パーツ インフラストラクチャによって決定されます。

public override void PartCommunicationConnect(string interfaceName,
   WebPart connectedPart,
   string connectedInterfaceName,
   ConnectionRunAt runAt)
{
   // Check to see if this is a client-side part
   if (runAt == ConnectionRunAt.Client)
   {
      // This is a client-side part
      _runAtClient = true;
      return;
   }

   // Must be a server-side part - create the Web Part's controls
   EnsureChildControls(); 

   // Check if this is my particular cell interface
   if (interfaceName == "MyCellProviderInterface_WPQ_")
   {
      // Keep a count of the connections
   _cellConnectedCount++;
   }
}
Public Overrides Sub PartCommunicationConnect(ByVal interfaceName As String, ByVal connectedPart As WebPart, ByVal connectedInterfaceName As String, ByVal runAt As ConnectionRunAt)
   ' Check to see if this is a client-side part
   If runAt Is ConnectionRunAt.Client Then
       ' This is a client-side part
       _runAtClient = True
        Return
   End If

   ' Must be a server-side part - create the Web Part's controls
   EnsureChildControls()

   ' Check if this is my particular cell interface
   If interfaceName = "MyCellProviderInterface_WPQ_" Then
      ' Keep a count of the connections
      _cellConnectedCount += 1
   End If
End Sub

ステップ 6 : PartCommunicationInit メソッドを無効にする

接続可能な Web パーツは、PartCommunicationInit メソッドを必要に応じて無効にできます。このメソッドは、Web パーツが任意の初期化イベントを開始できるようにするために、Web パーツ インフラストラクチャによって呼び出されます。Web パーツは、末尾に "Init" が付くイベントを開始します (たとえば、CellProviderInit)。

Init パラメータは、Web パーツ自体に関する情報を他のパーツにブロードキャストする必要がある場合に便利です。たとえば、リスト パーツがフォーム パーツに接続している場合、リスト パーツはフィールド名をブロードキャストできます。その後、フォーム パーツは、リスト パーツからのフィールド名に基づいて、ユーザー インターフェイスをレンダリングできます。

注意

クライアント側 Web パーツでは、このイベントとイベント ハンドラをクライアントに実装する必要があります。

public override void PartCommunicationInit()
{
   //If the connection wasn't formed then don't send Init event
   if(_cellConnectedCount > 0)
   {
      //If there is a listener, send Init event
      if (CellProviderInit != null)
      {
         //Need to create the args for the CellProviderInit event
         CellProviderInitEventArgs cellProviderInitEventArgs = new
         CellProviderInitEventArgs();

         //Set the FieldName
         cellProviderInitEventArgs.FieldName = _cellName;
         cellProviderInitEventArgs.FieldDisplayName = _cellDisplayName;

         //Fire the CellProviderInit event
         CellProviderInit(this, cellProviderInitEventArgs);
      }
   }
}
Public Overrides Sub PartCommunicationInit()
    'If the connection wasn't formed then don't send Init event
    If _cellConnectedCount > 0 Then
        'If there is a listener, send Init event
        If CellProviderInit IsNot Nothing Then
            'Need to create the args for the CellProviderInit event
            Dim cellProviderInitEventArgs As New CellProviderInitEventArgs()

            'Set the FieldName
            cellProviderInitEventArgs.FieldName = _cellName
            cellProviderInitEventArgs.FieldDisplayName = _cellDisplayName

            'Fire the CellProviderInit event
            CellProviderInit(Me, cellProviderInitEventArgs)
        End If
    End If
End Sub

ステップ 7 : PartCommunicationMain メソッドを無効にする

接続可能な Web パーツは、PartCommunicationMain メソッドを必要に応じて無効にできます。このメソッドは、Web パーツがインターフェイスからの他の任意のイベント (たとえば、CellReady) を開始できるようにするために、Web パーツ インフラストラクチャによって呼び出されます。PartCommunicationMain メソッドの実行中に、スキーマではなく実際のデータ値が Web パーツ間でやり取りされます。

注意

クライアント側 Web パーツでは、このイベントとイベント ハンドラをクライアントに実装する必要があります。

public override void PartCommunicationMain()

{
   // NOTE: THIS CODE IS SPECIFIC TO EACH AND EVERY WEB PART’S IMPLEMENTATION.
   // If the connection wasn't formed then don't send Ready event
   if(_cellConnectedCount > 0)
   {
      // If there is a listener, send CellReady event
      if (CellReady != null)
      {
         // Need to create the args for the CellProviderInit event
         CellReadyEventArgs cellReadyEventArgs = new CellReadyEventArgs();

         // If user clicked button then send the value
         if (_cellClicked)
         {
            // Set the Cell to the value of the TextBox text
            // This is the value that will be sent to the Consumer
            cellReadyEventArgs.Cell = _cellInput.Text;
         }

         else
         {
            // The user didn't actually click the button
            // so just send an empty string to the Consumer
            cellReadyEventArgs.Cell = "";
         }

         // Fire the CellReady event
         // The Consumer will then receive the Cell value
         CellReady(this, cellReadyEventArgs);
      }
   }
}
 Public Overrides Sub PartCommunicationMain()

    ' NOTE: THIS CODE IS SPECIFIC TO EACH AND EVERY WEB PART’S IMPLEMENTATION.
    ' If the connection wasn't formed then don't send Ready event
    If _cellConnectedCount > 0 Then
        ' If there is a listener, send CellReady event
        If CellReady IsNot Nothing Then
            ' Need to create the args for the CellProviderInit event
            Dim cellReadyEventArgs As New CellReadyEventArgs()

            ' If user clicked button then send the value
            If _cellClicked Then
                ' Set the Cell to the value of the TextBox text
                ' This is the value that will be sent to the Consumer
                cellReadyEventArgs.Cell = _cellInput.Text

            Else
                ' The user didn't actually click the button
                ' so just send an empty string to the Consumer
                cellReadyEventArgs.Cell = ""
            End If

            ' Fire the CellReady event
            ' The Consumer will then receive the Cell value
            CellReady(Me, cellReadyEventArgs)
        End If
    End If
End Sub

ステップ 8 : GetInitEventArgs メソッドを無効にする

接続可能な Web パーツは GetInitEventArgs メソッドを必要に応じて無効にします。GetInitEventArgs メソッドは、トランスフォーマを使用するインターフェイスにのみ必須です。たとえば、IRowProviderICellConsumer、および IFilterConsumerIParametersOutProvider、および IParametersInConsumer はトランスフォーマをサポートできます。GetInitEventArgs メソッドは、トランスフォーマ ユーザー インターフェイスの作成に必要なすべての初期データに対して、接続作成ツールによって呼び出されます。メソッドは、InitEventArgs オブジェクトを返し、インターフェイス名を受け取ります。

たとえば、IRowProvider インターフェイスと ICellConsumer インターフェイスをサポートする 2 つの Web パーツを接続する場合、ユーザーは IRowProvider Web パーツのどのフィールドを ICellConsumer Web パーツの入力値に対応付けるかを指定する必要があります。これを行うには、Web パーツ インフラストラクチャが各インターフェイスで GetInitEventArgs メソッドを呼び出します。SharePoint Designer などの接続作成ツールやブラウザーでは、渡された Init パラメーターを使用してトランスフォーマーのユーザー インターフェイスを構築します。これにより、ユーザーはフィールド マッピングを選択できます。

メソッド定義

public override InitEventArgs GetInitEventArgs(string interfaceName)
Public Overrides Function GetInitEventArgs(ByVal interfaceName As String) As InitEventArgs
End Function

メソッド パラメータ

パラメータ

説明

interfaceName

インターフェイスのフレンドリ名を表す文字列プロパティ。

注意

このメソッドは、サーバーまたはクライアントに実装できます。

重要重要

これらのステップ全体の例として、ICellProvider インターフェイスを実装する Web パーツのコード例を使用しています。しかし、ICellProvider インターフェイスはトランスフォーマを使用しないので、GetInitEventArgs メソッドを無効にしません。ただし、完全を期すために、このプログラミング作業の終わりの CellConsumer.cs コード サンプルから以下に例を示します。この例では、GetInitEventArgs メソッドが無効にされます。

public override InitEventArgs GetInitEventArgs(string interfaceName)
{
   //Check if this is my particular cell interface
   if (interfaceName == "MyCellConsumerInterface_WPQ_")
   {
      EnsureChildControls();

      //Need to create the args for the CellConsumerInit event
      CellConsumerInitEventArgs cellConsumerInitArgs = 
         new CellConsumerInitEventArgs();

      //Set the FieldName and FieldDisplayName
      cellConsumerInitArgs.FieldName = _cellName;
      cellConsumerInitArgs.FieldDisplayName = _cellDisplayName;

      //return the InitArgs
      return(cellConsumerInitArgs);
   }
   else
   {
      return(null);
   }
}
Public Overrides Function GetInitEventArgs(ByVal interfaceName As String) As InitEventArgs
    'Check if this is my particular cell interface
    If interfaceName = "MyCellConsumerInterface_WPQ_" Then
        EnsureChildControls()

        'Need to create the args for the CellConsumerInit event
        Dim cellConsumerInitArgs As New CellConsumerInitEventArgs()

        'Set the FieldName and FieldDisplayName
        cellConsumerInitArgs.FieldName = _cellName
        cellConsumerInitArgs.FieldDisplayName = _cellDisplayName

        'return the InitArgs
        Return cellConsumerInitArgs
    Else
        Return Nothing
    End If
End Function

ステップ 9 : インターフェイス イベント ハンドラを実装する

使用しているインターフェイスのタイプに基づいて適切なイベント ハンドラを実装します。この例では、ICellProvider インターフェイスは CellConsumerInitEventHandler イベント ハンドラを実装する必要があります。このイベント ハンドラは、ICellConsumer インターフェイスによって渡されるデータが使用されるかどうかにかかわらず、実装する必要があります。コンシューマ パーツは、PartCommunicationInit メソッドの実行時にこのイベントを開始します。

メソッド定義

public void CellConsumerInit(object sender, CellConsumerInitEventArgs cellConsumerInitEventArgs)

メソッド パラメータ

パラメータ

説明

sender

このメソッドを呼び出すオブジェクト。

cellConsumerInitEventArgs

PartCommunicationInit フェーズでコンシューマ Web パーツによって渡されるパラメータ。

public void CellConsumerInitEventHandler(object sender, CellConsumerInitEventArgs cellConsumerInitEventArgs)
{
   // This is where the Provider part could see what type of "Cell" 
   //  the Consumer was expecting/requesting.
   // For this simple code example, this information is not used
   // anywhere.

}
Public Sub CellConsumerInitEventHandler(ByVal sender As Object, ByVal cellConsumerInitEventArgs As CellConsumerInitEventArgs)
   ' This is where the Provider part could see what type of "Cell" 
   '  the Consumer was expecting/requesting.
   ' For this simple code example, this information is not used
   ' anywhere.

End Sub

ステップ 10 : RenderWebPart メソッドを無効にする

すべての Web パーツは RenderWebPart メソッドを無効にする必要があります。細部は、Web パーツごとに異なります。Web パーツ インフラストラクチャはこのメソッドを呼び出して Web パーツをレンダリングします。完全な例については、このプログラミング作業トピックの最後にある CellProvider.cs ソース コードを参照してください。ここではスケルトン サンプルだけを示します。

protected override void RenderWebPart(HtmlTextWriter output)
{
   // Need to ensure that all of the Web Part's controls are created
   EnsureChildControls();

   // Render client connection code if the connection is client-side
   if (_runAtClient)
   {
      // Script for client-side rendering
   }
   else
   {
      // If connected then display all cell child controls
      if (_cellConnectedCount > 0)
      {
         // Code for server-side rendering
      }

      else
      {
         // There wasn't a cell connection formed,
      }
   }
}
Protected Overrides Sub RenderWebPart(ByVal output As HtmlTextWriter)
    ' Need to ensure that all of the Web Part's controls are created
    EnsureChildControls()

    ' Render client connection code if the connection is client-side
    If _runAtClient Then
        ' Script for client-side rendering
    Else
        ' If connected then display all cell child controls
        If _cellConnectedCount > 0 Then
            ' Code for server-side rendering

        Else
            ' There wasn't a cell connection formed,
        End If
    End If
End Sub

ステップ 11 : 関連するメソッドを実装する

ICellProvider ソース コードのこの部分で、関連するメソッドをすべて定義します。スケルトンを以下に示します。完全な例については、このプログラミング作業トピックの最後にある CellProvider.cs ソース コードを参照してください。

// Create all controls for this Web Part
protected override void CreateChildControls()
{
   //Code for Child Controls
}

// The Button OnClick event handler
private void CellButtonClicked(object sender, EventArgs e)
{
   _cellClicked = true; //user clicked button, set to true
}
' Create all controls for this Web Part
Protected Overrides Sub CreateChildControls()
   'Code for Child Controls
End Sub

' The Button OnClick event handler
Private Sub CellButtonClicked(ByVal sender As Object, ByVal e As EventArgs)
   _cellClicked = True 'user clicked button, set to true
End Sub

ICellProvider インターフェイスと ICellConsumer インターフェイスを実装する一組のサンプル Web パーツ

以下の 2 つのコード サンプルは、ICellProvider インターフェイスと ICellConsumer インターフェイスを実装する 2 つの接続可能な Web パーツの作成方法を示しています。

このプログラミング作業を完成するには、以下のコード サンプルを切り取って、Web パーツ プロジェクトの 2 つの C# ファイルに貼り付けてから、プロジェクトをビルドします。

//--------------------------------------------------------------------
// File : CellProvider.cs
//
// Purpose : A sample connectable Web Part that implements the 
//          ICellProvider interface.
//
//---------------------------------------------------------------------

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.WebPartPages.Communication;
using System.Runtime.InteropServices;

namespace ICellDemo
{
   /// <summary>
   /// The CellProvider Web Part class implementes the ICellProvider 
   /// interface. Its UI is very basic - it displays a simple text 
   /// box and button.  The CellConsumer Web Part class implements 
   /// the ICellConsumer interface.  When the CellProvider is
   /// connected to the CellConsumer on a Web Part Page, the CellProvider 
   /// can pass the value in its text box to the CellConsumer which displays 
   /// the value inline.
   /// </summary>
   /// 

   //Step #1: Implement the Connection Interface (ICellProvider)
   public class CellProvider : WebPart, ICellProvider
   {
      //Step #2: Declare Connection Events
      public event CellProviderInitEventHandler CellProviderInit;
      public event CellReadyEventHandler CellReady;

      //Used to keep track of whether or not the connection will be running client-side
      private bool _runAtClient = false;

      //Keep a count of ICell connections
      private int _cellConnectedCount = 0;

      //Web Part UI
      private Button _cellButton;   
      private TextBox _cellInput;
      
      //Cell information
      private string _cellName;
      private string _cellDisplayName;

      //Used to keep track of whether or not the Button in the Web Part was clicked
      private bool _cellClicked = false;


      //Step #3: EnsureInterfaces
      //Notification to the Web Part that is should ensure that all
      //its interfaces are registered using RegisterInterface.
      public override void EnsureInterfaces()
      {
         //Registers an interface for the Web Part
         RegisterInterface("MyCellProviderInterface_WPQ_",  //InterfaceName
            InterfaceTypes.ICellProvider,               //InterfaceType
            WebPart.UnlimitedConnections,               //MaxConnections
            ConnectionRunAt.ServerAndClient,            //RunAtOptions
            this,                                 //InterfaceObject
            "CellProviderInterface_WPQ_",               //InterfaceClientReference
            "Provide String from Textbox",               //MenuLabel
            "Provides a Textbox string");               //Description
      }


      //Step #4: CanRunAt - called by framework to determine where a part can run.
      public override ConnectionRunAt CanRunAt()
      {
         //This Web Part can run on both the client and the server
         return ConnectionRunAt.ServerAndClient;
      }

      //Step #5: PartCommunicationConnect - Notification to the Web Part that it has been connected.
      public override void PartCommunicationConnect(string interfaceName,
         WebPart connectedPart,
         string connectedInterfaceName,
         ConnectionRunAt runAt)
      {
         //Check to see if this is a client-side part
         if (runAt == ConnectionRunAt.Client)
         {
            //This is a client-side part
            _runAtClient = true;
            return;
         }
         
         //Must be a server-side part so need to create the Web Part's controls
         EnsureChildControls(); 

         //Check if this is my particular cell interface
         if (interfaceName == "MyCellProviderInterface_WPQ_")
         {
            //Keep a count of the connections
            _cellConnectedCount++;
         }
      }

      //Step #6: PartCommunicationInit - Notification to the Web Part that it has been connected.
      public override void PartCommunicationInit()
      {
         //If the connection wasn't actually formed then don't want to send Init event
         if(_cellConnectedCount > 0)
         {
            //If there is a listener, send Init event
            if (CellProviderInit != null)
            {
               //Need to create the args for the CellProviderInit event
               CellProviderInitEventArgs cellProviderInitArgs = new CellProviderInitEventArgs();
               
               //Set the FieldName
               cellProviderInitArgs.FieldName = _cellName;
               cellProviderInitArgs.FieldDisplayName = _cellDisplayName;
               
               //Fire the CellProviderInit event.
               CellProviderInit(this, cellProviderInitArgs);
            }
         }
      }

      //Step #7: PartCommunicationMain - Called by the framework to allow part to fire any remaining events
      public override void PartCommunicationMain()
      {
         //If the connection wasn't actually formed then don't want to send Ready event
         if(_cellConnectedCount > 0)
         {
            //If there is a listener, send CellReady event
            if (CellReady != null)
            {
               //Need to create the args for the CellProviderInit event
               CellReadyEventArgs cellReadyArgs = new CellReadyEventArgs();

               //If user clicked button then send the value
               if (_cellClicked)
               {
                  //Set the Cell to the value of the TextBox text
                  //This is the value that will be sent to the Consumer
                  cellReadyArgs.Cell = _cellInput.Text;
               }
               else
               {
                  //The user didn't actually click the button
                  //so just send an empty string to the Consumer
                  cellReadyArgs.Cell = "";
               }

               
               //Fire the CellReady event.
               //The Consumer will then receive the Cell value
               CellReady(this, cellReadyArgs);
            }
         }
      }

      //Step #8: GetInitArgs is not needed in this case. GetInitEventArgs only needs to be
      //implemented for interfaces that can participate in a transformer which are 
      //the following: ICellConsumer, IRowProvider, IFilterConsumer, IParametersOutProvider, 
      //IParametersInConsumer
 
      //Step #9: Implement CellConsumerInit event handler.
      public void CellConsumerInit(object sender, CellConsumerInitEventArgs cellConsumerInitArgs)
      {
         //This is where the Provider part could see what type of "Cell" the Consumer
         //was expecting/requesting.
         //For this simple code example, this information is not used anywhere.
      }

      //Step #10: RenderWebPart - defines Web Part UI and behavior
      protected override void RenderWebPart(HtmlTextWriter output)
      {
         //Need to ensure that all of the Web Part's controls are created
         EnsureChildControls();

         //Render client connection code if the connection is client-side
         if (_runAtClient)
         {
            //Connected client-side
            output.Write(ReplaceTokens("<br><h5>Connected Client-Side</h5><br>\n"
               + "<input type=\"text\" id=\"CellInput_WPQ_\"/>\n"
               + "<button id=\"CellButton_WPQ_\" onclick=\"CellButtonOnClick_WPQ_()\">Fire CellReady</button>\n"
               + "<SCRIPT LANGUAGE=\"JavaScript\">\n"
               + "<!-- \n"
               + "    var CellProviderInterface_WPQ_ = new myCellProviderInterface_WPQ_();\n"

               + "    function myCellProviderInterface_WPQ_()\n"
               + "    {\n"
               + "        this.PartCommunicationInit = myInit;\n"
               + "        this.PartCommunicationMain = myMain;\n"
               + "        this.CellConsumerInit = myCellConsumerInit;\n"

               + "        function myInit()\n"
               + "        {\n"
               + "            var cellProviderInitArgs = new Object();\n"
               + "            cellProviderInitArgs.FieldName = \"CellName\";\n"

               + "            WPSC.RaiseConnectionEvent(\"MyCellProviderInterface_WPQ_\", \"CellProviderInit\", cellProviderInitArgs);\n"
               + "        }\n"

               + "        function myMain()\n"
               + "        {\n"
               + "            var cellReadyArgs = new Object();\n"
                    + "            cellReadyArgs.Cell = \"\";\n"

               + "            WPSC.RaiseConnectionEvent(\"MyCellProviderInterface_WPQ_\", \"CellReady\", cellReadyArgs);\n"
               + "        }\n"

               + "        function myCellConsumerInit(sender, cellConsumerInitArgs)\n"
               + "        {\n"
                + "        }\n"
               + "    }\n"

               + "    function CellButtonOnClick_WPQ_()\n"
               + "    {\n"
               + "        var cellReadyArgs = new Object();\n"
               + "        cellReadyArgs.Cell = document.all(\"CellInput_WPQ_\").value;\n"

               + "        WPSC.RaiseConnectionEvent(\"MyCellProviderInterface_WPQ_\", \"CellReady\", cellReadyArgs);\n"
               + "    }\n"
               + "//-->\n"
               + "</SCRIPT>"));
         }
         else //Connected server-side
         {
            //If connected then display all cell child controls
            if (_cellConnectedCount > 0)
            {
               //Just render some informational text
               output.RenderBeginTag(HtmlTextWriterTag.Br);
               output.RenderEndTag();
               output.RenderBeginTag(HtmlTextWriterTag.H5);
               output.Write("Connected Server-Side");
               output.RenderEndTag();
               output.RenderBeginTag(HtmlTextWriterTag.Br);
               output.RenderEndTag();

               //Render the TextBox control
               _cellInput.RenderControl(output);

               //Render the Button
               _cellButton.RenderControl(output);
            }
            else
            {
               //There wasn't a cell connection formed,
               //so just output a message
               output.Write("NO CELL INTERFACE CONNECTION");
            }
         }
      }

      //Step #11.1 (Supporting Methods): CreateChildControls
      protected override void CreateChildControls()
      {
         //Create the Button
         _cellButton = new Button();
         _cellButton.ID = "CellButton";
         _cellButton.Text = "Fire CellReady";
         Controls.Add(_cellButton);
      
         //Create the TextBox
         _cellInput = new TextBox();
         _cellInput.ID = "CellInput";
         Controls.Add(_cellInput);

         //Set the Cell information.
         //This information will be passed to the Consumer by
         //firing the CellProviderInit event.
         _cellName = "CellInput";
         _cellDisplayName = "CellDisplayInput";
   
         _cellClicked = false; // Initialize to false -- user hasn't clicked yet
         _cellButton.Click += new EventHandler(CellButtonClicked); // listen for Button's click event
      }

      //Step #11.2 (Supporting Methods): CellButtonClicked
      // <param name="sender">The Button object</param>
      // <param name="e">The Event Arguments</param>
      private void CellButtonClicked(object sender, EventArgs e)
      {
         _cellClicked = true; //user clicked button, set to true
      }
   }
}
'--------------------------------------------------------------------
' File : CellProvider.cs
'
' Purpose : A sample connectable Web Part that implements the 
'          ICellProvider interface.
'
'---------------------------------------------------------------------

Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.ComponentModel
Imports Microsoft.SharePoint.WebPartPages
Imports Microsoft.SharePoint.WebPartPages.Communication
Imports System.Runtime.InteropServices

Namespace ICellDemo
    ''' <summary>
    ''' The CellProvider Web Part class implementes the ICellProvider 
    ''' interface. Its UI is very basic - it displays a simple text 
    ''' box and button.  The CellConsumer Web Part class implements 
    ''' the ICellConsumer interface.  When the CellProvider is
    ''' connected to the CellConsumer on a Web Part Page, the CellProvider 
    ''' can pass the value in its text box to the CellConsumer which displays 
    ''' the value inline.
    ''' </summary>
    ''' 

    'Step #1: Implement the Connection Interface (ICellProvider)
    Public Class CellProvider
        Inherits WebPart
        Implements ICellProvider
        'Step #2: Declare Connection Events
        Public Event CellProviderInit As CellProviderInitEventHandler
        Public Event CellReady As CellReadyEventHandler

        'Used to keep track of whether or not the connection will be running client-side
        Private _runAtClient As Boolean = False

        'Keep a count of ICell connections
        Private _cellConnectedCount As Integer = 0

        'Web Part UI
        Private _cellButton As Button
        Private _cellInput As TextBox

        'Cell information
        Private _cellName As String
        Private _cellDisplayName As String

        'Used to keep track of whether or not the Button in the Web Part was clicked
        Private _cellClicked As Boolean = False


        'Step #3: EnsureInterfaces
        'Notification to the Web Part that is should ensure that all
        'its interfaces are registered using RegisterInterface.
        Public Overrides Sub EnsureInterfaces()
            'Registers an interface for the Web Part
            RegisterInterface("MyCellProviderInterface_WPQ_", InterfaceTypes.ICellProvider, WebPart.UnlimitedConnections, ConnectionRunAt.ServerAndClient, Me, "CellProviderInterface_WPQ_", "Provide String from Textbox", "Provides a Textbox string") 'Description - MenuLabel - InterfaceClientReference - InterfaceObject - RunAtOptions - MaxConnections - InterfaceType - InterfaceName
        End Sub


        'Step #4: CanRunAt - called by framework to determine where a part can run.
        Public Overrides Function CanRunAt() As ConnectionRunAt
            'This Web Part can run on both the client and the server
            Return ConnectionRunAt.ServerAndClient
        End Function

        'Step #5: PartCommunicationConnect - Notification to the Web Part that it has been connected.
        Public Overrides Sub PartCommunicationConnect(ByVal interfaceName As String, ByVal connectedPart As WebPart, ByVal connectedInterfaceName As String, ByVal runAt As ConnectionRunAt)
            'Check to see if this is a client-side part
            If runAt Is ConnectionRunAt.Client Then
                'This is a client-side part
                _runAtClient = True
                Return
            End If

            'Must be a server-side part so need to create the Web Part's controls
            EnsureChildControls()

            'Check if this is my particular cell interface
            If interfaceName = "MyCellProviderInterface_WPQ_" Then
                'Keep a count of the connections
                _cellConnectedCount += 1
            End If
        End Sub

        'Step #6: PartCommunicationInit - Notification to the Web Part that it has been connected.
        Public Overrides Sub PartCommunicationInit()
            'If the connection wasn't actually formed then don't want to send Init event
            If _cellConnectedCount > 0 Then
                'If there is a listener, send Init event
                If CellProviderInitEvent IsNot Nothing Then
                    'Need to create the args for the CellProviderInit event
                    Dim cellProviderInitArgs As New CellProviderInitEventArgs()

                    'Set the FieldName
                    cellProviderInitArgs.FieldName = _cellName
                    cellProviderInitArgs.FieldDisplayName = _cellDisplayName

                    'Fire the CellProviderInit event.
                    RaiseEvent CellProviderInit(Me, cellProviderInitArgs)
                End If
            End If
        End Sub

        'Step #7: PartCommunicationMain - Called by the framework to allow part to fire any remaining events
        Public Overrides Sub PartCommunicationMain()
            'If the connection wasn't actually formed then don't want to send Ready event
            If _cellConnectedCount > 0 Then
                'If there is a listener, send CellReady event
                If CellReadyEvent IsNot Nothing Then
                    'Need to create the args for the CellProviderInit event
                    Dim cellReadyArgs As New CellReadyEventArgs()

                    'If user clicked button then send the value
                    If _cellClicked Then
                        'Set the Cell to the value of the TextBox text
                        'This is the value that will be sent to the Consumer
                        cellReadyArgs.Cell = _cellInput.Text
                    Else
                        'The user didn't actually click the button
                        'so just send an empty string to the Consumer
                        cellReadyArgs.Cell = ""
                    End If


                    'Fire the CellReady event.
                    'The Consumer will then receive the Cell value
                    RaiseEvent CellReady(Me, cellReadyArgs)
                End If
            End If
        End Sub

        'Step #8: GetInitArgs is not needed in this case. GetInitEventArgs only needs to be
        'implemented for interfaces that can participate in a transformer which are 
        'the following: ICellConsumer, IRowProvider, IFilterConsumer, IParametersOutProvider, 
        'IParametersInConsumer

        'Step #9: Implement CellConsumerInit event handler.
        Public Sub CellConsumerInit(ByVal sender As Object, ByVal cellConsumerInitArgs As CellConsumerInitEventArgs)
            'This is where the Provider part could see what type of "Cell" the Consumer
            'was expecting/requesting.
            'For this simple code example, this information is not used anywhere.
        End Sub

        'Step #10: RenderWebPart - defines Web Part UI and behavior
        Protected Overrides Sub RenderWebPart(ByVal output As HtmlTextWriter)
            'Need to ensure that all of the Web Part's controls are created
            EnsureChildControls()

            'Render client connection code if the connection is client-side
            If _runAtClient Then
                'Connected client-side
                output.Write(ReplaceTokens("<br><h5>Connected Client-Side</h5><br>" & vbLf & "<input type=""text"" id=""CellInput_WPQ_""/>" & vbLf & "<button id=""CellButton_WPQ_"" onclick=""CellButtonOnClick_WPQ_()"">Fire CellReady</button>" & vbLf & "<SCRIPT LANGUAGE=""JavaScript"">" & vbLf & "<!-- " & vbLf & "    var CellProviderInterface_WPQ_ = new myCellProviderInterface_WPQ_();" & vbLf & "    function myCellProviderInterface_WPQ_()" & vbLf & "    {" & vbLf & "        this.PartCommunicationInit = myInit;" & vbLf & "        this.PartCommunicationMain = myMain;" & vbLf & "        this.CellConsumerInit = myCellConsumerInit;" & vbLf & "        function myInit()" & vbLf & "        {" & vbLf & "            var cellProviderInitArgs = new Object();" & vbLf & "            cellProviderInitArgs.FieldName = ""CellName"";" & vbLf & "            WPSC.RaiseConnectionEvent(""MyCellProviderInterface_WPQ_"", ""CellProviderInit"", cellProviderInitArgs);" & vbLf & "        }" & vbLf & "        function myMain()" & vbLf & "        {" & vbLf & "            var cellReadyArgs = new Object();" & vbLf & "            cellReadyArgs.Cell = """";" & vbLf & "            WPSC.RaiseConnectionEvent(""MyCellProviderInterface_WPQ_"", ""CellReady"", cellReadyArgs);" & vbLf & "        }" & vbLf & "        function myCellConsumerInit(sender, cellConsumerInitArgs)" & vbLf & "        {" & vbLf & "        }" & vbLf & "    }" & vbLf & "    function CellButtonOnClick_WPQ_()" & vbLf & "    {" & vbLf & "        var cellReadyArgs = new Object();" & vbLf & "        cellReadyArgs.Cell = document.all(""CellInput_WPQ_"").value;" & vbLf & "        WPSC.RaiseConnectionEvent(""MyCellProviderInterface_WPQ_"", ""CellReady"", cellReadyArgs);" & vbLf & "    }" & vbLf & "//-->" & vbLf & "</SCRIPT>"))
            Else 'Connected server-side
                'If connected then display all cell child controls
                If _cellConnectedCount > 0 Then
                    'Just render some informational text
                    output.RenderBeginTag(HtmlTextWriterTag.Br)
                    output.RenderEndTag()
                    output.RenderBeginTag(HtmlTextWriterTag.H5)
                    output.Write("Connected Server-Side")
                    output.RenderEndTag()
                    output.RenderBeginTag(HtmlTextWriterTag.Br)
                    output.RenderEndTag()

                    'Render the TextBox control
                    _cellInput.RenderControl(output)

                    'Render the Button
                    _cellButton.RenderControl(output)
                Else
                    'There wasn't a cell connection formed,
                    'so just output a message
                    output.Write("NO CELL INTERFACE CONNECTION")
                End If
            End If
        End Sub

        'Step #11.1 (Supporting Methods): CreateChildControls
        Protected Overrides Sub CreateChildControls()
            'Create the Button
            _cellButton = New Button()
            _cellButton.ID = "CellButton"
            _cellButton.Text = "Fire CellReady"
            Controls.Add(_cellButton)

            'Create the TextBox
            _cellInput = New TextBox()
            _cellInput.ID = "CellInput"
            Controls.Add(_cellInput)

            'Set the Cell information.
            'This information will be passed to the Consumer by
            'firing the CellProviderInit event.
            _cellName = "CellInput"
            _cellDisplayName = "CellDisplayInput"

            _cellClicked = False ' Initialize to false -- user hasn't clicked yet
            AddHandler _cellButton.Click, AddressOf CellButtonClicked ' listen for Button's click event
        End Sub

        'Step #11.2 (Supporting Methods): CellButtonClicked
        ' <param name="sender">The Button object</param>
        ' <param name="e">The Event Arguments</param>
        Private Sub CellButtonClicked(ByVal sender As Object, ByVal e As EventArgs)
            _cellClicked = True 'user clicked button, set to true
        End Sub
    End Class
End Namespace
//--------------------------------------------------------------------
// File : CellConsumer.cs
//
// Purpose : A sample connectable Web Part that implements the 
//          ICellConsumer interface.
//
//---------------------------------------------------------------------
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.WebPartPages.Communication;
using System.Runtime.InteropServices;

namespace ICellDemo
{

   //Step #1: Implement the Connection Interface (ICellConsumer)
   public class CellConsumer : WebPart, ICellConsumer
   {
      
      //Step #2: Declare Connection events
      public event CellConsumerInitEventHandler CellConsumerInit;

      //Used to keep track of whether or not the connection will be running client-side
      private bool _runAtClient = false;

      //Keep a count of ICell connections
      private int _cellConnectedCount = 0;

      //Web Part UI
      private Label _cellLabel;

      //Cell information
      private string _cellName;
      private string _cellDisplayName;

      //Step #3: EnsureInterfaces
      //Notification to the Web Part that is should ensure that all
      //its interfaces are registered using RegisterInterface.
      public override void EnsureInterfaces()
      {
         //Registers an interface for the Web Part.
         RegisterInterface("MyCellConsumerInterface_WPQ_",   //InterfaceName
            InterfaceTypes.ICellConsumer,               //InterfaceType
            WebPart.UnlimitedConnections,               //MaxConnections
            ConnectionRunAt.ServerAndClient,            //RunAtOptions
            this,                                 //InterfaceObject
            "CellConsumerInterface_WPQ_",               //InterfaceClientReference
            "Get String Value",                        //MenuLabel
            "Just a simple ICellConsumer");               //Description
      }

      //Step #4: CanRunAt - called by framework to determine where a part can run.
      public override ConnectionRunAt CanRunAt()
      {
         //This Web Part can run on both the client and the server
         return ConnectionRunAt.ServerAndClient;
      }

      //Step #5: PartCommunicationConnect - Notification to the Web Part that it has been connected.
      public override void PartCommunicationConnect(string interfaceName,
         WebPart connectedPart,
         string connectedInterfaceName,
         ConnectionRunAt runAt)
      {
         //Check to see if this is a client-side part
         if (runAt == ConnectionRunAt.Client)
         {
            //This is a client-side part
            _runAtClient = true;
            return;
         }
         
         //Must be a server-side part so need to create the Web Part's controls
         EnsureChildControls(); 

         //Check if this is my particular cell interface
         if (interfaceName == "MyCellConsumerInterface_WPQ_")
         {
            //Keep a count of the connections
            _cellConnectedCount++;
         }
      }

      //Step #6: PartCommunicationInit - Notification to the Web Part that it has been connected.
      public override void PartCommunicationInit()
      {
         //If the connection wasn't actually formed then don't want to send Init event
         if(_cellConnectedCount > 0)
         {
            //If there is a listener, send init event
            if (CellConsumerInit != null)
            {
               //Need to create the args for the CellConsumerInit event
               CellConsumerInitEventArgs cellConsumerInitArgs = new CellConsumerInitEventArgs();
               
               //Set the FieldNames
               cellConsumerInitArgs.FieldName = _cellName;

               //Fire the CellConsumerInit event.
               //This basically tells the Provider Web Part what type of
               //cell the Consuemr is expecting in the CellReady event.
               CellConsumerInit(this, cellConsumerInitArgs);
            }
         }
      }

      //Step #7: PartCommunicationMain - this method doesn't need to be implemented for the Consumer
      //because the Consumer doesn't have any events that need to be fired during this phase.


      //Step #8: GetInitArgs - called by the connection authoring tool, e.g., browser or SharePoint Designer
      //to get the data required to build the transformer UI.
      public override InitEventArgs GetInitEventArgs(string interfaceName)
      {
         //Check if this is my particular cell interface
         if (interfaceName == "MyCellConsumerInterface_WPQ_")
         {
            EnsureChildControls();

            //Need to create the args for the CellConsumerInit event
            CellConsumerInitEventArgs cellConsumerInitArgs = new CellConsumerInitEventArgs();
               
            //Set the FieldName
            cellConsumerInitArgs.FieldName = _cellName;
            cellConsumerInitArgs.FieldDisplayName = _cellDisplayName;
               
            //return the InitArgs
            return(cellConsumerInitArgs);
         }
         else
         {
            return(null);
         }
      }

      
   
      //Step #9.1: Implement CellProviderInit Event Handler.
      public void CellProviderInit(object sender, CellProviderInitEventArgs cellProviderInitArgs)
      {
         //This is where the Consumer part could see what type of "Cell" the Provider
         //will be sending.
         //For this simple code example, this information is not used anywhere.
      }

      //Step #9.2: Implement CellReady Event Handler. 
      //Set label text based on value from the CellProvider Web Part
      public void CellReady(object sender, CellReadyEventArgs cellReadyArgs)
      {
         //Set the label text to the value of the "Cell" that was passed by the Provider
         if(cellReadyArgs.Cell != null)
         {
            _cellLabel.Text = cellReadyArgs.Cell.ToString();
         }
      }

      //Step #10: RenderWebPart - defines Web Part UI and behavior
      protected override void RenderWebPart(HtmlTextWriter output)
      {
         //Need to ensure that all of the Web Part's controls are created
         EnsureChildControls();

         //Render client connection code if needed
         if (_runAtClient)
         {
            //Connected client-side
            string strClientCode = "<br><h5>Connected Client-Side</h5><br>\n";
            strClientCode += "<div id=\"ConsumerDiv_WPQ_\"/>\n";
            strClientCode += "<SCRIPT LANGUAGE=\"JavaScript\">\n";
            strClientCode += "<!-- \n";
            strClientCode += "    var CellConsumerInterface_WPQ_ = new myCellConsumerInterface_WPQ_();\n";

            strClientCode += "    function myCellConsumerInterface_WPQ_()\n";
            strClientCode += "    {\n";
            strClientCode += "        this.PartCommunicationInit = myInit;\n";
            strClientCode += "        this.CellProviderInit = myCellProviderInit;\n";
            strClientCode += "        this.CellReady = myCellReady;\n";

            strClientCode += "        function myInit()\n";
            strClientCode += "        {\n";
            strClientCode += "            var cellConsumerInitArgs = new Object();\n";
            strClientCode += "            cellConsumerInitArgs.FieldName = \"CellName\";\n";

            strClientCode += "            WPSC.RaiseConnectionEvent(\"MyCellConsumerInterface_WPQ_\", \"CellConsumerInit\", cellConsumerInitArgs);\n";
            strClientCode += "        }\n";

            strClientCode += "        function myCellProviderInit(sender, cellProviderInitArgs)\n";
            strClientCode += "        {\n";
            strClientCode += "        }\n";

            strClientCode += "        function myCellReady(sender, cellReadyArgs)\n";
            strClientCode += "        {\n";
            strClientCode += "            document.all('ConsumerDiv_WPQ_').innerHTML = cellReadyArgs.Cell;\n";
            strClientCode += "        }\n";

            strClientCode += "    }\n";
            strClientCode += "//-->\n";
            strClientCode += "</SCRIPT>";

            output.Write(ReplaceTokens(strClientCode));
         }
         else //Connected server-side
         {
            //If we are connected then display all child controls
            if (_cellConnectedCount > 0)
            {         
               //Just render some informational text
               output.RenderBeginTag(HtmlTextWriterTag.Br);
               output.RenderEndTag();
               output.RenderBeginTag(HtmlTextWriterTag.H5);
               output.Write("Connected Server-Side");
               output.RenderEndTag();
               output.RenderBeginTag(HtmlTextWriterTag.Br);
               output.RenderEndTag();

               //Render the Label control
               _cellLabel.RenderControl(output);
            }
            else
            {
               //else display no connection message
               output.Write("NO CELL INTERFACE CONNECTION");
            }
         }         
      }

      //Step #11.1 (Supporting Methods): CreateChildControls
      protected override void CreateChildControls()
      {
         //Create the Label
         _cellLabel = new Label();
         _cellLabel.ID = "CellLabel";
         Controls.Add(_cellLabel);

         //Set the Cell information.
         //This information will be passed to the Provider by
         //firing the CellConsumerInit event.
         _cellName = "CellInputabc";
         _cellDisplayName = "My CellInput";
      }
   }
}
'--------------------------------------------------------------------
' File : CellConsumer.cs
'
' Purpose : A sample connectable Web Part that implements the 
'          ICellConsumer interface.
'
'---------------------------------------------------------------------
Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.ComponentModel
Imports Microsoft.SharePoint.WebPartPages
Imports Microsoft.SharePoint.WebPartPages.Communication
Imports System.Runtime.InteropServices

Namespace ICellDemo

    'Step #1: Implement the Connection Interface (ICellConsumer)
    Public Class CellConsumer
        Inherits WebPart
        Implements ICellConsumer

        'Step #2: Declare Connection events
        Public Event CellConsumerInit As CellConsumerInitEventHandler

        'Used to keep track of whether or not the connection will be running client-side
        Private _runAtClient As Boolean = False

        'Keep a count of ICell connections
        Private _cellConnectedCount As Integer = 0

        'Web Part UI
        Private _cellLabel As Label

        'Cell information
        Private _cellName As String
        Private _cellDisplayName As String

        'Step #3: EnsureInterfaces
        'Notification to the Web Part that is should ensure that all
        'its interfaces are registered using RegisterInterface.
        Public Overrides Sub EnsureInterfaces()
            'Registers an interface for the Web Part.
            RegisterInterface("MyCellConsumerInterface_WPQ_", InterfaceTypes.ICellConsumer, WebPart.UnlimitedConnections, ConnectionRunAt.ServerAndClient, Me, "CellConsumerInterface_WPQ_", "Get String Value", "Just a simple ICellConsumer") 'Description - MenuLabel - InterfaceClientReference - InterfaceObject - RunAtOptions - MaxConnections - InterfaceType - InterfaceName
        End Sub

        'Step #4: CanRunAt - called by framework to determine where a part can run.
        Public Overrides Function CanRunAt() As ConnectionRunAt
            'This Web Part can run on both the client and the server
            Return ConnectionRunAt.ServerAndClient
        End Function

        'Step #5: PartCommunicationConnect - Notification to the Web Part that it has been connected.
        Public Overrides Sub PartCommunicationConnect(ByVal interfaceName As String, ByVal connectedPart As WebPart, ByVal connectedInterfaceName As String, ByVal runAt As ConnectionRunAt)
            'Check to see if this is a client-side part
            If runAt Is ConnectionRunAt.Client Then
                'This is a client-side part
                _runAtClient = True
                Return
            End If

            'Must be a server-side part so need to create the Web Part's controls
            EnsureChildControls()

            'Check if this is my particular cell interface
            If interfaceName = "MyCellConsumerInterface_WPQ_" Then
                'Keep a count of the connections
                _cellConnectedCount += 1
            End If
        End Sub

        'Step #6: PartCommunicationInit - Notification to the Web Part that it has been connected.
        Public Overrides Sub PartCommunicationInit()
            'If the connection wasn't actually formed then don't want to send Init event
            If _cellConnectedCount > 0 Then
                'If there is a listener, send init event
                If CellConsumerInitEvent IsNot Nothing Then
                    'Need to create the args for the CellConsumerInit event
                    Dim cellConsumerInitArgs As New CellConsumerInitEventArgs()

                    'Set the FieldNames
                    cellConsumerInitArgs.FieldName = _cellName

                    'Fire the CellConsumerInit event.
                    'This basically tells the Provider Web Part what type of
                    'cell the Consuemr is expecting in the CellReady event.
                    RaiseEvent CellConsumerInit(Me, cellConsumerInitArgs)
                End If
            End If
        End Sub

        'Step #7: PartCommunicationMain - this method doesn't need to be implemented for the Consumer
        'because the Consumer doesn't have any events that need to be fired during this phase.


        'Step #8: GetInitArgs - called by the connection authoring tool, e.g., browser or SharePoint Designer
        'to get the data required to build the transformer UI.
        Public Overrides Function GetInitEventArgs(ByVal interfaceName As String) As InitEventArgs
            'Check if this is my particular cell interface
            If interfaceName = "MyCellConsumerInterface_WPQ_" Then
                EnsureChildControls()

                'Need to create the args for the CellConsumerInit event
                Dim cellConsumerInitArgs As New CellConsumerInitEventArgs()

                'Set the FieldName
                cellConsumerInitArgs.FieldName = _cellName
                cellConsumerInitArgs.FieldDisplayName = _cellDisplayName

                'return the InitArgs
                Return (cellConsumerInitArgs)
            Else
                Return (Nothing)
            End If
        End Function



        'Step #9.1: Implement CellProviderInit Event Handler.
        Public Sub CellProviderInit(ByVal sender As Object, ByVal cellProviderInitArgs As CellProviderInitEventArgs)
            'This is where the Consumer part could see what type of "Cell" the Provider
            'will be sending.
            'For this simple code example, this information is not used anywhere.
        End Sub

        'Step #9.2: Implement CellReady Event Handler. 
        'Set label text based on value from the CellProvider Web Part
        Public Sub CellReady(ByVal sender As Object, ByVal cellReadyArgs As CellReadyEventArgs)
            'Set the label text to the value of the "Cell" that was passed by the Provider
            If cellReadyArgs.Cell IsNot Nothing Then
                _cellLabel.Text = cellReadyArgs.Cell.ToString()
            End If
        End Sub

        'Step #10: RenderWebPart - defines Web Part UI and behavior
        Protected Overrides Sub RenderWebPart(ByVal output As HtmlTextWriter)
            'Need to ensure that all of the Web Part's controls are created
            EnsureChildControls()

            'Render client connection code if needed
            If _runAtClient Then
                'Connected client-side
                Dim strClientCode As String = "<br><h5>Connected Client-Side</h5><br>" & vbLf
                strClientCode &= "<div id=""ConsumerDiv_WPQ_""/>" & vbLf
                strClientCode &= "<SCRIPT LANGUAGE=""JavaScript"">" & vbLf
                strClientCode &= "<!-- " & vbLf
                strClientCode &= "    var CellConsumerInterface_WPQ_ = new myCellConsumerInterface_WPQ_();" & vbLf

                strClientCode &= "    function myCellConsumerInterface_WPQ_()" & vbLf
                strClientCode &= "    {" & vbLf
                strClientCode &= "        this.PartCommunicationInit = myInit;" & vbLf
                strClientCode &= "        this.CellProviderInit = myCellProviderInit;" & vbLf
                strClientCode &= "        this.CellReady = myCellReady;" & vbLf

                strClientCode &= "        function myInit()" & vbLf
                strClientCode &= "        {" & vbLf
                strClientCode &= "            var cellConsumerInitArgs = new Object();" & vbLf
                strClientCode &= "            cellConsumerInitArgs.FieldName = ""CellName"";" & vbLf

                strClientCode &= "            WPSC.RaiseConnectionEvent(""MyCellConsumerInterface_WPQ_"", ""CellConsumerInit"", cellConsumerInitArgs);" & vbLf
                strClientCode &= "        }" & vbLf

                strClientCode &= "        function myCellProviderInit(sender, cellProviderInitArgs)" & vbLf
                strClientCode &= "        {" & vbLf
                strClientCode &= "        }" & vbLf

                strClientCode &= "        function myCellReady(sender, cellReadyArgs)" & vbLf
                strClientCode &= "        {" & vbLf
                strClientCode &= "            document.all('ConsumerDiv_WPQ_').innerHTML = cellReadyArgs.Cell;" & vbLf
                strClientCode &= "        }" & vbLf

                strClientCode &= "    }" & vbLf
                strClientCode &= "//-->" & vbLf
                strClientCode &= "</SCRIPT>"

                output.Write(ReplaceTokens(strClientCode))
            Else 'Connected server-side
                'If we are connected then display all child controls
                If _cellConnectedCount > 0 Then
                    'Just render some informational text
                    output.RenderBeginTag(HtmlTextWriterTag.Br)
                    output.RenderEndTag()
                    output.RenderBeginTag(HtmlTextWriterTag.H5)
                    output.Write("Connected Server-Side")
                    output.RenderEndTag()
                    output.RenderBeginTag(HtmlTextWriterTag.Br)
                    output.RenderEndTag()

                    'Render the Label control
                    _cellLabel.RenderControl(output)
                Else
                    'else display no connection message
                    output.Write("NO CELL INTERFACE CONNECTION")
                End If
            End If
        End Sub

        'Step #11.1 (Supporting Methods): CreateChildControls
        Protected Overrides Sub CreateChildControls()
            'Create the Label
            _cellLabel = New Label()
            _cellLabel.ID = "CellLabel"
            Controls.Add(_cellLabel)

            'Set the Cell information.
            'This information will be passed to the Provider by
            'firing the CellConsumerInit event.
            _cellName = "CellInputabc"
            _cellDisplayName = "My CellInput"
        End Sub
    End Class
End Namespace

関連項目

その他の技術情報

Web パーツ接続の概要