A simple NavigationService with Dependency Injection for WPF on .NET Core 3.0

21/05/2019 1 comment

We already talked about how to use Dependency Injection and Service Provider with WPF on .NET Core 3.0. In that occasion we said that windows themselves are registered in the IoC, so that we need to use the ServiceProvider to get and load them, for example:

var mainWindow = ServiceProvider.GetRequiredService<MainWindow>();
mainWindow.Show();

This approach works correctly, but we need to use two instructions every time we want to open a new window. Moreover, we don’t have a straight way to pass parameters to the new window. To make things simpler, we can write a couple of classes to manage this task:

public interface IActivable
{
    Task ActivateAsync(object parameter);
}

public class SimpleNavigationService
{
    private readonly IServiceProvider serviceProvider;

    public SimpleNavigationService(IServiceProvider serviceProvider)
    {
        this.serviceProvider = serviceProvider;
    }

    public async Task ShowAsync<T>(object parameter = null) where T : Window
    {
        var window = serviceProvider.GetRequiredService<T>();
        if (window is IActivable activableWindow)
        {
            await activableWindow.ActivateAsync(parameter);
        }

        window.Show();
    }

    public async Task<bool?> ShowDialogAsync<T>(object parameter = null) 
        where T : Window
    {
        var window = serviceProvider.GetRequiredService<T>();
        if (window is IActivable activableWindow)
        {
            await activableWindow.ActivateAsync(parameter);
        }

        return window.ShowDialog();
    }
}

First of all, at lines 1-4 we define an IActivable interface to mark Windows that support “activation”, i.e. the ability to receive parameters upon loading. Then, the SimpleNavigationService class encapsulates all the logic we need:

  • it provides methods to open a window, getting it from the ServiceProvider (lines 15-36), so every dependency is automatically resolved and passed to its constructor;
  • if the window implements the IActivable interface, it calls the ActivateAsync method before actually showing it.

Now we just need to properly register the SimpleNavigationService and all the windows of our application in the ConfigureServices methods we defined in the previous post:

private void ConfigureServices(IServiceCollection services)
{
    // ...

    // Add SimpleNavigationService for the application.
    services.AddScoped<SimpleNavigationService>();

    // Register all the windows of the applications.
    services.AddTransient<MainWindow>();
    services.AddTransient<DetailWindow>();
}

At the end of the OnStartup method, we can use the new service to show the MainWindow:

protected override void OnStartup(StartupEventArgs e)
{
    // ....

    var navigationService = ServiceProvider
                            .GetRequiredService<SimpleNavigationService>();
    var task = navigationService.ShowAsync<MainWindow>();
}

Now let’s see how to use it. Let’s suppose to have a window with a TextBox and a Button:

<Window
    ...>

    <Grid>
        <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
            <TextBlock Text="Parameter:" />
            <TextBox x:Name="ParameterTextBox" Width="300" />
            <Button
                x:Name="OpenDetailWindowButton"
                Click="OpenDetailWindowButton_Click"
                Content="Go to Detail Window" />
        </StackPanel>
    </Grid>
</Window>

We want that, pressing the Button at lines 8-11, the DetailWindow will be opened, receiving the value of the TextBox. So, the code-behind in MainWindow.xaml.cs is the following:

public partial class MainWindow : Window
{
    private readonly SimpleNavigationService navigationService;

    public MainWindow(SimpleNavigationService navigationService)
    {
        // ...
        this.navigationService = navigationService;
    }

    private async void OpenDetailWindowButton_Click(object sender, 
                                                    RoutedEventArgs e)
    {
        var result = await navigationService
                           .ShowDialogAsync<DetailWindow>(ParameterTextBox.Text);
    }
}

We pass the SimpleNavigationService in the MainWindow constructor through Dependency Injection, then in the button event handler we call the ShowDialogAsync method specifying the type of the Window to open and the parameter to initialize it. To be able to handle this, the DetailWindow code-behind should be something like that:

public partial class DetailWindow : Window, IActivable
{
    public DetailWindow()
    {
        // ...
    }

