Skip to content

Instantly share code, notes, and snippets.

@ahelland
Created December 20, 2017 17:14
Show Gist options
  • Save ahelland/74619d850b428b88b090e3803028778f to your computer and use it in GitHub Desktop.
Save ahelland/74619d850b428b88b090e3803028778f to your computer and use it in GitHub Desktop.
Azure Function for sending a simple son payload to an Azure Event Hub
using System;
using System.Text;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
public static void Run(string input, TraceWriter log)
{
var resourceUri = "contoso.servicebus.windows.net";
var keyName = "RootManageSharedAccessKey";
var key = "randomkey";
TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970,1,1);
var week = 60 * 60 * 24 *7;
var expiry = Convert.ToString((int)sinceEpoch.TotalSeconds + week);
string stringToSign = Uri.EscapeDataString(resourceUri) + "\n" + expiry;
HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
var sasToken = $"sr={Uri.EscapeDataString(resourceUri)}&sig={Uri.EscapeDataString(signature)}&se={expiry}&skn={keyName}";
var eventHubUrl = "https://contoso.servicebus.windows.net/foo/messages";
var content = "{\"on\":true, \"sat\":254, \"bri\":254, \"hue\":10000}";
HttpClient Client = new HttpClient();
Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SharedAccessSignature", sasToken);
var foo = Client.PostAsync(eventHubUrl, new StringContent(content.ToString())).Result;
log.Info($"result: {foo}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment