Azure Notification Hubs output bindings for Azure Functions

This article explains how to send push notifications by using Azure Notification Hubs bindings in Azure Functions. Azure Functions supports output bindings for Notification Hubs.

You must configure Notification Hubs for the Platform Notifications Service (PNS) you want to use. For more information about how to get push notifications in your client app from Notification Hubs, see Quickstart: Set up push notifications in a notification hub.

Packages: Functions 1.x

The Notification Hubs bindings are provided in the Microsoft.Azure.WebJobs.Extensions.NotificationHubs NuGet package, version 1.x. Source code for the package is in the azure-webjobs-sdk-extensions GitHub repository.

The following table tells how to add support for this binding in each development environment.

Development environment To add support in
Functions 1.x
Local development - C# class library Install the package
Local development - C# script, JavaScript, F# Automatic
Portal development Automatic

Packages: Functions 2.x and higher

Output binding isn't available in Functions 2.x and higher.

Example: template

The notifications you send can be native notifications or template notifications. A native notification targets a specific client platform, as configured in the platform property of the output binding. A template notification can be used to target multiple platforms.

Template examples for each language:

C# script template example: out parameter

This example sends a notification for a template registration that contains a message placeholder in the template:

using System;
using System.Threading.Tasks;
using System.Collections.Generic;

public static void Run(string myQueueItem,  out IDictionary<string, string> notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");
    notification = GetTemplateProperties(myQueueItem);
}

private static IDictionary<string, string> GetTemplateProperties(string message)
{
    Dictionary<string, string> templateProperties = new Dictionary<string, string>();
    templateProperties["message"] = message;
    return templateProperties;
}

C# script template example: asynchronous

If you're using asynchronous code, out parameters aren't allowed. In this case, use IAsyncCollector to return your template notification. The following code is an asynchronous example of the previous example:

using System;
using System.Threading.Tasks;
using System.Collections.Generic;

public static async Task Run(string myQueueItem, IAsyncCollector<IDictionary<string,string>> notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");

    log.Info($"Sending Template Notification to Notification Hub");
    await notification.AddAsync(GetTemplateProperties(myQueueItem));    
}

private static IDictionary<string, string> GetTemplateProperties(string message)
{
    Dictionary<string, string> templateProperties = new Dictionary<string, string>();
    templateProperties["user"] = "A new user wants to be added : " + message;
    return templateProperties;
}

C# script template example: JSON

This example sends a notification for a template registration that contains a message placeholder in the template using a valid JSON string:

using System;

public static void Run(string myQueueItem,  out string notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");
    notification = "{\"message\":\"Hello from C#. Processed a queue item!\"}";
}

C# script template example: library types

This example shows how to use types defined in the Azure Notification Hubs Library:

#r "Microsoft.Azure.NotificationHubs"

using System;
using System.Threading.Tasks;
using Microsoft.Azure.NotificationHubs;

public static void Run(string myQueueItem,  out Notification notification, TraceWriter log)
{
   log.Info($"C# Queue trigger function processed: {myQueueItem}");
   notification = GetTemplateNotification(myQueueItem);
}

private static TemplateNotification GetTemplateNotification(string message)
{
    Dictionary<string, string> templateProperties = new Dictionary<string, string>();
    templateProperties["message"] = message;
    return new TemplateNotification(templateProperties);
}

F# template example

This example sends a notification for a template registration that contains location and message:

let Run(myTimer: TimerInfo, notification: byref<IDictionary<string, string>>) =
    notification = dict [("location", "Redmond"); ("message", "Hello from F#!")]

JavaScript template example

This example sends a notification for a template registration that contains location and message:

module.exports = async function (context, myTimer) {
    var timeStamp = new Date().toISOString();

    if (myTimer.IsPastDue)
    {
        context.log('Node.js is running late!');
    }
    context.log('Node.js timer trigger function ran!', timeStamp);  
    context.bindings.notification = {
        location: "Redmond",
        message: "Hello from Node!"
    };
};

Example: APNS native

This C# script example shows how to send a native Apple Push Notification Service (APNS) notification:

#r "Microsoft.Azure.NotificationHubs"
#r "Newtonsoft.Json"

using System;
using Microsoft.Azure.NotificationHubs;
using Newtonsoft.Json;