    public Task ActivateAsync(object parameter)
    {
        ParameterTextBox.Text = parameter?.ToString();
        return Task.CompletedTask;
    }
}

As DetailWindow implements the IActivable interface (line 1), SimpleNavigationService will ensure that the ActivateAsync method is called before showing the UI. In this sample, we just set the parameter in a TextBox (line 10). Of course, also the DetailWindow class could receive dependencies in its constructor, if necessary.

You can download the sample app using the link below:

A simple NavigationService with Dependency Injection for WPF on .NET Core 3.0

Advertisements
Categories: .NET Core, C#, WPF

Using Entity Framework Core with WPF on .NET Core 3.0

19/03/2019 2 comments

We talked about how to configure a .NET Core 3.0 WPF application in the same way as we do with ASP.NET Core. We can keep using this approach also if we need to use Entity Framework Core. It is important to note that tipically we use an external service to perform data access (for example, a REST Web APIs backend), but in some cases (especially if we’re working with a legacy system) it might be necessary to access a database directly from within our application.

And the story is again the same: you use the same code of ASP.NET Core. Let’s see how to do that. As always, take this sample as reference. First of all, we need to add the NuGet package for Entity Framework Core:

Adding Entity Framework Core to .NET Core 3.0 WPF application

Adding Entity Framework Core to .NET Core 3.0 WPF application

In this example, we’re using Entity Framework with SQL Server, but of course we can use every database supported by this OR/M.

Now, let’s add a connection string in the appsettings.json file:

{
  "ConnectionStrings": {
    "SqlConnection": ""
  }
}

Then, we must create our data context, i.e., a class that inherits form DbContext and provides access to the database:

public class DataContext : DbContext
{
    // DbSet properties declarations...

    public DataContext(DbContextOptions<DataContext> options) : base(options)
    {
    }
}

The DataContext class contains a constructor that takes a DbContextOptions as argument. It is used to pass configuration settings to the Context via Dependency Injection. For the rest, we can add to the class the usual DbSets we are accustomed to and configure the model by overriding the OnConfiguring and OnModelCreating methods.

Finally, we need to register the DbContext in the ServiceProvider collection, like we did in the previous post:

private void ConfigureServices(IServiceCollection services)
{
     services.AddDbContext<DataContext>
        (options => options.UseSqlServer(
                    Configuration.GetConnectionString("SqlConnection")));

            
     services.AddTransient(typeof(MainWindow));
}

At lines 4-5 we setup the DataContext to use SQL Server with the connection string from the appsettings.json file we defined before.

Now we’re ready to use the DataContext in every Window we need it. For example:

private readonly DataContext dataContext;

public MainWindow(DataContext dataContext)
{
    InitializeComponent();

    this.dataContext = dataContext;
}

As we can see, also in this case the approach is the same we use with ASP.NET Core. Of course, we can choose to pass the DataContext to a business service, instead of accessing it directly: as long as the service is itself in the IoC container, everything works in the same way.

Categories: .NET Core, C#, Entity Framework, WPF

Using HttpClientFactory with WPF on .NET Core 3.0

13/03/2019 1 comment

In the last post, we talked about how to use Dependency Injection with WPF applications running on .NET 3.0. We saw that with .NET Core 3.0 we can use the same approach that we are accustomed to when working with ASP.NET Core.

An interesting feature that we typically use with ASP.NET Core is the HttpClientFactory: it is a factory, available since .NET Core 2.1, for creating HttpClient instances to be used in our applications. Also in this case, we can use the same pattern within a WPF application running on .NET Core 3.0.

Let’s start from the sample we created in the last post. First of all, we need to add the Microsoft.Extensions.Http NuGet package (as always, remember to select the Include prerelease check):

Adding Microsoft.Extensions.Http NuGet package to WPF application

Adding Microsoft.Extensions.Http NuGet package to WPF application

Then, we need to register the HttpClientFactory. Let’s do it in the ConfigureServices method of App.xaml.cs:

