目次
Dataverse の WebAPI を C# で叩く系記事たちの目次です。
今回の本文
前回の続きです。
前回はデータを取得してみましたが、今回はテーブルに列を追加してみます。
■ 動かし方
コマンドライン引数で、WebAPIのエンドポイントを入れます。Web の GUI で 「テーブル データへの API リンク」をした時の URL です。
■ 概要
- 認証してトークンを得る
- トークンを付けて HttpClient を準備する
- テーブルのwン度ポイントに
/Attributesを後ろにつけた URL に Post する。 - Post の Body は JSON で列定義情報
簡単ですね。列定義情報を作るのが難しそうですが。
あと、列追加は同時にいくつもの列を追加することが多いと思いますが、プログラムに対しして複数の JSON を引数などで渡す方法をどうするか。改行なしの JSON を改行区切りで複数テキストファイルに書いて、上から順に実行とかでもいいかな。
次回、改善してみますね。
string s = args[0] + "/Attributes"; string json = """ { "AttributeType": "String", "AttributeTypeName": { "Value": "StringType" }, "Description": { "@odata.type": "Microsoft.Dynamics.CRM.Label", "LocalizedLabels": [ { "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel", "Label": "Type the name of the bank", "LanguageCode": 1033 } ] }, "DisplayName": { "@odata.type": "Microsoft.Dynamics.CRM.Label", "LocalizedLabels": [ { "@odata.type": "Microsoft.Dynamics.CRM.LocalizedLabel", "Label": "Bank Name", "LanguageCode": 1033 } ] }, "RequiredLevel": { "Value": "None", "CanBeChanged": true, "ManagedPropertyLogicalName": "canmodifyrequirementlevelsettings" }, "SchemaName": "new_BankName", "@odata.type": "Microsoft.Dynamics.CRM.StringAttributeMetadata", "FormatName": { "Value": "Text" }, "MaxLength": 100 } """; string r = await new RkDataverseHttpClient(s).PostAsync(json); Console.WriteLine(r); class RkDataverseHttpClient { public string Resource { get; init; } public Uri BaseAddress { get; init; } public string Path { get; init; } public static string ClientId { get; } = "51f81489-12ee-4a9e-aaae-a2591f45987d"; public static string RedirectUri { get; } = "http://localhost"; Microsoft.Identity.Client.AuthenticationResult Token { get; set; } HttpClient HttpClient { get; init; } public RkDataverseHttpClient(string resource) { var uri = new Uri(resource); Resource = uri.Scheme + "://" + uri.Host; BaseAddress = new Uri(Resource + "/api/data/v9.2/"); Path = new string(resource.Skip(BaseAddress.AbsoluteUri.Length).ToArray()); Authentication().GetAwaiter().GetResult(); HttpClient = BuildHttpClient(); } async Task<Microsoft.Identity.Client.AuthenticationResult> Authentication() { var authBuilder = Microsoft.Identity.Client.PublicClientApplicationBuilder.Create(ClientId) .WithAuthority(Microsoft.Identity.Client.AadAuthorityAudience.AzureAdMultipleOrgs) .WithRedirectUri(RedirectUri) .Build(); string[] scopes = { Resource + "/user_impersonation" }; Microsoft.Identity.Client.AuthenticationResult token = await authBuilder.AcquireTokenInteractive(scopes).ExecuteAsync(); return Token = token; } HttpClient BuildHttpClient() { HttpClient client = new HttpClient() { BaseAddress = BaseAddress, Timeout = new TimeSpan(0, 2, 0) }; System.Net.Http.Headers.HttpRequestHeaders headers = client.DefaultRequestHeaders; headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Token.AccessToken); headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); return client; } public async Task<string> PostAsync(string json) { var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await HttpClient.PostAsync(Path, content); string jsonContent = null; if (response.IsSuccessStatusCode) { jsonContent = await response.Content.ReadAsStringAsync(); } return jsonContent ?? ""; } }