Microsoft-crm-plugins

提供:Dev Guides
移動先:案内検索

Microsoft Dynamics CRM-プラグイン

プラグインは、Microsoft Dynamics CRMと統合してプラットフォームの標準動作を変更または拡張するカスタムビジネスロジックです。 プラグインはイベントハンドラーとして機能し、CRMの特定のイベントで実行するように登録されます。 プラグインはC#またはVBで記述され、同期モードまたは非同期モードで実行できます。

プラグインを作成するシナリオは次のとおりです-

  • レコードの特定のフィールドの更新や関連レコードの更新など、いくつかのビジネスロジックを実行したい。 CRMレコードを作成または更新するとき。
  • レコードの保存や更新などの特定のイベントで外部Webサービスを呼び出します。
  • レコードが開かれたときにフィールド値を動的に計算したい場合。
  • CRMの特定のイベントで顧客に電子メールを送信するなどのプロセスを自動化します。

イベントフレームワーク

CRMのイベント処理フレームワークは、イベント実行パイプラインに渡すことにより、同期および非同期のプラグイン要求を処理します。 イベントがプラグインロジックをトリガーするたびに、メッセージがCRM組織Webサービスに送信され、そこで他のプラグインまたはプラットフォームのコア操作によって読み取りまたは変更できます。

プラグインパイプラインステージ

プラグインパイプライン全体は、カスタムビジネスロジックを登録できる複数の段階に分割されます。 指定されたパイプラインステージは、プラグインの実行サイクルのどのステージでプラグインコードが実行されるかを示します。 次の表で指定されているすべてのパイプラインステージのうち、カスタムプラグインは、事前イベントおよび事後イベントでのみ登録できます。 Platform Core Main Operationsにプラグインを登録することはできません。

Event Stage Name Description
Pre-Event Pre-validation Stage in the pipeline for plug-ins that are to execute before the main system operation. Plug-ins registered in this stage may execute outside the database transaction.
Pre-Event Pre-operation Stage in the pipeline for plug-ins that are to executed before the main system operation. Plugins registered in this stage are executed within the database transaction.
Platform Core Operation MainOperation Intransaction,the main operation of the system, such as create, update, delete, and so on. No custom plug-ins can be registered in this stage. For internal use only.
Post-Event Post-operation Stage in the pipeline for plug-ins which are to executed after the main operation. Plug-ins registered in this stage are executed within the database transaction.

CRMアプリケーションがイベント(レコードの保存や更新など)を呼び出すたびに、次の一連のアクションが行われます-

  • イベントはWebサービス呼び出しをトリガーし、実行はイベントパイプラインステージ(イベント前、プラットフォームコア操作、イベント後)を通過します。
  • 情報はOrganizationRequestメッセージとして内部的にパッケージ化され、最終的に内部CRM Webサービスメソッドとプラットフォームコア操作に送信されます。
  • OrganizationRequestメッセージは、イベント前プラグインによって最初に受信され、プラットフォームコア操作に渡す前に情報を変更できます。 プラットフォームのコア操作の後、メッセージはOrganizationResponseとしてパッケージ化され、操作後プラグインに渡されます。 postoperationsプラグインは、オプションでこの情報を変更してから、非同期プラグインに渡すことができます。
  • プラグインはこの情報をコンテキストオブジェクトの形式で受け取り、Executeメソッドに渡された後、さらに処理が行われます。
  • すべてのプラグインの処理が完了すると、実行がイベントをトリガーしたアプリケーションに返されます。

プラグインメッセージ

メッセージは、プラグイン(またはビジネスロジック)が登録されるイベントです。 たとえば、連絡先エンティティのメッセージの作成にプラグインを登録できます。 これにより、新しい連絡先レコードが作成されるたびにビジネスロジックが起動します。

カスタムエンティティの場合、エンティティがユーザー所有か組織所有かによって、サポートされるメッセージは次のとおりです。

Message Name Ownership Type
Assign User-owned entities only
Create User-owned and organization-owned entities
Delete User-owned and organization-owned entities
GrantAccess User-owned entities only
ModifyAccess User-owned entities only
Retrieve User-owned and organization-owned entities
RetrieveMultiple User-owned and organization-owned entities
RetrievePrincipalAccess User-owned entities only
RetrieveSharedPrincipalsAndAccess User-owned entities only
RevokeAccess User-owned entities only
SetState User-owned and organization-owned entities
SetStateDynamicEntity User-owned and organization-owned entities
Update User-owned and organization-owned entities

既定の既定のエンティティには、100を超えるメッセージがサポートされています。 これらのメッセージの一部はすべてのエンティティに適用できますが、一部のメッセージは特定のエンティティに固有です。 サポートされているメッセージの完全なリストは、SDK内のExcelファイルで見つけることができます: SDK \ Message-entity support for plug-ins.xlsx

プラグインを書く

このセクションでは、プラグイン作成の基本を学びます。 新しい顧客がシステムに追加されるたびに、顧客にフォローアップするタスクアクティビティを作成するサンプルプラグインを作成します。 CRMで新しいContactrecordが作成されるたび。

まず、 Microsoft.Xrm.Sdk 名前空間への参照を含める必要があります。 CRM SDKには、必要なすべてのSDKアセンブリが含まれています。 第2章でSDKを既にダウンロードしてインストールしていると仮定して、Visual Studioを開きます。 タイプクラスライブラリの新しいプロジェクトを作成します。 プロジェクトにSamplePluginsという名前を付けて、[OK]をクリックします。

Mscrmプラグインの作成とソリューション

*Microsoft.Xrm.Sdk* アセンブリの参照をプロジェクトに追加します。 アセンブリは *SDK/Bin* にあります。

