Service Bus Notification Hubs - Code Walkthrough - Windows 8 Edition

Play Service Bus Notification Hubs - Code Walkthrough - Windows 8 Edition
Sign in to queue


In this clip I'll walk you through the basic principles of the brand-new Windows Azure Service Bus Notification Hubs in a somewhat more formal and serious fashion than in my chat with Elio.

Recapping from the other post,Service Bus Notification Hubs are an intrinsic feature of Windows Azure Service Bus and are different from other push notification services in four key areas:

  • Complete client registration management. Your backend application (if you even have one) does not need to worry at all about device-ids or channels or other particulars of push notifications and doesn't need to cooperate in management. It doesn't even have to be a web app that's publicly accessible.  
  • Platform independence. Service Bus Notification Hubs allow cross-platform push notifications so that iOS Alerts and Windows Live Tiles can be targeted with a single event message. 
  • Broadcast and tag-based Multicast - Service Bus Notification Hubs are optimized around automatic notification broadcast to many thousand devices with low latency. One message in, thousands of notifications out.
  • Mass customization - Notification Hub notification templates allow for customization of notification delivery for each individual registration, allowing each instance of a client App to choose how it wants to receive events.

In this preview, Notification Hubs are able to push notifications to Windows Store apps and iOS apps from .NET back-ends. Support for Android and Windows Phone, along with additional back-end technologies (including Windows Azure Mobile Services) will be added soon.

After the basic intro, I'm showing how to create and provision a Windows 8 application from scratch, how to hook it up to a new Notification Hub, and send it a notification "Toast" using the portals and Visual Studio 2012. (The equivalent iOS walkthrough will follow later this week)

