MAUI Push Notifications using Azure Notification Hub

maui net8 push notification

It is more than 2 weeks since I tried to configure and implement in my NET8 MAUI application the push notifications using Azure Notification Hubs. Also, I paid the Azure support (not very useful), and I still can’t configure the hub for Windows and Android. So, I tried another plugin at this point but had to ignore the Windows notification (sigh!).

I tried:

Could not find a part of the path ‘C:\Users\enric.nuget\packages\xamarin.firebase.ios.installations\8.10.0.3\lib\net6.0-ios15.4\Firebase.Installations.resources\FirebaseInstallations.xcframework\ios-arm64_x86_64-simulator\FirebaseInstallations.framework\Headers\FirebaseInstallations-umbrella.h’.

Could not find a part of the path ‘C:\Users\enric.nuget\packages\xamarin.firebase.ios.installations\8.10.0.3\lib\net6.0-ios15.4\Firebase.Installations.resources\FirebaseInstallations.xcframework\ios-arm64_x86_64-simulator\FirebaseInstallations.framework\Headers\FirebaseInstallations-umbrella.h’.

  • I followed the implementation of Vladislav Antonyuk but at the moment it is not working for me
  • I read some comments on GitHub where Microsoft said that the push notification is embedded in MAUI but I can’t find any further documentation

After a lot – very a lot – of bad words and nights without sleeping, I sorted it out. It is quite complicated because the settings are difficult to understand and the documentation is not really clear.

So, I show you everything I discovered without using external plugin but only what MAUI offers and HttpClient. I split this topic in a few posts:

Setting up Azure Notification Hubs

First, I have to set up the Azure Notification Hubs and this is a piece of cake, just follow the process in the Azure portal.

Creation of the Notification Hub

So, in order to create a new Azure Notification Hub, navigate to the Azure portal, and then create or use a Resource Group.

  1. Click on Create a resource
  2. In the search box, type Notification Hub and click on it.
- MAUI Push Notifications using Azure Notification Hub
  1. Enter all the necessary details and click Create. In my case, and this is important I type those values to use later in the code:
  • Notification Hub Namespace: languageinuse
  • Notification Hub: app
- MAUI Push Notifications using Azure Notification Hub

Important note

This is an update after a month I’m running this Notification Hub. I have just received a bill from Microsoft of £368 for a month related to the Notification Hub.

Azure cost of the Notification Hub
Azure cost of the Notification Hub

In the screenshot above, you see the option Enable availability zones. Although the price for the Notification Hub is Free, this service costs you a lot.

Azure Notification Hub - Availability zone cost
Azure Notification Hub – Availability zone cost

So, if you are doing your tests, uncheck the option to avoid this expensive service.

Disable the Availability zone

After a long search, if you created an Azure Notification Hub Namespace checking the Availability zone, there is no way to remove it. You have to re-create the namespace. So, check the following screenshot.

Disable the Availability zone
Disable the Availability zone

Disable the disaster recovery

Now, if you checked the option Enable availability zones, probably you want to disable it. For that, open each Notification Hub (not the Notification Hub Namespace) and in the Essentials section, you find Flexible recovery region.

When you click on the link on the right – in the screenshot Southeast Asia – a blade is opened and the title is Edit Disaster Recovery.

From here, uncheck Enable disaster recovery and then click Save.

Configuring the Notification Hub

After creation, configure your newly created Notification Hub:

  1. Go to your Notification Hub and under the Manage section, select Access Policies.
- MAUI Push Notifications using Azure Notification Hub
  1. Note down the DefaultListenSharedAccessSignature connection strings provided. In particular, the last part of the connection is important: that is your key to use in the code later.

Setting up Windows Notification Service (WNS)

Now, sit back, relax and start to swear. WNS delivers notifications from cloud servers to Windows apps running on Windows 8, Windows Phone (sigh, unfortunately it doesn’t exist anymore) and later. My focus is Windows 11 and later.

Find the Package SID for your Windows application

  1. Go to the Windows Dev Center’s Dashboard, and sign in with your account.
  2. Choose your app from the list of apps.
  3. Click on Product identity.
  4. Find the Package SID value. We will need it later when configuring WNS with Azure. The Package SID is a very long ID like S-1-15-2-283421221-……….-……….-………

Now, from the documentation, Microsoft says to go to the WNS\MPNS section and register from here your application. Unfortunately, this is not valid anymore. Be careful because this is a tricky part.

Add your app in the Azure App Registration

First, a little bit of background. I’m using the Developer Windows portal and Azure portal with the same account. In all the documentation, I found that I have to create a new App Registration for my app. The real problem is where creating this new registration.

If I create a new registration and this will appear under Owned applications tab, when you try to add an app in the Azure Notification Hub, an error occurs:

