Floating FB popout byF5debug

Learn Windows Phone 7 Development in 31 Days – Day 12 – Working with Toast Notification in WP7

 

Introduction:

In this article we are going to see how to use the Toast Notification in windows phone 7. Windows Phone 7 application development supports push notification which provides developers a much more convenient option to transfer message Windows Phone 7 device from a web service when ever a new event occurs. Push notifications are of 3 types as follows

  • Toast Notification – This notification is launched at the top of the screen with the custom message such as an email alert or weather alert. The notification will be displayed for 10 second unless and until the user will dismiss the alert. If the user clicks on the alert then the application which sends the notification will be launched.       [more]
  • Tile Notification – This notification is used to display dynamic representation of the application state, we can control the image, text and badge count of the notification.
  • Raw Notification – This notification is used only when the application is running on the foreground and if the application services are running background the notification will not be delivered and it gets discarded which is not delivered to the windows phone device.

We will see in depth on each notification and see a demo application for each notification one by one in our upcoming articles. Let us see the step by step process on how to create a TOAST application, we need to create a client application to send the notification to the device which we will be covering in this article.

Steps:

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

clip_image002

Now add a button to create the push channel which will be required to create a Toast notification, 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="Toast 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 let we need to add the below two using statements.

C# Code:

1

using Microsoft.Phone.Notification;

2

using System.Diagnostics;

Now we need to write the code to get the open channel details which will be used to send the Toast Notification, to do that we will use the output window to get the channel details. Copy the below code to the code behind page.

C# Code:

01

</pre>

02

private void getChannelURI(Uri value)

03

{

04

Dispatcher.BeginInvoke(() =>

05

{

06

Debug.WriteLine("URI: " + value.ToString());

07

});

08

 

09

Debug.WriteLine("URI: " + value.ToString());

10

}

11

<pre>

Now we need to handle the BindToShellToast of HttpNotificationChannel to bind the toast notifications to do that add the below code.

01

</pre>

02

private static void ShellBinding(HttpNotificationChannel httpChannel)

03

{

04

try

05

{

06

httpChannel.BindToShellToast();

07

}

08

catch (Exception)

09

{

10

//Catach if required.

11

}

12

}

13

<pre>

Now we need to add the below code to check if the application is running correctly and get the toast notification message in order to log it for administrating purpose.

C# Code:

01

void Channel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)

02

{

03

Dispatcher.BeginInvoke(() =>

04

{

05

Debug.WriteLine("Toast Notification Received!!!");

06

if (e.Collection != null)

07

{

08

Dictionary collection = (Dictionary)e.Collection;

09

System.Text.StringBuilder messageBuilder = new System.Text.StringBuilder();

10

}

11

});

12

}

13

 

14

void ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)

15

{

16

getChannelURI(e.ChannelUri);

17

}

Now 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.

C# Code:

01

private void ChannelSetup()

02

{

03

HttpNotificationChannel httpChn = null;

04

string chnName = "Channel0";

05

 

06

httpChn = HttpNotificationChannel.Find(chnName);

07

 

08

if (httpChn != null)

09

{

10

if (httpChn.ChannelUri == null)

11

{

12

httpChn.UnbindToShellToast();

13

httpChn.Close();

14

ChannelSetup();

15

return;

16

}

17

else

18

{

19

getChannelURI(httpChn.ChannelUri);

20

}

21

ShellBinding(httpChn);

22

}

23

else

24

{

25

httpChn = new HttpNotificationChannel(chnName);

26

httpChn.ChannelUriUpdated += new EventHandler(ChannelUriUpdated);

27

httpChn.ShellToastNotificationReceived += new EventHandler(Channel_ShellToastNotificationReceived);

28

httpChn.Open();

29

ShellBinding(httpChn);

30

}

31

}

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

C# Code:

1

private void button1_Click(object sender, RoutedEventArgs e)

2

{

3

ChannelSetup();

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

Now copy and keep the channel details on to a separate notepad, Now we need to create a Server to post the toast notifications to the application device to show the toast.

We will create a web page from which we will post the toast 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 and notification message) and a button to trigger the event for the toast message to be sent to the Windows Phone 7 Device .

ASPX Code:

001

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

002

CodeBehind="Default.aspx.cs" Inherits="F5debugWp7ToastNotificationServer._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 Toast 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 and pass the message to the Microsoft Push Notification services. Just copy the below code to proceed further.

Code Behind:

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 F5debugWp7ToastNotificationServer

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

string PushNotificationXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<wp:Notification xmlns:wp=\"WPNotification\">" + "<wp:Toast>" + "<wp:Text1>{0}</wp:Text1>" + "<wp:Text2>{1}</wp:Text2>" + "</wp:Toast>" + "</wp:Notification>";

22

 

23

string strChannelURI = TextBox1.Text.ToString();

24

string strNotifitcationTitle = TextBox2.Text.ToString();

25

string strNotifitcationsubTitle = TextBox3.Text.ToString();

26

 

27

if (strChannelURI == string.Empty || strNotifitcationTitle == string.Empty || strNotifitcationsubTitle == string.Empty)

28

{

29

lblresult.Text = "All the fields are Mandatory!!!";

30

return;

31

}

32

 

33

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

34

sendNotificationRequest.Method = "POST";

35

sendNotificationRequest.Headers = new WebHeaderCollection();

36

sendNotificationRequest.ContentType = "text/xml";

37

sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");

38

sendNotificationRequest.Headers.Add("X-NotificationClass", "2");

39

string str = string.Format(PushNotificationXML, strNotifitcationTitle, strNotifitcationsubTitle);

40

byte[] strBytes = new UTF8Encoding().GetBytes(str);

41

sendNotificationRequest.ContentLength = strBytes.Length;

42

using (Stream requestStream = sendNotificationRequest.GetRequestStream())

43

{

44

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

45

}

46

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

47

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

48

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

49

 

50

lblresult.Text = "Status: " + notificationStatus + " : " + deviceConnectionStatus;

51

}

52

}

53

}

Now run the Windows Phone 7 Toast notification application to get the channel URI, once we got the channel URI keep the application running in background and navigate to the home page of the Windows Phone 7 Application. Now run the Server application (F5debugWp7ToastNotificationServer) and enter the details as shown in the screen below.

clip_image012

Now click on the Send Notification button and navigate to the Windows Phone 7 Emulator to see the Toast Notification Message on the top as shown in the screen below.

clip_image014

Conclusion:

So in this article we have seen what Push Notification is in Windows Phone 7 and the types of notification available. Also we have seen how to create a Toast Notification step by step in detail.

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