Windows 10 1607, UWP and Project Rome–Transferring Browser Tabs Across Devices

I was inspired by this article that I saw on the Windows Blog in the past week or so;

Cross-device experiences with Project Rome

to revisit ‘Project Rome’ that I’ve had a look at in these previous posts;

Project Rome posts.

The article is a great read and, having it read it once,  I later went back to it to see if I could get hold of the ‘Contoso Music’ app that it talks about but then I realised that ‘Contoso Music’ is being used in the article to talk about concepts rather than being a code sample in itself and so I set off to build my own sample.

For me, the Rome APIs in Windows 10 1607 today enable;

  1. A developer’s code to discover the user’s device graph that they’ve registered under the same Microsoft Account.
  2. A developer’s code to do a remote launch of a (custom/standard) URI on a remote system.
  3. A developer’s code to invoke a remote app service on a remote system.

Naturally, all under the control of the user and under the control of the remote app being invoked.

I wanted to try this out for a scenario that I find I’m often doing where I’ve opened up a set of tabs in my browser and I want to transfer that set of tabs to another device whether that be a PC or a phone or whatever.

I wrote a basic browser in order to try that out and I demo it in the video below;

There’s a few things that I found interesting in build that and so I thought I’d share those here.

The Device Discovery Code is Tiny

Here’s the code that I wrote in order to figure out which remote systems I have available to me. I like how short and neat it can be;

    async Task StartRemoteSystemDetectionAsync()
      var result = await RemoteSystem.RequestAccessAsync();

      if (result == RemoteSystemAccessStatus.Allowed)
        this.RemoteSystems = new ObservableCollection<RemoteSystem>();
        this.remoteWatcher = RemoteSystem.CreateWatcher();
        this.remoteWatcher.RemoteSystemAdded += (s, e) =>
          this.Dispatch(() =>

I ultimately data-bind the DisplayName, Kind and IsAvailableByProximity properties of the RemoteSystem object into a data template within the ComboBox that sits on the UI and it’s as simple as that.

The Remote App Service Invocation Code is Also Tiny

When it comes time to invoke the remote app service, that’s pretty easy to do as well, mostly relying on AppServiceConnection.OpenRemoteAsync() to do the work for me. In my app, the code looks like this;

    internal async void OnTransfer()
      var errorString = string.Empty;
      this.IsTransferring = true;
      this.TransferStatus = "connecting...";

      using (var connection = new AppServiceConnection())
        connection.PackageFamilyName = App.PackageFamilyName;
        connection.AppServiceName = App.AppServiceName;

        var remoteRequest = new RemoteSystemConnectionRequest(this.SelectedRemoteSystem);

        var result = await connection.OpenRemoteAsync(remoteRequest);

        if (result == AppServiceConnectionStatus.Success)
          this.TransferStatus = "Connected, calling...";

          var message = new ValueSet();
          var content = this.Serialize();
          message[App.AppServiceParameterKey] = content;

          var response = await connection.SendMessageAsync(message);

          if (response.Status != AppServiceResponseStatus.Success)
            this.TransferStatus = $"Failed to call - status was [{response.Status}]";
          this.TransferStatus = "Succeeded";
          this.TransferStatus = $"Failed to open connection with status {result}";
        this.transferStatus = "Closing";
      // time for the display of errors etc. to be seen.
      await Task.Delay(2000);

      this.IsTransferring = false;

Some of that might seem a little opaque without seeing the code for the whole app but it’s essentially;

  1. Create an AppServiceConnection, filling in the details of the PackageFamlyName and AppServiceName.
  2. Create a RemoteSystemConnectionRequest to the RemoteSystem that is selected in the UI.
  3. Make a call to OpenRemoteAsync()
  4. Create a ValueSet with the serialized list of web page URLs in it.
  5. Send it over the connection.
  6. Add a few pieces to update the UI and delay a little so that I can visually see whether it thinks it’s working or not.

and that’s pretty much it although it’s important to flag that the app manifest for the app has to advertise the right app service in the right way via;

        <uap:Extension Category="windows.appService">
          <uap3:AppService Name="OpenTabsService" SupportsRemoteSystems="true"/>

to flag that it’s available for remoting.

Using LeavingBackground and EnteringBackground in my App Class

In this app, I tried the technique of creating my UI when the app goes through its LeavingBackground event and destroying that UI when it hits its EnteringBackground event. I also saved state for the app when it hits EnteringBackground. This was the first time I’d tried this and it worked fine for me but I wasn’t sure whether my choice to destroy the UI at the point where the app moved into the background was a great idea because it might mean that a user who frequently moved the app foreground->background got frustrated with the UI keep rebuilding itself so perhaps I’m being too enthusiastic there.

As an example, my App.EnteringBackground handler does;

  async void OnEnteringBackground(object sender, EnteredBackgroundEventArgs e)
      // NB: getting rid of the UI here means that if the user opens up
      // N tabs then when they come back to the app those tabs will still
      // be there but will all start loading fresh again. That might not
      // be the best user experience as it loses their position on the
      // page.
      if (BrowserViewModel.ForegroundInstance != null)
        var deferral = e.GetDeferral();

          var serialized = BrowserViewModel.ForegroundInstance.Serialize();
          await Storage.StoreAsync(serialized);

      Window.Current.Content = null;
      this.background = true;

and so it serializes any state (i.e. the URLs of the web pages) and then it clears the contents of the Window entirely and sets a flag to note that we are now in the background. When I come back from the background I have code that does the reverse;

    void OnLeavingBackground(object sender, LeavingBackgroundEventArgs e)
      this.background = false;

and EnsureUI is pretty much the boilerplate code from a blank UWP template in that it creates a Frame, puts it into the Window and navigates it to a MainPage.

Using the Single Process Execution Model for Background Tasks

This app also uses the single process execution model for its background task implementation, override App.OnBackgroundActivated;

protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args)