Mscrmプラグインソリューション追加リファレンス

ここで、 PostCreateContact.cs という名前のクラスを作成し、 IPlugin からクラスを拡張します。 これまで、コードは次のようになります。

Mscrmプラグインサンプルコード

System.Runtime.Serializationへの参照も追加する必要があります。 必要な参照を追加したら、次のコードを PostCreateContact クラス内にコピーします。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;

namespace SamplePlugins {
   public class PostCreateContact:IPlugin {
     ///A plug-in that creates a follow-up task activity when a new account is created.
     ///Register this plug-in on the Create message, account entity,
     ///and asynchronous mode.

      public void Execute(IServiceProviderserviceProvider) {
        //Obtain the execution context from the service provider.
         IPluginExecutionContext context =(IPluginExecutionContext)
            serviceProvider.GetService(typeof(IPluginExecutionContext));

        //The InputParameters collection contains all the data
            passed in the message request.

         if(context.InputParameters.Contains("Target")&&
            context.InputParameters["Target"]isEntity) {

           //Obtain the target entity from the input parameters.
            Entity entity = (Entity)context.InputParameters["Target"];
            try {

              //Create a task activity to follow up with the account customer in 7 days
               Entity followup = new Entity("task");
               followup["subject"] = "Send e-mail to the new customer.";
               followup["description"] =
                  "Follow up with the customer. Check if there are any new issues
                  that need resolution.";

               followup["scheduledstart"] = DateTime.Now;
               followup["scheduledend"] = DateTime.Now.AddDays(2);
               followup["category"] = context.PrimaryEntityName;

              //Refer to the contact in the task activity.
               if(context.OutputParameters.Contains("id")) {
                  Guid regardingobjectid = new Guid(context.OutputParameter
                     s["id"].ToString());
                  string regardingobjectidType = "contact";
                  followup["regardingobjectid"] =
                     new EntityReference(rega rdingobjectidType,regardingobjectid);
               }

              //Obtain the organization service reference.
               IOrganizationServiceFactory serviceFactory =
                  (IOrganizationSer viceFactory)serviceProvider.GetService
                  (typeof(IOrganizationServiceFactory));
               IOrganizationService service =
                  serviceFactory.CreateOrganizationService(context.UserId);

              //Create the followup activity
               service.Create(followup);
            } catch(Exception ex) {
               throw new InvalidPluginExecutionException(ex.Message);
            }
         }
      }
   }
}

以下は、このコードが何をするかの段階的な説明です-

  • ステップ1 *-IServiceProviderオブジェクトをパラメーターとして使用して、Executeメソッドを実装します。 サービスプロバイダーには、プラグイン内で使用する多くの便利なオブジェクトへの参照が含まれています。
  • ステップ2 *-IServiceProviderのGetServiceメソッドを使用してIPluginExecutionContextオブジェクトを取得します。
  • ステップ3 *-コンテキストオブジェクトのInputParametersコレクションからターゲットエンティティのオブジェクトを取得します。 このEntityクラスオブジェクトは、プラグインが登録されるContactエンティティレコードを参照します。
  • ステップ4 *-タスクエンティティのオブジェクトを作成し、適切な件名、説明、日付、カテゴリ、および関連するobjectidを設定します。 relatedobjectidは、このアクティビティレコードが作成されている連絡先レコードを示します。 context.OutputParametersを使用して、コードが親のContactレコードのIDを取得し、作成したタスクエンティティレコードに関連付けることがわかります。
  • ステップ5 *-IServiceProviderオブジェクトを使用してIOrganizationServiceFactoryのオブジェクトを作成します。
  • ステップ6 *-IOrganizationServiceFactoryオブジェクトを使用してIOrganizationServiceのオブジェクトを作成します。
  • ステップ7 *-最後に、このサービスオブジェクトのCreateメソッドを使用します。 CRMに保存されるフォローアップアクティビティを作成します。

プラグインアセンブリに署名する

このセクションは、初めてプラグインアセンブリを登録する場合にのみ適用されます。 プラグインをデプロイするには、キーを使用してアセンブリにサインインする必要があります。 ソリューションを右クリックして、[プロパティ]をクリックします。

Mscrmプラグインソリューションプロパティ

左側のオプションから[署名]タブを選択し、[アセンブリに署名]オプションをオンにします。 次に、[厳密な名前のキーファイルの選択]オプションから[新規]を選択します。

Mscrmプラグインサインアセンブリ

キーファイル名をsamplepluginsとして入力します(他の任意の名前を使用できます)。 [キーファイルをパスワードで保護する]オプションをオフにして、[OK]をクリックします。 保存をクリックします。

Mscrmプラグインサインアセンブリキーの追加

最後に、ソリューションを構築します。 右クリック→ビルド。 ソリューションをビルドすると、アセンブリDLLが生成されます。これは、次の章でこのプラグインを登録するために使用します。

プラグインでの例外処理

多くの場合、プラグインロジックはランタイム例外を処理する必要があります。 同期プラグインの場合、ユーザーにエラーダイアログボックスを表示する InvalidPluginExecutionException 例外を返すことができます。 エラーダイアログには、例外オブジェクトのメッセージオブジェクトに渡すカスタムエラーメッセージが含まれます。

コードを見ると、catchブロックでInvalidPluginExecutionException例外をスローしています。

throw new InvalidPluginExecutionException(ex.Message);

結論

プラグインは、カスタムCRMの実装に不可欠です。 この章では、イベントフレームワークモデル、パイプラインステージ、メッセージの理解、およびサンプルプラグインの作成に焦点を当てました。 次の章では、このプラグインをCRMに登録し、エンドツーエンドのシナリオで機能することを確認します。