public static async Task Run(string myQueueItem, IAsyncCollector<Notification> notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");

    // In this example, the queue item is a new user to be processed in the form of a JSON string with 
    // a "name" value.
    //
    // The JSON format for a native Apple Push Notification Service (APNS) notification is:
    // { "aps": { "alert": "notification message" }}  

    log.LogInformation($"Sending APNS notification of a new user");    
    dynamic user = JsonConvert.DeserializeObject(myQueueItem);    
    string apnsNotificationPayload = "{\"aps\": {\"alert\": \"A new user wants to be added (" + 
                                        user.name + ")\" }}";
    log.LogInformation($"{apnsNotificationPayload}");
    await notification.AddAsync(new AppleNotification(apnsNotificationPayload));        
}

Example: WNS native

This C# script example shows how to use types defined in the Azure Notification Hubs Library to send a native Windows Push Notification Service (WNS) toast notification:

#r "Microsoft.Azure.NotificationHubs"
#r "Newtonsoft.Json"

using System;
using Microsoft.Azure.NotificationHubs;
using Newtonsoft.Json;

public static async Task Run(string myQueueItem, IAsyncCollector<Notification> notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");

    // In this example, the queue item is a new user to be processed in the form of a JSON string with 
    // a "name" value.
    //
    // The XML format for a native WNS toast notification is ...
    // <?xml version="1.0" encoding="utf-8"?>
    // <toast>
    //      <visual>
    //     <binding template="ToastText01">
    //       <text id="1">notification message</text>
    //     </binding>
    //   </visual>
    // </toast>

    log.Info($"Sending WNS toast notification of a new user");    
    dynamic user = JsonConvert.DeserializeObject(myQueueItem);    
    string wnsNotificationPayload = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                    "<toast><visual><binding template=\"ToastText01\">" +
                                        "<text id=\"1\">" + 
                                            "A new user wants to be added (" + user.name + ")" + 
                                        "</text>" +
                                    "</binding></visual></toast>";

    log.Info($"{wnsNotificationPayload}");
    await notification.AddAsync(new WindowsNotification(wnsNotificationPayload));        
}

Attributes

In C# class libraries, use the NotificationHub attribute.

The attribute's constructor parameters and properties are described in the Configuration section.

Configuration

The following table lists the binding configuration properties that you set in the function.json file and the NotificationHub attribute:

function.json property Attribute property Description
type n/a Set to notificationHub.
direction n/a Set to out.
name n/a Variable name used in function code for the notification hub message.
tagExpression TagExpression Tag expressions allow you to specify that notifications be delivered to a set of devices that are registered to receive notifications matching the tag expression. For more information, see Routing and tag expressions.
hubName HubName The name of the notification hub resource in the Azure portal.
connection ConnectionStringSetting The name of an app setting that contains a Notification Hubs connection string. Set the connection string to the DefaultFullSharedAccessSignature value for your notification hub. For more information, see Connection string setup.
platform Platform The platform property indicates the client platform your notification targets. By default, if the platform property is omitted from the output binding, template notifications can be used to target any platform configured on the Azure Notification Hub. For more information about using templates to send cross-platform notifications with an Azure Notification Hub, see Notification Hubs templates. When platform is set, it must be one of the following values:

When you're developing locally, add your application settings in the local.settings.json file in the Values collection.

function.json file example

Here's an example of a Notification Hubs binding in a function.json file:

{
  "bindings": [
    {
      "type": "notificationHub",
      "direction": "out",
      "name": "notification",
      "tagExpression": "",
      "hubName": "my-notification-hub",
      "connection": "MyHubConnectionString",
      "platform": "apns"
    }
  ],
  "disabled": false
}

Connection string setup

To use a notification hub output binding, you must configure the connection string for the hub. You can select an existing notification hub or create a new one from the Integrate tab in the Azure portal. You can also configure the connection string manually.

To configure the connection string to an existing notification hub:

  1. Navigate to your notification hub in the Azure portal, choose Access policies, and select the copy button next to the DefaultFullSharedAccessSignature policy.

    The connection string for the DefaultFullSharedAccessSignature policy is copied to your notification hub. This connection string lets your function send notification messages to the hub. Screenshot that shows how to copy the notification hub connection string.

  2. Navigate to your function app in the Azure portal, expand Settings, and then select Environment variables.

  3. From the App setting tab, select + Add to add a key such as MyHubConnectionString. The Name of this app setting is the output binding connection setting in function.json or the .NET attribute. For more information, see Configuration.

  4. For the value, paste the copied DefaultFullSharedAccessSignature connection string from your notification hub, and then select Apply.

When you're developing locally, add your application settings in the local.settings.json file in the Values collection.

Exceptions and return codes

Binding Reference
Notification Hub Operations Guide