private void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddHttpClient();

    services.AddTransient(typeof(MainWindow));
}

There are multiple way to use the HttpClientFactory. At line 5 we can see the simplest approach: using the AddHttpClient extension method we register a default HttpClientFactory from which we can get the actual HttpClient when we need it.

So, for example in the constructor of MainWindow we pass a reference to it:

private readonly IHttpClientFactory httpClientFactory;

public MainWindow(IHttpClientFactory httpClientFactory)
{
    InitializeComponent();

    this.httpClientFactory = httpClientFactory;
}

In this way, when we need an HttpClient, we just need to retrieve it from the factory, as usual:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    var client = httpClientFactory.CreateClient();
    var response = await client.GetStringAsync
                         ("https://marcominerva.wordpress.com/feed/");
    
    // ...
}

That’s it. That simple. If you want to read a great article that explains why we should always use HttpClientFactory, take a look to HttpClient Creation and Disposal Internals: Should I Dispose of HttpClient? by Steve Gordon.

Categories: .NET Core, C#, WPF

Using .NET Core 3.0 Dependency Injection and Service Provider with WPF

06/03/2019 9 comments

Note: this article is based on a preview release of .NET Core 3.0, so this approach may change in the future.

We all know that .NET Core provides built-in support for Dependency Injection. We typically use it in ASP.NET Core (starting form the ConfigureServices method in the Startup.cs file), but the feature isn’t limited to this framework. So, as .NET Core 3.0 supports also Windows Clients development, we can use it in our WPF and Windows Forms applications.

Let’s see how to do that, for example, in WPF using Visual Studio 2019. Suppose we want to create a service and we also have some application settings; we want to pass both of them to each window of our application via Dependency Injection.

First of all, we must add the required NuGet packages to the project. Right click on the Solution Explorer, select the Manage NuGet Packages command and add the following packages (be sure to select the Include prerelease check):

  • Microsoft.Extensions.DependencyInjection
  • Microsoft.Extensions.Options.ConfigurationExtensions
  • Microsoft.Extensions.Configuration.Json
Adding Dependency Injection support to a .NET Core 3.0 WPF application

Adding Dependency Injection support to a .NET Core 3.0 WPF application

These packages are necessary to enable Dependency Injection support (the first one) and to store and retrieve application settings in the classic appsettings.json file (the other ones). They will automatically get all the required dependencies.

Then, let’s add a file named appsettings.json to the root folder of the project. Set its Build Action property to Content and Copy to Output Directory to Copy if newer:

{
  "AppSettings": {
    "StringSetting": "Value",
    "IntegerSetting": 42,
    "BooleanSetting": true
  }
}

All the prerequisites are met, so we can start writing our code. Let’s open the App.xaml file and remove the StartupUri property of the Application class. Then, we need to override the OnStartup method in App.xaml.cs:

public partial class App : Application
{
    public IServiceProvider ServiceProvider { get; private set; }

    public IConfiguration Configuration { get; private set; }

    protected override void OnStartup(StartupEventArgs e)
    {
        var builder = new ConfigurationBuilder()
         .SetBasePath(Directory.GetCurrentDirectory())
         .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

        Configuration = builder.Build();

        var serviceCollection = new ServiceCollection();
        ConfigureServices(serviceCollection);

        ServiceProvider = serviceCollection.BuildServiceProvider();

        var mainWindow = ServiceProvider.GetRequiredService<MainWindow>();
        mainWindow.Show();
    }

    private void ConfigureServices(IServiceCollection services)
    {
        // ...

        services.AddTransient(typeof(MainWindow));
    }
}

In this method we create the Service Provider and configure the IoC container in a similar way of ASP.NET Core. We only need a bit of initialization. First of all, at line 9-13 we create an IConfiguration object that allows to read settings from the appsettings.json file (line 11). Then, we create an instance of a ServiceCollection class that will hold our services. Finally we call the ConfigureServices method (as we have in ASP.NET Core).

