An Alternative to SQLite in Windows Store Apps

SQLite is a popular embedded database in use in Windows Store and Windows Phone apps, thought it can sometimes be tricky to get setup: there are a few different choices of NuGet packages / Visual Studio extensions to get up and running with.

An alternative embeddable database to use in Windows Store apps is BrightstarDB.

BrightstarDB is embeddable like SQLite but one big difference is that it’s a NoSQL database based on RDF. It still remains accessible to .NET developers via its entity framework like layer that supports niceties such as LINQ. BrightstarDB can also be used in desktop/web applications in addition to Windows Phone (Silverlight) apps.

Usage

First, in a Windows Store project install the NuGet packages: “BrightstarDB” and “BrightstarDB.Platform”

This will install the relevant libraries and will also create a file called “MyEntityContext.tt” which will generate a strongly typed data context for us to work with.

To define an entity, an interface is used and marked with the [Entity] attribute:

[Entity]
interface IToDoItem
{
    string Id { get; }
    string Description { get; set; }
}

Now when the MyEntityContext.tt file is right clicked and the option Run Custom Tool is selected, the MyEntityContext.cs file will be generated that knows how to save and retrieve ToDoItems. Entities can also be defined with relationships.

As a basic user interface that allows creation of a to do and loading existing todos in alphabetical order:

<Page
    x:Class="ToDo.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Width="300">
        <StackPanel>
            <TextBox PlaceholderText="New task description" Name="NewDescription"></TextBox>
            <Button Name="Create" Click ="Create_OnClick">Create</Button>
            <Button Name="Load" Click ="Load_OnClick">Load</Button>
            <ListView Name="Tasks" DisplayMemberPath="Description"></ListView>
        </StackPanel>
    </Grid>
</Page>

To implement the code that saves a new ToDoItem to the embedded database:

private const string _connectionString = "type=embedded;storesDirectory=data;storename=tasksdb";

private void Create_OnClick(object sender, RoutedEventArgs e)
{
    using (var ctx = new MyEntityContext(_connectionString))
    {
        var newTask = ctx.ToDoItems.Create();

        newTask.Description = NewDescription.Text;

        ctx.SaveChanges();
    }
}

This click handler creates an instance of the generated MyEntityContext, creates a new entity, sets some property values, and finally calls SaveChanges() to write the changes to the underlying database store. Also note the BrightstarDB connection string field.

To retrieve data:

private void Load_OnClick(object sender, RoutedEventArgs e)
{
    using (var ctx = new MyEntityContext(_connectionString))
    {
        Tasks.ItemsSource = ctx.ToDoItems.OrderBy(x => x.Description);                                
    }
}

Here we’re using some LINQ to sort by description and assign the result to the list in the UI.

So if we add the values in the order “Zulu”, “Tango”, “Foxtrot”; when we retrieve them they will look like the following screenshot:

Windows Store app using BrightstarDB

 

For more information check out the documentation or my Introduction to BrightstarDB Pluralsight Course.

SHARE:

Run Local Development and Store-Installed Versions of Windows Store Apps Side-by-Side

If you’ve released a Windows Store app and you want to actually use the released version yourself on the same machine you develop the app on, running the dev version from Visual Studio may overwrite the real Store-installed version.

As a workaround you can edit some files to change the package name so when you run it in dev it won’t override the store version. But you need to remember to change back when you release next version.

A while ago I came across a post using various steps to achieve this but it seem a bit complex an involved additional targets, etc.

So I hacked together my own utility: CohabitStoreApp.

It’s a low tech utility that you add as a pre-build step in your Store App project and it does 2 things:

  1. In DEBUG config, adds LOCALDEV to package identity and changed background color to red
  2. in non-DEBUG config removes LOCALDEV from package identity and restores background color

Check out the example app and the readme for more info.

SHARE:

Using LinqToTwitter in Windows Store Apps

LinqToTwitter is an open source library to help work with the Twitter API. It can be used in a Windows Store app to authorise a user and your app and allow querying and sending of Tweets.

