ARTICLE

Working With Raw Notification in Windows Phone 7

Posted by Karthikeyan Anbarasan Articles | Windows Phone April 03, 2012
In this article we are going to see how to use the Raw Notifications to sent messages.
Reader Level:

Introduction

In this article we are going to see how to use the Raw Notifications to sent messages. In our earlier article we have seen how to use the Toast and Tile notifications to send receive message as per the requirement and nature of the usage. Raw Notifications are not like the TOAST and TILE notification, these notifications are generated by the application itself or from a web service. The application needs to be up and running in order to receive these notifications. If the application is not running then the message will be discarded and we will be getting error on the notification

Let us jump start to see the step by step process on how to use Raw Notification Mechanism to do notifications, unlike Tile we will not have a much good looking image to show the notification rather we will try to catch the notification to the message box.

Steps

Open Visual Studio 2010 and create a new Silverlight for Windows Phone 7 Application with a valid project name as shown in the screen below.

img9.gif

Now let us start designing the interface to create a channel, as we discussed in our previous article () we will create the channel first which will be required to communicate for the Raw Notifications. if there are any already available notification events available it will use the same else it will create a new notification event and then connects through the channel. Add the below XAML code to get the channel notification to trigger.

XAML Code

<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
    <
RowDefinition Height="Auto"/>
    <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <!--TitlePanel contains the name of the application and page title-->
    <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
        <TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource PhoneTextNormalStyle}"/>
        <TextBlock x:Name="PageTitle" Text="Raw Notification" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
    </StackPanel>
    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <Button Content="Establish Channel!!!" Height="149" HorizontalAlignment="Left" Margin="73,88,0,0" Name="button1" VerticalAlignment="Top" Width="299" Click="button1_Click" />
    </Grid>
</
Grid

Now we need to go to the code behind and start the process of establishing the Notification channel to get the events trigger. To do that first we need to add the below two using statements.

Code Behind

using Microsoft.Phone.Notification;
using System.Diagnostics;

Now let us add the event handlers for sending the URI to the web service, to handle notification errors and for receiving the raw notification which is application specific as shown in the below 3 event handler codes.

Code Behind

<Grid x:Name="LayoutRoot" Background="Transparent">

    <Grid.RowDefinitions>

        <RowDefinition Height="Auto"/>

        <RowDefinition Height="*"/>

    </Grid.RowDefinitions>

 
   <!--TitlePanel contains the name of the application and page title-->

    <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">

        <TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource PhoneTextNormalStyle}"/>

        <TextBlock x:Name="PageTitle" Text="Raw Notification" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>

    </StackPanel>

 

    <!--ContentPanel - place additional content here-->

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

        <Button Content="Establish Channel!!!" Height="149" HorizontalAlignment="Left" Margin="73,88,0,0" Name="button1" VerticalAlignment="Top" Width="299" Click="button1_Click" />

    </Grid>

</Grid>

Now we need to write the code to get the open channel details which will be used to send the Raw Notification, to do that we will use the output window to get the channel details. Copy the below code to the code behind page. Also we need to have a method which will do the channel setup step by step, first it will check if the channel is already available if its available we need to check the channel is null if null then we need to close the channel and open a new channel. But initially if the channel is not available then we can directly create the HttpNotificationChannel and do the process to create the channel as shown in the screen below.

Code Behind

private void SetupChannel()

 {

      HttpNotificationChannel pushRawChannel;

      string strRawchannelName = "RawChannel0";

      pushRawChannel = HttpNotificationChannel.Find(strRawchannelName);

     if (pushRawChannel == null)

      {

      pushRawChannel = new HttpNotificationChannel(strRawchannelName);

      pushRawChannel.ChannelUriUpdated += new EventHandler(RawNotificationChannelURI);

      pushRawChannel.ErrorOccurred += new EventHandler(RawNotificationError);

      pushRawChannel.HttpNotificationReceived += new EventHandler(RawNotificationReceived);

      pushRawChannel.Open();

     }

 else

 {
      pushRawChannel.ChannelUriUpdated += new EventHandler(RawNotificationChannelURI);

      pushRawChannel.ErrorOccurred += new EventHandler(RawNotificationError);

      pushRawChannel.HttpNotificationReceived += new EventHandler(RawNotificationReceived);

      System.Diagnostics.Debug.WriteLine(pushRawChannel.ChannelUri.ToString());

      Debug.WriteLine(String.Format("Channel Uri = {0}", pushRawChannel.ChannelUri.ToString()));

 }

}

 

Now we need to call the above method on the button click event as shown in the screen below.

Code Behind

private void button1_Click(object sender, RoutedEventArgs e)

 {

 SetupChannel();

 }
 

Now we are done with the Windows phone 7 client notification application, we will check by building and executing the application and we can see the Windows Phone 7 Emulator as shown in the screen below.

img2.png

Now click on the Establish Channel button which will establish the channel if not already created else will use existing channel and we can see the channel URI in the Output window since we have coded to get the channel details. To get the output window just go to the Visual Studio tool bar and select View –> Output window and we can see the output window as shown in the screen below.

img3.png

Let us copy and keep the channel details on to a separate notepad, Now we need to create a Server to post the tile notifications to the application device to show the Raw Notification message. We will create a web page from which we will post the Raw Notifications and get the notification on to the Windows Phone 7 device. To start with first create a ASP.NET Web application in C# as shown in the screen below.