Within the latter (lines 24-29), we register all the services used by the application in the exact same way of ASP. NET Core. We’ll complete this method in a moment, but for now let’s notice that we register also the MainWindow class (line 28). This is important because, in this way, the window itself becomes part of the Dependency Injection chain. It means that, after calling this method, at line 20-21 we can get it from the ServiceProvider and then show it. But, more important, it means that we can pass to the MainWindow constructor all the dependencies it needs, as we do for ASP.NET Core Controllers.

Even if the actual services aren’t yet registered, we can run the application and see that everything works as expected.

Now it’s time to complicate the things a bit. First of all, let’s create an AppSettings.cs file to hold configuration settings. This file will map the settings that we write in appsettings.json:

public class AppSettings
{
    public string StringSetting { get; set; }

    public int IntegerSetting { get; set; }

    public bool BooleanSetting { get; set; }
}

Then, create also a sample service with its interface:

public interface ISampleService
{
    string GetCurrentDate();
}

public class SampleService : ISampleService
{
    public string GetCurrentDate() => DateTime.Now.ToLongDateString();
}

Now we must register these services in the IoC Container, as usual:

private void ConfigureServices(IServiceCollection services)
{
    services.Configure<AppSettings>
        (Configuration.GetSection(nameof(AppSettings)));
    
    services.AddScoped<ISampleService, SampleService>();

    // ...
}

As said before, the MainWindow itself is in the IoC Container. So, when we get it from the Service Provider, it will automatically be injected with all required services, if any. So, we just need to modify its constructor:

public partial class MainWindow : Window
{
    private readonly ISampleService sampleService;
    private readonly AppSettings settings;

    public MainWindow(ISampleService sampleService, 
                      IOptions<AppSettings> settings)
    {
        InitializeComponent();

        this.sampleService = sampleService;
        this.settings = settings.Value;
    }

    // ...
}

Running this code, we’ll obtain a result like the following:

The .NET Core 3.0 WPF application with dependencies injected

The .NET Core 3.0 WPF application with dependecies injected

You can download the sample app using the link below:

Using .NET Core 3.0 Dependency Injection and Service Provider with WPF

Categories: .NET Core, C#, WPF

Integrating Cognitive Service Speech Recognition in UWP apps

09/08/2018 1 comment

The Speech service, part of Cognitive Services, is powered by the same technologies used in other Microsoft products, including Cortana and Microsoft Office.

We just need to create a speech resource in Azure Portal to obtain the keys to use it in our apps. Note that, at the time of writing, the service is in Preview and is available only in East Asia, North Europe and West US.

The service is available either using the SDK or the REST API. Let’s see how to use the former in a UWP app.

First of all, we have to add the Microsoft.CognitiveServices.Speech NuGet package to the solution:

Microsoft.CognitiveServices.Speech NuGet package

Microsoft.CognitiveServices.Speech NuGet package

Then, we create a simple UI with a Button to start recognition and a TextBox to show the result:

<Grid Padding="50">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Button
        x:Name="RecognitionButton"
        Grid.Row="0"
        Margin="0,0,0,20"
        Click="RecognitionButton_Click"
        Content="Start Recognition" />
    <TextBox
        x:Name="RecognitionTextBox"
        Grid.Row="1"
        HorizontalAlignment="Stretch"
        Header="Recognized text"
        IsReadOnly="True" />
</Grid>

As the app need to use the microphone, it’s important to add the corresponding capability by double clicking the Package.appxmanifest file and go to the Capabilities tab:

Addung Micophone Capability to app

Addung Micophone Capability to app

Then, we can finally write the code to perform recognition:

