外部データ ソースのデータを読み書きできる SharePoint 2010 の Web パーツを作成する

SharePoint Visual How To

概要:  Microsoft SharePoint Server 2010 で Microsoft Business Connectivity Services (BCS) 外部コンテンツ タイプを使用して AdventureWorks サンプル データベースとの間でデータを読み書きする視覚的 Web パーツを、Microsoft Visual Studio 2010 を使用して作成する方法を説明します。

最終更新日: 2012年9月12日

適用対象: Business Connectivity Services | Office 2010 | SharePoint Foundation 2010 | SharePoint Server 2010 | Visual Studio | Visual Studio 2008 | Visual Studio 2010

提供元:  Joel Krist、iSoftStone

概要

Microsoft Business Connectivity Services (BCS) は、Microsoft Office 2010 および SharePoint 2010 で提供されています。BCS は、Microsoft Office SharePoint Server 2007 のビジネス データ カタログの機能に基づいて構築され、外部システム書き戻しサポート、リッチ クライアントの統合など、新しい機能が導入されています。Visual Studio 2010 には視覚的 Web パーツ プロジェクト テンプレートが導入されています。これを利用すると、視覚的 Web パーツ デザイナーを使用して SharePoint Web パーツを作成した後、それをビルド プロセスの一部としてパッケージ化して展開できます。この Visual How To では、Visual Studio 2010 で BCS オブジェクト モデルを使用する視覚的 Web パーツを作成し、AdventureWorks Customer エンティティに基づいて外部コンテンツ タイプを使用する方法を説明します。

コード化する

この Visual How To は、外部コンテンツ タイプを使用する Web パーツの作成方法と使用方法を説明する次のセクションで構成されます。

  • Web パーツを使用する前提条件

  • Visual Studio 2010 を使用して視覚的 Web パーツを作成する

  • 視覚的 Web パーツ プロジェクトへの参照を追加する

  • Web パーツにコードを追加して、ユーザー インターフェイスを定義し、外部コンテンツ タイプを使用するためのサポートを追加する

  • Web パーツをビルドし、SharePoint Server に展開し、Web パーツ ページで使用する

Web パーツを使用する前提条件

この記事で説明する Web パーツは、Microsoft SQL Server AdventureWorks サンプル データベースの Person.Contact、Sales.Customer、Sales.Individual テーブルに基づく BCS 外部コンテンツ タイプを使用します。外部コンテンツ タイプは Microsoft SharePoint Designer 2010 で作成され、Microsoft SharePoint 2010 SDK で提供される AdventureWorks Web サービスを使用します。

この記事では Web パーツの作成方法に焦点を当てます。AdventureWorks サンプル データベースのインストール方法、AdventureWorks Web サービスの展開方法、SharePoint Designer での外部コンテンツ タイプの作成方法については詳しく説明しません。代わりに、前提条件についての基本情報を提供し、詳細については他のコンテンツを参照します。

ここで説明されている Web パーツを使用するには、次のものが必要です。

  • Microsoft SQL Server 2005 または Microsoft SQL Server 2008 を実行するサーバー。

  • SQL Server を実行するサーバーにインストールされた AdventureWorks 2005 オンライン トランザクション処理 (OLTP) データベース。AdventureWorks サンプル データベースは CodePlex (英語) からダウンロードできます。

  • SharePoint Server 2010 を実行するサーバー。

  • Web サーバーに展開されたサンプル AdventureWorks Web サービス。この Web サービスは Microsoft SharePoint 2010 SDK (英語) に含まれます。既定では、SDK をインストールすると、AdventureWorks Web サービスのファイルは次のフォルダーに格納されます。C:\Program Files (x86)\Microsoft SDKs\SharePoint Server 2010\Samples\Business Connectivity Services\bcs sample kit\BCS Sample Kit\LOB Systems\Adventure Works Web Service。

  • クライアント コンピューターにインストールされた Microsoft SharePoint Designer 2010。

  • AdventureWorks Web サービスに基づく WSCustomer 外部コンテンツ タイプ。SharePoint Designer 2010 で WSCustomer 外部コンテンツ タイプを作成する詳細な手順については、「[方法] Web サービスに基づく外部コンテンツ タイプを作成する」を参照してください。

以下でのセクションでの説明では、これらの前提条件がすべて満たされているものとします。

Visual Studio 2010 を使用した視覚的 Web パーツ プロジェクトの作成

以下の手順では、視覚的 Web パーツ プロジェクトを作成する方法を説明します。

