Azure Event Hubs from WinRT/UWP Apps

Just a small thing that caught me out the other day. I wanted to send some simple data from a Windows 10 UWP app to an event hub in Azure.

There’s a great guide to getting started with event hubs here;

Getting Started with Event Hubs

which worked really well for me up until the section ‘Send messages to Event Hubs’ which has a step 3 which asks you to install the NuGet package WindowsAzure.ServiceBus.

Now, in the tutorial I think that’s all fine because it’s a console application that’s being built on top of .NET Framework.

However, Windows Store/Phone apps and UWP apps are all on .NET Core, not .NET Framework and when I try and install that NuGet package I get;

image

which seems to be saying that the package Microsoft.WindowsAzure.ConfigurationManager isn’t compatible with .NET Core.

I did a bit of a web search and came across a bug report on this;

Microsoft.WindowsAzure.ConfigurationManager doesn’t support Windows 8.1

and it looks like this has been closed off as ‘by design’ so I’m not sure at the time of writing what the recommended way of using event hubs from a Windows Store or UWP app is meant to be.

Naturally, a UWP app might be running on an IoT device like a Raspberry Pi 2 powered by Windows 10 for IoT Core which would be a scenario where you may well want to use an event hub for gathering data so I was a bit disappointed not to be able to use this package because it contains the EventHubClient class which makes it pretty easy to publish data to an event hub but I asked around a little and ended up using the package ampqnetlite instead and switching to AMQP protocol to get the data to my event hub.

So…just a note if you find yourself in the same situation and I’ll update the post if I find that there’s a way of getting that EventHubClient class to be a part of a UWP app, it’s possible that it’s just an awareness thing on my part.

A Quick Parse of the //Build 2015 Session List

I just flicked through the session list for //Build and was making a note of the sessions that (on first pass) line up with my particular set of interests and I thought I’d publish it here given that I was making the list anyway Smile

Note that the list;

  • isn’t sorted or prioritised in any way
  • has been made without any visibility about what’s happening in any of these sessions
  • is long – looks like around 80-100 hours of material to watch here at least
  • would be likely to be revised once the material starts to show up

With a big conference like this, I always watch the keynotes and then I typically make a few folders on my disk;

  • queue
  • watched
    • vital
    • useful
    • other

and I download as many videos as I can into that queue folder and then watch them and, once watched, I partition them across into one of the other 3 folders for future reference. It’s worth saying that ‘other’ category is often a reflection of whether I think the session is of use to me rather than a reflection on a talk.

I do generally download the videos because I can then watch them when travelling and so on and also because I usually watch them at 1.4x speed or similar.

Here’s the big list (so far);

Windows App sessions

Cross Platform App sessions

IoT sessions

Visual Studio sessions

Web sessions

.NET sessions

Azure sessions

Security sessions

Some ‘mystery’ sounding sessions;

Windows/Phone 8.1–Running Code in Response to Cloud Push Notifications

One of the features of Windows 8.0/8.1 apps is the ability to respond to a raw push notification delivered from the Windows Notification Service in the cloud.

