Floating FB popout byF5debug

Learn Windows Phone 7 Development in 31 Days – Day 14 – Working with Raw Notification in WP7

 

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.     [more]

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.

clip_image002

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:

01

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

02

<Grid.RowDefinitions>

03

<RowDefinition Height="Auto"/>

04

<RowDefinition Height="*"/>

05

</Grid.RowDefinitions>

06

 

07

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

08

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

09

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

10

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

11

</StackPanel>

12

 

13

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

14

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

15

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

16

</Grid>

17

</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:

1

using Microsoft.Phone.Notification;

2

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:

01

void RawNotificationChannelURI(object sender, NotificationChannelUriEventArgs e)

02

{

03

Dispatcher.BeginInvoke(() =>

04

{

05

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

06

Debug.WriteLine(String.Format("URI : {0}", e.ChannelUri.ToString()));

07

 

08

});

09

}

10

 

11

void RawNotificationError(object sender, NotificationChannelErrorEventArgs e)

12

{

13

Dispatcher.BeginInvoke(() =>

14

Debug.WriteLine(String.Format("Notification {0}.  {1} ({2}) {3}",

15

e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData)));

16

}

17

 

18

void RawNotificationReceived(object sender, HttpNotificationEventArgs e)

19

{

20

string strRawMessage;

21

 

22

using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))

23

{

24

strRawMessage = reader.ReadToEnd();

25

}

26

 

27

Dispatcher.BeginInvoke(() =>

28

Debug.WriteLine(String.Format("Raw Notification {0}:\n{1}",

29

DateTime.Now.ToShortTimeString(), strRawMessage)));

30

}

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:

01

private void SetupChannel()

02

{

03

HttpNotificationChannel pushRawChannel;

04

string strRawchannelName = "RawChannel0";

05

 

06

pushRawChannel = HttpNotificationChannel.Find(strRawchannelName);

07

 

08

if (pushRawChannel == null)

09

{

10

pushRawChannel = new HttpNotificationChannel(strRawchannelName);

11

 

12

pushRawChannel.ChannelUriUpdated += new EventHandler(RawNotificationChannelURI);

13

pushRawChannel.ErrorOccurred += new EventHandler(RawNotificationError);

14

pushRawChannel.HttpNotificationReceived += new EventHandler(RawNotificationReceived);

15

 

16

pushRawChannel.Open();

17

 

18

}

19

else

20

{

21

pushRawChannel.ChannelUriUpdated += new EventHandler(RawNotificationChannelURI);

22

pushRawChannel.ErrorOccurred += new EventHandler(RawNotificationError);

23

pushRawChannel.HttpNotificationReceived += new EventHandler(RawNotificationReceived);

24

 

25

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

26

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

     

27

 

28

}

29

}

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

Code Behind:

1

private void button1_Click(object sender, RoutedEventArgs e)

2

{

3

SetupChannel();

4

}

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.

clip_image004

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.

clip_image006

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.

clip_image008

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:

001

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"

002

CodeBehind="Default.aspx.cs" Inherits="F5debugWp7RawNotificationServer._Default" %>

003

 

004

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

005

<style type="text/css">

006

.style1

007

{

008

width: 100%;

009

}

010

.style2

011

{

012

}

013

.style3

014

{

015

width: 690px;

016

}

017

.style4

018

{

019

width: 143px;

020

}

021

.style5

022

{

023

width: 38px;

024

}

025

</style>

026

</asp:Content>

027

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

028

<table>

029

<tr>

030

<td colspan="3">

031

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

032

</td>

033

<td>

034

&nbsp;</td>

035

</tr>

036

<tr>

037

<td>

038

&nbsp;</td>

039

<td>

040

&nbsp;</td>

041

<td>

042

&nbsp;</td>

043

<td>

044

&nbsp;</td>

045

</tr>

046

<tr>

047

<td>

048

&nbsp;</td>

049

<td>

050

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

051

</td>

052

<td>

053

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

054

</td>

055

<td>

056

&nbsp;</td>

057

</tr>

058

<tr>

059

<td>

060

&nbsp;</td>

061

<td>

062

&nbsp;</td>

063

<td>

064

&nbsp;</td>

065

<td>

066

&nbsp;</td>

067

</tr>

068

<tr>

069

<td>

070

&nbsp;</td>

071

<td>

072

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

073

</td>

074

<td>

075

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

076

</td>

077

<td>

078

&nbsp;</td>

079

</tr>

080

<tr>

081

<td>

082

&nbsp;</td>

083

<td>

084

&nbsp;</td>

085

<td>

086

&nbsp;</td>

087

<td>

088

&nbsp;</td>

089

</tr>

090

<tr>

091

<td>

092

&nbsp;</td>

093

<td>

094

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

095

</td>

096

<td>

097

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

098

</td>

099

<td>

100

&nbsp;</td>

101

</tr>

102

<tr>

103

<td>

104

&nbsp;</td>

105

<td>

106

&nbsp;</td>

107

<td>

108

&nbsp;</td>

109

<td>

110

&nbsp;</td>

111

</tr>

112

<tr>

113

<td>

114

&nbsp;</td>

115

<td>

116

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

117

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

118

</td>

119

<td>

120

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

121

</td>

122

<td>

123

&nbsp;</td>

124

</tr>

125

</table>

126

</asp:Content>

clip_image010

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:

01

using System;

02

using System.Collections.Generic;

03

using System.Linq;

04

using System.Web;

05

using System.Web.UI;

06

using System.Web.UI.WebControls;

07

using System.Net;

08

using System.IO;

09

using System.Text;

10

 

11

namespace F5debugWp7RawNotificationServer

12

{

13

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

14

{

15

protected void Page_Load(object sender, EventArgs e)

16

{

17

}

18

 

19

protected void Button1_Click(object sender, EventArgs e)

20

{

21

try

22

{

23

string strChannelURI = TextBox1.Text.ToString();

24

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

25

 

26

sendRawNotification.Method = "POST";

27

 

28

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

29

"" +

30

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

31

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

32

"";

33

 

34

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

35

 

36

sendRawNotification.ContentLength = notificationMessage.Length;

37

sendRawNotification.ContentType = "text/xml";

38

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

39

 

40

using (Stream requestStream = sendRawNotification.GetRequestStream())

41

{

42

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

43

}

44

 

45

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

46

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

47

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

48

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

49

 

50

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

51

}

52

catch (Exception ex)

53

{

54

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

55

}

56

 

57

}

58

}

59

}

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.

clip_image012

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

clip_image014

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.

clip_image016

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.

About Author: Karthikeyan Anbarasan, Microsoft MVP (Most Valuable Professional) in ASP.NET/IIS Architecture. He is the Founder and Chief Editor of the www.f5debug.net website and has authored books on Windows Phone and Business Intelligence(SSIS). He is also a Passionate Speaker and a Blogger on Microsoft Technologies.

You can Join Me On: Facebook, Twitter, Google Plus, LinkedIn

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

Recent Posts

Random Posts

Most Viewed

URL Shortner

Create your own short urls!!!

Site Counter

free counters

Disclaimer

This is a personal weblog. The opinions expressed here represent my own and not those of my employer. For accuracy and official reference refer to MSDN/ TechNet. I have documented my personal experience on this blog.

Protected by Copyscape Web Plagiarism Finder

Site Meter