private async void RecognitionButton_Click(object sender, RoutedEventArgs e)
{
    const string SpeechSubscriptionKey = "";
    const string SpeechRegion = "";
    const string Culture = "it-IT";

    var isMicAvailable = await CheckEnableMicrophoneAsync();
    if (!isMicAvailable)
    {
        return;
    }

    RecognitionButton.Content = "Recognizing...";
    RecognitionButton.IsEnabled = false;
    RecognitionTextBox.Text = string.Empty;

    var cognitiveSpeechFactory = SpeechFactory.FromSubscription
        (SpeechSubscriptionKey, SpeechRegion);

    // Starts recognition. It returns when the first utterance has been 
    // recognized.
    using (var cognitiveRecognizer = cognitiveSpeechFactory.
        CreateSpeechRecognizer(Culture, OutputFormat.Simple))
    {
        var result = await cognitiveRecognizer.RecognizeAsync();

        // Checks result.
        if (result.RecognitionStatus == RecognitionStatus.Recognized)
        {
            RecognitionTextBox.Text = result.Text;
        }
        else
        {
            await new MessageDialog(result.RecognitionFailureReason,
                result.RecognitionStatus.ToString()).ShowAsync();
        }
    }

    RecognitionButton.Content = "Start recognition";
    RecognitionButton.IsEnabled = true;
}

private async Task<bool> CheckEnableMicrophoneAsync()
{
    var isMicAvailable = false;

    try
    {
        var mediaCapture = new MediaCapture();
        var settings = new MediaCaptureInitializationSettings
        {
            StreamingCaptureMode = StreamingCaptureMode.Audio
        };

        await mediaCapture.InitializeAsync(settings);
        isMicAvailable = true;
    }
    catch
    {
        await Windows.System.Launcher.LaunchUriAsync
            (new Uri("ms-settings:privacy-microphone"));
    }

    return isMicAvailable;
}

The lines 3-5 must be completed with the Speech subscription key that we can find on Azure portal, the name of the region in which the service has been created (eastasia, northeurope or westus at this time) and the language of the speech. At the moment, the service supports Arabic, Italian, German, Japanes, English, Portoguese, Spanish, Russian, France and Chinese.

At lines 7-11 we check whether the microphone is available. The CheckEnableMicrophoneAsync methods (43-65) tries to initialize a MediaCapture object for audio: in this way, if necessary, the app will prompt the user to consent the microphone usage.

After that, we can finally start the real recognition process. We instantiate a SpeechFactory at lines 17-18 and use it for creating the Cognitive Speech recognizer at lines 22-23. The RecognizeAsync method (line 25) actually starts speech recognition, and stops after the first utterance is recognized.

If the RecognitionStatus property is equal to Recognized (line 28), it means that the recognition succeeded, so we can read the Text property to access the recognized text.

You can download the sample app using the link below:

Integrating Cognitive Service Speech in UWP apps

As said before, RecognizeAsync returns when the first utterance has been recognized, so it is suitable only for single shot recognition like command or query. For long-running recognition, we can use the StartContinuousRecognitionAsync method instead.

Introducing the Windows UI Library

25/07/2018 1 comment

As we can read at https://docs.microsoft.com/en-us/uwp/toolkits/winui:

The Windows UI Library is a set of NuGet packages that provide controls and other user interface elements for UWP apps. It also enables down-level compatibility with earlier versions of Windows 10, so your app works even if users don’t have the latest OS.

Thanks to it, we can use UWP XAML controls, that usually are shipped and updated as part of the Windows SDK, even on older versions of Windows 10 down to the Anniversary Update (1607). In addition, the library contains also updated versions of existing controls, so we won’t have to include version checks or conditional XAML markup to use these controls or features on earlier versions of Windows.

At this moment, the library is available as a Prerelease package. Let’s see how to start using it in our apps.

Let’s create a new UWP app using the Blank app template and be sure to select Build 1803 (17134) as Target version and at least Anniversary Update (14393) as Min version. Right click on the project, select Manage NuGet Packages and search for Microsoft.UI.Xaml (the Include Prerelease checkbox must be active):

Adding Windows UI Library from NuGet

Adding Windows UI Library from NuGet

After the installation, a TXT files will be automatically opened in Visual Studio telling us to add WinUI Theme Resources to our app. We simply need to add the following code in the App.xaml:

<Application.Resources>
    <XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls" />
</Application.Resources>

Let’s say that we want to use the new MenuBar control, that isn’t part of Windows SDK v17134 and we can’t install the Insider Preview SDK. First of all, we need to add the XAML namespace in the page declaration:

<Page
    x:Class="WinUILibraryDemo.MainPage"
    ...
    xmlns:controls="using:Microsoft.UI.Xaml.Controls"
    ...>

Then, simply define the menu in XAML:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <controls:MenuBar Grid.Row="0">
        <controls:MenuBarItem Title="File" AccessKey="F">
            <MenuFlyoutItem Click="FileNew_Click" Text="New" />
            <MenuFlyoutItem Text="Open..." />
            <MenuFlyoutItem Icon="Save" Text="Save" />
            <MenuFlyoutSeparator />
            <MenuFlyoutItem Text="Exit" />
        </controls:MenuBarItem>

        <controls:MenuBarItem Title="Edit" AccessKey="E">
            <MenuFlyoutItem Text="Undo" />
            <MenuFlyoutSeparator />
            <MenuFlyoutItem Icon="Cut" Text="Cut" />
            <MenuFlyoutItem Icon="Copy" Text="Copy" />
            <MenuFlyoutItem Icon="Paste" Text="Paste" />
        </controls:MenuBarItem>

        <controls:MenuBarItem Title="Help" AccessKey="H">
            <MenuFlyoutItem Icon="Help" Text="About..." />
        </controls:MenuBarItem>
    </controls:MenuBar>
</Grid>

At lines 7-27 we are creating a MenuBar with tree MenuBarItem. Note that menu commands are standard MenuFlyoutItem objects:

Windows UI Library Menu control

Windows UI Library Menu control

Another new interesting control is the DropDownButton, that is available starting from the Windows 10 SDK Preview Build 17686. Thanks to the Windows UI Library, we can use it right now in Windows 10 Anniversary Update and later:

<controls:DropDownButton Grid.Row="1" HorizontalAlignment="Center">
    <controls:DropDownButton.Content>
        <SymbolIcon Symbol="Mail" />
    </controls:DropDownButton.Content>
    <controls:DropDownButton.Flyout>
        <MenuFlyout Placement="Bottom">
            <MenuFlyoutItem Icon="Send" Text="Send" />
            <MenuFlyoutItem Icon="MailReply" Text="Reply" />
            <MenuFlyoutItem Icon="MailReplyAll" Text="Reply All" />
        </MenuFlyout>
    </controls:DropDownButton.Flyout>
</controls:DropDownButton>

With this XAML, we obtain the following UI, with the Flyout appearing when we tap on the button (as we expect):

Windows UI Library DropDownButton control

Windows UI Library DropDownButton control

These are only two examples of what the Windows UI Library allows to do. Keep in mind that is an early prerelease, so we can expect new controls, new properties on existing controls and new features as the project evolves.

Managing the Windows Timeline within a Windows Template Studio app

01/06/2018 2 comments

One of the most interesting features that comes with Windows 10 April 2018 Update (v1803) is the Timeline, that tracks our PC activities history (like a sort of browser history): it allows users to pick up where they left off within an app up to 30 days in the past, congregating all the work we do on our PC into one convenient timeline for us to look through. It works across devices too, meaning you can resume work you were doing on another device whenever it suits you.

Starting from Windows SDK for Windows 10 Fall Creators Update (10.0.16299), developers have the ability to create the so called User Activities to notify the system of a user work stream that can be continued on another device, or at another time on the same device. Creating a User Activity causes it to appear in Windows Timeline and in Cortana’s Pick up where I left off feature.

Creating a User Activity is straightforward, implementing the “pick up where I left off” feature we need to support Activation Deep Links, in order to resume the app with specific context. To handle them effectively, it is necessary to write some boilerplate code. Fortunately, in cases like this we can leverage the great Windows Template Studio, a Visual Studio 2017 Extension that accelerates the creation of new Universal Windows Platform apps using a wizard-based experience, providing code for most common scenarios, such as master/detail navigation, suspend and resume, settings and, of course, deep links support. So, let’s see how to use it to manage the Windows Timeline.