{"error":{"code":"BadRequest","message":"Invalid WNS credentials."}}

All the support I got and the answers to my question was to register the application in the App Registration. I tried quite a few times to register the app but I have never seen or been told to create the app under the Applications from personal account.

App Registration in the Azure portal from personal account
App Registration in the Azure portal from personal account

So, when in you Microsoft Entra ID, you add a New registration, in the prompt Where should this application be registered?, you have to select Only associate with personal account.

Then, fill the form and create the new app. At this point, you are ready to continue. Now, clik on your app and follow the steps:

  1. Click on Certificates & secrets
  2. Click on New client secret and create a new secret. Note down the secret value. It is your Security Key. We will need it later when configuring WNS with Azure.

Configure WNS with Azure

  1. Go to the Azure portal.
  2. In your Notification Hub, under Settings, select Windows (WNS).
  3. Fill in the Package SID and Security Key details:
    • Package SID: the value you obtained in the previous step. The format is ms-app://<Package SID>.
    • Security Key: the value you obtained in the previous step.
  4. Click Save.

The format of the Package SID must be ms-app://S-x-xxxx-xxxxxx

Setting up your .NET MAUI Project for Windows

Windows doesn’t require any additional packages. We only need to register our device and configure what to do when the a message arrives.

Only the application is running or running in the background, it will receive the notification from the sever.

This is quite important. If you send a push notification to Windows, only if the users have the application open, they will receive your message. If you want to be sure your message will be delivered also when it is close, you have to create a background service. Here some documentation. I haven’t tried to create that yet.

Registering for Push Notifications

In your Platforms/Windows/App.xaml.cs handle the startup logic to register for push notifications. For Windows, use PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync() to create a channel and register it with NotificationHub. For that, I’m using the code from Vladislav Antonyuk with my correction.

Create a valid token

First, we have to be sure that we have a valid token in order to call the API for the Azure Notification Hub to register our device. The reference for that is in the Microsoft documentation.

private static string CreateToken(string resourceUri, string keyName, string key)
{
    var sinceEpoch = DateTime.UtcNow - DateTime.UnixEpoch;
    var week = 60 * 60 * 24 * 7;
    var expiry = Convert.ToString((int)sinceEpoch.TotalSeconds + week);
    var stringToSign = HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;

    using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
    var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));

    var sasToken = string.Format(CultureInfo.InvariantCulture,
                                    "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}",
                                    HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry,
                                    keyName);
    return sasToken;
}

Register your device

Then, we have to register our devices to the Azure Notification Hub. This is the full function.

private async Task RegisterDevice(string notificationHub, string key)
{
    var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
    channel.PushNotificationReceived += Channel_PushNotificationReceived;

    var deviceInstallation = new
    {
        InstallationId = new EasClientDeviceInformation().Id,
        Platform = "wns",
        PushChannel = channel.Uri
    };

    using var httpClient = new HttpClient();
    httpClient.DefaultRequestHeaders.Add("x-ms-version", "2015-01");
    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization",
                                            CreateToken($"https://{notificationHubNamespace}.servicebus.windows.net",
                                                        "DefaultListenSharedAccessSignature",
                                                        key));
    await httpClient.PutAsJsonAsync($"https://{notificationHubNamespace}.servicebus.windows.net/" + 
                                    $"{notificationHub}/installations/{deviceInstallation.InstallationId}" +
                                    "?api-version=2015-01", deviceInstallation);
}

Remember that notificationHubNamespace is different from notificationHub. The notificationHubNamespace is the name of the Azure Notification Hub (in my case languageinuse) and the notificationHub is the spefic part of the hub (in my case app).

Then, I have to add the code to receive the push notification message from the line 4 and doing something with the message (for example show it)

private void Channel_PushNotificationReceived(PushNotificationChannel sender, 
    PushNotificationReceivedEventArgs args)
{
    var notification = args.RawNotification;
    // implement your logic here...
}

At the end, I have to call the function to register the device when the app starts.

protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
    base.OnLaunched(args);
    await RegisterDevice("notificationHubNamespace", "YOUR SharedAccessKey");
}

The SharedAccessKey is the key I saved from the App Registration before.

Test your implementation

Finally, this is the easy part. Open your hub and click on Test Send. Select Windows as a platform and then click on Send.

If everything is correct and the app is open, you will receive the message. Now, you can display it or read the data to do something else.

Wrap up

In conclusion, after almost 3 weeks, I found how to implement in MAUI the push notifications using Azure Notification Hub for Windows. I’m writing a new post about Android that it is working already. For iOS, I need a little bit of support and understand how to do it. Hopefully, soon, I can show you also iOS.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.