rksoftware

Visual Studio とか C# とかが好きです

Dataverse の WebAPI で Dataverse のテーブルに行追加する C# コード

目次

Dataverse の WebAPI を C# で叩く系記事たちの目次です。

rksoftware.hatenablog.com

今回の本文

rksoftware.hatenablog.com

rksoftware.hatenablog.com

前回の続きです。
これまでデータ取得、テーブルに列追加をしてきましたが、今回はテーブルに行を追加してみます。

■ 動かし方

コマンドライン引数で、WebAPIのエンドポイントを入れます。Web の GUI で 「テーブル データへの API リンク」をした時の URL です。

■ 概要

  1. 認証してトークンを得る
  2. トークンを付けて HttpClient を準備する
  3. テーブルのエンドポイントに Post する。
  4. Post の Body は JSON で行のデータ情報

簡単ですね。
実際はもっと様々な方の列に値を設定したり、行追加だけでなく行更新などもあるでしょううから、プログラムに対して複数の JSON を引数などで渡す方法をどうするか考慮事項は多いです。それはまた今度。
次回以降、改善してみますね。

string s = args[0];

string json = """
{
"crf6f_user_multiline_richtext_01": "リッチー",
"crf6f_user_multiline_text_01": "マルチ",
}
""";

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 ?? "";
    }
}