Universal Windows Platform – Agent

Agent demonstrates how to create a Background Task that implements IBackgroundTask to display a Toast Notification when the Time Zone is changed

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 the Name as Agent and select a Location and then select Ok to create the Project
vs2017-new-project-agent

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 the Project has been created, from the Menu choose File, Add then New Project…

vs2017-file-add-new-project

Step 6

From New Project choose Visual C# from Installed, Templates then choose Windows Runtime Component (Universal Windows) and then type in the Name as Agent.Background and then select Ok to create the Project

vs2017-new-project-agent-background

The Windows Runtime Component (Universal Windows) Project type allows various types of Components to be created for use with a Universal Windows Project

Step 7

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

Step 8

Once the Project is created from the Solution Explorer select Class1.cs from the Agent.Background Project

vs2017-mainpage

Step 9

After the Class has been selected in Properties set the File Name to Trigger when changed select Yes when You are renaming a file. Would you also like to perform a rename in this project of all references to the code element ‘Class1’?” is displayed

vs2017-properties-agent-background

Step 10

Then in the Code View for Trigger.cs next to public sealed class Trigger the following should be entered:

<sourcecode language="csharp"]
: Windows.ApplicationModel.Background.IBackgroundTask
[/sourcecode]

Also while in the Code View inside public sealed class Trigger : IBackgroundTask { … } the following should be entered:

public void Run(Windows.ApplicationModel.Background.IBackgroundTaskInstance taskInstance)
{
	try
	{
		string value =
			Windows.Storage.ApplicationData.Current.LocalSettings.Values.ContainsKey("value") ?
			(string)Windows.Storage.ApplicationData.Current.LocalSettings.Values["value"] :
			string.Empty;
		Windows.Data.Xml.Dom.XmlDocument xml =
			Windows.UI.Notifications.ToastNotificationManager
			.GetTemplateContent(Windows.UI.Notifications.ToastTemplateType.ToastText02);
		xml.GetElementsByTagName("text")[0].InnerText = "Time Zone Changed";
		xml.GetElementsByTagName("text")[1].InnerText = value;
		Windows.UI.Notifications.ToastNotificationManager.CreateToastNotifier().Show(
			new Windows.UI.Notifications.ToastNotification(xml));
	}
	catch
	{

	}
}

In the Trigger.cs there is the usage of an Interface for IBackgroundTask. The Run Method takes an IBackgroundTaskInstance as part of the requirements of the Interface, within the LocalSettings of the Application and then a ToastNotificationManager is used to create a ToastNotification when the Background Agent is triggered.

Step 11

Once done select from the Menu, Build, then Build Solution

vs2017-build-build-solution

Step 12

In the Solution Explorer select MainPage.xaml in the Agent Project

vs2017-mainpage-agent

Step 13

Once done select from the Menu, Project, then Add Reference…

vs2017-project-add-reference

Step 14

From the Reference Manager window select Projects then Solution and then make sure that Agent.Background is Checked then select Ok to add the reference

vs2017-reference-manager-agent

Step 15

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

vs2017-project-add-new-item

Step 16

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 17

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

using System;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Storage;

public class Library
{
    private IBackgroundTaskRegistration _registration;

    public void Save(string value)
    {
        ApplicationData.Current.LocalSettings.Values["value"] = value;
    }

    public bool Init()
    {
        if (BackgroundTaskRegistration.AllTasks.Count > 0)
        {
            _registration = BackgroundTaskRegistration.AllTasks.Values.First();
            return true;
        }
        else
        {
            return false;
        }
    }

    public async Task<bool> Toggle()
    {
        if (BackgroundTaskRegistration.AllTasks.Count > 0)
        {
            _registration = BackgroundTaskRegistration.AllTasks.Values.First();
            _registration.Unregister(true);
            _registration = null;
            return false;
        }
        else
        {
            try
            {
                await BackgroundExecutionManager.RequestAccessAsync();
                BackgroundTaskBuilder builder = new BackgroundTaskBuilder
                {
                    Name = typeof(Agent.Background.Trigger).FullName
                };
                builder.SetTrigger(new SystemTrigger(SystemTriggerType.TimeZoneChange, false));
                builder.TaskEntryPoint = builder.Name;
                builder.Register();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}

In the Library.cs there are using statements to include the necessary functionality. There is a Member for IBackgroundTaskRegistration and the Init Method is used to get the Background Agent if it’s already running. The Save Method has IBackgroundTaskRegistration to help Register the Background Task it will also set the LocalSettings for “value” and the Toggle Task will either Unregister it if it’s already running or it will RequestAccessAsync to create a Background Task with the BackgroundTaskBuilder with a SystemTrigger of SystemTriggerType.TimeZoneChange and then will Register it.

Step 18

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-library-agent

Step 19

From the Menu choose View and then Designer

vs2017-view-designer

Step 20

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

<TextBox Margin="50" VerticalAlignment="Top" Name="Value"/>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Icon="Save" Label="Save" Click="Save_Click"/>
	<AppBarButton Name="Toggle" Icon="Play" Label="Start Agent" Click="Toggle_Click"/>
</CommandBar>

The first block of XAML the main user interface of the Application, this features a TextBox to enter the text that will be shown in a Toast Notification by the Background Task. The second block of XAML is the CommandBar which contains the Save and Toggle options to manage the Background Task.

Step 21

From the Menu choose View and then Code

vs2017-view-code

Step 22

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

Library library = new Library();

private void SetToggle(bool value)
{
	if (value)
	{
		Toggle.Icon = new SymbolIcon(Symbol.Stop);
		Toggle.Label = "Stop Agent";
	}
	else
	{
		Toggle.Icon = new SymbolIcon(Symbol.Play);
		Toggle.Label = "Start Agent";
	}
}

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

private void Save_Click(object sender, RoutedEventArgs e)
{
	library.Save(Value.Text);
}

private async void Toggle_Click(object sender, RoutedEventArgs e)
{
	SetToggle(await library.Toggle());
}

Below the MainPage() Method an instance of the Library Class is created. The SetToggle Method is used to update the state of the Toggle AppBarButton, the OnNavigatedTo Event handler will use the Init from the Library Class along with SetToggle to get the current status of the Background Agent. The Save_Click Method will set the contents of the TextBox to the Save Method of the Library Class and Toggle_Click will trigger the Toggle Method of the Library Class.

Step 23

In the Solution Explorer select Package.appxmanifest

vs2017-manifest-agent

Step 24

From the Menu choose View and then Designer

vs2017-view-designer

Step 25

Then in the Package.appxmanifest select Declarations and then Select Background Tasks from the drop-down list, then select Add then make sure that System Event is Checked and the Entry point is set to Agent.Background.Trigger.

vs2017-declarations-agent

Step 26

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 27

After the Application has started running you can then type some text then select Save and can select Start Agent

run-agent

Step 28

Then in Windows 10 select Start, Settings, then Time & Language and then change the Time zone this will cause the text entered from the Application to appear in a Toast Notification or you can then within the Application select Stop Agent to end the Background Task.

ran-agent

Step 29

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

vs2017-close

Creative Commons License

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 )

Connecting to %s