Kyle
Kyle

Reputation: 154

Sending notification to Azure Notification Hub from Universal Windows Platform (UWP) app

As the title suggests, I need to send a notification FROM a UWP app (written in C#) to my Azure's hub (and from there it's sent to an Android app that I've already created). I obviously use GCM in order to send push notification to my Android app.

After countless hours of searching I have yet to find a single tutorial that would somehow be of use, since most of them use a console application in order to send the notification, not a Universal Windows Platform app.

If anyone could please help me I'd be really thankful.

Upvotes: 0

Views: 1245

Answers (2)

Kyle
Kyle

Reputation: 154

I'm gonna answer my own question here since a lot of people struggled with this like me. So here's a code that sends a notification from a Universal Windows Platform (UWP) through an Azure Notification Hub, to an Android app (using GCM).

Please note that MUST slightly change the code for it to work on your own notification hub (see the comments in the code for more details)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;


namespace SendNotification
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            this.sendNotification();
        }

        string Endpoint = "";
        string SasKeyName = "";
        string SasKeyValue = "";

        public void ConnectionStringUtility(string connectionString)
        {
            //Parse Connectionstring
            char[] separator = { ';' };
            string[] parts = connectionString.Split(separator);
            for (int i = 0; i < parts.Length; i++)
            {
                if (parts[i].StartsWith("Endpoint"))
                    Endpoint = "https" + parts[i].Substring(11);
                if (parts[i].StartsWith("SharedAccessKeyName"))
                    SasKeyName = parts[i].Substring(20);
                if (parts[i].StartsWith("SharedAccessKey"))
                    SasKeyValue = parts[i].Substring(16);
            }
        }


        public string getSaSToken(string uri, int minUntilExpire)
        {
            string targetUri = Uri.EscapeDataString(uri.ToLower()).ToLower();

            // Add an expiration in seconds to it.
            long expiresOnDate = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
            expiresOnDate += minUntilExpire * 60 * 1000;
            long expires_seconds = expiresOnDate / 1000;
            String toSign = targetUri + "\n" + expires_seconds;

            // Generate a HMAC-SHA256 hash or the uri and expiration using your secret key.
            MacAlgorithmProvider macAlgorithmProvider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
            BinaryStringEncoding encoding = BinaryStringEncoding.Utf8;
            var messageBuffer = CryptographicBuffer.ConvertStringToBinary(toSign, encoding);
            IBuffer keyBuffer = CryptographicBuffer.ConvertStringToBinary(SasKeyValue, encoding);
            CryptographicKey hmacKey = macAlgorithmProvider.CreateKey(keyBuffer);
            IBuffer signedMessage = CryptographicEngine.Sign(hmacKey, messageBuffer);

            string signature = Uri.EscapeDataString(CryptographicBuffer.EncodeToBase64String(signedMessage));

            return "SharedAccessSignature sr=" + targetUri + "&sig=" + signature + "&se=" + expires_seconds + "&skn=" + SasKeyName;
        }


        public async void sendNotification()
        {
            //insert your HubFullAccess here (a string that can be copied from the Azure Portal by clicking Access Policies on the Settings blade for your notification hub)
            ConnectionStringUtility("YOURHubFullAccess"); 

            //replace YOURHUBNAME with whatever you named your notification hub in azure 
            var uri = Endpoint + "YOURHUBNAME" + "/messages/?api-version=2015-01";
            string json = "{\"data\":{\"message\":\"" + "Hello World!" + "\"}}";


            //send an HTTP POST request
            using (var httpClient = new HttpClient())
            {
                var request = new HttpRequestMessage(HttpMethod.Post, uri);
                request.Content = new StringContent(json);

                request.Headers.Add("Authorization", getSaSToken(uri, 1000));
                request.Headers.Add("ServiceBusNotification-Format", "gcm");
                var response = await httpClient.SendAsync(request);
                await response.Content.ReadAsStringAsync();
            }
        }
    }
}

Upvotes: 1

Addys
Addys

Reputation: 2501

You can use the Notification Hub REST APIs to push a notification from anywhere (backend or device) over vanilla HTTP/HTTPS.

There is a sample (using a Java client) here: https://msdn.microsoft.com/en-us/library/azure/dn495628.aspx

And the API reference is here: https://msdn.microsoft.com/en-us/library/azure/dn495827.aspx

Upvotes: 1

Related Questions