For those of you with a "TL;DW" attention span (too long; didn't watch), here's the whole extent of the code added to the stock Windows Store Grid template to enable Service Bus Notifications and that includes re-registering existing registrations at App startup. 5 lines without cosmetic wrapping and some massaging of XML for the template:


public App()
    var cn = ConnectionString.CreateUsingSharedAccessSecretWithListenAccess(
    this.notificationHub = new NotificationHub("myhub", cn);
async Task InitNotificationsAsync()
    await notificationHub.RefreshRegistrationsAsync();

    if (!await notificationHub.RegistrationExistsForApplicationAsync("myToast"))
        await notificationHub.CreateTemplateRegistrationForApplicationAsync(
            CreateTemplate(), "myToast");
XmlDocument CreateTemplate()
    var t = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
    var n = t.SelectSingleNode("//text[@id='1']") as XmlElement;
    if (n != null)
        n.InnerText = "$(msg)";
    return t;

The event-source code is similarly terse:

var cn = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessSecretWithFullAccess(
    "clemensv1", "{{{secret key}}");

var hubClient = NotificationHubClient.
    CreateClientFromConnectionString(cn, "myhub");

hubClient.SendTemplateNotification(new Dictionary<string, string>{
    { "msg", TextBox1.Text }});

3 lines. Three lines. No management of device ids. No public endpoint for the phone to talk to. Service Bus does all that. It really is worth playing with. 

And here are all the key links ....





Download this episode

The Discussion

  • User profile image

    Nice video.  I can't wait to use this feature since it make alot of the push notifications easier.  One Thing that I am having a hard time with tho is that the Windows 8 Managed Client Library is strong named in the zip file.  It won't compile in my app that is already in the Win8 store.  Other than that, the code and demo was great.

  • User profile image

    Ask and thou shall receive... And we didn't even ask. Big Smile

    Wonderful stuff. Amazing synchronicity in our development challenges and Azure releases.


  • User profile image

    Thanks, @YsFred4. The code signing issue is something we caught just before going live and the signed bits are either in the pipeline or already in the download location, so I'd encourage you to download them once more and check.

  • User profile image

    I was following the video with my own app but always fail in the line (!await notificationHub.RegistrationExistsForApplicationAsync(


    Any clue?
    Microsoft.WindowsAzure.Messaging.RegistrationException was unhandled by user code
    Message=The type initializer for 'Microsoft.WindowsAzure.Messaging.Http.Resources' threw an exception.
    at Microsoft.WindowsAzure.Messaging.RegistrationManager.<GetRegistrationAsync>d__3.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
    at Microsoft.WindowsAzure.Messaging.NotificationHub.<RegistrationExistsForApplicationAsync>d__29.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
    at App1.App.<InitializeNotificationsAsync>d__0.MoveNext() in c:\Projects\123Photo\App1\App1\App.xaml.cs:line 55
    --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
    at App1.App.<OnLaunched>d__5.MoveNext() in c:\Projects\123Photo\App1\App1\App.xaml.cs:line 85
    InnerException: System.TypeInitializationException
    Message=The type initializer for 'Microsoft.WindowsAzure.Messaging.Http.Resources' threw an exception.
    at Microsoft.WindowsAzure.Messaging.Http.Resources.get_ErrorFailedRequest()
    at Microsoft.WindowsAzure.Messaging.Http.Internal.HttpChannel.ProcessResponse(HttpResponse response, Func`2[] handlers)
    at Microsoft.WindowsAzure.Messaging.Http.Internal.HttpChannel.<>c__DisplayClass4.<SendAsyncInternal>b__3(Task`1 t)
    at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
    at System.Threading.Tasks.Task.Execute()
    Message=ResourceMap Not Found. (Exception from HRESULT: 0x80073B1F)
    at Windows.ApplicationModel.Resources.ResourceLoader..ctor(String name)
    at Microsoft.WindowsAzure.Messaging.Http.Resources..cctor()

  • User profile image

    We will take a look at that, @GeraldH. Could you send me an email to, please?

    -- edit: We think this related to the code signing issue we fixed earlier.

  • User profile image

    My sample application also fails at the RegistrationExistsForApplicationAsync() call.

    I'm getting a WindowsAzureHttpException exception with the message "HTTP request failed. HTTP Details: Status: 404 Reason: Not Found" and the ErrorCode=-2147217004.

    Any ideas what can be wrong? I can provide more details about my namespace and hub name, shared listen key and actual http request/response taken from Fiddler.


  • User profile image
    Mathias Rost

    Having the same issue like GeraldH! Any news on the issue?

  • User profile image

    Redownload the SDK if you see issues like Gerald has; also, the 404 error VkDev reports is actually a false-positive "error" reported by the VS Debugger based on the WinRT Http library. Just continue execution.

  • User profile image

    Is there a guide on how to troubleshoot issues when using with iOS? I've walked the guide multiple times and am still having issues, but I'm not sure where the problem lies. iOS reports it registered, but doesn't receive any events. The send on the server also does not report issues on send. How do I see in the middle?

  • User profile image

    Hi Andrew,

    Make sure to check the dashboard of the Notification Hub on the portal, and check for:
    - the status of the notification hub: if APNs rejected your credentials, the hub might have gone in the "blocked" state. To unblock it, simply reupload your credentials.
    - the metric for "APNs authentication error", "APNs errors" and "Invalid payload". The hub reports the errors after some time so you might have to wait up to 20mins

    - remember that in order to receive the application you need to use an actual device (not the simulator) and the app has to be *inactive* to receive notifications (to exit an app, double click on home, then hold the app and press the minus sign)
    - final advice: sending notifications with expiry set to 0, is extremely dependent on the signal quality for the device. I suggest you to put an expiry date in the future (in your templates or in the native send) so that the notification will be delivered when the device comes back online.

    Let us know how it goes!

  • User profile image

    Any news on the RegistrationException problem? I am getting the same issue.

  • User profile image

    @GeraldH: if you are building a WinRT app and referencing the preview notification hubs SDK, make sure you include the PRI file together with the DLL. Otherwise you may see that error.


  • User profile image

    Very nice video.

  • User profile image


    I'm trying to implement a small proof of concept, but I'm getting errors on both client and server side.

    On the server side I'm getting the 404 error, and on the client side I'm getting:

    HTTP request failed.HTTP Details:Status: 401Reason: Unauthorized

    Full content: <Error><Code>401</Code><Detail>InvalidSignature: The token has an invalid signature..TrackingId:70f1ac92-56fa-4cca-9a7c-3ef9dd9c45d7_G10,TimeStamp:4/3/2013 6:36:36 PM</Detail></Error>


    My app is associated with the store and I've tried all types of variants of the code, but with no luck.

    Can anyone help me on this? I really need some kind of solution to this problem Smiley.


    Thanks in advance!

Add Your 2 Cents