Here are the steps:
Step 1:
At first we have to reserve or register our app in Windows Store.
Go to https://dev.windows.com and login with your Microsoft account that is Developer account registered.
Go to Dashboard, and Create new app.
Step 2:
Reserve a name of an app. I used ‘PushNotificationService’ for this tutorial.
Step 3:
From the left side of the dashboard, Go to Services > Push Notifications section. We can see the Live Service Site link from where we get the Package-SID and Client Secret that is needed for in Web-Service.
Note down those Package-SID and Client Secret.
Step 4:
Create a Windows Project. Associate this app with the Windows Store. For that, Right click on Project, Store, Associate App with the Store.
Log in with your Microsoft developer account and associate your app.
Step 5:
Next, we will need Channel URI. In the MainPage.xaml, add a Button and a TextBox to get Channel URI of app.
Complete XAML Code:
- <Page
- x:Class="PushNotificationService.MainPage"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:local="using:PushNotificationService"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- mc:Ignorable="d">
-
- <Grid Background="#FF425799">
- <Button x:Name="PushChannelBtn" Content="Get Channel Uri" FontSize="40" Click="PushChannelBtn_Click" Margin="243,164,0,482" Height="122" Width="429" />
- <TextBox x:Name="txtChannelURI" FontSize="22" Foreground="Black" TextWrapping="Wrap" Margin="51,484,53,203" Background="White" />
- </Grid>
- </Page>
Step 6:
In the code behind of MainPage.xaml.cs, update your code with the following code snippet i.e. for the Button Click Event. When we run our app, we will get the Channel URI in the TextBox. Note down this Channel Uri, we will need this in Web Service part.
- private async void PushChannelBtn_Click(object sender, RoutedEventArgs e)
- {
- var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
- txtChannelURI.Text = channel.Uri.ToString();
- }
Note: We have to enable Toast Capabilities in Package.appxmanifest.
Step 7: WEB-SERVICE Part
Now we need a Web Service (Web Application) to send push notification to our registered devices.
For that add a new project. File > Add > New Project > Visual C# > Web > ASP.NET Web Application. Click OK, On Template select Empty. After that Add a new Web Form in your Web Application. Name it SendToast.
Step 8:
In the SendToast.aspx.cs, we need to implement methods and functions to get the Access Token using Package SID, Client Secret and Channel URI.
Add your Package SID, Client Secret, and Channel URI in the respective places.
Complete code snippet for SendToast.aspx.cs:- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Json;
- using System.Text;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
-
- namespace Webservice
- {
- public partial class SendToast : System.Web.UI.Page
- {
- private string packageSID = "Your Package SID";
- private string clinetSecret = "Your Client Secret";
- private string channelUri = "Your Channel URI obtained from APP";
- private string accessToken = string.Empty;
-
- [DataContract]
- public class OAuthToken
- {
- [DataMember(Name = "access_token")]
- public string AccessToken { get; set; }
- [DataMember(Name = "token_type")]
- public string TokenType { get; set; }
- }
-
- OAuthToken GetOAuthTokenFromJson(string jsonString)
- {
- using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
- {
- var ser = new DataContractJsonSerializer(typeof(OAuthToken));
- var oAuthToken = (OAuthToken)ser.ReadObject(ms);
- return oAuthToken;
- }
- }
- protected void Page_Load(object sender, EventArgs e)
- {
- if (Application["channelUri"] != null)
- {
- Application["channelUri"] = channelUri;
- }
- else
- {
- Application.Add("channelUri", channelUri);
- }
-
- if (Application["channelUri"] != null)
- {
- string aStrReq = Application["channelUri"] as string;
- string toast1 = "<?xml version=\"1.0\" encoding=\"utf-8\"?> ";
- string toast2 = @"<toast>
- <visual>
- <binding template=""ToastText01"">
- <text id=""1"">Hello Push Notification Service!!</text>
- </binding>
- </visual>
- </toast>";
- string xml = toast1 + toast2;
-
- Response.Write("Result: " + PostToCloud(aStrReq, xml));
- }
- else
- {
- Response.Write("Application 'channelUri=' has not been set yet");
- }
- Response.End();
- }
- protected string PostToCloud(string uri, string xml, string type = "wns/toast")
- {
- try
- {
- if (accessToken == "")
- {
- GetAccessToken();
- }
- byte[] contentInBytes = Encoding.UTF8.GetBytes(xml);
-
- WebRequest webRequest = HttpWebRequest.Create(uri);
- HttpWebRequest request = webRequest as HttpWebRequest;
- webRequest.Method = "POST";
-
- webRequest.Headers.Add("X-WNS-Type", type);
- webRequest.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken));
-
- Stream requestStream = webRequest.GetRequestStream();
- requestStream.Write(contentInBytes, 0, contentInBytes.Length);
- requestStream.Close();
-
- HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
-
- return webResponse.StatusCode.ToString();
- }
- catch (WebException webException)
- {
- string exceptionDetails = webException.Response.Headers["WWW-Authenticate"];
- if ((exceptionDetails != null) && exceptionDetails.Contains("Token expired"))
- {
- GetAccessToken();
- return PostToCloud(uri, xml, type);
- }
- else
- {
- return "EXCEPTION: " + webException.Message;
- }
- }
- catch (Exception ex)
- {
- return "EXCEPTION: " + ex.Message;
- }
- }
- public void GetAccessToken()
- {
- var urlEncodedSid = HttpUtility.UrlEncode(String.Format("{0}", this.packageSID));
- var urlEncodedSecret = HttpUtility.UrlEncode(this.clinetSecret);
-
- var body =
- String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com", urlEncodedSid, urlEncodedSecret);
-
- var client = new WebClient();
- client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
-
- string response = client.UploadString("https://login.live.com/accesstoken.srf", body);
- var oAuthToken = GetOAuthTokenFromJson(response);
- this.accessToken = oAuthToken.AccessToken;
- }
- }
- }
Step 9:
Run the windows app first and get the Channel URI and put it in SendToast.aspx.cs. After that run the web application. If all things are set correctly, then you will get ‘Result: OK’ response.
And you get the notifications in your device.
That’s it!
Thanks, Happy Coding!
Read more articles on Windows Runtime Apps: