Universal Windows Platform – Toasts

Toasts demonstrates how to display ScheduledToastNotification items to the Action Centre of Windows 10

Step 1

If not already, follow Setup and Start on how to Install and get Started with Visual Studio 2017 or in Windows 10 choose Start, and then from the Start Menu find and select Visual Studio 2017.

vs2017

Step 2

Once Visual Studio Community 2017 has started, from the Menu choose File, then New then Project…

vs2017-file-new-project

Step 3

From New Project choose Visual C# from Installed, Templates then choose Blank App (Universal Windows) and then type in a Name and select a Location and then select Ok to create the Project
vs2017-new-project-window

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.

vs2017-target-platform

The Target Version will control what features your application can use in Windows 10 so by picking the most recent version you’ll be able to take advantage of those features. To make sure you always have the most recent version, in Visual Studio 2017 select Tools Extensions and Updates… then and then see if there are any Updates

Step 5

Once done select from the Menu, Project, then Add New Item…

vs2017-project-add-new-item

Step 6

From the Add New Item window select Visual C#, then Code from Installed then select Code File from the list, then type in the Name as Library.cs before selecting Add to add the file to the Project

vs2017-add-new-item-library

Step 7

Once in the Code View for Library.cs the following should be entered:

using System;
using System.Collections.Generic;
using System.Linq;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using Windows.UI.Xaml.Controls;

public class Item
{
    public string Id { get; set; }
    public string Content { get; set; }
    public string Time { get; set; }
}

public class Library
{
    private ToastNotifier _notifier = ToastNotificationManager.CreateToastNotifier();
    private Random _random = new Random((int)DateTime.Now.Ticks);

    public void Init(ListBox display)
    {
        display.Items.Clear();
        IReadOnlyList<ScheduledToastNotification> list = _notifier.GetScheduledToastNotifications();
        foreach (ScheduledToastNotification item in list)
        {
            display.Items.Add(new Item
            {
                Id = item.Id,
                Time = item.Content.GetElementsByTagName("text")[0].InnerText,
                Content = item.Content.GetElementsByTagName("text")[1].InnerText,            
            });
        }
    }

    public void Add(ref ListBox display, string value, TimeSpan occurs)
    {
        DateTime when = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,
            occurs.Hours, occurs.Minutes, occurs.Seconds);
        if (when > DateTime.Now)
        {
            XmlDocument xml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
            xml.GetElementsByTagName("text")[0].InnerText = when.ToLocalTime().ToString();
            xml.GetElementsByTagName("text")[1].InnerText = value;
            ScheduledToastNotification toast = new ScheduledToastNotification(xml, when)
            {
                Id = _random.Next(1, 100000000).ToString()
            };
            _notifier.AddToSchedule(toast);
            display.Items.Add(new Item { Id = toast.Id, Content = value, Time = when.ToString() });
        }
    }

    public void Remove(ListBox display)
    {
        if (display.SelectedIndex > -1)
        {
            _notifier = ToastNotificationManager.CreateToastNotifier();
            try
            {
                _notifier.RemoveFromSchedule(_notifier.GetScheduledToastNotifications().Where(
                    p => p.Id.Equals(((Item)display.SelectedItem).Id)).SingleOrDefault());
            }
            catch(Exception)
            {

            }
            display.Items.RemoveAt(display.SelectedIndex);
        }
    }
}

In the Library.cs there are using statements to include the necessary functionality. The Item Class represents a pinned Tile, then in the Library Class there is a Member for ToastNotifier to work with Toast Notifications and one for Random to generate an identifier. The Init Method is used to get any Toast Notifications that have been Scheduled with GetScheduledToastNotifications. The Add Method will not only insert an item in to the ListBox but also will Schedule a Toast Notification as a ScheduledToastNotification to displat at the specified DateTime based on the passed in TimeSpan. Remove will call RemoveFromSchedule to de-schedule the Toast Notification and remove the entry from the ListBox.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage

Step 9

From the Menu choose View and then Designer

vs2017-view-designer

Step 10

The Design View will be displayed along with the XAML View and in this between the Grid and /Grid elements, enter the following XAML:

<Grid>
	<Grid.RowDefinitions>
		<RowDefinition Height="Auto"/>
		<RowDefinition Height="*"/>
	</Grid.RowDefinitions>
	<Grid Grid.Row="0">
		<Grid.ColumnDefinitions>
			<ColumnDefinition Width="*"/>
			<ColumnDefinition Width="Auto"/>
		</Grid.ColumnDefinitions>
		<TextBox Grid.Column="0" Margin="10" Name="Value"/>
		<TimePicker Grid.Column="1" Margin="10" Name="Occurs"/>
	</Grid>
	<ListBox Name="Display" Grid.Row="1">
		<ListBox.ItemTemplate>
			<DataTemplate>
				<StackPanel>
					<TextBlock TextWrapping="Wrap" Text="{Binding Path=Content}"/>
					<TextBlock Text="{Binding Path=Time}"/>
				</StackPanel>
			</DataTemplate>
		</ListBox.ItemTemplate>
	</ListBox>
</Grid>
&amp;lt;CommandBar VerticalAlignment=&amp;quot;Bottom&amp;quot;&amp;gt;
	&amp;lt;AppBarButton Icon=&amp;quot;Add&amp;quot; Label=&amp;quot;Add&amp;quot; Click=&amp;quot;Add_Click&amp;quot;/&amp;gt;
	&amp;lt;AppBarButton Icon=&amp;quot;Remove&amp;quot; Label=&amp;quot;Remove&amp;quot; Click=&amp;quot;Remove_Click&amp;quot;/&amp;gt;
&amp;lt;/CommandBar&amp;gt;

The first block of XAML the main user interface of the Application, this features a Grid with the first row containing a TextBox where text may be entered to show on the Toast Notification and then there’s a TimePicker to set when it will be displayed. The second row contains a ListBox to display the list of Toast Notifications that have been scheduled. The second block of XAML is the CommandBar which contains the Add and Remove options to manage the list.

Step 11

From the Menu choose View and then Code

vs2017-view-code

Step 12

Once in the Code View, below the end of public MainPage() { … } the following Code should be entered:

Library library = new Library();

protected override void OnNavigatedTo(NavigationEventArgs e)
{
	library.Init(Display);
}

private void Add_Click(object sender, RoutedEventArgs e)
{
	library.Add(ref Display, Value.Text, Occurs.Time);
}

private void Remove_Click(object sender, RoutedEventArgs e)
{
	library.Remove(Display);
}

Below the MainPage() Method an instance of the Library Class is created. The OnNavigatedTo Event handler will call the Init Method in the Library Class. The Add_Click Method will schedule Toast Notification to be displayed in the Action Centre and also to the ListBox and Remove_Click will delete items from the list.

Step 13

That completes the Universal Windows Platform Application so Save the Project then in Visual Studio select the Local Machine to run the Application

vs2017-local-machine

Step 14

After the Application has started running you can then type some text then select a Time, then select Add to schedule a Toast Notification for that Time with the Text selected, which will appear at the specified Time

ran-toasts

Step 15

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Creative Commons License

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s