手記
Time Series Insights サービスは、2024 年 7 月 7 日に廃止されます。 既存の環境をできるだけ早く別のソリューションに移行することを検討してください。 非推奨と移行の詳細については、
注意
これは Gen1 の記事です。
この記事では、C#、MSAL.NET、および Microsoft Entra ID を組み合わせて、Azure Time Series Insights Gen 1 Reference Data Management APIにプログラムによる API 要求を行う方法について説明します。
ヒント
https://github.com/Azure-Samples/Azure-Time-Series-Insightsで GA C# コード サンプルを表示します。
概要
次のサンプル コードは、次の機能を示しています。
PublicClientApplicationを使用してアクセス トークン
MSAL.NET 取得します。 Gen 1 Reference Data Management APIに対して、順次 CREATE、READ、UPDATE、DELETE の操作を行う。
一般的なエラー コード
含む一般的な応答コード。 Reference Data Management API は各項目を個別に処理し、1 つの項目でエラーが発生しても、他の項目が正常に完了するのを妨げることはありません。 たとえば、要求に 100 個の項目があり、1 つの項目にエラーがある場合、99 個の項目が書き込まれ、1 つが拒否されます。
前提条件とセットアップ
サンプル コードをコンパイルして実行する前に、次の手順を実行します。
Gen 1 Azure Time Series Insights 環境をプロビジョニングします。
環境内に 参照データ セットを作成します。 次の参照データスキームを使用します。
キー名 種類 UUID (ユニバーサリー・ユニーク・アイデンティファイア) 糸 「認証と承認ので説明されているように、Microsoft Entra ID 用に Azure Time Series Insights 環境を構成します。
http://localhost:8080/
を リダイレクト URIに使用します。必要なプロジェクトの依存関係をインストールします。
各 #PLACEHOLDER# を適切な環境識別子に置き換えて、以下のサンプル コードを編集します。
プロジェクトのルート ディレクトリ内で
dotnet run
を実行します。 メッセージが表示されたら、ユーザー プロファイルを使用して Azure にサインインします。
プロジェクトの依存関係
最新バージョンの Visual Studio と NETCore.appを使用することをお勧めします。
- Visual Studio 2019 - バージョン 16.4.2 以降
- NETCore.app - バージョン 2.2.8
サンプル コードには、次の 2 つの必須の依存関係があります。
- MSAL.NET Microsoft.Identity.Client - 4.7.1 パッケージ。
- Newtonsoft.Json - 12.0.3 パッケージ。
NuGet 2.12 以降のを使用してパッケージを追加します。
dotnet add package Newtonsoft.Json --version 12.0.3
dotnet add package Microsoft.Identity.Client --version 4.7.1
又は:
csharp-tsi-msal-ga-sample.csproj
ファイルを宣言します。<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp2.1</TargetFramework> <LangVersion>latest</LangVersion> <RootNamespace>csharp-tsi-msal-ga-sample</RootNamespace> <RunWorkingDirectory>$(MSBuildThisFileDirectory)</RunWorkingDirectory> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Identity.Client" Version="4.7.1.0" Culture="neutral" PublicKeyToken="0a613f4dd989e8ae" /> <PackageReference Include="Newtonsoft.Json" Version="12.0.3" /> </ItemGroup> </Project>
次に、
dotnet restore
実行します。
C# サンプル コード
// Copyright (c) Microsoft Corporation. All rights reserved.
namespace CsharpTsiMsalGaSample
{
using Microsoft.Identity.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public static class Program
{
/**
* Review the product documentation for detailed configuration steps or skip ahead and configure your environment settings.
*
* https://learn.microsoft.com/azure/time-series-insights/time-series-insights-authentication-and-authorization
*/
// Azure Time Series Insights environment configuration
internal static string EnvironmentFqdn = "#PLACEHOLDER#.env.timeseries.azure.com";
internal static string EnvironmentReferenceDataSetName = "#PLACEHOLDER#";
// Azure Active Directory application configuration
internal static string AadClientApplicationId = "#PLACEHOLDER#";
internal static string[] AadScopes = new string[] { "https://api.timeseries.azure.com//user_impersonation" };
internal static string AadRedirectUri = "http://localhost:8080/";
internal static string AadTenantName = "#PLACEHOLDER#";
internal static string AadAuthenticationAuthority = "https://login.microsoftonline.com/" + AadTenantName + ".onmicrosoft.com/oauth2/authorize?resource=https://api.timeseries.azure.com/";
private static async Task<string> AcquireAccessTokenAsync()
{
if (AadClientApplicationId == "#PLACEHOLDER#" || AadScopes.Length == 0 || AadRedirectUri == "#PLACEHOLDER#" || AadTenantName.StartsWith("#PLACEHOLDER#"))
{
throw new Exception($"Use the link {"https://learn.microsoft.com/azure/time-series-insights/time-series-insights-get-started"} to update the values of 'AadClientApplicationId', 'AadScopes', 'AadRedirectUri', and 'AadAuthenticationAuthority'.");
}
/**
* MSAL.NET configuration. Review the product documentation for more information about MSAL.NET authentication options.
*
* https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/
*/
IPublicClientApplication app = PublicClientApplicationBuilder
.Create(AadClientApplicationId)
.WithRedirectUri(AadRedirectUri)
.WithAuthority(AadAuthenticationAuthority)
.Build();
AuthenticationResult result = await app
.AcquireTokenInteractive(AadScopes)
.ExecuteAsync();
Console.WriteLine("MSAL Authentication Token Acquired: {0}", result.AccessToken);
Console.WriteLine("");
return result.AccessToken;
}
// System.Net.HttpClient helper to wrap HTTP POST made to the GA Reference Data API
private static async Task<HttpResponseMessage> AsyncHttpPostRequestHelper(HttpClient httpClient, string input)
{
if (EnvironmentFqdn.StartsWith("#PLACEHOLDER#") || EnvironmentReferenceDataSetName == "#PLACEHOLDER#")
{
throw new Exception($"Use the link {"https://learn.microsoft.com/azure/time-series-insights/time-series-insights-authentication-and-authorization"} to update the values of 'EnvironmentFqdn' and 'EnvironmentReferenceDataSetName'.");
}
Console.WriteLine("HTTP JSON Request Body: {0}", input);
Console.WriteLine("");
HttpContent requestBody = new StringContent(input, Encoding.UTF8, "application/json");
Uri uri = new UriBuilder("https", EnvironmentFqdn)
{
Path = $"referencedatasets/{EnvironmentReferenceDataSetName}/$batch",
Query = "api-version=2016-12-12"
}.Uri;
Console.WriteLine("Making HTTP POST to URI: {0}", uri);
Console.WriteLine("");
HttpResponseMessage response = await httpClient.PostAsync(uri, requestBody);
if (response.IsSuccessStatusCode)
{
var jsonString = await response.Content.ReadAsStringAsync();
var jsonStringTransferObject = JsonConvert.DeserializeObject<object>(jsonString);
Console.WriteLine("HTTP JSON Response Body: {0}", jsonStringTransferObject);
Console.WriteLine("");
return response;
}
return null;
}
private static async Task TsiMsalGaSample()
{
Console.WriteLine("Beginning demo...");
Console.WriteLine("");
Console.WriteLine("The following samples assume a single Key Name (uuid) with String type...");
Console.WriteLine("");
string accessToken = await AcquireAccessTokenAsync();
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
{
// CREATE reference data
Console.WriteLine("CREATE reference data example...");
Console.WriteLine("");
string createInput = @"
{
""put"": [
{
""uuid"": ""Fan1""
},
{
""uuid"": ""Fan2"",
""color"": ""White"",
""floor"": 2
},
{
""uuid"": ""Fan3"",
""color"": ""Red"",
""maxSpeed"": 5
}
]
}";
var createResponse = await AsyncHttpPostRequestHelper(httpClient, createInput);
// READ reference data
Console.WriteLine("READ reference data example...");
Console.WriteLine("");
string readInput = @"
{
""get"": [
{
""uuid"": ""Fan1""
},
{
""uuid"": ""Fan2"",
""color"": ""White"",
""desc"": ""example""
},
{
""uuid"": ""Fan3"",
""color"": ""Red"",
""maxSpeed"": 5
}
]
}";
var readResponse = await AsyncHttpPostRequestHelper(httpClient, readInput);
// UPDATE reference data
Console.WriteLine("UPDATE reference data example...");
Console.WriteLine("");
string updateInput = @"
{
""patch"": [
{
""uuid"": ""Fan1"",
""color"": ""Red""
},
{
""uuid"": ""Fan2"",
""color"": ""Orange""
},
{
""uuid"": ""Fan3"",
""desc"": ""Example""
}
]
}";
var inputResponse = await AsyncHttpPostRequestHelper(httpClient, updateInput);
// DELETE reference data
Console.WriteLine("DELETE reference data example...");
Console.WriteLine("");
string deleteInput = @"
{
""delete"": [
{
""uuid"": ""Fan1""
},
{
""uuid"": ""Fan2"",
""color"": ""Orange""
},
{
""uuid"": ""Fan2"",
""desc"": ""Blue""
}
]
}";
var deleteResponse = await AsyncHttpPostRequestHelper(httpClient, deleteInput);
}
}
internal static void Main(string[] args)
{
Task.Run(async () => await TsiMsalGaSample()).Wait();
}
}
}
次の手順
- Gen 1 リファレンス データ管理 API リファレンス ドキュメントを参照してください。