Click here to Skip to main content
15,881,380 members
Articles / Desktop Programming / Universal Windows Platform

Send Push Notifications in Windows Universal App Using WNS

Rate me:
Please Sign up or sign in to vote.
1.00/5 (1 vote)
28 Mar 2016CPOL2 min read 13.8K   493   3  
In this article, we will learn how to send Push notifications in Windows Universal app using WNS

Introduction

Implementation of Push notifications in Windows phone 8.1 is totally different from Windows phone 8. So here we will see how to receive notification in Windows 8.1 devices. For receiving Push notifications, we need a client and a server. Client is one which will receive notification and the server is one which will send notification to the client. We will create client in Windows Universal app and server in console application.

Client (Windows Universal App)

Take a new project, i.e., Blank App (Universal Apps) and give it whatever name you want.

You need to associate your app with Windows store first. So register your app in your developer account here. After registering your app at store, right click on your project in solution explorer and click on Store-->Associate App with Store...

You will get the below screen:

Image 1

Image 2

After login, you will get mobile number verification screen. After mobile number verification, you will get a list of all the apps that you have registered in your developer account. Select the app name and click Next button.

Image 3

Create channel and generate uri. This uri is unique for any device. WNS will send notification to this uri. We can call it Device Token or Device Id.

C#
string notificationUrl;
var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
notificationUrl= channel.Uri.ToString();

It will be generated by client app itself and we need to give this uri to the server because the server will send notification using this uri.

Server (Console Application)

For sending push notification to Windows 8.1 devices, we need the following three things:

  1. Package SID
  2. Client secret
  3. Uri

You will get Package SID and Client secret from your Windows developer account. In your developer account, go to Services-->Push notifications in left navigation bar. Then, click on Live Services site.

Image 4

You will get Package SID and Client secret here.

Image 5

Uri will be generated by client app and we have already seen this.

Take a console project and write the below code in it.

C++
 class Program
    {
        private static string secret = "Client secret";
        private static string SID = "Package SID";
        private static OAuthToken _token;
        private static string XmlToastTemplate = @"<toast launch="""">
<visual lang=""en-US"">
<binding template=""ToastText01"">
<text id=""1"">Test message</text>
</binding>
</visual>
</toast>";
        private static Uri accesTokenuri = new Uri("https://login.live.com/accesstoken.srf");
        static void Main(string[] args)
        {
            if (_token == null)
            {
                CreateToken();
            }

            var message = String.Empty;
            Console.WriteLine("Enter toast message");
            message = Console.ReadLine();

            Console.WriteLine("Enter device uri");
            string uriWithToken = Console.ReadLine();

            var wc = HttpWebRequest.Create(uriWithToken) as HttpWebRequest;
            wc.Method = "POST";
            wc.Headers.Add("X-WNS-Type", "wns/toast");
            wc.Headers.Add("X-WNS-RequestForStatus", "true");
            wc.Headers.Add("Authorization", String.Format("Bearer {0}", _token.AccessToken));
            wc.ContentType = "text/xml";
            var byteContent = Encoding.UTF8.GetBytes(XmlToastTemplate);
            using (var requestStream = wc.GetRequestStream())
            {
                requestStream.Write(byteContent, 0, byteContent.Length);
            }

            using (var response = wc.GetResponse() as HttpWebResponse)
            {
                if (response != null)
                {
                    var statusCode = response.StatusCode;
                    Console.WriteLine(statusCode);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        private static OAuthToken GetOAuthJSON(string json)
        {
            using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
            {
                var ser = new DataContractJsonSerializer(typeof(OAuthToken));
                var oAuthToken = (OAuthToken)ser.ReadObject(ms);
                return oAuthToken;
            }
        }//GetOAuthJSON

        private static void CreateToken()
        {
            var encSid = WebUtility.UrlEncode(SID);
            var encSecret = WebUtility.UrlEncode(secret);

            var body =
                String.Format("grant_type=client_credentials&client_id={0}&
                client_secret={1}&scope=notify.windows.com",
                    encSid, encSecret);

            var wb = new WebClient();
            wb.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            var response = wb.UploadString(accesTokenuri, body);
            _token = GetOAuthJSON(response);
        }//CreateToken

        [DataContract]
        class OAuthToken
        {
            [DataMember(Name = "access_token")]
            public string AccessToken { get; set; }
            [DataMember(Name = "token_type")]
            public string TokenType { get; set; }
        }
    }

When you will run console app and pass correct uri, you will receive notification in your app.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
-- There are no messages in this forum --