img 4.png

Now add the below design code to the ASPX page so that we will get the same look and feel for this tutorial, here we have added 3 labels and 3 textboxes to get the user inputs (Channel URI, Title and Sub Title) and a button to trigger the event for the tile message to be sent to the Windows Phone 7 Device. Just copy and paste the below ASPX code.

ASPX Code

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="F5debugWp7RawNotificationServer._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">

<style type="text/css">

.style1

{

width:100%;

}

.style2

{

}

.style3

{

width:690px;

}

.style4

{

width:143px;

}

.style5

{

width:38px;

}

</style>

</asp:Content>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

<table>

<tr>

<td colspan="3">

<asp:Label ID="Label1" runat="server" Font-Bold="true" Font-Size="Large" Text="F5Debug Windows Phone 7 Raw Notification"></asp:Label>

</td>

<td>

&nbsp;</td>

</tr>

<tr>

<td>

&nbsp;</td>

<td>

&nbsp;</td>

<td>

&nbsp;</td>

<td>

&nbsp;</td>

</tr>

<tr>

<td>

&nbsp;</td>

<td>

<asp:Label ID="Label2" runat="server" Text="Channel URI"></asp:Label>

</td>

<td>

<asp:TextBox ID="TextBox1" runat="server" Width="661px"></asp:TextBox>

</td>

<td>

&nbsp;</td>

</tr>

<tr>

<td>

&nbsp;</td>

<td>

&nbsp;</td>

<td>

&nbsp;</td>

<td>

&nbsp;</td>

</tr>

<tr>

<td>

&nbsp;</td>

<td>

<asp:Label ID="Label3" runat="server" Text="Notification Title"></asp:Label>

</td>

<td>

<asp:TextBox ID="TextBox2" runat="server" Width="661px"></asp:TextBox>

</td>

<td>

&nbsp;</td>

</tr>

<tr>

<td>

&nbsp;</td>

<td>

&nbsp;</td>

<td>

&nbsp;</td>

<td>

&nbsp;</td>

</tr>

<tr>

<td>

&nbsp;</td>

<td>

<asp:Label ID="Label4" runat="server" Text="Notification SubTitle"></asp:Label>

</td>

<td>

<asp:TextBox ID="TextBox3" runat="server" Width="659px"></asp:TextBox>

</td>

<td>

&nbsp;</td>

</tr>

<tr>

<td>

&nbsp;</td>

<td>

&nbsp;</td>

<td>

&nbsp;</td>

<td>

&nbsp;</td>

</tr>

<tr>

<td>

&nbsp;</td>

<td>

<asp:Button ID="Button1" runat="server" Font-Bold="True"

onclick="Button1_Click" Text="Send Notification" Width="134px" />

</td>

<td>

<asp:Label ID="lblresult" runat="server"></asp:Label>

</td>

<td>

&nbsp;</td>

</tr>

</table>

</asp:Content>

img5.png

Now go to the code behind and add the below code, this code will get the user inputs mainly the Channel URI, background and the Raw Message information and pass the message to the Microsoft Push Notification services. Just copy the below code to proceed further.

C# Code

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Net;

using System.IO;

using System.Text;

namespace F5debugWp7RawNotificationServer

{

    public partial class _Default : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

        }

        protected void Button1_Click(object sender, EventArgs e)

        {

            try

            {

                string strChannelURI = TextBox1.Text.ToString();

                HttpWebRequest sendRawNotification = (HttpWebRequest)WebRequest.Create(strChannelURI);

 

                sendRawNotification.Method = "POST";

 

                string strRawMessage = "<!--?xml version=\"1.0\" encoding=\"utf-8\"?-->" +

                 "" +

                 "" + TextBox2.Text.ToString() + "" +

                 "" + TextBox3.Text.ToString() + "" +

                 "";

 

                byte[] notificationMessage = Encoding.Default.GetBytes(strRawMessage);

 

                sendRawNotification.ContentLength = notificationMessage.Length;

                sendRawNotification.ContentType = "text/xml";

                sendRawNotification.Headers.Add("X-NotificationClass", "3");

 

                using (Stream requestStream = sendRawNotification.GetRequestStream())

                {

                    requestStream.Write(notificationMessage, 0, notificationMessage.Length);

                }

 

                HttpWebResponse response = (HttpWebResponse)sendRawNotification.GetResponse();

                string notificationStatus = response.Headers["X-NotificationStatus"];

                string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];

                string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];

 

                lblresult.Text = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus;

            }

            catch (Exception ex)

            {

                lblresult.Text = "Exception caught: " + ex.ToString();

            }

 

        }

    }

}

 
Now we are done with our server code, to test raw notification first run the Windows Phone 7 application (F5debugWp7RawNotification) and get the Channel URI or make use of the URI which we saved in our notepad. Note that the application should be in running mode in order to get the notification message. Now run the project F5debugWp7RawNotificationServer web application and enter the values as shown in the screen below.

img6.png

Now click on Send Notification button and we can see the result in the label at the bottom as shown in the screen below.

img7.png

Now go to the Windows Phone 7 Emulator and we can see the Raw Notification Message which we sent from the web application in the Message Box as shown in the screen below.

img8.png

Conclusion

So in this article we have seen how to use the RAW Notification Mechanism to send and receive the notifications while the application is running on the foreground.

COMMENT USING