accountテーブルのtelephone1の入力チェックを作成する場合の手順は以下の通りです。
入力チェックは正規表現で「^[0-9]+$」とします。
クラスファイルはプロジェクト内に2つあっても問題ありません。
1つのAssembly(dllファイル)に2つのPluginが出来上がる形になります。
クラスファイルの中身以外は以前の手順踏襲となります。
-
クラスファイルの編集
クラス名を変更し、開発を行います。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using System.Text.RegularExpressions;
namespace MyDataversePluginVS462
{
public class FollowupPlugin2 : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
// プラグイン実行コンテキストの取得
IPluginExecutionContext context = serviceProvider.GetService(typeof(IPluginExecutionContext)) as IPluginExecutionContext;
if (context == null)
{
throw new InvalidPluginExecutionException("プラグイン実行コンテキストが取得できませんでした。");
}
// 組織サービスファクトリの取得
IOrganizationServiceFactory serviceFactory = serviceProvider.GetService(typeof(IOrganizationServiceFactory)) as IOrganizationServiceFactory;
if (serviceFactory == null)
{
throw new InvalidOperationException("IOrganizationServiceFactory が取得できませんでした。");
}
// トレーシングサービスの取得
ITracingService tracingService = serviceProvider.GetService(typeof(ITracingService)) as ITracingService;
if (tracingService == null)
{
throw new InvalidPluginExecutionException("トレーシングサービスが取得できませんでした。");
}
// ターゲットエンティティがAccountであるか
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity account && account.LogicalName == "account")
{
tracingService.Trace("PhoneCheckプラグインが実行されました。");
// ターゲットエンティティのCreateかどうか
if (context.MessageName == "Create")
{
// 電話番号フィールドが存在するか
if (account.Attributes.Contains("telephone1"))
{
string phoneNumber = account.Attributes["telephone1"] as string;
if (!string.IsNullOrEmpty(phoneNumber) && Regex.IsMatch(phoneNumber, "^[0-9]+$"))
{
tracingService.Trace("電話番号の書式は問題ありません。");
}
else
{
throw new InvalidPluginExecutionException("新規登録時は電話番号の書式は数値のみで入力してください。");
}
}
else
{
throw new InvalidPluginExecutionException("電話番号(telephone1)フィールドが存在しません。");
}
}
else
{
throw new InvalidPluginExecutionException("プラグインが実行できませんでした。(メッセージ違い)");
}
}
else
{
throw new InvalidPluginExecutionException("プラグインが実行できませんでした。(テーブル違い)");
}
// 処理全体をtry-catchで囲って、catchでInvalidPluginExecutionExceptionするのもあり。
}
}
}