Setting Up

First install the NuGet package into your Windows Store app. You’ll then need to head over to https://dev.twitter.com/ and sign in and define an app – you’ll end up with a couple of items that you’ll need later to authorise your app to use the API: API Key (aka consumer key) & API Secret (aka consumer secret).

image

 

Authorising Your App for a Given User

The first step is that the user must sign in to Twitter and grant your app access to their Twitter account.

First include the namespaces: LinqToTwitter and LinqToTwitter.WindowsStore.

Next create an instance of an InMemoryCredentialStore and set the consumer key and secret for your app as defined above.

var c = new InMemoryCredentialStore
{
    ConsumerKey = "your API key here",
    ConsumerSecret = "your API secret here"
};

Next, create a WindowsStoreAuthorizer and use the InMemoryCredentialStore and a callback address – this callback doesn’t actually have to do anything):

var authorizer = new WindowsStoreAuthorizer
{
    CredentialStore = c,
    Callback = "http://somecallbackaddresshere.com/blah.html"
};

Now calling the AuthorizeAsync method will bring up the Twitter auth dialog.

await authorizer.AuthorizeAsync();

Following the await, if the auth succeeded you can get the OAuthToken and OAuthTokenSecret with: authorizer.CredentialStore.OAuthToken and authorizer.CredentialStore.OAuthTokenSecret.

Sending a Tweet

To send a Tweet, an instance of a TwitterContext is needed. To create this an authorizer is passed to its constructor. You can use the instance (“authorizer”) you already have, or if you’re sending from a different part of the app codebase you may need to re-create one. To do this:

var authorizer = new WindowsStoreAuthorizer
{
    CredentialStore = new InMemoryCredentialStore
                      {
                          ConsumerKey = "your key",
                          ConsumerSecret = "your secret",
                          OAuthToken = token received from AuthorizeAsync,
                          OAuthTokenSecret = token received from AuthorizeAsync
                      }
};

To create the context:

var context = new TwitterContext(authorizer);

Now that we have a context, we can use it to send a new Tweet:

await _context.TweetAsync("tweet content here");

SHARE:

Debugging Share To and Background Agents in Windows Store Apps

When your main app is running via Visual Studio, when there is a problem you’ll get an exception and Visual Studio will break into the debugger to help you figure out the problem.

There’s a couple of scenarios that are a little more difficult to debug but are easy enough to do once you know how to access it in Visual Studio.

The two things that can be problematic are debugging background agents and debug share to functionality if your app is a share target. If you share to your app if it’s not already running you may not have things like dependency injection registered or other setup code. This is because a differnt code path executes when you launch the app normally to when you launch via share charm. The other thing is debugging background agents, if you are (for example) using a timed agent that executes every hour you don’t want to wait around for an hour before you can test.

Debugging Apps Launched from Share Charm

This technique also applies if you want to start debugging when you start your app from the desktop, even if you didn’t start it from Visual Studio.

Make sure your app is built and deployed: if you just want to deploy but not launch go to the Build menu and choose Deploy Solution.

At this point your app is freshly installed but is not running.

More...

SHARE:

Implementing Platform Specific Code in Universal Windows Apps with MVVMLight and Dependency Injection

In previous articles I’ve covered using MVVMLight in Universal Windows Apps and using C# partial classes and methods to implement different code on Windows Phone and Windows Store apps.

While partial classes/methods are a quick win to alter small amounts of code for each platform, overuse might become painful as the solution gets bigger. There are also limitations of partial methods such as they can only return void, they are implicitly private, cannot be virtual, etc.

If we’re using MVVMLight (or another framework or hand-rolled viewmodels) we can use dependency injection.

The viewmodel class is still shared between the two apps and doesn’t need to have partial methods which means we have more flexibility in the code we write.

As a dependency in the constructor, the viewmodel takes an instance of a class that implements an interface.

This interface-implementing class can then be two different classes, one in the phone project and one in the store project.

architecture diagram