You can read about raw push notifications on the developer centre (I dug out the link – http://msdn.microsoft.com/en-us/library/windows/apps/jj676791.aspx – to save you having to search around).

A raw notification is just a string up to around 5KB of data in size. When an app receives a raw notification, I think it can do one of two things;

  1. If the app was lucky enough to be actually running then it can register an event handler to receive the data from a raw notification as it hits the device.
  2. The app can register a background task which will run on receipt of the raw notification.

Of the two I think it’s fair to say that (2) is the only pragmatic approach unless you want some kind of UI like this in your app Winking smile

image

that second option though is a powerful thing – it effectively means that code running in the cloud can trigger the execution of code on a device.

That code running on the device might do something “quiet” like writing the received data into a file or it might take an active step like executing some web request to get new data from the cloud and it might combine this with something a bit more “invasive” like popping up a toast message to tell the user that something has happened.

I drew out an example scenario at one point that looked as below;

image

The idea here is that there’s a football app on the phone which has registered a background task to receive raw push notifications. In the cloud there’s some football service which is monitoring a game and sending raw push notifications to the app whenever there’s a goal scored in the game.

The app on the device can then choose (maybe based on a setting) to simply record the details of all of these goals in storage until the game ends and then (perhaps) notify the user that the game is over and their team won/lost having quietly recorded the details of 4 raw push notifications (goals) in the meantime;

image

What does it take to get this sort of thing up and running?

“Not too much” – here’s a quick step by step way of getting this working. There are perhaps 4 main steps if using Windows Azure;

  1. Creating a notification hub.
  2. Creating an app, associating it with the Store and configuring the notification hub to talk to WNS for it.
  3. Executing code on the client-side to register with that hub.
  4. Writing a background task to execute on receipt of a raw push notification and writing code to register that background task.
  5. Writing server-side logic to send raw notifications when something “interesting/relevant” to the user happens.

I’m going to miss out step 5 here but I thought I’d run through 1-4. It’s worth saying that Azure Mobile Services has ways of making this easier but I’ll work here without Mobile Services just for novelty Smile

Step 1 – Creating a Notification Hub

I can use the Azure Portal to create a notification hub;

image

and now I’ve got a hub called “mtaultyHub”. What I’m going to need from this hub are two things;

  1. I need to configure the hub to be able to speak to the Windows Notification Service in the cloud and to do that I’m going to need an app..
  2. I need to be able to configure the app to speak to the hub and to do that I’m going to need a connection string for the hub.

Step 2 I can gather from the hub’s dashboard page;

image

which launches up a dialog;

image

where I can copy out the connection string highlighted – I’ll need this in a moment.

Step 2- Create a New App, Associate with Store & Grab Identifiers

On the client side, I can make a new, blank Windows Phone 8.1 app in Visual Studio 2013 Update 2 RC and then I can associate it with the Windows Phone Store via the Visual Studio menu;

image

and that pops up a dialog where I can make a new app name or re-use an existing one;

image

and once the association is made I can navigate to http://dev.windowsphone.com and then to Dashboard;

image

and that leads to Apps and including my “Not Started” apps;

image

and if I navigate into that mtaultyTestHub app I have to get past the initial question;

image

and then I can scroll right to the bottom of that page and find this link;

image

and that gets me to this page;

image

and I can take the Package SID and the Client Secret and I can copy them across to the configuration page for my notification hub;

image

and that’s then configured the hub to be able to talk to WNS.

Step 3 – Run Client Side Code to Register with Notification Hub

I can then write some code in my phone app to obtain a push notification channel URI – e.g;

 private async void OnRegister(object sender, RoutedEventArgs e)
    {
      var channel = 
        await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
    
      
    }

and that gets me a channel (with a URI) for the app for the user on the device and I also need to send the URI to the notificaton hub to register this client as a possible recipient of push notifications. One way to do that is to add client-side SDK classes for Azure Notification Hubs from Nuget for which I used;

Install-Package WindowsAzure.Messaging.Managed

in the Nuget console. With that in place I can then expand out that previous code;

    private async void OnRegister(object sender, RoutedEventArgs e)
    {
      var channel = 
        await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();

      NotificationHub hub = new NotificationHub(
        "mtaultyhub",
        "Endpoint=sb://mtaultyhub-ns.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=notIncluded");

      await hub.RegisterNativeAsync(channel.Uri, new string[] { "Group1", "MikeTaulty" });
    }

and then if I run this code, I have this particular client registered for push notifications from the hub. If I switch on “Toast Notifications” in my app’s manifest;

image

then I could use Visual Studio to send a quick test toast notification to see if things have registered correctly;

image

which raises this page in Visual Studio;

image

and pressing the “Send” button talks to the cloud which talks to the device which pops this toast in response (I’m doing this in the emulator);

image

and if I stop broadcasting and use a made-up tag like “Foo” then nothing happens down on the device;

image

whereas if I pass one of the tags that I associated with the registration;

image

then I see the toast down on the device and so I can feel comfy that things are working ok at least from the point of view of a toast notification but what about a raw notification activating a background task?

Step 3 – Writing a Background Task to Execute on Receipt of a Raw Push Notification

I need to write a background task – it’s important to make sure that you’re writing a Windows Runtime Component here rather than a .NET class library because background tasks need to be implemented as Windows Runtime Components.

I can add a project to my solution;

image

and then do a quick implementation of a background task which will just dump the received data out to the debugger;

namespace WindowsRuntimeComponent1
{
    public sealed class MyTask : IBackgroundTask
    {
      public void Run(IBackgroundTaskInstance taskInstance)
      {
        RawNotification rawNotification = taskInstance.TriggerDetails as RawNotification;

        if (rawNotification != null)
        {
          Debug.WriteLine(
            string.Format("Received from cloud: [{0}]",
            rawNotification.Content));
        }
      }
    }
}

and I can reference that project from my main app project and write a little code to register the background task;

      await BackgroundExecutionManager.RequestAccessAsync();

      // Get rid of existing registrations.
      foreach (var task in BackgroundTaskRegistration.AllTasks)
      {
        try
        {
          task.Value.Unregister(false);
        }
        catch // hack
        {
        }
      }
      BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
      builder.Name = "Push Task";
      builder.TaskEntryPoint = typeof(WindowsRuntimeComponent1.MyTask).FullName;
      builder.SetTrigger(new PushNotificationTrigger());
      builder.Register(); 

and update my manifest to make sure that this registration is going to be allowed;

image

and then I can run that code to get the background task register and then use the test page in Visual Studio to send a raw notification to the device;

image

and I see the debugger output;

image

and that all works quite nicely – we have the cloud able to deliver string data down to the device and the device able to respond to that notification by executing code which can pick up the payload sent as part of the push notification.

“All” that’s left is to come up with a proper scenario and a cloud-based service to run logic and deliver notifications as/when something of relevance to a user (or group of users) happens. Again, Azure Mobile Services can help in terms of implementing that cloud service and its logic.

I think this is a very powerful new capability for Windows Phone 8.1 development – the device able to pick up almost “real time” notifications from the cloud and act upon them.