Unable to Activate Windows Store App

Unable to Activate Windows Store App

I was running up one of our Windows 10 projects today and I encountered a somewhat cryptic error stating that Visual Studio was “Unable to activate Windows Store app…. The … process started, but the activation request failed with the error ‘The app didn’t start’”.

image

I figured there would be more information in the event log but this was not the case, with only this same message appearing there. Luckily it turns out that this issue isn’t specific to Windows 10 applications, and it was in fact this post that clued me on to removing the somewhat unnecessary app.config file that was still in my solution structure. Removing this file worked an absolute treat, although I can’t seem to work out why it fails since Visual Studio does sometimes warn about multiple versions of an assembly being referenced.

Package Manifest for Windows 10

Package Manifest for Windows 10

As the tools for Windows 10 applications are still in preview there are some limitations and some features that aren’t quite ready yet. One of these is the designer for the package.manifest file, so the question is how do you know what elements can go in the manifest file. The manifest file is validated using a number of .xsd files that exist in the folder C:Program Files (x86)Windows Kits8.2Include10.0.10030.0winrt

image

These include the various namespaces defined at the beginning of the package.manifest file:

http://schemas.microsoft.com/appx/manifest/foundation/windows10"”>http://schemas.microsoft.com/appx/manifest/foundation/windows10″
http://schemas.microsoft.com/appx/2014/phone/manifest"”>http://schemas.microsoft.com/appx/2014/phone/manifest”
>http://schemas.microsoft.com/appx/manifest/uap/windows10

Code Reorganisation for Real Estate Inspector Sample

Code Reorganisation for Real Estate Inspector Sample

I’ve just published up to GitHub a massive reorganisation of the code that I’ve been covering in previous posts. It also includes initial support for Windows 10 UAP support. However, it has been upgraded to work with Visual Studio 2015 and there are a few c# vNext features that are now being used. Download the code from GitHub to see the details.

Dynamic Layout with the Windows Platform

Dynamic Layout with the Windows Platform

Today there have been a number of announcements in regards to the Windows 10 universal app platform, including the availability of the tools preview:

http://channel9.msdn.com/Shows/Inside-Windows-Platform/A-First-Look-at-Building-Windows-10-Universal-Applications

http://blogs.windows.com/buildingapps/2015/03/23/windows-10-developer-tooling-preview-now-available-to-windows-insiders/

http://www.microsoftvirtualacademy.com/training-courses/a-developers-guide-to-windows-10-preview

http://dev.windows.com/en-us/whats-new-windows-10-dev-preview

http://microsoft.github.io/windows/

http://blogs.msdn.com/b/somasegar/archive/2015/03/23/visual-studio-tools-for-windows-10-technical-preview.aspx

Microsoft have been talking for quite some time about Windows 10 being a single platform that developers can target and have applications run across a multitude of different devices ranging from phone, to slate/tablet, to desktop and even up to Xbox and Surface Hub. This has in part been achievable to a less degree with previous iterations of the framework and as developers we’ve learnt to maximise the reuse along the way. However, for the first time a single executable will run across all devices without recompile. Is this the nirvana that we’ve all been looking for? Here are a couple of things to consider:

– There are still going to be device differences – whilst the core will be common, there are extension sdks for different platforms. Developers will have to query for the existence of contracts before invoking specific extension methods.

– Previously there was a forced break between phone and full screen (ignoring split mode) tablet/desktop, which was convenient for designers. Windows 10 introduces a significant challenge for designers as they have to scale up/down the user experience to handle all manner of sizes and shapes.

– The restricted form factors of the past lead themselves well to a page based navigation, although the page sequence often differed between Windows Phone and Windows. With Windows 10 the page based navigation model doesn’t lend itself well to resizing and adapting to different screen sizes.

The last point is worth expanding on. When an application is resized down to the size of a phone the experience should be similar to a phone application where navigation appears to be page based, including a back button to navigate back between pages. As the application is resized up, initially it would be acceptable to simply scale the size or amount of content being shown. However, at some point there is too much screen real estate available which is either being wasted (voids of empty space) or content is oversized (assuming content continues to scale). Now a different approach is required which will involve presenting more content on the screen. This additional content, which may have been on a different page when on the phone or smaller layout, now needs to be rendered on the same page – this completely breaks the page lifecycle model that most applications are based on, leading to an open question as to how best to handle resizing of applications?

Breaking up the User Experience to Allow for Reuse across Windows and Windows Phone

Breaking up the User Experience to Allow for Reuse across Windows and Windows Phone

Last post I talked about the basic flow of the Real Estate Inspector application (overly simplified of course as it’s a sample application) and I eluded to the need to have a different user experience for different form factors and to allow the user experience to adapt as screen size varies. This problem is going to escalate as we go into the Windows 10 timeframe where a single application will need to deal with a number of different form factors.

The first page to deal with is the login page – the big difference here is that on Windows Phone it’ll be a separate page, whereas on a larger screen it’ll be displayed as a modal style dialog across the current page. In both cases the login page/view will double up as a profile page for the currently signed in user, as well as perhaps any settings that may apply to the current user. Either way this is going to be a simple view that doesn’t need to vary substantially between form factors.

The main page of the application is relatively straight forward as it will simply show the properties that the user has access to. The only difference might be that when the display is portrait (ie similar ratio to a typical phone) the properties could be in a list, whereas when there is more screen real estate the properties can be expanded into a tile array. One of the issues associated with tile array is that there isn’t an implied order; well this isn’t quite true but it’s harder for the user to know whether the order is across-then-down, or down-then-across, at least until they attempt to scroll the screen and then it becomes easier to follow. Luckily in this case the properties aren’t in any particular order.

image  image

If we did decide that properties needed to be ordered, we might adopt a layout similar to the new Photos app on Windows 10 where it uses vertical grouping to imply some level of ordering. For example properties could be order by suburb, or could be ordered by upcoming inspection times (date or week groupings)

image

Now comes the hard part – what does the Property page look like. A Property has both details of the Property itself, as well as a list of inspections that have been carried out. Each inspection will then have to be made up of any number of rooms/areas where inspection information needs to be recorded. The experience on the phone might be:

– User clicks on a Property on the main page

– Property is displayed in a pivot with the details making up any number of pivot items, and the list of inspections being on a separate pivot item.