what I found interesting in there is that I can now check the value of my background flag to decide what to do with an incoming app service request as below;

 async Task ProcessAppServiceRequestAsync(AppServiceRequestReceivedEventArgs args)
      var webPages = args.Request.Message[AppServiceParameterKey] as string;

      if (!string.IsNullOrEmpty(webPages))
        // What we do now depends on whether we are running in the foreground
        // or not.
        if (!this.background)
          BrowserViewModel.ForegroundInstance.Dispatch(() =>
          // Store the pending web pages into our state file.
          await Storage.StoreAsync(webPages);

          // Flag that the app should read that state next time it launches
          // regardless of whether it was terminated or not.

where the code is essentially extracting the list of web pages from the incoming App Service message and then it’s deciding based on the background flag whether to simple store that data into a file for the next time the app runs or whether to feed it into a ‘live’ ViewModel such that the UI will actively update.

Using x : Bind

The other thing that I played with quite a bit in this (admittedly simple) bit of code was to use x : Bind for everything. I still find myself forgetting to say Mode=OneWay from time to time but I’m increasingly getting used to it and a few things that I did here were quick/easy wins.

One of those is the simple binding to a boolean property as a visibility as you can see in the code below with the IsClosable property;


in that same snippet you can see that I’m also binding the Click event to a function on the ViewModel called OnClose and I really like that too as it (arguably) avoids me having to create an ICommand implementation. I also did that here on my Pivot control with the SelectionChanged event;


Where this fell down for me slightly was that I wanted to run code at the point where my WebView has loaded and has updated its DocumentTitle property. I ended up bringing in the UWP behaviors/interactivity pieces for this as below;

              Source="{x:Bind BrowserUrl,Mode=OneWay}"
                    Value="{Binding ElementName=webView,Path=DocumentTitle}" />

It’s certainly descriptive! Smile but what I really wanted to do was something a little bit like this;

              Source="{x:Bind BrowserUrl,Mode=OneWay}"
	      LoadCompleted="{x:Bind OnLoaded, Parameter={Binding DocumentTitle}"/>

which, as far as I know, isn’t quite achievable with the current xBind implementation because the docs state that the function that is bound to an event must;

For events, the target method must not be overloaded and must also:

  • Match the signature of the event.
  • OR have no parameters.
  • OR have the same number of parameters of types that are assignable from the types of the event parameters.

and so I don’t think it’s possible for me to bind this event to a method which takes a string parameter and then somehow pass the DocumentTitle into that method but it’s what I’d have liked to do.

The last thing I found with x : Bind is that there were places where I used converters as below;

                <ColumnDefinition />
                  Width="Auto" />
                <Run Text="{x:Bind DisplayName}" />
                  Text=" " /> <!-- Iknow, I know -->
                <Run Text="{x:Bind IsAvailableByProximity,Converter={StaticResource cxnTypeConverter}}"/>
                Source="{x:Bind Kind,Converter={StaticResource deviceImageConverter}}" />

In that snippet, I’m using converters to convert the Kind and IsAvailableByProximity properties into different types of objects for display. I couldn’t use a binding to a function on the ViewModel here because I’d been lazy and simply bound a collection of RemoteSystem objects (which I don’t own) as the ItemsSource of the ComboBox. I can’t just add a method to a RemoteSystem class to do my conversions.

I could have;

  • Wrapped a ViewModel around the RemoteSystem, enabling me to bind to a function on that ViewModel to do this conversion
  • Maybe bound to a static function which did the conversion, passing it the property to convert.
  • Gone with a converter.

I went with the 3rd option but it was perhaps just laziness and I should have done the first as I usually would but I did get a little side-tracked thinking about the middle option.

Wrapping Up

I spent maybe 1-2 hours putting this together. I’ve shared the source here if you want to play with it but it’s not intended for anything beyond just experimenting with Rome APIs.

Windows 10, UWP at UK Future Decoded in November

At this year’s Future Decoded event in a couple of weeks I will be speaking with the half-man-half-sofware-legend that is Andy Wigley on the topics of developing for Windows 10 and the UWP in the Anniversary Edition (1607) of Windows.

We’ll be looking at lots of areas that are new/changed in Anniversary Edition over and above what was present in earlier versions. This adds up to 3 afternoon breakout sessions making for 3 hours of UWP and Windows 10 development at Future Decoded.

We’d love to see you there, click the banner below to register (it’s free);


We look forward to seeing people there on the day and I’ve pasted the abstract descriptions for the sessions below;

image image image

Windows 10 1607, UWP and Background Media

It’s been a while since I looked at background audio/video in a UWP app – perhaps long enough ago that I was still talking about Windows 8 and I was working in HTML/JS at the time I wrote this post;

Windows 8 Metro style simple music app example

and made the screencast videos that went along with it.

Here in 2016 on the UWP with build 1607 it’s a joy to find that the various changes around the background model described here;

Background activity with the Single Process Model

have found their way into the world of background media as described on MSDN over here;

Play Media in the Background

and I wanted to try out the very basics of this for myself armed with some of what I’d referenced in this post;

Windows 10 1607, UWP, Single Process Execution and Lifecycle Changes

and so I made a simple, blank app and I added a video into the Assets folder;


and then got rid of the MainPage.xaml/.cs files and concentrated purely on my App class which I tried to keep as simple as I could. I’m not sure that I have it entirely right just yet but I wound up with;

namespace VideoPlayerBackground
  using System;
  using Windows.ApplicationModel;
  using Windows.ApplicationModel.Activation;
  using Windows.Media;
  using Windows.Media.Core;
  using Windows.Media.Playback;
  using Windows.UI.Xaml;
  using Windows.UI.Xaml.Controls;

  sealed partial class App : Application
    public App()
      this.EnteredBackground += OnEnteredBackground;
      this.LeavingBackground += OnLeavingBackground;
    void OnLeavingBackground(object sender, LeavingBackgroundEventArgs e)
      this.isForeground = true;
    void OnEnteredBackground(object sender, EnteredBackgroundEventArgs e)
      this.isForeground = false;
    protected override void OnLaunched(LaunchActivatedEventArgs e)
      if ((e.PreviousExecutionState != ApplicationExecutionState.Running) &&
          (e.PreviousExecutionState != ApplicationExecutionState.Suspended))
    void CreateMediaPlayer()
      this.mediaPlayer = new MediaPlayer()
        Source = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/video.mp4"))        
      this.mediaPlayer.SystemMediaTransportControls.IsEnabled = true;
      this.mediaPlayer.SystemMediaTransportControls.AutoRepeatMode = MediaPlaybackAutoRepeatMode.Track;
    void CreateUI()
      this.mediaPlayerElement = new MediaPlayerElement();
      this.mediaPlayerElement.AreTransportControlsEnabled = true;
      Window.Current.Content = this.mediaPlayerElement;
    void DestroyUI()
      this.mediaPlayerElement = null;
      Window.Current.Content = null;
    MediaPlayerElement mediaPlayerElement;
    MediaPlayer mediaPlayer;
    bool isForeground;

and what surprised me is the simplicity of it – I have a MediaPlayer which I set playing (in this example) from the start and then when the app is in the foreground I associate the MediaPlayer with a MediaPlayerElement (not a MediaElement) which I’ve simply parented in the window and when the app moves into the background I clear the contents of the window and get rid of the MediaPlayerElement but I keep the MediaPlayer around.

It’s worth saying that this work with the system transport controls so that I can hit the pause/play buttons on my keyboard as expected.

It seems so much nicer from what I had to do back in the days of early iterations of the platform that I’m wondering whether I’m missing some additional pieces that make it more complex than I’ve got it here? Answers on a postcard please! Smile