Nick's .NET Travels

Continually looking for the yellow brick road so I can catch me a wizard....

Remote Desktop Connection Fail from Windows 10 Using Azure AD Credentials

Just over a week ago I repaved my Surface Pro 3 to a clean install of Windows 10 build 10074 (since then I've upgraded to 10122) and since we don't run our own domain at Built to Roam I figured I would sign into Windows 10 using my Office 365 credentials (ie my Azure Active Directory credentials). For the most part this seems to be relatively stable except for a couple of scenarios:

Firstly, after the upgrade to 10122 it looked like it had completely junked my user profile as I couldn't sign in using either my PIN or Password. The error was actually a little cryptic as it was complaining it couldn't reach a login server. In the end I rebooted and I was able to sign in fine.

The second, and slightly more annoying thing is that the AzureAD credentials seem to be causing some issues with authentication in a couple of places.

–  The first is with Remote Desktop into a cloud service running in Azure. Normally I would only have to specify my username (eg “admin”) and my password and it would authenticate without any issues. However, now I get the following error dialog

Remotefail

Remote Desktop Connection
An authentication error has occurred (Code: 0x80004005).
Remote computer: xxxxxxx.cloudapp.net

 In the end I prefix my username with “local” (eg local\admin) and it worked fine.

–  The second occurence is trying to connect to a network resource. This network resource is actually a NAS but for the life of me I can't work out what domain prefix to give it. It somehow tries to resolve my AzureAD credentials and then is failing. Very frustrating as I now have to retrieve the data off my NAS using a different computer.

Compiled DataBinding in Windows Universal Applications (UAP)

This question on stackoverflow which references the Windows 10 jumpstart videos (http://www.microsoftvirtualacademy.com/training-courses/a-developers-guide-to-windows-10-preview?prid=ch9courselink) raises the topic of compiled data bindings. Currently there is no documentation about this feature and I doubt that we’ll see much out of Microsoft prior to Build. However, the x:Bind syntax is available in the insiders preview of the Windows 10 SDK so I figured I’d explore it a little.

Let’s start with a simple expression:

<TextBlock Text="{x:Bind}" />

When you add this to a page and run it, you’ll see the Type name of the page displayed in the TextBlock (eg CompiledDataBindingSample.MainPage). In order to examine this further let’s create a simple custom control with a dependency property and corresponding change handler:

public class CustomControl : Control
{
    Windows.UI.Xaml.Markup.IComponentConnector x;

    public string Test
    {
        get { return (string)GetValue(TestProperty); }
        set { SetValue(TestProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Test.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty TestProperty =
        DependencyProperty.Register("Test", typeof(string), typeof(CustomControl), new PropertyMetadata(null, TestChanged));

    private static void TestChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var newData = (d as CustomControl).Test;
        Debug.WriteLine(newData.GetType().Name);
    }
}

Now let’s add an instance of this control onto the page and data bind to the Test property:

<local:CustomControl Test="{x:Bind}" />

When this is run we can set a breakpoint on the Debug.WriteLine and we can examine the newData object. What’s interesting is that the newData object is the instance of the page that is hosting the control. In other words, the value being passed into the binding expression is the page itself (in this case an instance of MainPage) – this explains why in the TextBlock showed the type name, as this is the default ToString() value. This is interesting in itself as it means that the context for data binding with x:Bind is the page itself, in contrast to the default DataContext of null when using Binding.

The other thing that’s worth looking at is the Call Stack window. The first two frames make sense, being the set and change handler for the dependency property but then it gets interesting as it references a class called MainPage_obj1_Bindings with methods such as SetValue_obj3_Test, Update_, InitializeCore, Initialize etc.

image

At this point I think it’s time to go take a look at what’s been generated when the application was compiled. In this case we’ll use ILSpy to get a list of the classes that make up the application. As you can see from this screenshot MainPage has a couple of nested types, MainPage.IMainPage_Bindings and MainPAge.MainPage_obj1_Bindings, along with a field/property combination that exposes an instance of MainPage.IMainPage_Bindings. There is also an additional method, Connect, which has been injected into the MainPage during compilation.

image

A further examination of the base types collection shows that in addition to inheriting from Page, MainPage implements Windows.UI.Xaml.Markup.IComponentConnector, which no surprises defines a method, Connect(int, object). So, what does this method do? Using ILSpy to inspect the contents on the Connect method we can see that it generates an instance of the MainPage_obj1_Bindings class and associates it with the elements on the page (in this case the TextBlock and the CustomControl). Clearly this method is going to be invoked during the initialization phase of a page.

Now, let’s turn our attention to the MainPage_obj1_Bindings class. It would appear that this class has instance variables for each of the elements that has an x:Bind expression. In this case it has variables obj2 (TextBlock) and obj3 (CustomControl). It also has some generated methods such as SetValue_obj2_Text which explicitly sets the Text value on the TextBlock. This makes me think back to a time before data binding where properties had to be explicitly set in code. Whilst data binding has been an effective way for developers to declaratively wire up properties to underlying data, it did add a significant overhead and subsequent performance hit – for large data sets this can be quite significant and hard to work around. By the looks of these generated methods, it would appear that by converting the data binding expression into compiled code, some of the performance overhead of data binding can be overcome.

Ok, so now that we’ve taken a bit of a look at some of the aspects of compiled data binding, let’s go back to XAML and take a look at extending the binding expression to include a path. In most cases we’ll want to bind attributes on the visual elements to properties on a view model. The question is how to do this using x:Bind. Let’s see what happens when we add ViewModel to the binding expression:

<TextBlock Text="{x:Bind ViewModel}" />

Normally, if you add a path to a binding expression that isn’t valid it will compile and run without any issues. In this case, there is no ViewModel property on the MainPage, so when the application is compiled the following build error is generated:

Invalid binding expression 'MyProperty' : Unrecognized property 'MyProperty' at offset '0'

Let’s add a ViewModel property to the MainPage:

public MainViewModel ViewModel { get; set; }

public MainPage()
{
    ViewModel = new MainViewModel();
    this.InitializeComponent();

}

The MainViewModel class exposes a property, HelloText, and implements the INotifyPropertyChanged interface. Of course, normally this would be implemented in a base class with an OnPropertyChanged or RaisePropertyChanged helper method.

public class MainViewModel : INotifyPropertyChanged
{
    private string hello = “Hello World”;
    public string HelloText
    {
        get { return hello; }
        set
        {
            hello = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("HelloText"));
            }
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

In order to reference the HelloText property, we’ll extend the binding expression:

<TextBlock Text="{x:Bind ViewModel.HelloText}" />

Running this appears to work with the text “Hello World” appearing in the TextBlock. Let’s try updating the HelloText. A simple Run method will update the HelloText property every second.

public async void Run()
{
    var i = 0;
    while (true)
    {
        await Task.Delay(1000);
        HelloText = "Hello " + i++;
    }
}

Unfortunately this doesn’t seem to do anything, with the TextBlock not updating. This behaviour is consistent of a OneTime data binding. Let’s add Mode=OneWay to the binding expression.

<TextBlock Text="{x:Bind ViewModel.HelloText, Mode=OneWay}" />

Now the TextBlock updates every second as we’d expect. So it appears that unlike a traditional Binding, the x:Bind expression defaults to a OneTime mode, instead of OneWay. ILSpy also indicates that the MainPage_obj_Bindings has a sub-class, MainPage_obj1_Listener, which is designed to hook up to the INotifyPropertyChanged.PropertyChanged event. This again will help ensure updates are passed to the appropriate elements without any need for Reflection based calls.

Build it Beta for Windows and Windows Phone

Over the last couple of weeks we’ve done some major work to Build it Beta which will significantly improve and simplify the process of getting Build it Beta installed and setup across Windows and Windows Phone. If this is the first time you’ve heard of Build it Beta, it is a home-grown solution for the deployment of Windows platform applications. The primary scenario that Build it Beta solves, is the need for developers to deploy applications to testers so that they can provide feedback. It does this by leveraging the enterprise deployment capabilities of the Windows platform, where applications can be signed using a enterprise signing certificate and then deployed to devices that trust that certificate.

Supported platforms

The following Windows platforms are supported by Build it Beta for the installation of test applications.

Windows Phone 8.0
Windows Phone 8.1
Windows 8.1
Windows 10 (Phone and desktop)

Supported application platforms

Applications targeting the following platforms are supported by Build it Beta

Windows Phone 7.x (XAP)*
Windows Phone 8.0 (XAP)
Windows Phone 8.1 (XAP)
Windows Phone 8.1 (APPX)
Windows 8.0 (APPX)*
Windows 8.1 (APPX)
Windows 10 UAP (APPX)

*Build it Beta supports signing and deploying applications targeting Windows Phone 7.x and Windows 8.0. However, due to lack of enterprise distribution support in Windows Phone 7.x there is no way to deploy applications to those devices. Windows Phone 7.x applications can only be tested on Windows Phone 8+ devices. The Windows version of Build it Beta targets Windows 8.1 so there is no support for deploying to Windows 8.0 devices. Windows 8.0 applications need to be tested on Windows 8.1+.

Here are some useful links for getting started with Build it Beta

Distribution of Application for the Windows Platform for Testing

Last year I wrote an article for Visual Studio Magazine entitled Enterprise Distribution of Windows Phone Applications which looks at the requirements and steps required to deploy Windows Phone applications. The process for distributing Windows desktop/slate applications is slightly different but essentially involves signing the appx with an appropriate code signing certificate that is trusted by those computers that the application will be distributed to. We’re using these same techniques with Build it Beta to help developers distribute their applications for testing. Recently we’ve done a number of bug fixes and improvements and now have support for Windows Phone 8.0,  Windows Phone 8.1 (Silverlight), Windows Phone 8.1 (Appx), Windows 8.0 and 8.1, and now Windows 10 applications. There is still a bit of work to go in rounding off some of the rough edges but we’re really keen for developers to start using it.

We’ve also just created a new Build it Beta blog where we will be posting a series of post talking about distribution of applications for testing both in the generic sense (covering signing and enterprise distribution) and of course how Build it Beta works. Don’t forget you can follow Build it Beta on Twitter as well.

Microsoft Continues the Integration Between Blend and Visual Studio

Years after Microsoft attempted to lure designers into the world of app development by giving them a tool where they could assist with the designing of applications, it appears that Microsoft still recognises that design and development, whilst different roles, go hand in hand as part of the development process. In Visual Studio 2015 the integration between Visual Studio and Blend for Visual Studio becomes even more apparent. The changes range from the simple things, like the link to open Blend from within Visual Studio being renamed to “Design in Blend,” through to intellisense in the XAML editor in Blend and better alignment of the various tool windows.

image

Microsoft Partner, Office 365 and Visual Studio Online

This is a somewhat off-topic post which only applies to Microsoft Partners who happen to use Office 365 and Visual Studio Online. As a Microsoft Silver Partner we have a number of licenses which we’re able to use internally. This includes a number of MSDN subscriptions which can be assigned to staff and Office 365 seats.

Over the last couple of weeks we have migrated across to Office 365 (this was actually done over a 24 hour period as it was relatively simple to move from one hosted exchange account to Office 365). One of the awesome things about Office 365 is that users belong to the Azure AD tenant (ie we have builttoroam.com set up as a tenant and all Office 365 users with an email address of ***@builttoroam.com belong to that tenant).

We’ve been using Azure for development for a long time but as Azure AD is still in its infancy we were originally just adding staff in based on their Microsoft Account. We also did the same for Visual Studio Online. All in all this was quite messy and felt very disconnected. Well today we took the plunge and connected Visual Studio Online to our Azure AD account. To make sure the transition went smoothly we have temporarily added the Microsoft Account for each staff member to our Azure AD tenant – this will mean that in the short term they can continue to access VSO using their Microsoft Account. Going forward we would expect that everyone will start to use their workplace account (ie their ***@builttoroam.com Azure AD account) to sign into both the Azure portal and Visual Studio Online.

Here’s where the issue is. Currently in Visual Studio 2013 you can online sign in using a Microsoft Account (this is fixed in Visual Studio 2015 where you can both sign in with a workplace account, and you can have multiple accounts signed in). The upshot is that the staff will have to sign into VS2013 with their Microsoft Account, and then connect to VSO using their workplace account – this seems simple enough, right! wrong! well partially right. Firstly, we still need to assign the MSDN subscriptions to the staff. After being assigned a license, the staff simply go to MSDN and activate the subscription. This gives them a license to use Visual Studio 2013 which is automatically picked up when they sign in using their Microsoft Account.

The issue is that if they then go to Visual Studio 2015 and sign in with their workplace account, they won’t have access to the MSDN subscription (since it’s associated with their workplace account). The solution is to go to their MSDN subscription details (signing into msdn.microsoft.com with their Microsoft Account) and under the Visual Studio Online section, click the Link workplace account option and enter their workplace email address. After doing this, Visual Studio 2015 will pick up the linked MSDN subscription and license, as well as picking up the Visual Studio Online projects in the Team Explorer window.

The upshot is that after doing all this, staff should be able to sign into Visual Studio Online, Office 365, Azure Portal and Visual Studio 2015 using their workplace account. It’s only Visual Studio 2013 where they will have to sign in with their Microsoft Account, and then connect to VSO using their workplace account.

Windows 10 Jumpstart Training

Whenever I try to locate the jumpstart training for the Windows 10 Developer Preview tools it always seems to take longer than expected. Anyhow, I thought I’d re-post the direct links to each of the sessions here so that at least I can find them easily next time:

Developer's Guide to Windows 10 Preview- (01) Getting Started

Developer's Guide to Windows 10 Preview- (02) Start Simple- Hello World

Developer's Guide to Windows 10 Preview- (03) Migrating 8.1 Apps to Windows 10

Developer's Guide to Windows 10 Preview- (04) Extension SDKs

Developer's Guide to Windows 10 Preview- (05) SplitView Control

Developer's Guide to Windows 10 Preview- (06) Maps

Developer's Guide to Windows 10 Preview- (07) Pen & Ink

Developer's Guide to Windows 10 Preview- (08) RelativePanel Control

Developer's Guide to Windows 10 Preview- (09) Adaptive Triggers

Developer's Guide to Windows 10 Preview- (10) App-to-App Communication

Developer's Guide to Windows 10 Preview- (11) New XAML Controls and XAML Transform 3D

Developer's Guide to Windows 10 Preview- (12) App Services

Developer's Guide to Windows 10 Preview- (13) Action Center

Developer's Guide to Windows 10 Preview- (14) Evolving the Web Platform

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

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 Kits\8.2\Include\10.0.10030.0\winrt

image

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

xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap=http://schemas.microsoft.com/appx/manifest/uap/windows10

Disabling the Pinch-Zoom behaviour of the WebBrowser control on Windows Phone

This is an issue that seems to keep coming back to haunt us on various projects where we have to embed web content within a Windows Phone application. One of the best solutions is to modify the CSS of the page being displayed to disable the touch behaviour using the –ms-touch-action (noted that whilst in IE11+ the recommendation is to use the touch-action property but for WP the vendor prefix is still required).

One of the team that I work with came across a post by Colin Eberhardt that handles some of the manipulation events in the visual tree surrounding the actual web content, thereby disabling the pinch-to-zoom behaviour. This technique makes use of Linq to XAML/Visual Tree which is also worth a read

Fix Login Failures to Azure Mobile Services with Enhanced Users Features for Javascript Backends

One of the applications that we’ve been working on that leverages the older javascript backend version of Azure Mobile services was seeing some cases where users couldn’t login. For a while we put it down to incidental issues with our application but we then detected a pattern where it was related to Microsoft Accounts that belonged to one of the domains associated with outlook.com (eg live.com, outlook.com, outlook.com.au, hotmail.com). I don’t know exactly which domains it does affect, nor whether it was all email addresses on those domains. However, what I do know is that in order to fix the issue we had to follow the instructions that Carlos had posted a while ago on the Enhanced Users Feature. We hadn’t done this previously as I wasn’t confident that it wouldn’t break our production application but it turns out the only change we needed to do, as per his instructions, was change to use the asynchronous getIdentities method (which is also an update we were supposed to do a while ago!).

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

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

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

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

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

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!

Source Code for Real Estate Inspector Sample on GitHub

I’ve got around to publishing the current source code pieces to GitHub. It’s currently very hotch-potch as I’ve been focussing on demonstrating/fleshing out a lot of the concepts for my blog posts. Over the coming weeks I’ll be extending out the actual functionality and will periodically update the code on GitHub. For now, it’s a good place to pick through the various code I’ve been talking about over the last couple of months

Using a Refresh Token to Renew an Expired Access Token for Azure Active Directory

Currently my application attempts to acquire the access token silently which equates to looking to see if there is a current (ie not expired) token in the token cache. However, tokens don’t live for very long, so it’s quite likely that a token won’t be found. This unfortunately leads to a poor user experience as the user will quite often be prompted to sign in. There is an alternative, which is to use the refresh token, returned as part of initially acquiring the access token, to silently request a new access token. This of course is on the assumption that the refresh token hasn’t expired.

Here is a quick summary, as at the time of writing, of the different tokens and their expiry rules (a good explanation here):

  • Azure AD access tokens expire in 1 hour (see the expires_on attribute that is returned when acquiring an access token).
  • Refresh tokens expires in 14 days (see the refresh_token_expires_in attribute that is returned when acquiring an access token).
  • Access tokens can be refreshed using the refresh-token for a maximum period of time of 90 days, from the date that the access token was acquired by prompting the user.

The authentication logic can be amended to retrieve the list of refresh tokens, attempt to acquire token silently, followed by an attempt to acquire token via the refresh token. Failing that the user would be prompted to sign in.

var authContext = new AuthenticationContext(Configuration.Current.ADAuthority);

var tokens = authContext.Tokens();
var existing = (from t in tokens
                where t.ClientId == Configuration.Current.ADNativeClientApplicationClientId &&
                        t.Resource == Configuration.Current.MobileServiceAppIdUri
                select t).FirstOrDefault();
if (existing != null)
{
    try
    {
        var res = await authContext.AcquireTokenSilentAsync(
            Configuration.Current.MobileServiceAppIdUri,
            Configuration.Current.ADNativeClientApplicationClientId);
        if (res != null && !string.IsNullOrWhiteSpace(res.AccessToken))
        {
            return res.AccessToken;
        }
    }
    catch (Exception saex)
    {
        Debug.WriteLine(saex);
    }

    try
    {
        var res = await
            authContext.AcquireTokenByRefreshTokenAsync(existing.RefreshToken,
                Configuration.Current.ADNativeClientApplicationClientId);
        if (res != null && !string.IsNullOrWhiteSpace(res.AccessToken))
        {
            return res.AccessToken;
        }
    }
    catch (Exception saex)
    {
        Debug.WriteLine(saex);
    }

}