– Clicking an inspection opens up the inspection, showing a summary of the inspection (eg who did the inspection and date/time) and then a list of inspection rooms/areas – this again could be a pivot

– The inspection room/area would be a simple page made up of a number of form fields.

This layout also works well on tablet/desktop when the application has been reduced to a rough 16:9 portrait layout. However, here’s where things start to get more complex – as the screen size and orientation changes the challenge is how best to use the available real estate. The following image illustrates how expanding the page width or height can lead to unused screen space. I’m not implying you always have to make use of every bit of screen real estate but you also don’t want your application to feel like it is wasting screen space.

image

Starting with the tiled layout on the main screen, if the user taps on one of the Properties there are really three options:

– There is enough space to present a vertical list of Properties, Property details and list of Inspections as three columns

– There is enough space to present a horizontal grid of Properties (1 or two deep), with Property details and list of inspections as two columns under

– There isn’t enough space to present the list of Properties, in which case only the Property details are displayed, along with a Back button to allow for navigation back to the list of Properties.

Here you can see the break down of the developer experience already – we have three distinct user experiences, two of which are done on the same page, whilst the third would normally involve a page navigation (similar to what would happen on the phone).

The complexity escalates even further when you consider that the user might decide to dynamically resize the layout, going from just Property details out vertically where the grid of properties appear at the top, and then horizontally where the list of properties re-orientates to a vertical list, making better use of the screen size. I don’t see an easy way to deal with this dynamic resize operations given the relatively primitive controls the Windows platform offers out of the box.

Navigation Flow for Real Estate Inspector Application for Windows Phone

Navigation Flow for Real Estate Inspector Application for Windows Phone

In building out the pages for the Real Estate Inspector application the first step is to think through the core pages that make up the application. The following navigation flow diagram illustrates the four pages that would make up the phone application. In this case each of the four nodes represent pages or views that you’d expect to see within the application.

image

However, if we consider what might happen on a slate/tablet/desktop experience, not all of these nodes has to be a dedicated page. For example, the Login might be a popup/modal style dialog that appears across the centre of the screen. In fact, with Windows, this is exactly how the Web Authentication Broker appears. There may also be other non-core views that are not represented on here which will features as pages/views on phone but as nested views or modal style dialogs on the larger screen. For example viewing a photo may be a full screen, separate page, experience on phone. On larger devices it may be that this is again a popup/modal style interface.

One thing that can be noted from this diagram is that the Login can be accessed from any of the nodes. Whilst the initial experience will be to navigate to Login from the Home page on first run, at any point there after, if synchronisation fails due to an authentication issue, it’s important that the user is prompted to authenticate immediately to ensure they can continue to operate. This doesn’t need to be a blocking operation as it may be that the user needs to continue to work, despite authentication failing. It is however, important that some rules are in place to ensure the user does update their authentication information (ie enter correct password) within a nominated period for security reasons. After all, there is the scenario where the user no longer works for the organisation in which case their account should both be locked (ie can’t authenticate) and access should be prevented to the application.

Data Synchronization and Sqlite Data Model For Multi-User Scenarios

Data Synchronization and Sqlite Data Model For Multi-User Scenarios

Most consumer application are built to either run anonymously (ie not captured information about who the user is) or they are designed with a single user in mind (think the Facebook application – whilst you can log out, typically to stay logged in, even across multiple sessions of running the application). Enterprise or Line of Business applications, particularly on slate/tablet devices are often multi-tenanted with users picking up the nearest device to them, running the app, signing in and getting to work. With this in mind the real estate inspector application has been architected so far to allow for login and switching between users. However, the local caching has been to a single Sqlite database which resides in the users application data folder. If users switch Windows profile then there isn’t an issue but this doesn’t work for devices where there isn’t a notion of user specific data folders. In this case all users will access the same database, which will result in synchronization issues or users seeing data that isn’t assigned to them.

A simple solution would be to simply create a different database for each user. However, if there is data that is common across all users (Eg property types) this will be synchronized into each database. An alternatively approach is to have a common or master database which is used to synchronise data that is common across all users, then to have individual user databases that just contain the user specific data.

View Models for Split Frame Windows

View Models for Split Frame Windows

In my previous post I talked about adapting the application UX for varying screen size. Currently the navigation model relies on a one to one mapping between pages and view models. However, with the need to support a split screen (eg list on left, details on right) and to continue to support the List/Details page model without too much rework, I need a mechanism for supporting multiple view models. The simplest approach is to again match what I did with the UI layer – the ListAndDetailsPage would have its own view model eg ListAndDetailsViewModel which would contain references to instances of the ListViewModel and DetailsViewModel (these would typically be used to match the ListPage and DetailsPage).

This approach could be taken a step further by having separate view models for the ListControl and DetailsControl – these could be based on a different base view model as they would only ever be created as child view models (ie you can’t navigate to them). In the coming posts I’m going to look at the layout of the real estate inspector sample app and build out the UX using this approach.

Navigation, View Models, Pages, Frames and Universal Windows Applications

Navigation, View Models, Pages, Frames and Universal Windows Applications

Over the past couple of month Microsoft has been laying the groundwork to get developers excited about the upcoming universal application model that will ship with Windows 10. The promise of a single executable that will just run anywhere seems to be the holy grail. However, just because an application will run anywhere, on any devices, doesn’t mean that the user experience is optimized. Take for example a simple list-details windows phone application which presents a list of items, which, when an item is tapped, navigates to a new page with the details of the item. On a desktop with a large screen it doesn’t make sense to navigate to a separate page in order to display the details of the item. Instead, the screen can be split with the list on the left and the details of the selected item displayed on the right.

The simple app navigation model I discussed previously assumes simple navigation between view models, and thus between pages on the Windows platform. However, it’s not that simple; as we just saw instead of navigating to a new page, the selected item is presented in full on the right side. This means we need to contemplate a more complex set of navigation rules, allowing for different navigation paths through the application dependent on available screen real estate. In fact to handle the scenario with a list on the left and details on the right, it may be necessary to consider sub-views with corresponding sub view-models.

Taking this example, let’s assume that we start off with two pages: ListPage and DetailsPage. When we have more space we want to extend the ListPage to include details for the selected item. It doesn’t make sense to duplicate the layout, which would result in a maintenance headache. Instead what we can do is to start extracting portions of the UI into usercontrols that can be reused. For example we might have ListControl, which displays the list of items, and DetailsControl, which not surprisingly displays the details of the item. Clearly these map to the existing ListPage and DetailsPage but now in the case of larger screens we have two options: we can either add the DetailsControl to the ListPage so that, space permitting, the details can be displayed on the right; or, we can create a completely different ListAndDetailsPage which as you’d imagine has both the ListControl and DetailsControl. Now a distinction could be made between phone and desktop platforms to navigate to the appropriate page.

The last challenge is how to handle resizing Windows – in Windows 8/8.1 this problem didn’t really exist. Well it did if you included snap/split mode but very few developers really went to any lengths to refactor their UX and it really only resized the display width-wise. In Windows 10, users will be able to more dynamically adjust the size of the Window and it is up to us application developers/designers to determine how the application behaves. Take the list-details example – with a minimal window, the application should almost mirror the UX of the phone. However, since we have the ListAndDetailsPage the UX will have to adjust the layout, rather than simply navigating to a new page.

There’s clearly a lot to think about and the holy grail of a single application is still going to take a lot of refinement to get right – time to find yourself a great UX person to add to the team!

Communication and Synchronization using Background Tasks with Windows and Windows Phone 8.1

Communication and Synchronization using Background Tasks with Windows and Windows Phone 8.1

In an earlier post I covered creating a background task for Windows platform applications that would allow for synchronization in the background, triggered by change in Internet availability. However, one thing I didn’t cover is what happens when the application is in use, in this case, not only might the user be interacting with the data (loading and writing new records), they might have even forced a synchronization within the application. For this reason it may be necessary to prevent background synchronization whilst the foreground application is being used.

If you haven’t worked with Windows/Windows Phone 8.1 before the OnActivated method might be confusing in the Application class – it’s not the same as the Activated/Deactivated pair from Windows Phone 7x/8.0 where they occurred reliably when the application went into the background. For Windows/Phone 8.1 you need to look at the Window VisibilityChanged event to detect when the Window goes into the background (note that there is an issue with this on Windows 10 where it isn’t triggered when you switch to another application as all applications are windowed by default).

protected override void OnWindowCreated(WindowCreatedEventArgs args)
{
    args.Window.VisibilityChanged += WindowVisibilityChanged;
}

In the event handler I’m going to take ownership of a named Mutex when the Window is visible, and release it when the Window is no longer visible:

private static Mutex backgroundMutex = new Mutex(false,”BackgroundSync”);
private async void WindowVisibilityChanged(object sender, Windows.UI.Core.VisibilityChangedEventArgs e)
{
    if (e.Visible)
    {
        backgroundMutex.WaitOne();

        await ReregisterTasks();
    }
    else
    {
        backgroundMutex.ReleaseMutex();
    }
}

You’ll notice that after taking ownership of the Mutex I then reregister my background task:

private async Task ReregisterTasks()
{
    try
    {
        BackgroundTaskManager.UnregisterBackgroundTasks(“Background Sync Task”, true);
        BackgroundTaskRegistration taskReg =
            await BackgroundTaskManager.RegisterBackgroundTask(typeof(SyncTask).FullName,
                “Background Sync Task”,
                new SystemTrigger(SystemTriggerType.InternetAvailable, false),
                null);
    }
    catch (Exception ex)
    {
        // Swallow this to ensure app doesn’t crash in the case of back ground tasks not registering
        Debug.WriteLine(ex.Message);
    }
}

The reason for this is that we want to cancel any running background task (the “true” parameter passed into the UnregisterBackgroundTasks call).

In the background task I have a Mutex with the same name (Named Mutexes are shared across processes so a great way to communicate between foreground/background tasks). At the beginning of the Run method I attempt to acquire the Mutex: if this succeeds I know my foreground application isn’t visible; if this fails (which it will do immediately since I specified a wait time of 0) it will simply return from the task as we don’t want to sync whilst the foreground application is visible. If the background task is going to run, I immediately release the Mutex which will ensure that if the foreground application is made visible, or launched, it won’t be blocked waiting to acquire the Mutex.

private static Mutex foregroundMutex = new Mutex(false,”BackgroundSync”);
public async void Run(IBackgroundTaskInstance taskInstance)
{
    try
    {
        if (!foregroundMutex.WaitOne(0)) return;
        foregroundMutex.ReleaseMutex();
        // do the rest of background task

It’s important within your background task to override and handle the OnCanceled method so that if the background task is executing when it is unregistered, the task can be cancelled gracefully.

Client Configurations for Different Mobile Service Environments

Client Configurations for Different Mobile Service Environments

In my previous post I talked about setting up different instance of the backend cloud services. The next thing is to control which environment a given build of the client applications will point to. I used to do this with build configurations (eg defining compilation symbols like DEBUG and TEST) to toggle which Constants are compiled into the application. This is a little painful if you want to actually debug against production (ie you want to run the application pointing at production data but in debug mode so you can step through code). It also meant that my configuration information quickly became distributed all over the place in my Constants file. I’m going to include here a simple Configuration class that I’m now using as an alternative. Note that I actually still use compilation constants as the default way of specifying which build configuration is used. However it can easily be overridden to allow for debugging against test or production.

public class Configuration
{
    static Configuration()
    {
#pragma warning disable 162 // This is to allow for easy override of configuration values to debug issues
        if (false)
        {
            Debug.WriteLine(“—————–WARNING – Default Configuration Values Overridden ——————“);
            Current = Configurations[ConfigurationType.Production];
        }
#pragma warning restore 162

#if DEBUG
#if DEBUGLOCAL
        Current = Configurations[ConfigurationType.LocalDevelopment];
#else
        Current = Configurations[ConfigurationType.Development];
#endif
#elif TEST
        Current = Configurations[ConfigurationType.LocalDevelopment];
#else
        Current = Configurations[ConfigurationType.Production];
#endif
    }

    public static Configuration Current { get; set; }

    public string ADTenant { get; set; }

    public string ADAuthority
    {
        get { return ClientConstants.ADAuthorityRoot + ADTenant; }
    }

    public string ADNativeClientApplicationClientId { get; set; }

    public string ADRedirectUri { get; set; }

    public string MobileServiceRootUri { get; set; }
    public string MobileServiceAppIdUri { get; set; }

    public string MobileServiceApiKey { get; set; }

    public enum ConfigurationType
    {
        LocalDevelopment,
        Development,
        Test,
        Production
    }

    public static IDictionary<ConfigurationType, Configuration> Configurations
    {
        get { return configurations; }
    }

    private static readonly IDictionary<ConfigurationType, Configuration> configurations
        = new Dictionary<ConfigurationType, Configuration>
        {
            {
                ConfigurationType.LocalDevelopment, new Configuration
                {
                    ADTenant = “realestateinspector.onmicrosoft.com”,
                    ADNativeClientApplicationClientId = “a5a10ee9-zzzzzzz-4bde-997f-3f1c323fefa5”,
                    ADRedirectUri = “
http://builttoroam.com”,
                    MobileServiceRootUri = “
http://localhost:51539/”,
                    MobileServiceAppIdUri =
https://realestateinspectordev.azure-mobile.net/login/aad,
                    MobileServiceApiKey=”wpxaI—————————EBcg12″
                }
            },
            {
                ConfigurationType.Development, new Configuration
                {
                    ADTenant = “realestateinspector.onmicrosoft.com”,
                    ADNativeClientApplicationClientId = “a5a10ee9-zzzzzzz-4bde-997f-3f1c323fefa5”,
                    ADRedirectUri = “
http://builttoroam.com”,
                    MobileServiceRootUri =
https://realestateinspectordev.azure-mobile.net/,
                    MobileServiceAppIdUri =
https://realestateinspectordev.azure-mobile.net/login/aad,
                    MobileServiceApiKey=”wpxaI—————————EBcg12″
                }
            },
            {
                ConfigurationType.Test, new Configuration
                {
                    ADTenant = “realestateinspector.onmicrosoft.com”,
                    ADNativeClientApplicationClientId = “a5a10ee9-tttt-4bde-997f-3f1c323fefa5”,
                    ADRedirectUri = “
http://builttoroam.com”,
                    MobileServiceRootUri =
https://realestateinspectortest.azure-mobile.net/,
                    MobileServiceAppIdUri =
https://realestateinspectortest.azure-mobile.net/login/aad,
                    MobileServiceApiKey=”wpxaI—————————EBcg12″
                }
            },
            {
                ConfigurationType.Production, new Configuration
                {
                    ADTenant = “realestateinspector.onmicrosoft.com”,
                    ADNativeClientApplicationClientId = “a5a10ee9-wwww-4bde-997f-3f1c323fefa5”,
                    ADRedirectUri = “
http://builttoroam.com”,
                    MobileServiceRootUri = “
https://realestateinspector.azure-mobile.net/”,
                    MobileServiceAppIdUri = “
https://realestateinspector.azure-mobile.net/login/aad”,
                    MobileServiceApiKey=”wpxaI—————————EBcg12″
                }
            }
        };
}

Adding a new configuration is easy:
– define a new enumeration value (eg LocalDevelopment)
– create a new entry in the Configurations dictionary
– (optional) test by changing “if (false)” to “if (true)” and changing the specified configuration

Adding Logging to Client Applications using MetroLog not NLog

Adding Logging to Client Applications using MetroLog not NLog

I wanted to add some logging to my set of applications and was somewhat disappointed to discover the complete lack of PCL support in NLog. After a quick search to find out what others are using I came across MetroLog which seems to be very similar in a lot of regards to NLog (in fact they claim the API surface is very similar indeed). I went to install the NuGet package…

image

and noticed that my Core library (a PCL) wasn’t in the list. Clearly my PCL profile doesn’t match one of the supported profiles which is a bit painful. However, it does support all my client application types so I was happy at least to use MetroLog.

image

I did have a couple of issues installing the NuGet package, namely Visual Studio decided to crash mid way through installing the packages. This meant I had to manually install Microsoft.Bcl.Compression which is a dependency for the Windows Phone 8.0 project, and then uninstall and reinstall the support for the Windows and Desktop projects.

After all this I was building successfully again so it was time to think about how to structure the logging support. Clearly with logging I want it to be a simple as possible and yet accessible virtually anywhere within the application. I want to define a service that is available within my Core library in a similar way to my IDataService and ISyncService implementation. I also wanted the log output to be written out to a sqlite database file for ease of access (there are plenty of third party tools capable of viewing sqlite db files) but rather than use the SqliteTarget that comes with MetroLog I felt I had to write my own (as you do). Luckily this whole process is relatively simple.

I start by creating an ILogWriterService interface which will provide the low level API for writing a LogEntry to a local Mobile Service sqlite table (I’m going to use the same process that is used to cache my synchronized data, except for the time being at least, the data won’t be synchronized anywhere).

public interface ILogWriterService
{

    IMobileServiceSyncTable<LogEntry> LogTable { get; }
    Task Initialize();
}

public class LogEntry : BaseEntityData
{
    public DateTime LogDateTime { get; set; }
    public string Entry { get; set; }
}

public class LogWriterService : ILogWriterService
{
    private readonly MobileServiceClient mobileService = new MobileServiceClient(Constants.MobileServiceRootUri);

    private IMobileServiceClient MobileService
    {
        get { return mobileService; }
    }

    public IMobileServiceSyncTable<LogEntry> LogTable
    {
        get { return MobileService.GetSyncTable<LogEntry>(); }
    }

    public async Task Initialize()
    {
        var data = new MobileServiceSQLiteStore(“log.db”);
        data.DefineTable<LogEntry>();

        await MobileService.SyncContext.InitializeAsync(data, new MobileServiceSyncHandler());
    }
}

Next I define the high level service interface, ILogService:

public interface ILogService
{
    void Debug(string message);

    void Exception(string message, Exception ex);
}

So far, all of these classes have been in the Core library. However, the implementation of the ILogService has to be in the Shared.Client project as it needs to be used by all the client projects.

public class LogService : ILogService
{
    public ILogWriterService Writer { get; set; }

    public ILogger Logger { get; set; }

    public LogService(ILogWriterService writer)
    {
        Writer = writer;
        var target = new MobileServiceTarget(Writer);

        LogManagerFactory.DefaultConfiguration.AddTarget(LogLevel.Debug, target);

        Logger = LogManagerFactory.DefaultLogManager.GetLogger(“Default”);
    }

    public void Debug(string message)
    {
        Logger.Debug(message);
    }

    public void Exception(string message, Exception ex)
    {
        Logger.Error(message, ex);
    }
}

As you can see the implementation sets up the MetroLog logger but uses a custom MobileServiceTarget as the destination. This is implemented as follows:

public class MobileServiceTarget : Target
{
    public ILogWriterService Writer { get; set; }
    public MobileServiceTarget(ILogWriterService writer)
        : base(new SingleLineLayout())
    {
        Writer = writer;
    }

    private bool InitCompleted { get; set; }
    protected async override Task<LogWriteOperation> WriteAsyncCore(LogWriteContext context, LogEventInfo entry)
    {
        try
        {
            if (!InitCompleted)
            {
                await Writer.Initialize();
                InitCompleted = true;
            }
            var log = new LogEntry { LogDateTime = DateTime.Now, Entry = entry.ToJson() };
            await Writer.LogTable.InsertAsync(log);
            return new LogWriteOperation(this, entry, true);
        }
        catch (Exception ex)
        {
            return new LogWriteOperation(this, entry, false);
        }
    }
}

I of course need to register the implementations with Autofac:

builder.RegisterType<LogWriterService>().As<ILogWriterService>();
builder.RegisterType<LogService>().As<ILogService>();

And the last thing is a static helper class that makes logging for two core scenarios really easy:

public static class LogHelper
{
    public static void Log<TEntity>(TEntity entity, [CallerMemberName] string caller = null)
    {
        var json = JsonConvert.SerializeObject(entity);
        Log(typeof(TEntity).Name + “: ” + json, caller);
    }

    public static void Log(string message = null, [CallerMemberName] string caller = null)
    {
        try
        {
            InternalWriteLog(“[” + caller + “] ” + message);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
    }

    public static void Log(this Exception ex, string message = null, [CallerMemberName] string caller = null)
    {
        try
        {
            Debug.WriteLine(“Exception ({0}): {1}”, caller, ex.Message);
            InternalWriteException(caller + “: ” + message, ex);
        }
        catch (Exception ext)
        {
            Debug.WriteLine(ext.Message);
        }
    }

    private static ILogService logService;

    private static ILogService LogService
    {
        get
        {
            if (logService == null)
            {
                logService = ServiceLocator.Current.GetInstance<ILogService>();

            }
            return logService;
        }
    }

    private static void InternalWriteLog(string message)
    {
        try
        {

            LogService.Debug(message);
        }
        catch (Exception ext)
        {
            Debug.WriteLine(ext.Message);
        }
    }

    private static void InternalWriteException(string message, Exception ex)
    {
        try
        {
            LogService.Exception(message, ex);
        }
        catch (Exception ext)
        {
            Debug.WriteLine(ext.Message);
        }
    }
}

The first scenario is a simple string output eg:

LogHelper.Log(“Startup complete”);

The second is logging the output of an Exception:

try
{
   …
}
catch (Exception ex)
{
    ex.Log();
}

Note that the Exception logging also does a Debug.WriteLine which is convenient during development to pick up any issues in the Output window.

Creating Design Time Data in Blend for Shared XAML Pages

Creating Design Time Data in Blend for Shared XAML Pages

In a previous post I created a second page for my Universal (Windows/Windows Phone) applications which was placed in the Shared project. Unfortunately Blend doesn’t support design time data for XAML pages that are in shared projects. However, there is a trick to get the design time data wired up and displaying for these pages.

I’ll start by opening the MainPage for the Windows application, which is in the Windows project as it’s not shared with the Windows Phone application. From the Data pane I can go ahead and create a sample data set. There are different ways to partition your sample data – I prefer to have a sample data set per page; in this case the data is for SecondPage, which is in the shared project.

image

In this case my design time data is just going to be made up of a single complex entity, CurrentProperty

image

Next I am going to remove the SecondPageDataSource that was created on the MainPage and add it instead to the Application.Resources section in the App.xaml. Note that I needed to add the d, mc and SampleData namespaces.

http://schemas.microsoft.com/expression/blend/2008"”>http://schemas.microsoft.com/expression/blend/2008″
    http://schemas.openxmlformats.org/markup-compatibility/2006"”>http://schemas.openxmlformats.org/markup-compatibility/2006″
   
    mc_Ignorable=”d”>
    <Application.Resources>
        <SampleData:SecondPageDataSource x_Key=”SecondPageDataSource” d_IsDataSource=”True”/>

Now when I open up the SecondPage I’ll see that there is a SecondPageDataSource under the Data pane.

image

One thing to be aware of is that this will only exist when designing the Windows application. Unfortunately you’ll need to create a different sample data set for use when designing the page for Windows Phone.

Blend Designer Error Due to Service Locator

Blend Designer Error Due to Service Locator

I was just about to get started using Blend to layout a page and noticed that there was an error in the Results pane in Blend, stating that the ServiceLocatorProvider must be set.

image

I was pretty certain that this was something I was doing during startup but clearly that code isn’t being run correctly at design time. Turns out I don’t really care at design time since I’m going to predominantly use design time data. This means that in the ViewModelLocator constructor I can simply exit if it’s being invoked at design time. Unfortunately the usual design mode property that you can query to determine if the code is being run at design time doesn’t exist in the view model locator scope. Luckily an alternative is to simply query if the service locator provider has been set:

public ViewModelLocator()
{
    if (!ServiceLocator.IsLocationProviderSet) return;
    DataService = ServiceLocator.Current.GetInstance<IDataService>();
    SyncService = ServiceLocator.Current.GetInstance<ISyncService>();
    NavigateService = ServiceLocator.Current.GetInstance<INavigateService>();
}

Synchronizing in a Background Task

Synchronizing in a Background Task

Now that we have implementations for IDataService and ISyncService I can update the backgounrd task for the Windows platform applications to perform synchronization in the background. To begin with I need to reference the Autofac libraries (including the Microsoft common service locator and extensions libraries) by adding the RealEstateInspector.Background in NuGet package manager

image

 

The next thing is to update the Run method of the background task so that it looks for a current access token and uses it to initialise the data service.

public async void Run(IBackgroundTaskInstance taskInstance)
{
    try
    {
        var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;

        var authContext = new AuthenticationContext(Constants.ADAuthority);
        if (authContext.TokenCache.ReadItems().Count() > 0)
        {
            authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
        }

        var authResult =
            await
                authContext.AcquireTokenSilentAsync(Constants.MobileServiceAppIdUri,
                Constants.ADNativeClientApplicationClientId);
        if (authResult != null && !string.IsNullOrWhiteSpace(authResult.AccessToken))
        {
            var dataService = ServiceLocator.Current.GetInstance<IDataService>();
            var syncService = ServiceLocator.Current.GetInstance<ISyncService>();

            await dataService.Initialize(authResult.AccessToken);

            if (cost == BackgroundWorkCostValue.High)
            {
                await syncService.ForceUpload();
            }
            else
            {
                await syncService.Synchronise(true);
            }
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }
    finally
    {
        if (deferral != null)
        {
            deferral.Complete();
        }
    }
}

Depending on the cost of the background task I either want the task to force an upload of pending updates (if high cost), or do a full synchronisation.

Navigation Service for Cross Platform Page/View Navigation from View Model

Navigation Service for Cross Platform Page/View Navigation from View Model

I already have a solution for allowing the view model to jump back onto the UI thread using the UIContext. However, I currently don’t have a mechanism that will allow one view model initiate navigation to a new page/view. What I want is the ability for one view model to request navigation by specifying the destination view model. Of course, this needs to work cross platform. Let’s take a look at the basics of how this could work – there are essentially two strategies that most mvvm style navigation frameworks use: The first is by convention where the lookup for the destination page/view is based on the name of the target view model; the second is by defining a mapping between view models and the corresponding page/view. In this case I’m going to go with the latter – In the Core library I define a couple of interfaces and an abstract implementation:

public interface INavigateService
{
    void Navigate<TViewModel>() where TViewModel : IDataViewModel;
}

public interface INativeNavigateService<TView> : INavigateService
    where TView : class,new()
{
    void Register<TViewModel, TViewType>() where TViewType : TView;
}

public abstract class CoreNavigateService<TView> : INativeNavigateService<TView> where TView : class, new()
{
    private readonly IDictionary<Type, Type> viewDictionary = new Dictionary<Type, Type>();

    protected Type ViewType<TViewModel>()
    {
        Type viewType = null;
        viewDictionary.TryGetValue(typeof(TViewModel), out viewType);
        return viewType;
    }

    public void Register<TViewModel, TViewType>() where TViewType : TView
    {
        viewDictionary[typeof(TViewModel)] = typeof(TView);
    }

    public void Navigate<TViewModel>() where TViewModel : IDataViewModel
    {
        var navType = ViewType<TViewModel>();
        NavigateToView(navType);
    }

    protected abstract void NavigateToView(Type viewType);
}

Next, in the client projects, I define a class that inherits from CoreNavigateService and implements the NavigateToView method. Here is the Windows Platform implementation:

public class WindowsPlatformNavigationService : CoreNavigateService<Page>
{
    protected override void NavigateToView(Type viewType)
    {
        (Window.Current.Content as Frame).Navigate(viewType);
    }
}

The ApplicationStartup method now looks like:

public void ApplicationStartup()
{
    CoreApplication.Startup(builder =>
    {

        builder.RegisterType<SignalRFactory>().As<ISignalR>();
#if NETFX_CORE
        builder.RegisterType<UniversalUIContext>().As<IUIContext>();

        builder.RegisterType<WindowsPlatformNavigationService>().SingleInstance().As<INavigateService>();
#endif
    });

    var navService = ServiceLocator.Current.GetInstance<INavigateService>() as WindowsPlatformNavigationService;

#if NETFX_CORE
    navService.Register<MainViewModel,MainPage>();
    navService.Register<SecondViewModel,SecondPage>();
#endif
}

Both the IDataViewModel, BaseViewModel and ViewModelLocator need to be extended to include an INavigateService property called NavigateService. Now from within the view model, navigation can be invoked by calling NavigateService.Navigate<SecondViewModel>()

Adding a Background Task to the Windows Platform Applications

Adding a Background Task to the Windows Platform Applications

At some point you’re likely to want to run code in the background – this might be to update live tiles, or to do periodic synchronization of data. In this post I’ll add a background task to the Windows platform applications. I’ll start by adding a new Windows Runtime Component to the solution.

image

As a Windows RT component there are some additional restrictions on the definition of types and the way methods are exposed. However, I can still add a reference to the background project to the Core library of the application. As the Core library encapsulates all the logic for the application this should be sufficient to perform background operations such as synchronizing data or updating tile contents.

Next I want to add a reference from the Universal applications (Windows and Windows Phone) to the background task project. Once done, it’s time to create the actual task that will be invoked in the background. I’ll replace the default Class1.cs with SyncTask.cs with the following templated structure:

public sealed class SyncTask : IBackgroundTask
{
    private BackgroundTaskCancellationReason cancelReason = BackgroundTaskCancellationReason.Abort;
    private volatile bool cancelRequested = false;
    private BackgroundTaskDeferral deferral = null;
    //
    // The Run method is the entry point of a background task.
    //
    public async void Run(IBackgroundTaskInstance taskInstance)
    {
        try
        {
            Debug.WriteLine(“Background ” + taskInstance.Task.Name + ” Starting…”);

            //
            // Get the deferral object from the task instance, and take a reference to the taskInstance;
            //
            deferral = taskInstance.GetDeferral();
            //
            // Associate a cancellation handler with the background task.
            //
            taskInstance.Canceled += OnCanceled;

            //
            // Query BackgroundWorkCost
            // Guidance: If BackgroundWorkCost is high, then perform only the minimum amount
            // of work in the background task and return immediately.
            var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;

            if (cost == BackgroundWorkCostValue.High)
            {
                // Only push changes
            }
            else
            {
                // Do full sync
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
        finally
        {
            if (deferral != null)
            {
                deferral.Complete();
            }
        }
    }

    //
    // Handles background task cancellation.
    //
    private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
    {
        //
        // Indicate that the background task is canceled.
        //
        cancelRequested = true;
        cancelReason = reason;
        Debug.WriteLine(“Background ” + sender.Task.Name + ” Cancel Requested…”);
    }
}

I also need to define this task as a background task in the Declarations section of the project manifest files. In this case we’re going to be triggering the background task based on a system event.

image

Lastly, the background task needs to be registered. For this I’m using this BackgroundTaskManager class which wraps the registration process for tasks.

public class BackgroundTaskManager
{
    /// <summary>
    /// Register a background task with the specified taskEntryPoint, name, trigger,
    /// and condition (optional).
    /// </summary>
    /// <param name=”taskEntryPoint”>Task entry point for the background task.</param>
    /// <param name=”name”>A name for the background task.</param>
    /// <param name=”trigger”>The trigger for the background task.</param>
    /// <param name=”condition”>An optional conditional event that must be true for the task to fire.</param>
    public static async Task<BackgroundTaskRegistration> RegisterBackgroundTask(String taskEntryPoint, String name, IBackgroundTrigger trigger, IBackgroundCondition condition)
    {
        BackgroundExecutionManager.RemoveAccess();
        var hasAccess = await BackgroundExecutionManager.RequestAccessAsync();
        if (hasAccess == BackgroundAccessStatus.Denied) return null;

        var builder = new BackgroundTaskBuilder();
        builder.Name = name;
        builder.TaskEntryPoint = taskEntryPoint;
        builder.SetTrigger(trigger);
        BackgroundTaskRegistration task = builder.Register();
        Debug.WriteLine(task);

        return task;
    }

    /// <summary>
    /// Unregister background tasks with specified name.
    /// </summary>
    /// <param name=”name”>Name of the background task to unregister.</param>
    /// <param name=”cancelRunningTask”>Flag that cancels or let task finish job</param>
    public static void UnregisterBackgroundTasks(string name, bool cancelRunningTask)
    {
        //
        // Loop through all background tasks and unregister any with SampleBackgroundTaskName or
        // SampleBackgroundTaskWithConditionName.
        //
        foreach (var cur in BackgroundTaskRegistration.AllTasks)
        {
            if (cur.Value.Name == name)
            {
                cur.Value.Unregister(cancelRunningTask);
            }
        }
    }
}

The actual registration is done when the application starts. In this case I’m going to cheat a little and include it in the OnNavigatedTo for the MainPage:

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    try
    {
        BackgroundTaskManager.UnregisterBackgroundTasks(“Background Sync Task”, true);
        BackgroundTaskRegistration taskReg =
            await BackgroundTaskManager.RegisterBackgroundTask(typeof(SyncTask).FullName,
                “Background Sync Task”,
                new SystemTrigger(SystemTriggerType.InternetAvailable, false),
                null);
    }
    catch (Exception ex)
    {
        // Swallow this to ensure app doesn’t crash in the case of back ground tasks not registering
        Debug.WriteLine(ex.Message);
    }
}

Notice that this task is registering interest in the InternetAvailable trigger, allowing the background task to be invoked whenever connectivity changes. Note that this process works for both Windows and Windows Phone Universal projects.

Update:

What I forgot to include here is that if you want tasks to run in the background on the Windows platform you need to make them lock screen enabled. To do this set the “Lock screen notifications” to either Badge or Badge and Tile Text.

image

This will cause a couple of red circles indicating issues with the configuration of the application. The first is that you need to specify either location, timer, control channel or push notifications in the Declarations tab – I’ve chosen to check the push notification checkbox

image

The other requirement is a badge logo – I’ve only specified one of the three options. I’d recommend providing all three if you are serious about delivering a high quality application.

image

Update 2:

When it actually came to run this I must confess I ran into an issue with a typo. Back on the second screenshot an observant reader would have noticed the spelling mistake on the namespace RealEstateInspector. When you attempt to register the service I saw something similar to the following:

image

Full exception details:

System.Exception occurred
  HResult=-2147221164
  Message=Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

Saving Image to Blob Storage Using Shared Access Signature

Saving Image to Blob Storage Using Shared Access Signature

In this post I’m  going to bring together a couple of my previous posts that discuss retrieving and saving images, and retrieving a Shared Access Signature from a controller which will allow me to write to a particular container within Blob Storage. To complete the implementation I’ll use the Windows Azure Storage library from NuGet – it only installs for Windows platforms as there’s no PCKL or Xamarin support for this library currently.

image

As the Windows Azure Storage library is current platform specific, I’ll need to wrap it in a simple interface that makes it easy for me to write data to Blob Storage – I’ll come back to that. For the time being I’m just going to retrieve the SAS and use it along with the storage library to upload an image. So I’ll start by invoking the sharedaccesssignature controller using the GET verb as I want to ensure the container is created if it doesn’t already exist. This will return a SAS which I can use in the upload process.

public async Task<string> RetrieveSharedAccessSignature()
{
    var sas = await MobileService.InvokeApiAsync<string>(“sharedaccesssignature”, HttpMethod.Get,
        new Dictionary<string, string> { { “id”, “test” } });
    return sas;
}

Next I want to capture an image, in this case picking a photo, and uploading it to a specified blobg.

private async void CaptureClick(object sender, RoutedEventArgs e)
{
    var picker = new MediaPicker();
    var sas = string.Empty;
    using (var media = await picker.PickPhotoAsync())
    using (var strm = media.GetStream())
    {
        sas = await CurrentViewModel.RetrieveSharedAccessSignature();

        Debug.WriteLine(sas);

        // Get the URI generated that contains the SAS
        // and extract the storage credentials.
        var cred = new StorageCredentials(sas);
        var imageUri = new Uri(“
https://realestateinspector.blob.core.windows.net/test/testimage.png”);

        // Instantiate a Blob store container based on the info in the returned item.
        var container = new CloudBlobContainer(
            new Uri(string.Format(“
https://{0}/{1}”,
                imageUri.Host, “test”)), cred);

        // Upload the new image as a BLOB from the stream.
        var blobFromSASCredential = container.GetBlockBlobReference(“testimage.png”);
        await blobFromSASCredential.UploadFromStreamAsync(strm.AsInputStream());
    }

}

Clearly this code isn’t well factored but it’s here as a quick example of how you can use a SAS to upload content to blob storage.

ViewModel Refactoring, INotifyPropertyChanged and Running on UI Context with Dispatcher

ViewModel Refactoring, INotifyPropertyChanged and Running on UI Context with Dispatcher

In a previous post I showed how to use SignalR as one option for providing feedback to the client application during a long running service operation. However, I didn’t display this on the UI because that would have made the blog post long and complicated as I tried to explain propagating a change from a non-UI thread, back onto the UI thread so it could be displayed within the app. In this post I’m going to do just that – what’s interesting is that each platform handles this scenario slightly different with some caring about thread affinity, whilst others do not.

Firstly, I’ll update the layout to include a TextBlock that’s going to display the progress:

<TextBlock Text=”{Binding Progress}” />

In this case databinding to the Progress property on the MainViewModel:

private string progress;
public string Progress
{
    get { return progress; }
    set
    {
        if (Progress == value) return;
        progress = value;
        OnPropertyChanged();
    }
}

Note that as this property changes it calls the OnPropertyChanged method which will be used to raise the PropertyChanged event specified in the INotifyPropertyChanged interface – this is what the XAML data binding framework uses to detect when bound properties are changed. In this case I’m going to implement this interface in BaseViewModel, and have MainViewModel inherit from BaseViewModel, rather than implement it in every view model.

public class MainViewModel:BaseViewModel  { … }

public class BaseViewModel:INotifyPropertyChanged
{
   
public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));

    }
}

Now, let’s modify the delegate that gets invoked when we receive an update from the service. Previously we just had Debug.WriteLine(msg), let’s change that to  Progress=msg. When you run this in your Universal Windows application – BANG – Exception due to an attempt to update the UI (ie the Text attribute on the TextBlock) from a non-UI thread. Interestingly doing the same thing in the WPF application doesn’t throw the same exception. In order to update the Progress property, we first need to jump back onto the UI thread, which is fine, if we were working directly with the Page/View. However, we don’t have any notion of a Dispatcher, UI threads etc from within the MainViewModel. This sounds like another scenario for a dependency injected implementation, so here goes:

My BaseViewModel is extended to include a UIContext object:

private readonly UIContext context=new UIContext();

public UIContext UIContext

{
    get { return context; }
}

The UIContext object wraps and abstracts away the loading of an implementation of IUIContext:

public interface IUIContext
{
    Task RunOnUIThreadAsync(Func<Task> action);
}

public class UIContext
{
    private IUIContext runContext;
    private IUIContext RunContext
    {
        get
        {
            if (runContext == null)
            {
                runContext = ServiceLocator.Current.GetInstance<IUIContext>();

            }
            return runContext;
        }
    }

    public async Task RunAsync(Action action)
    {
        await RunAsync(async () => action());
    }

    public async Task RunAsync(Func<Task> action)
    {
        var context = RunContext;
        await context.RunOnUIThreadAsync(action);
    }
}

Of course, we now need an implementation of IUIContext for our Universal Windows application:

public class UniversalUIContext : IUIContext
{
    public async Task RunOnUIThreadAsync(Func<Task> action)
    {
        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,async  () => await action());
    }
}

And this needs to be registered with Autofac in the ClientApplicationCore – note the use of the NETFX_CORE compilation attribute.

CoreApplication.Startup(builder =>
{
    builder.RegisterType<SignalRFactory>().As<ISignalR>();
#if NETFX_CORE
    builder.RegisterType<UniversalUIContext>().As<IUIContext>();
#endif
});

And finally I need to go back to my initial progress statement and update it from msg => Progress = msg, to the following:

async msg =>
    await UIContext.RunAsync(() =>
    {
        Progress = msg;
    })

This issue isn’t specific to Universal applications, and you should always make sure you have access to the UI thread when making UI changes (such as updating data bound properties).

A Simple ViewModelLocator for Spawning ViewModels for XAML Based Applications

A Simple ViewModelLocator for Spawning ViewModels for XAML Based Applications

There are numerous frameworks out there that provide mechanisms for instantiating view models. Long again, when I first started building XAML based applications and became familiar with MVVM, I stepped through a number of different ways of creating and wiring up view models. In this post I’m going to show a very basic implementation of a locator to instantiate view models. Into the Core library I will add a ViewModelLocator class which exposes a property, Main, that will return a new instance of the MainViewModel.

public class ViewModelLocator
{
    public MainViewModel Main
    {
        get { return CreateViewModel<MainViewModel>(); }
    }

    private T CreateViewModel<T>() where T:new()
    {
        return new T();
    }
}

I’m going to want a single instance of this class to be created and kept around for the duration of my application’s lifecycle. One option would be to instantiate it within my ApplicationCore class I introduced previously. However, I actually want the instance of the ViewModelLocator to be accessible via XAML, so for this reason it makes more sense to instantiate it as a XAML resource. In the WPF and Universal (Win/WP8.1) applications I can simply add this to the app.xaml file to the Application.Resource element.

<Application.Resources>
        <core:ViewModelLocator x_Key=”Locator” />
</Application.Resources>

In the MainWindow (WPF) and MainPage (Universal) I can now specify the DataContext in the opening element, removing the need to create the MainViewModel in code in the codebehind file. Eg

<Window x_Class=”RealEstateInspector.Desktop.MainWindow”
        http://schemas.microsoft.com/winfx/2006/xaml/presentation"”>http://schemas.microsoft.com/winfx/2006/xaml/presentation”
        http://schemas.microsoft.com/winfx/2006/xaml"”>http://schemas.microsoft.com/winfx/2006/xaml”
        DataContext=”{Binding Main, Source={StaticResource Locator}}” >

The current implementation of Xamarin.Forms doesn’t seem to support creating Application resources in XAML. However, by tweaking the App constructor, I can add an instance of the ViewModelLocator:

public App()
{
    Resources = new ResourceDictionary();
    Resources.Add(“Locator”, new ViewModelLocator());

    MainPage =new MainPage();
}

The syntax in the MainPage of the XForms application is similar except BindingContext replaces DataContext:

BindingContext=”{Binding Main, Source={StaticResource Locator}}”

There seems to be a quirk in XForms at the moment in that the Binding expression calls to the Main property repeatedly – since it gets a different instance of the MainViewModel back each time, it ends up in an endless loop trying to get a consistent value. To prevent this, we can add a view model dictionary to the ViewModelLocator and change the behaviour to always return the same instance of the view model.

private readonly Dictionary<Type, object> viewModels = new Dictionary<Type, object>();

private T CreateViewModel<T>() where T:new()
{
    var type = typeof (T);
    object existing;
    if (!viewModels.TryGetValue(type, out existing))
    {
        existing = new T();
        viewModels[type] = existing;
    }
    return (T)existing;
}

And there you have it – view model location across all applications.