視覚的 Web パーツ プロジェクトを作成するには

  1. 管理者として Visual Studio 2010 を開始します。

  2. Visual Studio で、[ファイル] メニューの [新規作成] をクリックし、[プロジェクト] をクリックします。

  3. [新しいプロジェクト] ダイアログ ボックスの [インストールされたテンプレート] ウィンドウで、[Visual C# SharePoint 2010] テンプレート タイプを選択します。

  4. テンプレートの一覧で、[視覚的 Web パーツ] テンプレートを選択します。

  5. プロジェクトとソリューションに「CustomerWebPart」という名前を設定し、ターゲット フレームワークのバージョンとして [.NET Framework 3.5] を選択します。

    図 1. ソリューションの作成

    ソリューションの作成
  6. [OK] をクリックします。

    Visual Studio で SharePoint カスタマイズ ウィザードが開始します。デバッグに使用するローカル SharePoint サイトの名前を入力し、[完了] をクリックします。

    図 2. SharePoint カスタマイズ ウィザード

    SharePoint カスタマイズ ウィザード
  7. Visual Studio によってソリューションが作成され、VisualWebPart1UserControl.ascx ユーザー コントロールがコード エディターで開かれます。

視覚的 Web パーツ プロジェクトの参照の追加

以下の手順では、視覚的 Web パーツ プロジェクトへの参照を追加する方法を説明します。

視覚的 Web パーツ プロジェクトへの参照を追加するには

  1. この記事で提供されている Web パーツ サンプル コードでは、Microsoft.BusinessData.dll アセンブリによって提供される Microsoft.BusinessData 名前空間のクラスと列挙を使用します。次のようにして、Microsoft.BusinessData アセンブリへの参照を追加します。

    1. Visual Studio で [プロジェクト] をクリックし、[参照の追加] をクリックします。

    2. [参照の追加] ダイアログ ボックスの [参照] タブで、次のフォルダーに移動します。C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI

    3. Microsoft.BusinessData.dll アセンブリが表示されるまで下にスクロールします。そのアセンブリを選択して、[OK] をクリックします。

      図 3. Microsoft.BusinessData への参照の追加

      Microsoft.BusinessData への参照の追加
  2. サンプル コードでは、System.Drawing アセンブリで定義されている Color クラスを使用します。System.Drawing アセンブリへの参照を追加します。

    1. Visual Studio で [プロジェクト] をクリックし、[参照の追加] をクリックします。

    2. [参照の追加] ダイアログ ボックスの [.NET] タブで、System.Drawing コンポーネントが表示されるまで下にスクロールし、コンポーネントを選択して、[OK] をクリックします。

      図 4. System.Drawing への参照の追加

      System.Drawing への参照の追加

Web パーツへのコードの追加

Web パーツのユーザー インターフェイスは単純です。WSCustomer 外部コンテンツ タイプ フィールドを入力および表示できる一連のテキスト ボックスと、外部コンテンツ タイプに対して作成アイテムの検索、および更新の各操作を実行できるボタンで構成されています。

コードを Web パーツに追加するには

  1. Visual Studio で、VisualWebPart1UserControl.ascx ファイルの Visual Studio によって作成された既定のディレクティブの後に、次のマークアップを追加します。

                  <style type="text/css">
      .style3
      {
        height: 81px;
      }
      .style4
      {
        width: 119px;
      }
      .style5
      {
        width: 559px;
      }
      .style6
      {
        height: 81px;
        width: 119px;
      }
      .style7
      {
       color : #FF3300;
      }
    </style>
    

    <table> <tr> <td colspan="2"> To work with the AdventureWorks Customer External Content Type (ECT) enter values for the ECT name and namespace, then do the following:

      &lt;ul style="padding-left: 0px; margin-left: 14px"&gt;
        &lt;li&gt;To create a new customer, leave the customer ID blank,
            enter values in the other fields, and then select
            &lt;strong&gt;Create New&lt;/strong&gt;.
        &lt;/li&gt;
        &lt;li&gt;To find a specific customer, enter the customer&amp;#39;s ID
            and then select &lt;strong&gt;Find by ID&lt;/strong&gt;.
        &lt;/li&gt;
        &lt;li&gt;To update a customer, enter the customer&amp;#39;s ID and
            updated values for the other fields and then select
            &lt;strong&gt;Update&lt;/strong&gt;.
        &lt;/li&gt;   
      &lt;/ul&gt;
            
      &lt;asp:Label ID="StatusLabel" runat="server"
       ForeColor="#FF3300"&gt;&lt;/asp:Label&gt;
            
      &lt;br /&gt;
      &lt;br /&gt;
    &lt;/td&gt;
    

    </tr> <tr> <td align="left" class="style4"> ECT Name<span class="style7"></span></td> <td class="style5"> <asp:TextBox ID="ECTName" runat="server" Width="100%"></asp:TextBox> </td> </tr> <tr> <td align="left" class="style4"> ECT Namespace<span class="style7"></span></td> <td class="style5"> <asp:TextBox ID="ECTNamespace" runat="server" Width="100%"></asp:TextBox> </td> </tr> <tr> <td align="left" class="style4">&nbsp;</td> <td class="style5">&nbsp;</td> </tr> <tr> <td align="left" class="style4"> Customer ID</td> <td class="style5"> <asp:TextBox ID="CustomerID" runat="server"></asp:TextBox> </td> </tr> <tr> <td align="left" class="style4"> Title</td> <td class="style5"> <asp:TextBox ID="Title" runat="server"></asp:TextBox> </td> </tr> <tr> <td align="left" class="style4"> First Name</td> <td class="style5"> <asp:TextBox ID="FirstName" runat="server" Width="100%"></asp:TextBox> </td> </tr> <tr> <td align="left" class="style4"> Middle Name</td> <td class="style5"> <asp:TextBox ID="MiddleName" runat="server" Width="100%"></asp:TextBox> </td> </tr> <tr> <td align="left" class="style4"> Last Name</td> <td class="style5"> <asp:TextBox ID="LastName" runat="server" Width="100%"></asp:TextBox> </td> </tr> <tr> <td align="left" class="style4"> Email</td> <td class="style5"> <asp:TextBox ID="Email" runat="server" Width="100%"></asp:TextBox> </td> </tr> <tr> <td align="left" class="style4"> Phone</td> <td class="style5"> <asp:TextBox ID="Phone" runat="server" Width="100%"></asp:TextBox> </td> </tr> <tr> <td align="center" class="style6"> &nbsp; </td> <td align="center" class="style3"> <asp:Button ID="CreateNewCustomer" runat="server" OnClick="CreateNewCustomer_Click" Text="Create New" Width="120px" /> &nbsp; <asp:Button ID="FindCustomerByID" runat="server" OnClick="FindCustomerByID_Click" Text="Find by ID" Width="120px" /> &nbsp; <asp:Button ID="UpdateCustomer" runat="server" OnClick="UpdateCustomer_Click" Text="Update" Width="120px" /> &nbsp; <asp:Button ID="ClearAllFields" runat="server" onclick="ClearAllFields_Click" Text="Clear All Fields" Width="120px" /> </td> </tr> </table>

    このマークアップを追加した後、VisualWebPart1UserControl.ascx のユーザー コントロールを [デザイン] ビューで表示すると、ユーザー インターフェイスは図 5 のようになります。

    図 5. ユーザー コントロールのユーザー インターフェイス

    ユーザー コントロール ユーザー インターフェイス
  2. VisualWebPart1UserControl.ascx ファイルを右クリックして、[コードの表示] を選択します。VisualWebPart1UserControl.ascx.cs ファイルが Visual Studio のコード エディターで開きます。

  3. VisualWebPart1UserControl.ascx.cs ファイルの内容を、次のコードに置き換えます。

    using System;
    using System.Drawing;
    using System.Web.UI;

    using Microsoft.SharePoint.BusinessData.SharedService; using Microsoft.BusinessData.MetadataModel; using Microsoft.BusinessData.Runtime; using Microsoft.SharePoint.Administration; using Microsoft.SharePoint;

    using Microsoft.BusinessData.Infrastructure; using Microsoft.BusinessData.MetadataModel.Collections;

    namespace CustomerWebPart.VisualWebPart1 { public partial class VisualWebPart1UserControl : UserControl { #region Properties

    protected string EntityNamespace
    {
      get { return ECTNamespace.Text.Trim(); }
    }
    
    protected string EntityName
    {
      get { return ECTName.Text.Trim(); }
    }
    
    protected bool EntityValuesAreSet
    {
      get
      {
        if (EntityNamespace == string.Empty ||
          EntityName == string.Empty)
          return false;
        else
          return true;
      }
    }
    
    #endregion
    
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    
    #region Create Customer
    
    protected void CreateNewCustomer_Click(object sender,
      EventArgs e)
    {
      // Ensure that we have values for the entity namespace and name.
      if (!EntityValuesAreSet)
      {
        DisplaySetPropertyValuePrompt(true);
        return;
      }
      else
        DisplaySetPropertyValuePrompt(false);
    
      try
      {
        using (new Microsoft.SharePoint.SPServiceContextScope(
          SPServiceContext.GetContext(SPContext.Current.Site)))
        {
          // Get the BDC service and metadata catalog.
          BdcService service =
           SPFarm.Local.Services.GetValue&lt;BdcService&gt;(String.Empty);
          IMetadataCatalog catalog =
            service.GetDatabaseBackedMetadataCatalog(
            SPServiceContext.Current);
    
          // Get the entity by using the specified name and namespace.
          IEntity entity =
            catalog.GetEntity(EntityNamespace, EntityName);
          ILobSystemInstance LobSysteminstance =
            entity.GetLobSystem().GetLobSystemInstances()[0].Value;
    
          // Get the fields on the entity.
          IView createView =
            entity.GetCreatorView("CreateCustomer");
          IFieldValueDictionary valueDictionary =
            createView.GetDefaultValues();
    
          // Set the values of the entity fields.
          valueDictionary["EmailAddress"] = Email.Text;
          valueDictionary["FirstName"] = FirstName.Text;
          valueDictionary["LastName"] = LastName.Text;
          valueDictionary["MiddleName"] = MiddleName.Text;
          valueDictionary["Phone"] = Phone.Text;
          valueDictionary["Title"] = Title.Text;
    
          // Call the creator method and display the returned
          // Customer ID.
          Identity id = entity.Create(valueDictionary,
            LobSysteminstance);
    
          CustomerID.Text =
            id.GetIdentifierValues().GetValue(0).ToString();
    
          StatusLabel.ForeColor = Color.Green;
          StatusLabel.Text = "Customer successfully created.";
        }
      }
      catch (Exception ex)
      {
        StatusLabel.ForeColor = Color.Red;
        StatusLabel.Text = "Unable to create customer." +
          ex.Message;
      }
    }
    
    #endregion
    
    #region Find Customer By ID
    
    protected void FindCustomerByID_Click(
      object sender, EventArgs e)
    {
      // Ensure that we have values for the entity namespace and name.
      if (!EntityValuesAreSet)
      {
        DisplaySetPropertyValuePrompt(true);
        return;
      }
      else
        DisplaySetPropertyValuePrompt(false);
    
      // Do simple validation of the customer ID. Ensure that it is
      // an integer.  
      int customerID = -1;
    
      if (!ValidateCustomerID(CustomerID.Text, ref customerID))
      {
        ClearFields(false);
        StatusLabel.ForeColor = Color.Red;
        StatusLabel.Text =
          "Please enter an integer for the Customer ID value.";
        return;
      }
    
      try
      {
        using (new Microsoft.SharePoint.SPServiceContextScope(
          SPServiceContext.GetContext(SPContext.Current.Site)))
        {
          // Get the BDC service and metadata catalog.
          BdcService service =
           SPFarm.Local.Services.GetValue&lt;BdcService&gt;(String.Empty);
          IMetadataCatalog catalog =
            service.GetDatabaseBackedMetadataCatalog(
            SPServiceContext.Current);
    
          // Get the entity by using the specified name and namespace.
          IEntity entity =
            catalog.GetEntity(EntityNamespace, EntityName);
          ILobSystemInstance LobSysteminstance =
            entity.GetLobSystem().GetLobSystemInstances()[0].Value;
    
          // Create an Identity based on the specified Customer ID.
          Identity identity = new Identity(customerID);
    
          // Get a method instance for the SpecificFinder method.
          IMethodInstance method =
            entity.GetMethodInstance("GetCustomerById",
            MethodInstanceType.SpecificFinder);
    
          // Execute the Specific Finder method to return the
          // customer data.
          IEntityInstance iei =
            entity.FindSpecific(identity, LobSysteminstance);
    
          // Display the data for the returned customer in the UI.
          Title.Text = iei["Title"] != null ?
            iei["Title"].ToString() : string.Empty;
          FirstName.Text = iei["FirstName"] != null ?
            iei["FirstName"].ToString() : string.Empty;
          MiddleName.Text = iei["MiddleName"] != null ?
            iei["MiddleName"].ToString() : string.Empty;
          LastName.Text = iei["LastName"] != null ?
            iei["LastName"].ToString() : string.Empty;
          Email.Text = iei["EmailAddress"] != null ?
            iei["EmailAddress"].ToString() : string.Empty;
          Phone.Text = iei["Phone"] != null ?
            iei["Phone"].ToString() : string.Empty;
        }
      }
      catch (Exception ex)
      {
        ClearFields(false);
    
        StatusLabel.ForeColor = Color.Red;
        StatusLabel.Text = "Unable to find customer with ID = " +
          CustomerID.Text + ". " + ex.Message;
      }
    }
    
    #endregion
    
    #region Update Customer
    
    protected void UpdateCustomer_Click(object sender, EventArgs e)
    {
      // Ensure that we have values for the entity namespace and name.
      if (!EntityValuesAreSet)
      {
        DisplaySetPropertyValuePrompt(true);
        return;
      }
      else
        DisplaySetPropertyValuePrompt(false);
    
      // Do simple validation of the customer ID. Ensure that it is
      // an integer.     
      int customerID = -1;
    
      if (!ValidateCustomerID(CustomerID.Text, ref customerID))
      {
        StatusLabel.ForeColor = Color.Red;
        StatusLabel.Text =
          "Please enter an integer for the Customer ID value.";
        return;
      }
    
      try
      {
        using (new Microsoft.SharePoint.SPServiceContextScope(
          SPServiceContext.GetContext(SPContext.Current.Site)))
        {
          // Get the BDC service and metadata catalog.
          BdcService service =
           SPFarm.Local.Services.GetValue&lt;BdcService&gt;(String.Empty);
          IMetadataCatalog catalog =
            service.GetDatabaseBackedMetadataCatalog(
            SPServiceContext.Current);
    
          // Get the entity by using the specified name and namespace.
          IEntity entity =
            catalog.GetEntity(EntityNamespace, EntityName);
          ILobSystemInstance LobSysteminstance =
            entity.GetLobSystem().GetLobSystemInstances()[0].Value;
          
          // Create an Identity based on the specified Customer ID.
          Identity identity = new Identity(customerID);
    
          // Get a method instance for the Updater method.
          IMethodInstance method =
            entity.GetMethodInstance("UpdateCustomer",
            MethodInstanceType.Updater);
    
          // The UpdateCustomer method of the external content type
          // maps to the UpdateCustomer method in the AdventureWorks
          // web service. Looking at the source for the web service
          // shows that the UpdateCustomer method has the following
          // signature:
          //
          // public void UpdateCustomer(SalesCustomer customer)
          //
          // The SalesCustomer type has the following layout: 
          //
          // public class SalesCustomer
          // {
          //     public int CustomerId { get; set; }
          //     public String Title { get; set; }
          //     public String FirstName { get; set; }
          //     public String MiddleName { get; set; }
          //     public String LastName   { get; set; }
          //     public String EmailAddress { get; set; }
          //     public String Phone { get; set; }
          //     public DateTime ModifiedDate { get; set; }
          // }
    
          // Get the collection of parameters for the method.
          // In this case, there is only one.
          IParameterCollection parameters =
            method.GetMethod().GetParameters();
    
          // Use type reflection to get an instance of a
          // SalesCustomer object to pass as a parameter.
          ITypeReflector reflector = parameters[0].TypeReflector;
          ITypeDescriptor rootTypeDescriptor =
            parameters[0].GetRootTypeDescriptor();
    
          object[] methodParamInstances =
            method.GetMethod().CreateDefaultParameterInstances(
            method);
          Object instance = methodParamInstances[0];
    
          // Get type descriptors for each of the SalesCustomer
          // members.
          ITypeDescriptor customerIDTypeDescriptor =
            rootTypeDescriptor.GetChildTypeDescriptors()[0];
          ITypeDescriptor titleTypeDescriptor =
            rootTypeDescriptor.GetChildTypeDescriptors()[1];
          ITypeDescriptor firstNameTypeDescriptor =
            rootTypeDescriptor.GetChildTypeDescriptors()[2];
          ITypeDescriptor middleNameTypeDescriptor =
            rootTypeDescriptor.GetChildTypeDescriptors()[3];
          ITypeDescriptor lastNameTypeDescriptor =
            rootTypeDescriptor.GetChildTypeDescriptors()[4];
          ITypeDescriptor emailAddressTypeDescriptor =
            rootTypeDescriptor.GetChildTypeDescriptors()[5];
          ITypeDescriptor phoneTypeDescriptor =
            rootTypeDescriptor.GetChildTypeDescriptors()[6];
          ITypeDescriptor modifiedDateTypeDescriptor =
            rootTypeDescriptor.GetChildTypeDescriptors()[7];
    
          // Set the values of the SalesCustomer object members
          // with the values specified by the user.
          reflector.Set(customerIDTypeDescriptor,
            rootTypeDescriptor,
            ref instance, customerID);
          reflector.Set(titleTypeDescriptor, rootTypeDescriptor,
            ref instance, Title.Text);
          reflector.Set(firstNameTypeDescriptor, rootTypeDescriptor,
            ref instance, FirstName.Text);
          reflector.Set(middleNameTypeDescriptor,
            rootTypeDescriptor,
            ref instance, MiddleName.Text);
          reflector.Set(lastNameTypeDescriptor, rootTypeDescriptor,
            ref instance, LastName.Text);
          reflector.Set(emailAddressTypeDescriptor,
            rootTypeDescriptor,
            ref instance, Email.Text);
          reflector.Set(phoneTypeDescriptor, rootTypeDescriptor,
            ref instance, Phone.Text);
          reflector.Set(modifiedDateTypeDescriptor,
            rootTypeDescriptor,
            ref instance, DateTime.Now);
    
          // Execute the updater method, passing the parameter.
          entity.Execute(method, LobSysteminstance,
            ref methodParamInstances);
    
          StatusLabel.ForeColor = Color.Green;
          StatusLabel.Text = "Customer successfully updated.";
        }
      }
      catch (Exception ex)
      {
        StatusLabel.ForeColor = Color.Red;
        StatusLabel.Text = "Unable to find customer with ID = " +
          CustomerID.Text + ". " + ex.Message;
      }
    }
    
    #endregion
    
    #region Helpers
    
    protected void DisplaySetPropertyValuePrompt(bool showPrompt)
    {
      if (showPrompt)
      {
        StatusLabel.ForeColor = Color.Red;
        StatusLabel.Text =
          "Please enter values for the ECT name and namespace!";
      }
      else
        StatusLabel.Text = string.Empty;
    }
    
    protected void ClearAllFields_Click(object sender, EventArgs e)
    {
      ClearFields(true);
    }
    
    protected bool ValidateCustomerID(string CustomerIDIn,
      ref int CustomerIDOut)
    {
      try
      {
        CustomerIDOut = Convert.ToInt32(CustomerIDIn);
        return true;
      }
      catch
      {
        CustomerIDOut = -1;
        return false;
      }
    }
    
    protected void ClearFields(bool clearCustomerID)
    {
      if (clearCustomerID)
        CustomerID.Text = string.Empty;
    
      Title.Text = string.Empty;
      FirstName.Text = string.Empty;
      MiddleName.Text = string.Empty;
      LastName.Text = string.Empty;
      Email.Text = string.Empty;
      Phone.Text = string.Empty;
    }
    
    #endregion
    

    } }

Web パーツのビルド、展開、使用

以下の手順では、Web パーツをビルド、展開、および使用する方法を説明します。

Web パーツをビルド、展開、および使用するには

  1. Visual Studio で、[ビルド] メニューの [ソリューションの展開] をクリックします。

    Visual Studio によって、Web パーツ アセンブリがビルドされ、必要なフィーチャーと展開ファイルが作成され、すべてが SharePoint ソリューション パッケージにパッケージ化されて、ソリューションの作成時にユーザーが指定したローカル SharePoint サイトに展開されます。

    図 6. Web パーツのビルドと展開

    Web パーツの構築と展開
  2. Web パーツを展開した SharePoint サイトを参照します。

  3. [サイトの操作] メニューの [新しいページ] をクリックします。

    図 7. [新しいページ] ダイアログ ボックス

    新規ページ ダイアログ ボックス
  4. [新しいページ] ダイアログ ボックスで、新しいページの名前を入力し、[作成] をクリックします。SharePoint Server によって新しいページが作成されて、そのページに移動します。

  5. 新しいページの [挿入] タブで、[Web パーツ] グループの [Web パーツ] をクリックします。

    図 8. ページへの Web パーツの追加

    Web パーツをページに追加
  6. SharePoint Server で表示されるユーザー インターフェイスを使用して、Web パーツを選択できます。[カテゴリ] で [Custom] を選択します。視覚的 Web パーツが、使用できる Web パーツの一覧に表示されます。Web パーツを選択して、[追加] をクリックします。

    図 9. Web パーツの選択

    Web パーツの選択

    Web パーツがページに追加されます。

    図 10. ページ上の Web パーツ

    ページの Web パーツ
  7. リボンの上の [保存] アイコンをクリックして、ページへの変更を保存します。

  8. 外部コンテンツ タイプの名前と名前空間の値を入力します。

    「[方法] Web サービスに基づく外部コンテンツ タイプを作成する」の手順に厳密に従った場合、外部コンテンツ タイプの名前は WSCustomer であり、名前空間は AdventureWorks Web サービスをホストしている Web サーバーの名前に基づきます。外部コンテンツ タイプの名前と名前空間を確認するには、以下の手順に従います。

    1. SharePoint Designer を使用して外部コンテンツ タイプを展開したサーバーで、SharePoint サーバーの全体管理サイトを開きます。

    2. [アプリケーション構成の管理] を選択します。

    3. [アプリケーション構成の管理] ページで、[サービス アプリケーションの管理] を選択します。

    4. [サービス アプリケーション] ページで、[Business Data Connectivity Service アプリケーション] のリンクをクリックします。

      [サービス アプリケーションの情報] ページが表示されます。AdventureWorks の WSCustomer 外部コンテンツ タイプの詳細が一覧表示されます。

      図 11. 外部コンテンツ タイプの詳細

      外部コンテンツ タイプの詳細
  9. Web パーツのユーザー インターフェイスで、[Customer ID] に有効な値を入力します。有効な Customer ID は、SQL Server Management Studio などのツールを使用して AdventureWorks データベースの Sales.Individual テーブルをクエリすることにより知ることができます。

  10. [Find by ID] をクリックします。

    指定した ID の顧客のデータが Web パーツに表示されます。これは、AdventureWorks Web サービスを使用して外部コンテンツ タイプを介して AdventureWorks データベースから返されたものです。

    図 12. AdventureWorks の顧客データが表示されている Web パーツ

    AdventureWorks を表示する Web パーツ
  11. 顧客のデータを変更し (Customer ID は変更しないでください)、[Update] をクリックします。Web パーツは、外部コンテンツ タイプを使用して顧客データを更新します。

    図 13. 顧客データの更新

    顧客データの更新
  12. [Clear All Fields] をクリックし、顧客のデータを入力して ([Customer ID] フィールドは空白のままにします)、新しい顧客を作成します。[Create New] をクリックすると、Web パーツは外部コンテンツ タイプを使用して AdventureWorks データベースに新しい顧客を追加します。

    図 14. 新しい顧客の作成

    新規顧客の作成

    SQL Server Management Studio を使用して AdventureWorks データベースをクエリし、外部コンテンツ タイプによる Web パーツ操作が正しく行われたことを確認できます。

    図 15. SQL Server Management Studio

    SQL Server Management Studio
手順

この Visual How To では、BCS 外部コンテンツ タイプを使用して AdventureWorks データベースとの間でデータを読み書きする視覚的 Web パーツを、Visual Studio 2010 を使用して作成する方法の手順とサンプル コードについて説明します。サンプル コードでは、外部コンテンツ タイプの Create メソッド、Specific Finder メソッド、および Update メソッドの使用方法が示されています。これは、SharePoint 2010 SDK で提供されているサンプルの AdventureWorks Web サービスが基になっています。

Web パーツの各メソッドは、同じ方法を使用して、BDC 共有サービスへの参照およびサーバー上のメタデータ カタログを取得し、カタログから顧客エンティティを取得します。

// Get the BDC service and metadata catalog.
BdcService service =
SPFarm.Local.Services.GetValue<BdcService>(String.Empty);
IMetadataCatalog catalog = service.GetDatabaseBackedMetadataCatalog(
SPServiceContext.Current);

// Get the entity by using the specified name and namespace. IEntity entity = catalog.GetEntity(EntityNamespace, EntityName); ILobSystemInstance LobSysteminstance = entity.GetLobSystem().GetLobSystemInstances()[0].Value;

その後、メソッドは異なる方法を使用してそれぞれの機能を実装します。作成関連のコードは、エンティティ フィールドを取得および設定できるように、外部コンテンツ タイプの CreateCustomer メソッドでビューを取得し、フィールドはエンティティの作成メソッドに渡されます。

// Get the fields on the entity.
IView createView = entity.GetCreatorView("CreateCustomer");
IFieldValueDictionary valueDictionary =
createView.GetDefaultValues();

// Set the values of the entity fields. valueDictionary["EmailAddress"] = Email.Text; valueDictionary["FirstName"] = FirstName.Text; valueDictionary["LastName"] = LastName.Text; valueDictionary["MiddleName"] = MiddleName.Text; valueDictionary["Phone"] = Phone.Text; valueDictionary["Title"] = Title.Text;

// Call the creator method and display the returned // Customer ID. Identity id = entity.Create(valueDictionary, LobSysteminstance);

特定検索関連のコードは、Identity オブジェクトを作成した後、外部コンテンツ タイプの Specific Finder メソッドでメソッド インスタンスを取得します。その後、エンティティで FindSpecific メソッドを呼び出し、メソッドは指定された顧客のデータを含む IEntityInstance オブジェクトを返します。

// Create an Identity based on the specified Customer ID.
Identity identity = new Identity(customerID);

// Get a method instance for the SpecificFinder method. IMethodInstance method = entity.GetMethodInstance("GetCustomerById", MethodInstanceType.SpecificFinder);

// Execute the Specific Finder method to return the // customer data. IEntityInstance iei = entity.FindSpecific(identity, LobSysteminstance);

更新関連のコードは、Identity オブジェクトを作成した後、外部コンテンツ タイプの Updater メソッドでメソッド インスタンスを取得します。このメソッド インスタンスを使用して Updater メソッドによって受け付けられるパラメーターのコレクションを取得し、タイプ リフレクションを使用してメソッドに渡すオブジェクトのインスタンスを作成して初期化します。最後に、IEntity.Execute を呼び出して外部コンテンツ タイプの Updater メソッドを呼び出し、顧客の更新された値のパラメーターを渡します。

// Create an Identity based on the specified Customer ID.
Identity identity = new Identity(customerID);

// Get a method instance for the Updater method. IMethodInstance method = entity.GetMethodInstance("UpdateCustomer", MethodInstanceType.Updater);

// Get the collection of parameters for the method. // In this case, there is only one. IParameterCollection parameters = method.GetMethod().GetParameters();

// Use type reflection to get an instance of a // SalesCustomer object to pass as a parameter. ITypeReflector reflector = parameters[0].TypeReflector; ITypeDescriptor rootTypeDescriptor = parameters[0].GetRootTypeDescriptor();

object[] methodParamInstances = method.GetMethod().CreateDefaultParameterInstances( method); Object instance = methodParamInstances[0];

// Get type descriptors for each of the SalesCustomer // members. ITypeDescriptor customerIDTypeDescriptor = rootTypeDescriptor.GetChildTypeDescriptors()[0]; ITypeDescriptor titleTypeDescriptor = rootTypeDescriptor.GetChildTypeDescriptors()[1]; ITypeDescriptor firstNameTypeDescriptor = rootTypeDescriptor.GetChildTypeDescriptors()[2]; ITypeDescriptor middleNameTypeDescriptor = rootTypeDescriptor.GetChildTypeDescriptors()[3]; ITypeDescriptor lastNameTypeDescriptor = rootTypeDescriptor.GetChildTypeDescriptors()[4]; ITypeDescriptor emailAddressTypeDescriptor = rootTypeDescriptor.GetChildTypeDescriptors()[5]; ITypeDescriptor phoneTypeDescriptor = rootTypeDescriptor.GetChildTypeDescriptors()[6]; ITypeDescriptor modifiedDateTypeDescriptor = rootTypeDescriptor.GetChildTypeDescriptors()[7];

// Set the values of the SalesCustomer object members // with the values specified by the user. reflector.Set(customerIDTypeDescriptor, rootTypeDescriptor, ref instance, customerID); reflector.Set(titleTypeDescriptor, rootTypeDescriptor, ref instance, Title.Text); reflector.Set(firstNameTypeDescriptor, rootTypeDescriptor, ref instance, FirstName.Text); reflector.Set(middleNameTypeDescriptor, rootTypeDescriptor, ref instance, MiddleName.Text); reflector.Set(lastNameTypeDescriptor, rootTypeDescriptor, ref instance, LastName.Text); reflector.Set(emailAddressTypeDescriptor, rootTypeDescriptor, ref instance, Email.Text); reflector.Set(phoneTypeDescriptor, rootTypeDescriptor, ref instance, Phone.Text); reflector.Set(modifiedDateTypeDescriptor, rootTypeDescriptor, ref instance, DateTime.Now);

// Execute the updater method, passing the parameter. entity.Execute(method, LobSysteminstance, ref methodParamInstances);

ビデオ

ビデオを見る

ビデオを見る (英語) (00:15:57)

クリックしてコードを取得

コードを取得する (英語)

関連情報