Nick's .NET Travels

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

BuildIt.States from a ViewModel

In my previous post on State Management using BuildIt.States I demonstrated using the BuildIt.States library to declare states for a page. However, it’s not enough to declare states in the UI space. The management of state should be done in the ViewModel space, making it possible to test and keep the logic separate from the UI implementation.

To do this, I can create another instance of the StateManager within the ViewModel for the page. I need to declare the same states, just without any of the additional attributes required to update the user interface. The ViewModel ends up looking like the following – I’ve included a StateName property and a method, UpdateState, which can be invoked to change the state.

public class MainViewModel : NotifyBase, IHasStates
{
    public IStateManager StateManager { get; } = new StateManager();
    private string stateName;
    public string StateName
    {
        get { return stateName; }
        set
        {
            stateName = value;
            OnPropertyChanged();
        }
    }
    public MainViewModel()
    {
        StateManager.Group<MainStates>()
            .DefineState(MainStates.StateOne)
            .DefineState(MainStates.StateTwo)
            .DefineState(MainStates.StateThree)
            .DefineState(MainStates.StateFour);
    }
    public async Task UpdatState(MainStates state)
    {
        var ok = await StateManager.GoToState(state);
        if (ok)
        {
            StateName = state.ToString();
        }
    }
}

Now, in the UI space, the page needs to wire to and unwire from the StateChanged event handler that is available on each of the StateGroup entities in the StateManager.

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

    var sm = ViewModel.StateManager;
    var grp = sm.StateGroups[typeof(MainStates)] as StateGroup<MainStates, DefaultTransition>;
    grp.StateChanged += Grp_StateChanged;
}
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
    base.OnNavigatingFrom(e);

    var sm = ViewModel.StateManager;
    var grp = sm.StateGroups[typeof(MainStates)] as StateGroup<MainStates, DefaultTransition>;
    grp.StateChanged -= Grp_StateChanged;
}

private void Grp_StateChanged(object sender, StateEventArgs<MainStates> e)
{
    manager.GoToState(e.State, e.UseTransitions);
}

I also updated each of the event handlers for the buttons to call the UpdateState method on the ViewModel. Now I can control the state of the UI by updating the state of the StateManager within the ViewModel.

State Management using BuildIt.States