After installing the extension, Windows Template Studio will be available as a new project template in the New Project dialog. Let’s select it to start the wizard:

New Windows Template Studio app

New Windows Template Studio app

For our purpose it is important to add Uri Scheme support, in the Features section of the wizard:

Add Uri Scheme support to app

Add Uri Scheme Support To app

Let’s click the Create button and wait until the app is ready. As said, the project is well-formed and includes a lot of boilerplate code. Let’s see how to update it to add support for User Activities and Timeline.

First of all, we need to use the UserActivityChannel class to create a User Activity and set its properties for the timeline. The following code helps us:

public class Activity
{
    public string ActivityId { get; set; }

    public string DisplayText { get; set; }

    public string Description { get; set; }

    public Color BackgroundColor { get; set; }

    public string ActivationUri { get; set; }

    public static Activity Create(string displayText, string activationUri)
        => Create(null, displayText, null, null, activationUri);

    public static Activity Create(string displayText, string description,
        string activationUri)
        => Create(null, displayText, description, null, activationUri);

    public static Activity Create(string activityId, string displayText,
        string description, Color? backgroundColor, string activationUri)
        => new Activity(activityId ??
            (NavigationService.Frame.Content as Page)?.GetType().Name,
            displayText, description,
            backgroundColor ?? Color.FromArgb(0, 0, 0, 0),
            activationUri);

    private Activity(string activityId, string displayText, string description,
        Color backgroundColor, string activationUri)
    {
        ActivityId = activityId;
        DisplayText = displayText;
        Description = description;
        BackgroundColor = backgroundColor;
        ActivationUri = activationUri;
    }
}

public static class ActivityManager
{
    public static UserActivitySession CurrentActivity { get; private set; }

    public static async Task<UserActivitySession> GenerateActivityAsync(
        Activity activity)
    {
        //Get the default UserActivityChannel and query it for our UserActivity.
        //If the activity doesn't exist, one is created.
        var channel = UserActivityChannel.GetDefault();
        var userActivity = await channel.GetOrCreateUserActivityAsync(
            activity.ActivityId);

        //Populate required properties
        userActivity.VisualElements.DisplayText = activity.DisplayText;
        userActivity.VisualElements.Description = activity.Description;
        userActivity.VisualElements.BackgroundColor = activity.BackgroundColor;
        userActivity.ActivationUri = new Uri(activity.ActivationUri);

        //Save
        await userActivity.SaveAsync(); //save the new metadata

        //Dispose of any current UserActivitySession, and create a new one.
        CurrentActivity?.Dispose();
        CurrentActivity = userActivity.CreateSession();

        return CurrentActivity;
    }
}

The Activity class at lines 1-37 allows us to pass all the information we need to create the activity itself. Then, the ActivityManager (lines 39-67) actually creates the Activity in the Timeline at lines 49-59. The ActivityId property, as the name implies, is used to identify the activity that we want to create. The app should name activities in such a way that same ID is generated each time the user is in a particular location in the app. For example, if our application is page-based, we use an identifier for the page, if it’s document based, use the name of the doc (or a hash of the name). In this case, it is set to the current page name if not otherwise specified.

Going forward, line 56 is one of the most important: it sets the ActivitionUri property of the activity, that we need to check to determine if our app is activated through the Timeline. We’ll talk about it in a moment.

Creating a User Activity using these classes is straightforward. Let’s open the MainPage.xml file and add the following XAML:

<StackPanel
    Width="500"
    HorizontalAlignment="Center"
    VerticalAlignment="Center"
    Spacing="20">
    <TextBox
        x:Name="ActivityNameTextBox"
        Header="Activity name"
        Text="Activity name sample" />
    <TextBox
        x:Name="ActivityDescriptionTextBox"
        Header="Activity data (description)"
        Text="Activity description sample" />
    <TextBox
        x:Name="ActivationUriTextBox"
        Header="Activitation arguments"
        Text="my-sample-arguments" />
    <Button
        x:Name="CreateActivityButton"
        Click="CreateActivityButton_Click"
        Content="Create User Activity" />
</StackPanel>