So for example, in the shared project the following interface can be defined:

interface IGreetingService
{
    string GenerateGreeting();
}

Again in the shared project, the viewmodel is defined:

internal class MainViewModel : ViewModelBase
{
    private readonly IGreetingService _greetingService;
    private string _greeting;

    public MainViewModel(IGreetingService greetingService)
    {
        _greetingService = greetingService;

        SayHi = new RelayCommand(() => Greeting = _greetingService.GenerateGreeting());
    }

    public RelayCommand SayHi { get; set; }

    public string Greeting
    {
        get { return _greeting; }
        set { Set(() => Greeting, ref _greeting, value); }
    }
}

The key thing here is the constructor: it takes an IGreetingService.

When the SayHi command is executed, whichever instance of an IGreetingService was passed to the viewmodel, it’s GenerateGreeting() method will be called.

So in the store project the following class can be created:

public class WindowsStoreGreeter : IGreetingService
{
    public string GenerateGreeting()
    {
        return "Hello from Windows Store app!";
    }
}

And in the phone app:

public class WindowsPhoneGreeter : IGreetingService
{
    public string GenerateGreeting()
    {
        return "Hello from Windows Phone app!";
    }
}

It is in these specific implementations of the interface that the platform specific code is written.

So in the code-behind of the main window in the store app (for demonstration simplicity we’re not using a view model locator or DI library here):

public MainPage()
{
    this.InitializeComponent();

    this.DataContext = new MainViewModel(new WindowsStoreGreeter());
}

And in the phone app:

public MainPage()
{
    this.InitializeComponent();

    this.NavigationCacheMode = NavigationCacheMode.Required;

    this.DataContext = new MainViewModel(new WindowsPhoneGreeter());
}

In these code fragments a new MainViewModel is being created and supplied with a platform-specific IGreetingService implementation.

So in this way the shared MainViewModel class can still contain the majority of the code so we only have to write it once. But we still get the ability to write platform-specific code.

SHARE:

Using MVVM Light in Universal Windows Apps

I though it would be interesting to see how easy it is to define an MVVM Light view model once and then use it in both a Universal Windows Phone and Windows Store project.

So I created a new blank universal apps project and added the “MVVM Light libraries only (PCL) NuGet” package to both the Windows 8.1 project and the Windows Phone 8.1 project.

Next create a new view model class in the shared project:

using System.Linq;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;

namespace UniMvvmLight
{
    class MainViewModel : ViewModelBase
    {
        public MainViewModel()
        {
            Words = "Hello";

            Reverse = new RelayCommand(() =>
                                       {
                                           Words = new string(Words.ToCharArray().Reverse().ToArray());
                                       });
        }

        private string _words;
        public RelayCommand Reverse { get; set; }

        public string Words
        {
            get
            {
                return _words;
            }
            set
            {
                Set(() => Words, ref _words, value);                
            }
        }
    }
}

I’m not going to create a view model locator etc, just simply set the datacontext in the code behind of both the phone and store MainWindow:

public MainPage()
{
    this.InitializeComponent();

    this.DataContext = new MainViewModel();
}

Next define the xaml in both the MainWindow.xaml in both phone and store projects:

<Grid>
    <StackPanel>
        <TextBox Text="{Binding Words}"></TextBox>
        <Button Command="{Binding Reverse}">Reverse</Button>
    </StackPanel>
</Grid>

Now running either the phone or store app works as expected, the view model binding works as expected and clicking the button reverses the string as expected. Whilst this is not surprising, the view model in the shared project is just like having a copy of it in both app projects, even so it’s still cool.

Windows phone simulator

If we wanted to we could then leverage C# partial classes and methods to define platform-specific viewmodel code.

SHARE:

Leveraging C# Partial Classes and Methods in Windows Universal Apps

There’s a number of ways we could implement platform specific code in Windows Universal Apps which I’ll cover in future articles.

In this article we’ll look at an often underused feature of C#: partial classes and methods.

Quick Overview

