In a simple scenario we will discover how to send a push notification to FCM/GCM in an Azure WebJob.

After several months in Beta, Azure WebJobs SDK 2.0 has been released March 1st 2017:

Azure WebJobs SDK 2.0 released

Along with this release several new extensions are now available. Today we will take a look at the version 1.0 of the following:

WebJobs Notification Hubs extension

 

Thanks to this extension, sending push notifications from an Azure WebJob become an easy task.

In this article, we will discover how to send a FCM/GCM (Firebase Cloud Messaging/Google Cloud Messaging) notification from an Azure WebJob with the Azure Notification Hubs extension. As a base, we will create a project with the Azure WebJob template in Visual Studio.

 

Creation

The first thing you will need is an Azure Notification Hub deployed on Azure. If don't know how, you can quickly deploy one with ARM template. Everything is detailed for you in a previous article.

 

Once your Notification Hub deployed and setup, add the following NuGet package to your project: Microsoft.Azure.WebJobs.Extensions.NotificationHubs

 

To enable the Notifications Hubs extension in your WebJob you will need to configure the JobHostConfiguration like the following:

using Microsoft.Azure.WebJobs;

namespace AzureWebJobs.NotificationHubExtension
{
	// To learn more about Microsoft Azure WebJobs SDK, please see https://go.microsoft.com/fwlink/?LinkID=320976
	class Program
	{
		// Please set the following connection strings in app.config for this WebJob to run:
		// AzureWebJobsDashboard and AzureWebJobsStorage
		static void Main()
		{
			var config = new JobHostConfiguration();

			if (config.IsDevelopment)
			{
				config.UseDevelopmentSettings();
			}

			config.UseNotificationHubs();

			var host = new JobHost(config);
			// The following code ensures that the WebJob will be running continuously
			host.RunAndBlock();
		}
	}
}

The important part here is to call the extension named UseNotificationHubs. This will enable the Notification Hubs extension.

 

We will now add two new application settings to be able to connect to Azure Notification Hubs:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <!-- The format of the connection string is "DefaultEndpointsProtocol=https;AccountName=NAME;AccountKey=KEY" -->
    <!-- For local execution, the value can be set either in this config file or through environment variables -->
    <add name="AzureWebJobsDashboard" connectionString="" />
    <add name="AzureWebJobsStorage" connectionString="" />
  </connectionStrings>
  <appSettings>
    <add key="AzureWebJobsNotificationHubsConnectionString" value="Endpoint=sb://mynotifhubnamespace.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=U3Mxxx" />
    <add key="AzureWebJobsNotificationHubName" value="myNotifHub" />
  </appSettings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Azure.KeyVault.Core" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.WindowsAzure.Storage" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-8.1.1.0" newVersion="8.1.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

 

Now using the default ProcessQueueMessage function that uses a QueueTrigger, we want to send a notification when a message is added to the queue:

using System.IO;
using AzureWebJobs.NotificationHubExtension.Extensions;
using Microsoft.Azure.NotificationHubs;
using Microsoft.Azure.WebJobs;

namespace AzureWebJobs.NotificationHubExtension
{
	public class Functions
	{
		// This function will get triggered/executed when a new message is written 
		// on an Azure Queue called queue.
		public static void ProcessQueueMessage([QueueTrigger("queue")] string message, TextWriter log, [NotificationHub] out Notification notification)
		{
			log.WriteLine(message);

			notification = new GcmNotification(message.ToGcmPayload());
		}
	}
}

You can notice two things here:

 

Example of use

Once the WebJob ready and properly configured, we will launch it and add a message to the queue:

Found the following functions:
AzureWebJobs.NotificationHubExtension.Functions.ProcessQueueMessage
Job host started
Executing 'Functions.ProcessQueueMessage' (Reason='New queue message detected on 'queue'.', Id=f7767465-adb0-46d7-83f4-926f1c526074)
Notification Hub test notification from WebJob
Executed 'Functions.ProcessQueueMessage' (Succeeded, Id=f7767465-adb0-46d7-83f4-926f1c526074)

If everything goes well, you should see the same kind of message in console output as above.

 

The ToGcmPayload() extension will generate the following payload and will be sent in the notification:

"{\"data\":{\"message\":\"Notification Hub test notification\"}}"

 

To go further

If you want to send more than one notification, the out parameter can be an array of notification like the following:

public static void ProcessQueueMessage([QueueTrigger("queue")] string message, TextWriter log, [NotificationHub] out Notification[] notifications)

There are many other ways to send notifications from the extension like template notification, more details can be found here:

Notification Hubs Extension Samples

 

 

Summary

We have seen how to send a notification from an Azure WebJob using the Azure Notification Hubs extension.

 

You can download the example solution here:

Download full sources

Or

Browse the GitHub repository

(Note that the project uses Microsoft.Azure.WebJobs version 2.0.0)

 

Please feel free to comment or contact me if you have any question about this article.

Add a comment

(Will not be published)

Back to articles