Over the last month or so I’ve been refactoring some code I prototyped earlier in the year that allows for easier state management within an entity. One of the outputs of this was a portable library that’s available via NuGet, and the source is available via the BuildIt repository on GitHub (https://github.com/builttoroam/BuildIt). In my post, Cross Platform Visual States, I gave an example of how to define states for a Xamarin.Forms page. The StateManager can be used in applications for any supported platform, making it easy to define states. In this post, I’ll provide a quick walk through of using the StateManager, this time in a UWP project as an alternative to using visual states.

To get started, add a reference to the BuildIt.States NuGet plackage. Then in the codebehind file for the page, create an instance of the StateManager class.

private readonly IStateManager manager = new StateManager();

Next, we’re going to create an enumeration that lists each of the possible states. Note that we include a placeholder “Base” state which will represent the default state before any call to change state. If you don’t define a placeholder state, the first state will become the default, meaning that any initial transition to the first state won’t have any effect, since the StateManager thinks it’s already in that state.

private enum MainStates
{
    Base,
    StateOne,
    StateTwo,
    StateThree,
    StateFour
}

I’ll add some XAML to the page in order to show a label using a TextBlock and some buttons that will trigger the state changes.

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

    <StackPanel VerticalAlignment="Center"
                HorizontalAlignment="Center">
        <TextBlock Text="Hello World!"
                   x:Name="HelloTextBlock" />
        <Button Click="FirstStateClick">State One</Button>
        <Button Click="SecondStateClick">State Second</Button>
        <Button Click="ThirdStateClick">State Third</Button>
        <Button Click="FourthStateClick">State Fourth</Button>
    </StackPanel>
</Page>

private void FirstStateClick(object sender, RoutedEventArgs e)
{
    manager.GoToState(MainStates.StateOne);
}

private void SecondStateClick(object sender, RoutedEventArgs e)
{
    manager.GoToState(MainStates.StateTwo);
}

private void ThirdStateClick(object sender, RoutedEventArgs e)
{
    manager.GoToState(MainStates.StateThree);
}

private void FourthStateClick(object sender, RoutedEventArgs e)
{
    manager.GoToState(MainStates.StateFour);
}

The event handlers for the buttons invoke GoToState on the StateManager in order to invoke a state change to the specified enum value. The only thing left to do is to define the different states.

manager.Group<MainStates>()
    .DefineState(MainStates.StateOne)
        .Target(HelloTextBlock)
        .Change(x=>x.Text,(x,v)=>x.Text=v)
        .ToValue("State One")

    .DefineState(MainStates.StateTwo)
        .Target(HelloTextBlock)
        .Change(x => x.Text, (x, v) => x.Text = v)
        .ToValue("State Two")

    .DefineState(MainStates.StateThree)
        .Target(HelloTextBlock)
        .Change(x => x.Text, (x, v) => x.Text = v)
        .ToValue("State Three")

    .DefineState(MainStates.StateFour)
        .Target(HelloTextBlock)
        .Change(x => x.Text, (x, v) => x.Text = v)
        .ToValue("State Four");

The fluid nature of the state declarations make it relatively straightforward to see what each state defines. In each case, the state changes the Text on the HelloTextBlock to a value that matches the state. When this application is run, preseing each of the buttons invokes the state change, updating the Text on the HelloTextBlock accordingly.

States v’s Regions for Multi-Window Applications

In previous posts I’ve talked a lot about visual states, application state and control states. However, one thing that I’ve been trying to wrap my head around is the disconnect that happens when you start to consider that an application can have multiple windows.What’s rather ironic is multi-window support was something we took for granted back when we were building complex line of business Windows Forms/WPF applications. However, the iOS era lead to the dumbing-down of application development – in the Apple world users are only able to do single operations and apparently can’t wrap their heads around anything more than a single screen full of data at a time. This lead to application models, and page/view lifecycles that assume that the application is either in the foreground, or in the background; no middle ground where the application is visible, just not in focus, which is the case in a multi-windowed environment.

The interesting side effect of a multi-windowed environment is less to do with having multiple applications open and visible at the same time but that a single application can have multiple windows open at the same time. One of the best features of the old Live Messenger application was that you could have each chat open in a separate window, each of which could be independently moved, pinned and closed. Currently, nearly every messaging application, be it Messenger (Facebook), WhatsApp, Skype or Line, use a similar single-window model that’s extremely painful when you are actively participating in multiple chats.

Of course, most platforms all support some limited form of multiple window support, for example when projecting the contents of the screen to an external monitor. The Universal Windows Platform has full support for the creation and management of multiple windows within a single application instance. A recent post on the Redmond Pie shows a concept of what multiple windows on an iPad would look like. It’s evident that multi-windowed applications are going to play an important part of all future platforms.

This leads me to my next challenge. In the context of a single window application we can think of the current page of the application as mapping to a state in the application. Transition from one state to another equates to moving between pages. Within the confines of a page, there may be multiple states; these map to visual states on the page. However, going the other direction, how do we represent multiple windows? Windows don’t map to another higher level set of states, since there may be any number of windows opened, and they can all exist in relative independence.

So, we need a different concept to represent them, which I’ve termed Application Regions. By default all applications have a default or start up region. A region has a current states, which will normally correspond to the current page or view. Regions can be created and closed independently, and usually correspond to separate windows (although I’m currently considering whether a region can manifest itself in other ways). Regions can also have different startup pages (ie a different startup state), and might in fact have a completely different set of states.

In the same way that we need a state manager to assist with the management and tracking of states, we’ll need a region manager that understands how to create, track and close regions. Whilst the region manager will itself live in the platform agnostic core of our application, it will of course need a mechanism to spawn new windows (ie when a region is created). The region manager will also need to be clever enough to do the right thing when run on a platform that doesn’t support multiple windows. On such an environment, when a new region is spawned, the new set of pages/view will simply have to be added to the navigation stack of the existing window; when the user closes the region, the pages/views will be popped off the stack, returning to the last page/view of the previous region.

This is just some early stage thoughts on the concept of application regions v’s application states.

Cross Platform Visual States

Last year I posted on “Taking Visual States Cross Platform to iOS and Android with Xamarin” and is a topic that I often come back when discussing the design and development of mobile applications. Let’s start by discussing what visual states are and why they’re important when building applications (and this really applies to any application, not just mobile applications). During the design of an application it’s common to prepare wireframes and visual designs that document each page, the key elements on each page and any associated behaviour. This typically includes documenting when elements are hidden or shown, often in response to either data changes or user interactions. The following screenshots show a recent application we worked on for Hungry Jack’s for Windows 10. This is the same page of the same application, running on the same device, just with a different window size. As you can see the difference between the first two images is quite significant as the navigation bar switches from being at the bottom (similar to what you’d expect for mobile) to on the left side. The third image simply augments the position of elements further to make better use of the available screen size.

image image image

Thorough analysis during the design phase will reveal all possible layout combinations for a page; these combinations are what we refer to (at least in the Windows/XAML world) as visual states. In the case of the screenshots from the Hungry Jack’s application, each of these layouts represents a different visual state for this page. If you don’t take the time to determine what visual states exist on each page and what triggers a transition between visual states, during development you’ll find yourself toggling attributes on element on the page in an attempt to recreate each required combination. This lack of a structured approach makes it not only hard to layout each page, it also makes it hard to test as there is no definitive list of layouts that need to be verified.

On the Windows platform, Visual States are something we take for granted; they can be declared in XAML and Blend has support for designing each visual state. However, other platforms are not so blessed and have to resort to changing attributes manually in code. Some cross platform technologies make use of data binding to allow visual elements to be dynamically updated based on changes in the corresponding data (ie the view model). These include MvvmCross and Xamarin.Forms. However, data binding should be reserved for updating data values on a view, not controlling the visual states on a page.

Learning to develop for the Windows platforms, developers go through a series of learning steps.

  • Coding Changes: Most developers come from building applications or web sites where they’re used to having to set data values in code.
  • Data Binding: The first step along the progression is learning how to use data binding to update content on the page (eg Text on a Textblock)
  • MVVM: After seeing the benefit of data binding, the next step is to appreciate the separation of concerns that MVVM offers. At this point developers often look at what MVVM libraries there are out there and usually settle on something like MvvmCross, MvvmLight, Caliburn.Micro, Prism etc
  • Converters: Equipped with the new found power of data binding, developers often go nuts and start data binding everything, including using properties on the view model to control when items should be visible. This is where they look to use converters to adapt properties on the view model (eg XYZIsVisible which would be a bool) to attributes on visual elements (eg XYZ.Visibility which is a Visibility). The issue with this is that at design time, in a tool like Blend, it’s very difficult to see what the layout looks like. You can’t simply change the Visibility property on elements, since they’re now data bind. You can temporarily remove the data binding, but then of course you forget to put it back and then spend hours trying to work out why the application is broken.
  • Visual States: Enter Visual States…. instead of data binding attributes that control the layout of a page, it’s better to use visual states to define what elements are visible and any layout changes required for a particular layout. Blend supports design time editing of visual states and the ability to visualize any combination of visual states from different state groups
  • View Model States: Eventually developers realise that not only should they use visual states, they should track and control them from their view model, thus making yet another aspect of their application testable. I’ve talked about this a couple of times (http://nicksnettravels.builttoroam.com/post/2015/08/10/application-development-using-states-and-transitions.aspx, http://nicksnettravels.builttoroam.com/post/2014/01/11/Visual-States-in-Windows-Phone-and-Windows-Applications-using-MvvmCross.aspx, http://nicksnettravels.builttoroam.com/post/2014/05/19/Taking-Visual-States-Cross-Platform-to-iOS-and-Android-with-Xamarin.aspx)

Ok, so now that you have the basics on what a visual state is, and some background on why I believe visual states are so important, let’s discuss the elephant in the room….. Visual States only exist in XAML on the Windows platform…. making it very difficult to use visual states when building cross platform applications. So, what can we use when building cross platform? Well let’s go through the progression that developers go through. As you’d expect, all platforms support developers being able to adjust values via code. Unfortunately, this is where most developer technologies end, for example neither iOS (Objective-C, Swift) or Android (Java) support data binding out of the box. There are some third party solutions that attempt to bridge this gap, such as the data binding support in MvvmCross and Xamarin.Forms. In fact both these options provide not only the ability to data bind, but also enable MVVM and support using converters as part of data binding.

In actual fact there’s no requirement to have data binding (and subsequently MVVM and the use of converters) in order to start using visual states to control layout. However, again there’s almost no platform, or even third party, support for defining visual states.Over the weekend, I was experimenting with Xamarin.Forms and was thinking about how to define and transition between visual states. Whilst it would be nice to do it declaratively in XAML, I thought I’d better walk before I run, so I figured I’d work out a way to define visual states in code. Before getting started I thought though the basic mechanics of how visual states should work:

- Visual States should be declared in groups, and each group can only have one active visual state at any given time

- A visual state should define any number of value actions

- A “value action” defines setting a property on an element to a specific value

- The visual state manager should be able to change to a specific visual state

- Changing to a specific visual state, should only adjust the current state of the group that the visual state belongs

I’ve always felt that one of the weaknesses of Visual states on the XAML platform is that they’re named using a string, and the only way to reference them when changing state, is using a string literal. So, for my attempt at a visual state manager I’m going to have my visual states defined as an enumeration. In fact, each group of states will use a different enumeration type – thus each visual state corresponds to a unique enumeration value. The end game is to be able to declare visual states in a relatively fluid manner, as shown in the following example which defines two groups based on the enumerations SecondStates and SecondStates2.

VisualStateManager
    .Group<SecondStates>()
        .DefineState(SecondStates.State1)
        .DefineState(SecondStates.State2)
            .Target(textBlock)
                .Change(x => x.TextColor, (x, c) => x.TextColor = c)
                .ToValue(Color.FromHex("FFFF008B"))
            .Target(textBlock)
                .Change(x => x.FontSize, (x, c) => x.FontSize= c)
                .ToValue(40)
        .DefineState(SecondStates.State3)
            .Target(textBlock)
                .Change(x => x.TextColor, (x, c) => x.TextColor = c)
                .ToValue(Color.FromHex("FFFFC500"))
            .Target(textBlock)
                .Change(x => x.FontSize, (x, c) => x.FontSize = c)
                .ToValue(10)
        .DefineState(SecondStates.State4)
    .Group(SecondStates2.Base)
        .DefineState(SecondStates2.StateX)
        .DefineState(SecondStates2.StateY)
            .Target(textBlock2)
                .Change(x => x.TextColor, (x, c) => x.TextColor = c)
                .ToValue(Color.FromHex("FFFF008B"))
            .Target(textBlock2)
                .Change(x => x.FontSize, (x, c) => x.FontSize = c)
                .ToValue(40)
        .DefineState(SecondStates2.StateZ)
            .Target(textBlock2)
                .Change(x => x.TextColor, (x, c) => x.TextColor = c)
                .ToValue(Color.FromHex("FFFFC500"))
            .Target(textBlock2)
                .Change(x => x.FontSize, (x, c) => x.FontSize = c)
                .ToValue(10);

In my next post we’ll look at the different classes that make up the visual state manager and the extension methods that allow for the fluid declaration seen in this example.

SplitView Bug in the Universal Windows Platform (UWP)

Last week we were trying to resolve an issue that had been raised in an application we were building for the Universal Windows Platform, where the user had to press the back button twice in order to navigate back to the previous page. Initially we thought that we must be subscribing to the hardware back button on Windows 10 Mobile, as the issue seem to only manifest itself on mobile. However, after eliminating all calls to subscribe to the back button, we were still seeing the same issue. After a bit of further testing the issue only seemed to arise if we were navigating to a new page with the pane of the SplitView visible, but not always…. Eventually we tracked it down to the scenario where the DisplayMode is set to Overlay and the pane of the SplitView is visible (ie IsPaneOpen set to true). Navigating to a new page without first either changing the DisplayMode to Inline, or closing the pane, will result in the pane staying open, and unfortunately it still keeps the event handler on the BackRequested event on the SystemNavigationManger.

SplitViewFail sample

Simple solution: make sure that you force the pane closed before navigating by setting IsPaneOpen to false (assuming the DisplayMode is set to Overlay).

Ignite Session Recordings

Earlier this month I delivered two sessions at Ignite Australia. The recording for these sessions are now available for watching

Application Development for the Universal Windows Platform
This session provides an overview of the Universal Windows Platform (UWP), a single platform that developers can target to build applications that will run across a myriad of devices. After years of progressive convergence, UWP offers a single application model, a single developer experience and a single store. The session will discuss building applications that can run on any device, whilst still being able to leverage the individual device features. It'll provide a roadmap for tools, frameworks, and guidance on building for the Universal Windows Platform.


Bare Metal Development with the Universal Windows Platform
Ignite Australia
The Universal Windows Platform offers developers a unique opportunity to build applications that run on an extensive range of devices. However, this comes the challenge of how to scale the user experience and how to adapt to different device capabilities. This session will dig deep into the use of Visual States, adaptive triggers, device family and feature detection, new binding syntax and new controls.

Changing DataContext and Compiled Data Binding in Universal Windows Platform Applications

Back in April I talked briefly about Compiled Data Binding and how it improves performance throughout your XAML application by eliminating all the reflection calls that go on in the background with traditional data binding. Recently I've been spending more time investigating the best way to structure code and design time data to ensure high quality applications. One of the easy pitfalls with the x:Bind syntax is a lack of understanding of the context of the data binding.

To start with, let's recap how traditional data binding works: Elements on the page have a DataContext, which you can think of as the object that is being data bound to. The DataBinding expression includes a Path, which determines the property on the DataContext that a particular attribute on an element is being data bound to. By default the DataContext flows down the page/usercontrol as each element inherits the DataContext from its parents. However, it is possible to override the DataContext by setting it explicitly for each element. There are plenty of sites/pages that can provide more detail on this form of data binding.

The new compiled data binding, which I'll refer to as x:Bind, tries to eliminate any use of reflection at runtime. In order to do this, the compiler generates a large quantity of code to connect the data entities and the visual elements. This means that the compiler must know Type information about both the attribute on the visual element, and the properties on the element being data bound. The starting point is that the context for x:Bind expressions on a Page is the Page itself, and similarly for a UserControl, it is the UserControl itself. If we assume that the data we want to data bind to is within our ViewModel, then we need to expose the ViewModel as a property on the Page. For example:
public MainViewModel CurrentViewModel => DataContext as MainViewModel;
and then in the XAML for the Page it can be referenced as follows:
<TextBlock Text="{x:Bind CurrentViewModel.Name, Mode=OneWay}" />
This references the Name property on the MainViewModel entity returned by the CurrentViewModel property on the page. What's not immediately obvious here is that despite indicating that the Mode is OneWay (ie it should detect changes) there is no code that notifies the data binding framework if the CurrentViewModel changes. This could happen if the DataContext changes, for example in the following code where the OnNavigatedTo method has a small latency before it sets the DataContext.
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    await Task.Delay(2000);

    DataContext = new MainViewModel();
}
In this case, the underlying DataContext is updated after 2 seconds to the new instance of the MainViewModel. This means that the CurrentViewModel value has also changed. However, there has been no attempt to notify the data binding framework, and subsequently the page, of this change. There are a number of ways to address this issue, the two I'm going to present here both rely on the Page implementing the INotifyPropertyChanged interface, exposing an event PropertyChanged, which the data binding framework will listen for.

Option 1 - Raise the PropertyChanged event manually after setting the new DataContext eg
DataContext = new MainViewModel();
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("CurrentViewModel"));
Option 2 - Intercept the DataContextChanged event and then raise the PropertyChanged
public MainPage()
{
    InitializeComponent();

    DataContextChanged += MainDataContextChanged;
}
private void MainDataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("CurrentViewModel"));
}
Both of these options use a hardcoded property name, CurrentViewModel, which is not recommended. A last option, that might appear more complex to begin with, has the advantage of being simple, clean and less riddled with string constants. It starts with a Wrapper class, which provides a level of indirection between the Page and the ViewModel:
public class Wrapper<T>:INotifyPropertyChanged
{
    public T Entity { get; set; }
    public event PropertyChangedEventHandler PropertyChanged;

