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

namespace WPReceiveToast
{
    public partial class MainPage : PhoneApplicationPage
    {
        string channelName = "WP7NotifyToast";
        HttpNotificationChannel channel;

        public MainPage()
        {
            InitializeComponent();
            channel = HttpNotificationChannel.Find(channelName);
            if (channel == null)
            {
                channel = new HttpNotificationChannel(channelName);
                channel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(channel_ChannelUriUpdated);
                channel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(channel_ErrorOccurred);
                channel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(channel_ShellToastNotificationReceived);
                channel.Open();
                //Aktiviert die Toast - Benachrichtigungen
                channel.BindToShellToast();
            }
            else
            {
                channel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(channel_ChannelUriUpdated);
                channel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(channel_ErrorOccurred);
                channel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(channel_ShellToastNotificationReceived);
            }
        }

        void channel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
        {
            Dispatcher.BeginInvoke(
                () =>
                    MessageBox.Show(String.Format(
                        "Toast empfangen!\r\nÜberschrift: {0}\r\nNachricht: {1}",
                            e.Collection["wp:Text1"], e.Collection["wp:Text2"]))
            );
        }

        void channel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
        {
            //Fehlerbehandlung
        }
        void channel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
        {
            Debug.WriteLine(e.ChannelUri.ToString());
        }
    }
}