NotificationHub send notification in registered tag UWP

无人久伴 提交于 2019-12-13 02:34:14

问题


Is there a way to send a notification with UWP app through NotificationHub? In many tutorials they send notifications with a C# console application using Microsoft.Azure.NotificationHubs Nuget package. I cannot install this package in a UWP app. Can i specifically send a notification to a tagged device that i register with RegisterNativeAsync?


回答1:


Per my experience, I think the simple way for sending notification in a UWP app is to using Notification Hub REST APIs via HttpClient, without the issues for platform compatibility.

Please refer to the document Notification Hubs REST APIs.

You can try to refer to the doc Using REST APIs from a Backend to make your UWP app as a backend to send messages. For example, Send a WNS Native Notification.

Hope it helps.




回答2:


I finally found the solution. The code is like @Kyle but i had to add

request.Headers.Add("X-WNS-Type", "wns/toast");

in order to send a push notification

More details




回答3:


Here's a working code that sends a notification from a UWP through an Azure Notification Hub (However, it uses GCM instead of WNS, see how to change the code in the approved answer). It obviously needs a few changes like your hub's name, see the comments in the code for more info.

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()
        {
            ConnectionStringUtility("YOURHubFullAccess"); //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)

            //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();
            }
        }
    }
}



回答4:


Did you try WindowsAzure.Messaging.Managed? Just tried it with the W10 UWP.

https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-windows-store-dotnet-get-started/



来源:https://stackoverflow.com/questions/36601278/notificationhub-send-notification-in-registered-tag-uwp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!