    public Wrapper(FrameworkElement element)
    {
        element.DataContextChanged += Element_DataContextChanged;
    }

    private void Element_DataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
    {
        if (args.NewValue is T)
        {
            Entity = (T) args.NewValue;
        }
        else
        {
            Entity = default(T);
        }
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Entity"));
    }

    public virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
And using this entity is simple as you just need to define the type of ViewModel:
public Wrapper<MainViewModel> Data => new Wrapper<MainViewModel>(this);
The only other difference is that there is an extra level of indirection in the x:Bind expression.
<TextBlock Text="{x:Bind Data.Entity.Name, Mode=OneWay}" />

Now as the DataContext on the Page changes the Wrapper class will detect the change and raise the PropertyChanged event indicating that the "Entity" has changed. Since x:Bind connects to any object in the binding path that implements INotifyPropertyChanged, it will handle this event and look for the updated Entity property, which will be the new DataContext value.

As you start to work with x:Bind, you will notice that your binding expressions are longer than you'd be used to. Don't worry about this, since the data binding itself will be orders of magnitude quicker


Certifying and Distributing Windows Store Applications to Earlier (ie Non-Supported) Versions of Windows 10 Mobile

In my previous post on Visual Studio 2015 RTM, Universal Windows Platform (UWP) Developer Tools and Debugging on a Windows Phone device I covered modifying the TargetPlatformMinVersion property in the Visual Studio project file in order to deploy your Universal Windows Platform application to a Windows 10 Mobile device. Granted that this post is probably a little too late, since the next build of Windows 10 Mobile is now out (I'm yet to install it), but it is possible to publish your application to the Store so that it can be installed on a non-developer enabled phone.

Now you'd think you'd just be able to create a Store package with the TargetPlatformMinVersion property set to the required value (in this case 10.0.10166.0 to match what I currently have on my device - see the OS Version attribute in the About screenshot below). Unfortunately this is not the case!


If you do attempt to generate a Store package you'll see an error similar to the following image - "10.0.10166.0" is not a supported value for TargetPlatformMinVersion. Please change it on the Project Property page



Ok, so step one is to revert the change to TargetPlatformMinVersion so that you can at least generate a Store package. From the Project menu in Visual Studio, select Store -> Create App Packages (if this option isn't enabled, make sure you have you UWP project selected in Solution Explorer). Follow the prompts to do a Store build - this should generate an .appx file you can work with.

What we're going to do is manually modify the generated package. From the Start menu, select the Developer Command Prompt for VS2015



Change directories to where the .appx file resides. Execute the following command, substituting you .appx filename. This will extract the contents of the .appx file into a sub-folder called "export"
makeappx unpack /nv /p myapplicationpackage.appx /d .\export
Open the AppxManifest.xml file using your text editor of choice. Locate the line that looks similar to the following and replace the MinVersion with the version number you want to target (ie 10.0.10166.0)

<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.10240.0" MaxVersionTested="10.0.10240.0" />
Close and save the updated AppxManifest.xml file. And return to the command prompt and execute the following (again feel free to replace the .appx filename)
makeappx pack /nv /d .\export /p myapplicationpackage-updatedversion.appx
And you're done - submit this package to the Store, and a couple of days later (yes, whilst certification only seems to take a couple of hours, the distribution of UWP apps is very slow at the moment, so expect to wait at least 24hours from when certification is completed) you'll be able to install your application...... of course, all of this could have been saved if you'd just updated to the latest Windows 10 Mobile build, which I'm about to do now!

Visual Studio 2015 RTM, Universal Windows Platform (UWP) Developer Tools and Debugging on a Windows Phone device

If you've upgraded to Visual Studio 2015 RTM with the associated Universal Windows Platform tools, you may have realised that you can't deploy apps to a real Windows Phone that's running the current Windows Insider Preview build for Windows Phone. This is because the version of the SDK, which has a version/minversion of 10.0.10240.0, is higher than what's currently available for the phone. For application development and testing this means using the emulators that ship with the SDK.

Of course, this isn't a great story as lots of developers much prefer debugging on a real device. In fact there are scenarios where a real device is the only way to test some scenarios. I came across the following post that provides a temporary, NON-SUPPORTED solution.

https://social.msdn.microsoft.com/Forums/en-US/46889785-07bd-4e10-9134-e8fa429b1486/uwp-is-it-possible-to-deploy-a-uwp-app-build-in-vs2015rtm-to-windows-phone-running-10010166?forum=wpdevelop

The solution rests on manually changing the TargetPlatformMinVersion property in the UWP project file to be the same as what's running on the phone (in my case 10.0.10166.0). Don't change the TargetPlatformVersion property - doing this will mean that you won't be able to open the project in Visual Studio since that version isn't supported with the SDK.

WARNING: Whilst making this change may mean that you can debug your application on a real device, just be aware that it may through weird errors if you happen to try to access an API that has actually changed between 166 and 240 builds. Your code is still going to be built against the 10.0.10240.0 API set, you're just lying in the package manifest, claiming that your app will run on a previous version.

As you can imagine this has been designed with future versions in mind. If you open the project properties dialog for the UWP application you'll see that on the Application tab there is a Targeting section. In the current SDK there is only one option for the target version and min version. Going forward you can imagine that a future SDK will allow for selection of 10.0.10240.0 (the current version) and a future version (where APIs may have evolved).

 

Application Development Using States and Transitions

Having worked with each of the different XAML based technologies Microsoft has released (WPF, SL, WP, Win, UWP...), I've long been a proponent of the use of visual states. Jerry Nixon discusses using visual states to build Windows 8.1 application. I've written articles that talk about using visual states for changing page layout to reflect states within a view model. Let me talk briefly about why I favour visual states and why the visibility property is often misused.... then we'll get onto discussing using states for building applications.

Developers new to working with XAML discover that they can hide/show items on the page by data binding a Boolean property on the view model (this assumes they're using mvvm/data binding) with the visibility property on an element. This of course requires a Boolean to visibility converter. It works nicely and assuming the developer has implemented INotifyPropertyChanged and is raising the PropertyChanged event correctly, the elements on the page will hide/show as required.

Whilst there isn't anything wrong with this approach, it makes it difficult to design the layout in Blend. In order to hide/show elements, you have to modify the design time data (assuming you've bothered to create design time data). The alternative is to use visual states to describe how the page looks for each state. Blend for Visual Studio includes a States window which allows for one or more states to be invoked, making it easy to create, view and edit visual states, at design time!


Ok, time to move on an talk more about using states as a foundation for application development. Unfortunately we can't jump there yet as we need to first look at different levels of how an application hangs together. Rather than get into a discussion on the similarities and differences between application platforms, let's just look at the Windows platform (this should apply to Windows Phone, Windows 8.x and Windows 10):

- An application typically has a frame, within which it navigates between pages

- A page can be made up of any number of visual state groups, and can have a single visual state selected at any time from each visual state group. Animations can be run as part of transitioning between states.

- Controls (including Usercontrols) can contain their own visual states that determine how they look under various conditions (pressed, checked, selected etc).

What's interesting about this is that the navigation between pages is actually the odd one out. Most application developers devote a large portion of the application development process to ensuring the navigation between pages is correct. They spend very little time working through the visual states of pages (often hacking away at hiding/showing elements on the screen). So, what happens if we make the assumption that each one of these scenarios can be expressed as a series of states?

As a starting point, we'd need a definition of a state. In the past, to keep the states of a view model separated from the visual states on a page I typically create an enumeration which has values that have the same names as the visual states. The view model then keeps track of which state is currently selected. Changing the current state raised a StateChanged event, which is handled by the page where it invokes the GoToState method on the VisualStateManager. My basic definition of a state will be an extension of this where the IStateDefinition is based on an enumeration type (well, at least a struct):

public interface IStateDefinition<TState> where TState : struct
{
    TState State { get; }
}

with a simple implementation:

public class BaseStateDefinition<TState> : IStateDefinition<TState>
    where TState : struct
{
    public TState State { get; set; }
}

And we can then define an interface for an entity which maintains current state, allows for a change in state and raise an event when the state changes:

public interface IStateManager<TState> : INotifyPropertyChanged
    where TState : struct
{
    event EventHandler<StateEventArgs<TState>> StateChanged;

    TState CurrentState { get; }

    IDictionary<TState, IStateDefinition<TState>> States { get; }

    Task<bool> ChangeTo(TState newState, bool useTransition = true);
}

The first instinct would be for the view model to implement this interface, but this won't work since the view model would have to implement the interface for each state group that it needs to track. This means we need an implementation of this interface that tracks current state for each state group:

public class BaseStateManager<TState> :
    NotifyBase, IStateManager<TState>
    where TState : struct
{
    public event EventHandler<StateEventArgs<TState>> StateChanged;

    public TState CurrentState { get; private set; }

    public IDictionary<TState, IStateDefinition<TState>> States { get; set; }


    public async Task<bool> ChangeTo(TState newState, bool useTransitions = true)
    {
        var current = CurrentState;
        if (current.Equals(newState)) return true;

        CurrentState = newState;

        try
        {
            StateChanged?.Invoke(this, new StateEventArgs<TState>(newState, useTransitions));
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            // Ignore any errors caused by the event being raised, as
            // the state change has still occurred
        }
        return true;
    }
}

We'll use this as the basis from which we can track states at an application, page and control level.







Microsoft and The Smith Family via the #WeSpeakCode Program Delivers Coding to Students at Mitchell High School on Windows 10 as part of #UpgradeYourWold Campaign

Yesterday I had the privilege of being involved in the delivery of introductory computer science and programming material to year 10 and 11 students out at Mitchell High School in Blacktown. The material was from http://studio.code.org which has a fantastic repository of material for high school students (specifically https://studio.code.org/s/20-hour which is the course we were delivering).

This program was a combined initiative from The Smith Family and Microsoft and the first day (yesterday) aligned with the release of Windows 10. It was fantastic to see the energy in the room and the excitement from the students as they played and explored all the new features of Windows 10.

It was also great to see the media pick up what a great experience this was:

http://www.smh.com.au/national/education/sydney-school-students-get-a-taste-of-careers-in-computing-and-agriculture-20150729-gimzax.html

http://www.theaustralian.com.au/business/technology/windows-10-australian-students-pass-their-verdict/story-e6frgakx-1227461837728


Launching Windows Store Applications from Code in Windows 10

On Windows 8/8.1 after installing an application from the Windows Store it was possible to interrogate the registry and find the AppUserModelId which could then be used to launch the application. This process is described in more detail here - http://www.codeproject.com/Articles/542316/Run-Windows-Store-Apps-From-Desktop.

There are a couple of ways to launch the application using the AppUserModelId:

- The first (as the link suggests) is to use the launcher utility that comes with the SDK eg:
C:\Program Files (x86)\Windows Kits\8.0\App Certification Kit\Microsoft.Windows.SoftwareLogo.AppxLauncher.exe “AppUserModelId

- The other way is to use the ApplicationActivationManager (https://msdn.microsoft.com/en-us/library/windows/desktop/hh706902(v=vs.85).aspx) which can be used as follows:

uint pid;
var mgr = new ApplicationActivationManager();
mgr.ActivateApplication("[AppUserModelId]", null, ActivateOptions.None, out pid);

This technique relies on getting the AppUserModelId from the following Registry:

HKEY_CURRENT_USER\Software\Classes\ActivatableClasses\Package\**PackageFullName**\Server

The installation process for Store applications on Windows 10 doesn't create this Registry key, which means we need another way to determine the AppUserModelId. I haven't found a definitive way to do this but I did manage to find a way which seems to work. Essentially you need to append "!App" to the package family name of your application (not the package full name).

If you haven't played around with the powershell commands for installing and querying installed packages, it's worth taking a look. For example to get a list of all packages for a particular publisher you can issue the following powershell command:

get-appxpackage -publisher "OID.0.9.2342.19200300.100.1.1=6434210, CN=Built to Roam Pty Ltd, OU=Built to Roam Pty Ltd"

This will return a listing for each application such as the following:

Which, as you can see contains the PackageFamilyName - add "!App" and you have a string that should work as the AppUserModelId, allowing you to launch the application from code.



Visual Studio 2015 RTM and the case of the missing Microsoft Advertising SDK for Windows 8.1

I just got around to upgrading to VS2015 RTM having run the RC since it was available (just as an aside VS2015 has been the only version of Visual Studio that I've been running for quite some time now). And as Murphy's law goes, the first project I open doesn't build and run - OMG what pain do I now need to endure?

It appears that someone has made the decision to remove the Windows 8.1 Advertising SDK (perhaps due to the recent sale of MS advertising assets), which means my Windows 8.1 application is now missing a reference.  According to the Ads in Apps website (http://adsinapps.microsoft.com/en-US/sdk) the SDK is installed in VS2013 update 2 or later (clearly not the case)

Luckily, a bit of searching revealed the SDK available via Visual Studio Gallery at https://visualstudiogallery.msdn.microsoft.com/3d3fa204-0641-4317-ab2c-50092f732edb

Windows Phone 8.1, Microsoft Lumia 640XL and the case of the Virtual Hardware Buttons

The Microsoft Lumia 640 and 640XL were one of the first Windows Phone devices to take advantage of the move to on-screen hardware buttons. Rather than the traditional hardware buttons for Back, Start and Search, these devices have software rendered buttons (note that there were previous devices that had the buttons as part of the same glass as the reset of the screen but this isn't the same as having them rendered in software). There were some that didn't like this move (eg http://www.7tutorials.com/reviewing-microsoft-lumia-640-xl-good-smartphone-business-users) but an nice effect of them being software is that they can be dismissed off the screen. This means that the buttons can be swiped away, leaving more screen available for applications.

The unfortunately thing about this is that because this feature shipped as an update to Windows Phone 8.1 there isn't good support for detecting when the available screen size changes, often leaving applications either with controls rendered under the buttons, or with empty screen space under the content of the application (where the buttons used to reside).

Side note: Rudy Huyn in his post, "How to test my app on phone with navigation bar and why it matters," covers how to use the Windows Phone emulator to test applications for this behaviour.

I spent a bit of time this afternoon trying to work out a workable solution to this. The result was a bit hit and miss but the following seems to work:

In order to take advantage of the full screen I added the following lines to the end of the OnLaunched method in the App.xaml.cs file:

var applicationView = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView();
applicationView.SetDesiredBoundsMode(Windows.UI.ViewManagement.ApplicationViewBoundsMode.UseCoreWindow);

The UX of the screen is very basic - it has a background color so that you can see where the page is being rendered and a textbox at the bottom of the screen so that you can see whether an element has been hidden. Note also that the VerticalAlignment of the page is set to Top. This might seem weird but if you don't, as you adjust the Height of the page in accordance with the visible bounds, you'll see the page rendered in the middle of the screen, which is not what you want.

<Page x:Class="AppBarTest.MainPage"
      xmlns="
http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="
http://schemas.microsoft.com/winfx/2006/xaml"
      VerticalAlignment="Top">
    <Page.BottomAppBar>
        <CommandBar>
            <AppBarButton Icon="Accept"
                          Label="appbarbutton" />
            <AppBarButton Icon="Cancel"
                          Label="appbarbutton" />
        </CommandBar>
    </Page.BottomAppBar>

    <Grid Background="LightBlue">
        <TextBox Text="Testing"
                 VerticalAlignment="Bottom"
                 Margin="0" />
    </Grid>
</Page>

The code for this page is where all the hacking happens - essentially it looks to determine how tall the page should be based on the space occluded by the status bar and the input pane. The trick is to make sure this is called anytime something adjusts the visible bounds available to the app.

public sealed partial class MainPage
{
    public MainPage()
    {
        InitializeComponent();
           
        var appView = ApplicationView.GetForCurrentView();
        appView.VisibleBoundsChanged += VisibleBoundsChanged;
    }

    private void VisibleBoundsChanged(ApplicationView sender, object args)
    {
        ResizeMe();
    }

    private void ResizeMe()
    {
        var statusBar = StatusBar.GetForCurrentView();

        var appView = ApplicationView.GetForCurrentView();
        var input = InputPane.GetForCurrentView();
        var newHeight = appView.VisibleBounds.Height + (statusBar?.OccludedRect.Height) ??
                                0 + (input?.OccludedRect.Height) ?? 0;
        if ((input?.OccludedRect.Height ?? 0) <= 0 || newHeight <
this.Height)
        {
            this.Height = newHeight;
        }
    }

Update: You should also attach an event handler to the Got and Lost focus on the TextBox and invoke ResizeMe otherwise there are some scenarios where the TextBox ends up under the virtual buttons

Visual Studio 2015 RC Crashing when installing packages with NuGet

Just spent half an hour trying to install a nuget package…. everytime Visual Studio 2015 would crash. I figured I mustn't be alone, so I went hunting. Turns out that whilst I had the most recent extension available on the VS Gallery, it wasn't actually the most recent. Anyhow –  if you go here there is a link to an updated vsix file which fixed all my issues.

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