accountテーブルのtelephone1の入力チェックを作成する場合の手順は以下の通りです。
入力チェックは正規表現で「^[0-9]+$」とします。
クラスファイルはプロジェクト内に2つあっても問題ありません。
1つのAssembly(dllファイル)に2つのPluginが出来上がる形になります。
クラスファイルの中身以外は以前の手順踏襲となります。
-
クラスファイルの編集
クラス名を変更し、開発を行います。1
using
System;
2
using
System.Collections.Generic;
3
using
System.Linq;
4
using
System.Text;
5
using
System.Threading.Tasks;
6
using
System.ServiceModel;
7
using
Microsoft.Xrm.Sdk;
8
using
System.Text.RegularExpressions;
9
10
namespace
MyDataversePluginVS462
11
{
12
public
class
FollowupPlugin2 : IPlugin
13
{
14
public
void
Execute(IServiceProvider serviceProvider)
15
{
16
// プラグイン実行コンテキストの取得
17
IPluginExecutionContext context = serviceProvider.GetService(
typeof
(IPluginExecutionContext))
as
IPluginExecutionContext;
18
if
(context ==
null
)
19
{
20
throw
new
InvalidPluginExecutionException(
"プラグイン実行コンテキストが取得できませんでした。"
);
21
}
22
23
// 組織サービスファクトリの取得
24
IOrganizationServiceFactory serviceFactory = serviceProvider.GetService(
typeof
(IOrganizationServiceFactory))
as
IOrganizationServiceFactory;
25
if
(serviceFactory ==
null
)
26
{
27
throw
new
InvalidOperationException(
"IOrganizationServiceFactory が取得できませんでした。"
);
28
}
29
30
// トレーシングサービスの取得
31
ITracingService tracingService = serviceProvider.GetService(
typeof
(ITracingService))
as
ITracingService;
32
if
(tracingService ==
null
)
33
{
34
throw
new
InvalidPluginExecutionException(
"トレーシングサービスが取得できませんでした。"
);
35
}
36
37
// ターゲットエンティティがAccountであるか
38
if
(context.InputParameters.Contains(
"Target"
) && context.InputParameters[
"Target"
]
is
Entity account && account.LogicalName ==
"account"
)
39
{
40
tracingService.Trace(
"PhoneCheckプラグインが実行されました。"
);
41
42
// ターゲットエンティティのCreateかどうか
43
if
(context.MessageName ==
"Create"
)
44
{
45
// 電話番号フィールドが存在するか
46
if
(account.Attributes.Contains(
"telephone1"
))
47
{
48
string
phoneNumber = account.Attributes[
"telephone1"
]
as
string
;
49
if
(!
string
.IsNullOrEmpty(phoneNumber) && Regex.IsMatch(phoneNumber,
"^[0-9]+$"
))
50
{
51
tracingService.Trace(
"電話番号の書式は問題ありません。"
);
52
}
53
else
54
{
55
throw
new
InvalidPluginExecutionException(
"新規登録時は電話番号の書式は数値のみで入力してください。"
);
56
}
57
}
58
else
59
{
60
throw
new
InvalidPluginExecutionException(
"電話番号(telephone1)フィールドが存在しません。"
);
61
}
62
}
63
else
64
{
65
throw
new
InvalidPluginExecutionException(
"プラグインが実行できませんでした。(メッセージ違い)"
);
66
}
67
}
68
else
69
{
70
throw
new
InvalidPluginExecutionException(
"プラグインが実行できませんでした。(テーブル違い)"
);
71
}
72
73
// 処理全体をtry-catchで囲って、catchでInvalidPluginExecutionExceptionするのもあり。
74
}
75
}
76
}