Microsoft & .NET.NETSending Notifications to Mobile Apps from Azure Function Apps

Sending Notifications to Mobile Apps from Azure Function Apps

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Introduction

In this article, we will send push notifications using a function app. A function app is a Microsoft Azure offering that can integrate with a service bus, event hubs, notification hubs, and many more. A ‘function app’ can run at regular intervals by specifying the timer schedule. It can be triggered when a message arrives in the service bus (when integrated with the service bus). In this article, we will integrate the service bus with the function app to send push notifications.

Description

As a prerequisite, a notification hub is created and configured with GCM (for Android devices), in Azure portal. In addition, create a Xamarin Android application to receive notifications.

Creating a Service Bus

The first step is to create a service hub. Navigate to the Azure portal. Search for Service bus and, in the filtered list, click “Service Bus,” as shown in Figure 1:

Creating a service bus
Figure 1: Creating a service bus

Fill in the required fields and create a service bus. The next step is to create a queue or a topic in the service bus. In this example, we create a queue named ‘servicebus.’ To retrieve the connection string of the service bus, click “Shared access policies” under the settings section as shown in Figure 2:

Clicking "Shared access policies"
Figure 2: Clicking “Shared access policies”

Click RootManageSharedAccessKey and save the ‘Connection String-Primary Key’ value in a notepad.

Saving the 'Connection String-Primary Key' value
Figure 3: Saving the ‘Connection String-Primary Key’ value

Creating a ‘Function App’

Click the ‘+’ sign and search for ‘Function App.’ In the filtered list, click it (see Figure 4):

Searching for 'Function App'
Figure 4: Searching for ‘Function App’

Fill in all the mandatory values and create the function app.

Completing the mandatory values
Figure 5: Completing the mandatory values

Once the function app is created, click the function app and then navigate to the “Platform features” tab:

Navigating to the "Platform features" tab
Figure 6: Navigating to the “Platform features” tab

Click ‘Application settings’ under the ‘General settings’ section. Add an ‘application settings’ entry to save the connection string to the service hub. Create a key with named ‘ServiceBusConnection;’ the value is the ‘Connection string – Primary Key’ in Figure 3. Save the changes.

Creating the 'ServiceBusConnection' key
Figure 7: Creating the ‘ServiceBusConnection’ key

The next step is to add a function. Click the ‘+’ sign next to the Functions heading and select the template as ‘ServiceBusQueueTrigger – C#.’

Selecting the 'ServiceBusQueueTrigger - C#' template
Figure 8: Selecting the ‘ServiceBusQueueTrigger – C#‘ template

Once the template is selected, it displays the properties to be filled in:

Ready to fill in the properties
Figure 9: Ready to fill in the properties

The ‘queue name’ is the name of the queue created in the service bus. The ‘service bus connection‘ displays the connection strings added in the application settings. Click Create to create the function.

Once the function is created, two files are added; one is ‘function.json‘ and the other ‘run.csx‘. The function.json file contains the input/output parameter details. function.json has the following values based on the configuration selected in the previous step.

{
   "bindings": [
      {
         "name": "myQueueItem",
         "type": "serviceBusTrigger",
         "direction": "in",
         "queueName": "servicebus",
         "connection": "ServiceBusConnection",
         "accessRights": "manage"
      }
   ],
   "disabled": false
}

Remember to set the accessRights value to ‘manage’ instead of ‘Manage’ (‘M’ in lowercase).

To enable notifications, first navigate to the Notification hub and then click ‘Access Policies‘. Copy the connection string for the ‘DefaultFullSharedAccessSignature‘ policy.

Copying the connection string
Figure 10: Copying the connection string

Navigate to the ‘application settings’ of the ‘Function App’ and add a new key, ‘NotificationConnString,’ and paste the connection string value copied in the earlier step.

Open the function.json file, and add the following JSON to the bindings.

{
   "name": "<notification name>",
   "type": "notificationHub",
   "hubName": "<notification hub name>",
   "connection": "<Notification connection string
                   in app settings>",
   "platform": "gcm",
   "tagExpression": "",
   "direction": "out"
}

The ‘name‘ can be any string value. This is passed as a parameter to the run.csx file. In this example, we name it ‘notification.’

The ‘type‘ value should be ‘notificationHub.’ This can’t be altered.

Then, specify the hub name, which is the name of the ‘Notification Hub.’

The connection is the key name in the app settings created for the notification connection string. Refer to Figure 9.

Because we are sending notifications to Android, the ‘platform‘ value is set to ‘gcm.’ ‘tagExpression’ needs to be specified if the messages are targeted for specific devices; otherwise, it can be left blank. Because it’s left blank, the notification is sent to all registered devices. And, lastly, the ‘direction’ has the value ‘out.’

In the run.csx file, add assembly references for ‘Microsoft.Azure.NotificationHubs‘ and ‘Newtonsoft.Json‘ as shown in the following code:

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

Add the namespace by using the ‘using‘ statement.

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

In the run method, add a new parameter named ‘notification‘ of type IAsyncCollector. The updated run method is as shown below:

1. public static async void Run(string myQueueItem,
      IAsyncCollector<Notification> notification, TraceWriter log)
2. {
3.    log.Info($"C# ServiceBus queue trigger function processed
         message: {myQueueItem}");

4.    var p = JsonConvert.DeserializeObject<InputPayload>(myQueueItem);

5.    string gcmNotificationPayload = "{"data": {"message":
         "A new device registered (" + p.UserId + ")" }}";
6.    log.Info($"{gcmNotificationPayload}");
7.    await notification.AddAsync(new GcmNotification
         (gcmNotificationPayload));
8. }

The run method is prefixed with async because notification.AddAsync in Line 7 is an asynchronous method call. The parameter myQueueItem is the JSON payload received from the service bus. In Line 4, the JSON payload is converted to an object. In Line 5, a notification payload is created very specific for GCM (Android) and, in Line 7, a notification is send to the devices.

To test this, use the ‘service bus explorer’ to send a message to the service bus. As and when the message is received in the service bus, the function app gets triggered and sends out the notification.

Summary

In this article, we reviewed integration of the service bus and the ‘Azure Function App’ and how function apps can be used to send notifications. Function apps also can be accessed using the URL from any client application by using HttpClient service call.

References

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories