[Cross-posted from blog.davemdavis.net]
I recently worked on a project where I had to use a mobile device, specifically Window 8.1 phone/tablet, as a hub for an external sensor. The mobile device then needed to pass the data to an Azure Event Hubs endpoint. The data was then going to be sent through Azure Stream Analytics to various storage solutions. Normally, you would fire up a project, go to NuGet package manager, install ‘Microsoft Azure Service Bus’ SDK, set your endpoint URL and send key, and be off and running. There is one slight problem with that in my architecture. One of the SDK dependencies is not compiled against WinRT so you are out of luck there.
Luckily, Azure Event Hubs exposes a REST API that is fairly straight forward–except for one thing. How do I assure the service I have has the appropriate authorization to send messages? The REST endpoint expects a Shared Access Signature in the header of the request. Here is some sample code for creating that token:
Basically, it is a string containing the base URL, a hash of the base URL and expiration (using the send key as the hash key), and the key rule name. You can go to the MSDN documentation for more information on Shared Access Signatures.
I created a little proxy class that encapsulates the generation of this token and handles sending the message:
My Event Hub expects all messages to be formatted as JSON. My proxy method takes the serialized object and packages it up as the content of the HTTP request. It also sets the SharedAccessSignature header value. Sending an event to the hub is as easy as:
One thing to note in this architecture is that mobile devices tend to be on metered connections. So, be aware that sending loads of data will count against the devices data plan. You may want to restrict sending data only when the device is not on a metered connection. You can get the code and play with it. I put TODO statements where you have to provide your environment specific values.