We use these fields to get the information needed by the Activity: in this sample, we set activity name, description and activation arguments. Then, in the code-behind we handle the CreateActivityButton Click event:

private async void CreateActivityButton_Click(object sender, RoutedEventArgs e)
{
    var activity = Activity.Create(ActivityNameTextBox.Text,
        ActivityDescriptionTextBox.Text,
        $"timeline:?args={ActivationUriTextBox.Text}");

    await ActivityManager.GenerateActivityAsync(activity);
}

We simply need to create the Activity using the Activity.Create method (line 3-5) and then invoke the GenerateActivityAsync method (line 7) of ActivityManager. Let’s note the format at line 5, because it will be very important: it is formed by a constant part and the value that the user has inserted in the corresponding TextBox.

This part is complete. We can run the app, set the required information and click the Create User Activity button to add the activity to the timeline. For example (note that we may need to click the “show activities” link near to the date in order to show all the timeline elements):

Windows Timeline

Windows Timeline

So far, we are able add all our activities to the timeline. But, on the other hand, we need to prepare our app so that it can be activated by a click on the timeline element. So, we must register a Protocol in the application manifest.

Let’s double click on the Package.appxamifest file in the Solution Explorer and go to the Declarations tab. In the Available Declarations drop down, we have to select Protocol and then click the Add button. As we are using the string timeline as activation uri prefix, let’s specify this value in the Name field:

Add Protocol Uri to app

Add Protocol Uri to app

In this way, our app will be automatically invoked when the operating system detects a request with this custom protocol. The last thing to do is to write the code to respond to this kind of activation.

Because we have created the app with Windows Template Studio adding Uri Scheme support, in the Activation folder we can find the SchemeActivationHandler.cs file, with a standard app activation workflow. We can easily modify it to handle our scenario:

protected override async Task HandleInternalAsync(
    ProtocolActivatedEventArgs args)
{
    if (args.Uri.ToString().ToLowerInvariant().StartsWith("timeline:"))
    {
        string arguments = null;

        try
        {
            if (args.Uri.Query != null)
            {
                // The following will extract the secret value and pass it to the
                // page. Alternatively, you could pass all or some of the Uri.
                var decoder = new Windows.Foundation.WwwFormUrlDecoder(
                    args.Uri.Query);
                arguments = decoder.GetFirstValueByName("args");
            }
        }
        catch (Exception)
        {
            // NullReferenceException if the URI doesn't contain a query
            // ArgumentException if the query doesn't contain a param
            // called 'secret'
        }

        // It's also possible to have logic here to navigate to different pages.
        // e.g. if you have logic based on the URI used to launch
        NavigationService.Navigate(typeof(Views.MainPage), arguments);
    }
    else if (args.PreviousExecutionState != ApplicationExecutionState.Running)
    {
        // If the app isn't running and not navigating to a specific page based
        // on the URI, navigate to the home page
        NavigationService.Navigate(typeof(Views.MainPage));
    }

    await Task.CompletedTask;
}

The HandleInternalAsync method is automatically invoked when the app is activated by a custom protocol. At line 4 we check whether the uri starts with timeline (this is necessary, for example, if we want to handle multiple protocols) and then we extract the args parameter from query string. Finally, we navigate to the MainPage passing this value to it.

For the sake of simplicity, in the MainPage.xaml.cs we show a MessageDialog if it is activated with a parameter:

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    var args = Convert.ToString(e.Parameter);
    if (!string.IsNullOrWhiteSpace(args))
    {
        var dialog = new MessageDialog(args, "Activation arguments");
        await dialog.ShowAsync();
    }

    base.OnNavigatedTo(e);
}

Now everything is in place. We can click an activity in the timeline, even when our app is closed: it will be automatically launched and a dialog will appear showing the activation arguments we set.

This is a very basic example to showcase the Windows Timeline feature. In more complex scenarios, we can use also Adaptive Cards, but this is the argument for another blog post.

You can download the sample app using the link below:

Managing the Windows Timeline within a Windows Template Studio app