Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
static void SASを用いたデバイス認証によるデータ送信()
{
var serviceNamespace = "<SERVICE_NAMESPACE>";
var eventHubsName = "<EVENTHUBs_NAME>";
var deviceName = "myDevice"; // 認証ユーザーのIdとかをセット
// 管理ポータルで設定した共有アクセスポリシーの情報
var sharedAccessPolicyName = "<NAME>";
var sharedAccessPolicyKey = "<KEY>";
// <EVENTHUBS_NAME>/publishers/<PUBLISHER_NAME>
var resourcePath = String.Format("{0}/publishers/{1}", eventHubsName, deviceName);
// sb://<SERVICE_NAMESPACE>.servicebus.windows.net/<EVENTHUBS_NAME>/publishers/<PUBLISHER_NAME>
Uri publisherUrl = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, resourcePath);
// SASTokenの生成
string sas = SharedAccessSignatureTokenProvider.GetSharedAccessSignature(
sharedAccessPolicyName,
sharedAccessPolicyKey,
publisherUrl.AbsoluteUri,
TimeSpan.FromSeconds(60));
var devideTokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(sas);
var factory = MessagingFactory.Create(ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, ""), new MessagingFactorySettings
{
TokenProvider = devideTokenProvider,
TransportType = TransportType.Amqp
});
// イベント送信用のクライアント
var client = factory.CreateEventHubClient(resourcePath); // ←このpublishers/<PUBLISHER_NAME>が、SAS作成時の<PUBLISHER_NAME>と一致している必要がある
var data = new EventData(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { message = "どうもこんにちは!" + DateTime.Now })));
// PartitionKeyにデバイス名を入れておいて、後で判別に使う
data.PartitionKey = deviceName;
client.Send(data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment