Ajay Gupta

Ajay Gupta

  • NA
  • 46
  • 21.7k

How to send/receive push notifications for Windows Phone 8.1

Aug 19 2015 7:54 AM
How to send and receive push notifications for Windows Phone 8.1
 
 
 
I tried it in windows phone 8.0 ,it work fine.
When we are implementing these code in windows phone 8.1 its not work Please help.
 
 
My class For recieving the toast in windows 8.0
 
namespace sdkToastNotificationCs
{
public partial class NotificationPage : PhoneApplicationPage, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private StringBuilder message;
ListBox messList;// = new List<string>();
private List<Movie> _newMovies;// = new List<Movie>();
static int count = 0; // public event EventHandler<NotificationEventArgs> ShellToastNotificationReceived
/// <summary>
/// MainPage constructor
/// </summary>
///
///
public NotificationPage()
{
/// Holds the push channel that is created or found.
HttpNotificationChannel pushChannel;
// The name of our push channel.
string channelName = "ToastSampleChannel";
List<string> messList;
InitializeComponent();
this.DataContext = this;
ListBox1.ItemsSource = new MovieList();// new MovieList();
SetCommonData.NewNotification = string.Empty;
Profileuser.EventForForpageNavigation += Profileuser_EventForForpageNavigation;
// Try to find the push channel.
pushChannel = HttpNotificationChannel.Find(channelName);
// If the channel was not found, then create a new connection to the push service.
if (pushChannel == null)
{
pushChannel = new HttpNotificationChannel(channelName);
// Register for all the events before attempting to open the channel.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
pushChannel.Open();
// Bind this new channel for toast events.
pushChannel.BindToShellToast();
}
else
{
// The channel was already open, so just register for all the events.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
// Display the URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
//System.Diagnostics.Debug.WriteLine(pushChannel.ChannelUri.ToString());
//MessageBox.Show(String.Format("Channel Uri is {0}",
// pushChannel.ChannelUri.ToString()));
}
}
/// <summary>
/// Event handler for when the push channel Uri is updated.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
// Display the new URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString());
//MessageBox.Show(String.Format("Channel Uri is {0}",
// e.ChannelUri.ToString()));
});
}
/// <summary>
/// Event handler for when a push notification error occurs.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
// Error handling logic for your particular application would be here.
Dispatcher.BeginInvoke(() =>
MessageBox.Show(String.Format("A push notification {0} error occurred. {1} ({2}) {3}",
e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData))
);
}
/// <summary>
/// Event handler for when a toast notification arrives while your application is running.
/// The toast will not display if your application is running so you must add this
/// event handler if you want to do something with the toast notification.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
//void PushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
//{
// messList=new List<string>();
// string str = "";
// message = new StringBuilder();
// string relativeUri = string.Empty;
// message.AppendFormat("Received Toast {0}:\n", DateTime.Now.ToShortTimeString());
// // Parse out the information that was part of the message.
// foreach (string key in e.Collection.Keys)
// {
// message.AppendFormat("{0}: {1}\n", key, e.Collection[key]);
// if (string.Compare(
// key,
// "wp:Param",
// System.Globalization.CultureInfo.InvariantCulture,
// System.Globalization.CompareOptions.IgnoreCase) == 0)
// {
// relativeUri = e.Collection[key];
// }
// str = str + "\n" + e.Collection[key];//aj
// }
// // Display a dialog of all the fields in the toast.
// Dispatcher.BeginInvoke(() => MessageBox.Show(message.ToString()));
// messList.Add(str);
// SetCommonData.MessagesList.AddRange(messList); //aj
// ListBox1.ItemsSource = SetCommonData.MessagesList;
// // ListBox1..Add(str);
//}
void PushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
{
StringBuilder str = new StringBuilder();
message = new StringBuilder();
string relativeUri = string.Empty;
message.AppendFormat("Received Toast {0}:\n", DateTime.Now.ToShortTimeString());
string getToastTime = "Received Toast : " + DateTime.Now.ToShortTimeString() + "";
str.AppendLine(getToastTime);
// Parse out the information that was part of the message.
foreach (string key in e.Collection.Values)
{
// message.AppendFormat("{0}\n", key, e.Collection[key]);
//if (string.Compare(
// key,
// "wp:Param",
// System.Globalization.CultureInfo.InvariantCulture,
// System.Globalization.CompareOptions.IgnoreCase) == 0)
//{
// relativeUri = e.Collection[key];
//}
if (!key.Contains("Login.xaml"))
str.AppendLine(key);
// = str + "\n" + e.Collection[key];//aj
}
SetCommonData.MessagesList.Add(str.ToString());
// ListBox1.ItemsSource = new MovieList();// new MovieList();
// Add the list box to a parent container in the visual tree.
// Display a dialog of all the fields in the toast.
Dispatcher.BeginInvoke(() => MessageBox.Show(message.ToString()));
count = count + 1;
if(count!=0)
SetCommonData.NewNotification = Convert.ToString(count);
}
/// <summary>
/// Navigate to page 2 button clicked event handler
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonNavigate_Click(object sender, RoutedEventArgs e)
{
// this.NavigationService.Navigate(new Uri("/NotificationPage.xaml?NavigatedFrom=" + message + "", UriKind.Relative));
}
# region Its own Event
private void BorderNotify_OnMouseEnter(object sender, MouseEventArgs e)
{
NavigationService.Navigate(new Uri("/NotificationPage.xaml", UriKind.Relative));
}
private void UIElement_OnMouseEnter(object sender, MouseEventArgs e)
{
Application.Current.Terminate();
}
void Profileuser_EventForForpageNavigation(object sender, EventArgs e)
{
if (SetCommonData._isProfile_Logout_navigate == "Profile")
{
NavigationService.Navigate(new Uri("/ProfilePage.xaml", UriKind.Relative));
}
else
{
NavigationService.Navigate(new Uri("/Login.xaml", UriKind.Relative));
}
}
private void NotificationPage_OnLoaded(object sender, RoutedEventArgs e)
{
// messList.ItemsSource = SetCommonData.MessagesList;
}
# endregion
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
http://s.notify.live.net/u/1/hk2/H2QAAABLZGI9m_TAqf1QDDDITYVBbJXS95eLn1pQ9dhLjq7EVqycUYXJZF3ueX_7zWqHCwI2Ppm7KEKW9msUegW4W8IRXWYMRJvEfdUBvTSnKBo7y0vc0PKwsbkucBmrywewquk/d2luZG93c3Bob25lZGVmYXVsdA/XJd7ZyiS8EaY8ofjzxGUEw/lt6drnZBbbdheU_pzjazdbFrZfk
base.OnNavigatedTo(e);
// If we navigated to this page
// from the MainPage, the DefaultTitle parameter will be "FromMain". If we navigated here
// when the secondary Tile was tapped, the parameter will be "FromTile".
//textBlockFrom.Text = "Navigated here from " + this.NavigationContext.QueryString["NavigatedFrom"];
// var ggh= "Navigated here from " + this.NavigationContext.QueryString["NavigatedFrom"];
}
public void Notify(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
 
And i have Sending A toast Through a web app as .
 
 
namespace SendToast
{
public partial class SendToast : System.Web.UI.Page
{
/// <summary>
/// Event handler for when the Send Toast Notification button is clicked. Forms the post message
/// and send it to the Microsoft Push Notification Service.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ButtonSendToast_Click(object sender, EventArgs e)
{
try
{
// Get the Uri that the Microsoft Push Notification Service returns to the Push Client when creating a notification channel.
// Normally, a web service would listen for Uri's coming from the web client and maintain a list of Uri's to send
// notifications out to.
string subscriptionUri = TextBoxUri.Text.ToString();
HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);
// We will create a HTTPWebRequest that posts the toast notification to the Microsoft Push Notification Service.
// HTTP POST is the only allowed method to send the notification.
sendNotificationRequest.Method = "POST";
// The optional custom header X-MessageID uniquely identifies a notification message.
// If it is present, the // same value is returned in the notification response. It must be a string that contains a UUID.
// sendNotificationRequest.Headers.Add("X-MessageID", "<UUID>");
// Create the toast message.
string toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>" + TextBoxTitle.Text.ToString() + "</wp:Text1>" +
"<wp:Text2>" + TextBoxSubTitle.Text.ToString() + "</wp:Text2>" +
"<wp:Param>/Page2.xaml?NavigatedFrom=Toast Notification</wp:Param>" +
"</wp:Toast> " +
"</wp:Notification>";
// Sets the notification payload to send.
byte[] notificationMessage = Encoding.Default.GetBytes(toastMessage);
// Sets the web request content length.
sendNotificationRequest.ContentLength = notificationMessage.Length;
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");
sendNotificationRequest.Headers.Add("X-NotificationClass", "2");
using (Stream requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}
// Send the notification and get the response.
HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
string notificationStatus = response.Headers["X-NotificationStatus"];
string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
// Display the response from the Microsoft Push Notification Service.
// Normally, error handling code would be here. In the real world, because data connections are not always available,
// notifications may need to be throttled back if the device cannot be reached.
TextBoxResponse.Text = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus;
}
catch (Exception ex)
{
TextBoxResponse.Text = "Exception caught sending update: " + ex.ToString();
}
}
}
}
So please help us.
How we Implement these in windows phone 8.1 
 
 
 
 
 
 
 
 
 

Answers (1)