Partial classes allow us to split the definition of a class over multiple .cs files. The files all contain the same namespace and class names, but the class name is preceded by the partial keyword modifier.

Partial methods allow a method to be defined but that doesn’t contain an implementation, the implementation can then be provided in another partial class file.

(Check out my C# Tips eBook for more info on partial types.)

Using Simple Conditional Compilation Directives

If you want to get an overview of Universal Apps, check out this previous article.

For the sake of this demo, say we have a class “Identity” that displays a message box stating whether we’re in a Windows Store or Phone app.

We could do this using conditional directives:

using System;
using System.Threading.Tasks;
using Windows.UI.Popups;

namespace UsingPartials
{
    public class Identity
    {             
        public async Task WhoAmI()
        {
            string message = CalcMessage();

#if WINDOWS_APP

            message = "I'm a Windows Store App!";

#elif WINDOWS_PHONE_APP

            message = "I'm a Windows Phone App!";            

#endif

            var dialog = new MessageDialog(message);
            await dialog.ShowAsync();
        }
        
    }
}

And from a button click event handler in both the apps:

private async void WhoAmI_Click(object sender, RoutedEventArgs e)
{
    var id = new Identity();

    await id.WhoAmI();
}

Clicking the button in the apps results in the following message boxes being displayed:

image

 

image

 

Refactoring to Partial

So this is a simple example, but if there were lots of these conditional directives, we can tidy things up a little.

The idea is that the shared class “Identity” is made partial:

public partial class Identity

This class still contains the method that’s called from each of the apps, but this time the creation of the content of the message is delegated to a method called “CalcMessage”. This method sets the private field to be used in the dialog.

In the “Identity” class, the “CalcMessage” is declared as a partial method. This means that it doesn’t contain an implementation, but the “WhoAmI” method can still call it.

The actual implementation of the code that decides on the message is unique to the two apps.

So now the “Identity” class now looks like this:

using System;
using System.Threading.Tasks;
using Windows.UI.Popups;

namespace UsingPartials
{
    public partial class Identity
    {
        string _message;

        public async Task WhoAmI()
        {
            CalcMessage();

            var dialog = new MessageDialog(_message);
            await dialog.ShowAsync();
        }

        partial void CalcMessage();    
    }
}

We now create a new class file in the Windows Store app:

namespace UsingPartials
{
    public partial class Identity
    {
        partial void CalcMessage()
        {            
            _message = "I'm a Windows Store App!";
        }
    }
}

And another one in the Phone app:

namespace UsingPartials
{
    public partial class Identity
    {
        partial void CalcMessage()
        {
            _message = "I'm a Windows Phone App!";
        }
    }
}

Now the implementation of CalcMessage can be different for both platforms, but other code can still be shared in the shared project version of Identity.cs.

We also now don’t have any conditional directives in use.

If we only have one or two of these conditional directives, then it’s probably easier to just keep them as is, but if there are lots of them and it’s making readability harder then partials may be a useful alternative.

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

Getting Started Building a Universal Windows App

Universal Windows apps promise to enable the sharing of app code between Windows 8.1 Store apps and Windows Phone 8.1 apps.

In this demo, we’ll create a simple app and see how much work we can share between the two platforms. The sample code and design is probably not how we’d choose to implement a final solution but it will suffice for demo purposes.

Getting Started

Install Visual Studio 2013 Update 2.

Create a new project, head to the Visual C#, Store Apps, Universal Apps; choose the Blank App (Universal Apps) as the following screenshot shows. Name the app “Speechless”.

Visual Studio Universal App Create New Project

Once the solution is created, there will be 3 projects, one for Windows Store, one for Windows Phone, and a third project where we can put all the code we want to share between the two apps.

Universal App Solution

Creating a Shared Class

First off let’s create a class that we can share between apps:

solution screenshot

using System.Collections.Generic;

namespace Speechless
{
    static class Messages
    {
        public static IEnumerable<string> Greetings
        {
            get
            {
                yield return "Hello";
                yield return "Yo!";
                yield return "What's up?";
                yield return "Good day sir!";
            }
        }
    }
}

This just gives a few greetings that the user can choose from. Because this class was added in the Speechless.Shared project, it can be used from both apps.

So we could just go and create some XAML in each app and use this class, but let’s see if we can actually share XAML between apps to further reduce effort.

Creating a shared User Control

In the Speechless.Shared project, add a new item of type User Control called “ChooseGreatingControl.xaml”.

Add some XAML:

<UserControl
    x:Class="Speechless.ChooseGreatingControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Speechless"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300"
    d:DesignWidth="400"    
    Width="300">
    
    <Grid>
        <StackPanel>
            <ComboBox Name="GreetingChoice" ></ComboBox>
            <Button Name="SayIt" Click="SayIt_OnClick">Speak</Button>
        </StackPanel>
    </Grid>
</UserControl>

This gives the user a ComboBox to choose which greeting to speak.

In the code behind:

using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Speechless
{
    public sealed partial class ChooseGreatingControl : UserControl
    {
        public ChooseGreatingControl()
        {
            this.InitializeComponent();

            GreetingChoice.ItemsSource = Messages.Greetings;

            GreetingChoice.SelectedIndex = 0;
        }

        private async void SayIt_OnClick(object sender, RoutedEventArgs e)
        {
        }
    }
}

Here we’re just wiring up the ComboBox items to those in the Messages class and setting the default selected item to the first one.

Next let’s try to add some code to do some text to speech:

private async void SayIt_OnClick(object sender, RoutedEventArgs e)
{
    var sayWhat = GreetingChoice.SelectedValue as string;

    var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();

    Windows.Media.SpeechSynthesis.SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(sayWhat);

    var mediaElement = new MediaElement();
    mediaElement.SetSource(stream, stream.ContentType);
    mediaElement.Play();
}

So now we have some UI XAML and some code, let’s see how easy it is to share this user control between the two apps.

Using the Same User Control from Both Windows Store and Windows Phone Apps

In the MainPage.xaml of the Windows Store app project, let’s add an instance of the user control:

<Page
    x:Class="Speechless.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Speechless"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <local:ChooseGreatingControl></local:ChooseGreatingControl>
    </Grid>
</Page>

Let’s go and do the same for the Windows Phone app:

<Page
    x:Class="Speechless.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Speechless"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <local:ChooseGreatingControl></local:ChooseGreatingControl>
    </Grid>
</Page>

Running the Apps

So lets try running now, first the Windows Store app (which is selected as the default start-up app), so F5…

Windows Store app screenshot

Clicking the Speak button works, and speaks outputs the selected greeting.

So let’s try the Windows Phone app, select it as the start-up app and hit F5…

System.UnauthorizedAccessException

This is because we need to add the Microphone capability to the Windows Phone app, once this is done the app runs and works as expected:

Windows Phone screenshot

Conclusions?

This is pretty cool. Having written an app in the past  that targets both Windows Store and Windows Phone this shared project makes things SO much easier – no linked file frustrations.

The next app I start writing (whether Store or Phone) I’ll use this Universal template just so if I want to port it to the other platform it will be ready to go.

It’s going to be interesting mixing this approach with Portable Class Libraries as well. Also a framework such as MVVMLight.

If there is code in the Shared project that only applies to either Store or Phone, we can use the predefined directives:

#if WINDOWS_APP
            // Store only app specific code here
#else
            // Phone only app specific code here
#endif

Whilst I don’t know what the plans are regarding Xbox One, it would be cool to have an Xbox One app store and we could just add an “Xbox One App” to our Universal Apps solution, build, and have the same app with most of the code and UI shared between Windows Store, Windows Phone, and Xbox One.

Exciting times!

SHARE:

Creating a Windows Store App NuGet Package for ARM, x86 and x64

It’s possible to create a NuGet package from a Window Store class library project that contains 3 different DLLs, one for each of the platform types: ARM, x86, and x64.

When the NuGet package is included in a Windows Store app, if the build platform for the app is changed to ARM for example, if the DLL that’s in the NuGet package was built for x86, there will be a build error.

The secret to making this happen is to use the “build” folder in your NuGet package.

This “build” folder sits alongside the lib and content folders.

If we are creating a package to be used in Windows 8.1 Store apps, this build folder will contain a sub folder called “netcore451”. It’s in this folder where the magic happens.

screenshot of file structure

This is a screen shot of the contents of the build folder. (It’s from my open source FeatureToggle library). Notice the platform specific folders. In each of these folder we place the relevant DLL, compiled for each platform.

screenshot of file structure

We also place the x86 version in the lib folder (apparently this can stop Visual Studio/designer from complaining.)

screenshot of file structure

Back to the build folder.

Notice the FeatureToggle.targets file.

For the following to to work it needs to be named the same as the package ID, in the case the NuGet package id is “FeatureToggle”.

The contents of this file allows NuGet to add to the .csproj file in the app that the package is installed into.

The contents of this .targets file look like this:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

  <Target Name="PlatformCheck" BeforeTargets="InjectReference"
    Condition=" ( ('$(Platform)' != 'x86') AND ('$(Platform)' != 'ARM') AND  ('$(Platform)' != 'x64') )">
    <Error  Text="$(MSBuildThisFileName) does not work correctly on '$(Platform)' 
                     platform. You need to specify platform (x86 / x64 or ARM)." />
  </Target>
  
  <Target Name="InjectReference" BeforeTargets="ResolveAssemblyReferences">

    <ItemGroup Condition=" '$(Platform)' == 'x86' or '$(Platform)' == 'x64' or '$(Platform)' == 'ARM'">
      <Reference Include="FeatureToggle.WindowsStore">
        <HintPath>$(MSBuildThisFileDirectory)$(Platform)\FeatureToggle.WindowsStore.dll</HintPath>
      </Reference>
    </ItemGroup>

  </Target>
</Project>

When the NuGet package is installed it will change the host apps .csproj file and add in the logic contained in this targets file. Now, before the app is built, the current build platform will be examined and the reference will be changed so that the relevant platform binary is used from either the ARM, x86, or x64 folder in our NuGet build folder. If the platform is not set to either ARM, x86, or x64 then the build will error with a message saying that a specific platform needs to be built –as opposed to AnyCPU for example.

The .targets file above is based on this MSDN article by Sebastien Pertus. The article also discusses packaging WinRT components.

SHARE:

Portable Class Library (PCL) Timer when Targeting Both Windows 8 and Windows Phone using Reactive Extensions

Currently the Timer class is not available when targeting both Windows Phone 8 and Windows 8 Store Apps.

For the app I’m building I want the MVVMLight PCL ViewModel to update a property every second – the databound View then simply updates itself.

One solution is to implement your own Task based Timer as described in this Stack Overflow article.

Another approach could be to make use of Reactive Extensions Observable.Interval method to create a sequence that updates every n-seconds.

First off add the Reactive Extensions NuGet package to your PCL project.

Next, in the ViewModel constructor (or command, etc.) create the interval stream and then tell it to execute a method every second:

var timer = Observable.Interval(TimeSpan.FromSeconds(1)).DistinctUntilChanged();

timer.ObserveOn(SynchronizationContext.Current).Subscribe(TimerTick);

 

I’m using SynchronizationContext.Current because the TimerTick method (below) updates the ViewModel property, without this there is a thread access problem.

So the TimerTick method ends up being called every second and simply updates the (MVVMLight) TotalTimeLeft property:

private void TimerTick(long l)
{
    TotalTimeLeft = DateTime.Now.Second.ToString();
}

I’m not an expert on Rx so there may be a better way of using it in this instance (or some potential hidden problems) but it’s working in the app so far (and on ARM Surface RT)…

It’s however cool to know that Rx has portable class library support.

Any Rx experts feel free to comment on a better way :)

SHARE: