Windows 8.1 and Visual Studio 2013–Blank Template Explorations

In order to start getting myself feeling “comfortable” with Visual Studio 2013 from the point of view of developing Windows Store apps, I thought I’d make a quick blank project.

Where better to start than “Hello World” to figure out your surroundings? So, I took two machines – one running VS 2012 and one running VS 2013 and had a quick look to see if I could spot differences on something as “simple” as the blank project template.

In creating my first app I came across the new “Hub Project” template and also the new “Coded UI Test” project template;

image

so, clearly, that needs some digging into and there’s a BUILD 2013 video around the idea of the Coded UI Test support in Visual Studio 2013 which I had a look at previously but there’s a lot more digging there that I could do.

Beyond there, I ended up with a blank project that looked pretty much like the one from VS 2012 (as you’d expect) but I did notice a few differences along the way.

Manifest Changes

I noticed a few differences in the manifest editor in Visual Studio. The first one of those is the new setting for a “Minimum Width” for the application. This is the change that comes in from Windows 8.1 apps not making use of “Snap View” as Windows 8.0 apps did. I’ll follow up with more on this but, essentially, you now specify a minimum width for an app that’s either 500 pixels (default) or 320 pixels ( like snap view ) and that shows up in the manifest editor;

image

Another new feature which I’ll again follow up on is an addition to what we already had in Windows 8.0 with respect to updating Live Tile information by having the system poll a URL on some interval. In Windows 8.0, there’s an API that allows your application to programmatically tell the system to update a particular tile every so often by downloading new XML content from a URL. That’s detailed up here on MSDN but there’s a bit of a downside in that this can only be triggered from code so if the user isn’t enticed to run your application then you can’t run the code to update the tile to entice them to run your application!

In Windows 8.1, it’s possible to set this up declaratively as part of the application package’s installation rather than having to run code to set it up. There’s a slot for this in the manifest;

image

and it looks like you can pass {language} and {region} tokens but I’d imagine that there are scenarios where you need more than this in the sense that you probably want to build up a polling URI which has some unique piece of identify information about the user built into it. For that scenario, you’re presumably still going to have to write code but I’ll revisit this feature in a follow on post.

The other thing that stands out on this screen as being different from VS 2012 is the option around providing tile/badge UI. 2012 had this layout for the UI pieces;

image

but, as we know from BUILD 2013 session “Alive with Activity- Tiles, Notifications, and Background Tasks” there’s a new, large tile size in Windows 8.1 and so VS 2013 Preview has some additional slots for this;

image

and so now there’s a 310×310 tile size. It’s also worth flagging the “Scale 80” image size there as well even though it shows up in both VS2012 (update 3) and VS2013 Preview I don’t think that scale factor of 80 was around when Windows 8.0 first shipped – it arrived later. I notice on my XPS 12 if I set the resolution of my display down to 1024×768 then the Start Screen uses that 80% scale image for my tile based on the DPI that I’m getting. The docs for this don’t look to have yet been updated to talk about the 80% scaling factor and what particular threshold of DPI causes it to kick in but it’s there and happening.

I didn’t spot anything obvious that’s been added to the “Capabilities” tab of the manifest but there are definitely changes within the “Declarations” area depending on what you’re declaring your app to do. For example, if I state that my app can do sharing as a target of operations;

image

then there’s a new piece of UI that gets displayed by the system when someone tries to share to this app;

image

and so there are going to be some changes in that area of the manifest editor and I think this specific change is mentioned in the BUILD 2013 session about getting apps to work together.

I didn’t notice any other changes inside of the app manifest but I’m sure that there will be some that I missed.

Debugging Changes

One thing I definitely noticed in just exploring the manifest above is that when I hit F5 inside of Visual Studio 2013 to install and debug my new app a couple of new things happened.

Firstly, Windows 8.1 does not automatically put newly installed applications onto the Start Screen. So, whereas in Visual Studio 2012 I was used to making a new app and then hitting F5 and panning to the end of the Start Screen (usually to move the app all the way back to the start of the Start Screen) I now find I have to go off into the “All Apps” view and find my app in there and then pin it to the Start Screen manually. No big deal.

The next thing I noticed made me feel like I might have arrived on Windows Phone. It looked like my app suddenly grew some performance counters in the top left and top right of the screen. I changed my background colour to red and had a look – here’s the top left;

image

and up in the top right I have frame rate counters. For a moment, I thought that these related to the debugger but in fact it’s more a reflection of a change in the template such that App.xaml.cs includes a little line of code;

  1. #if DEBUG  
  2.             if (System.Diagnostics.Debugger.IsAttached)  
  3.             {  
  4.                 this.DebugSettings.EnableFrameRateCounter = true;  
  5.             }  
  6. #endif 
 

which switches on the framerate counter by default.

There are many more debugging changes in Visual Studio 2013 Preview but I didn’t encounter them in running my blank app.

One thing I will say though is around stopping debugging. I usually close applications by swiping from the top of the screen to the bottom. In Windows 8.0 this would close the app and, sure enough, around 10 seconds later you’d see Visual Studio come out of debug mode and back into whatever the mode is called that isn’t debug mode (‘regular mode’).

On Windows 8.1, this doesn’t work (by design). If you drag an application from the top of the screen down to the bottom it won’t close. To really close it you have to hold it in position at the bottom of the screen until it spins around and the app’s logo is displayed.

I find this one a bit ‘odd’ but then I’m perhaps not thinking like a regular user. If I go and run my app (without the debugger) and then close it by dragging it to the bottom of the screen (like Windows 8.0) then I can see in Task Manager;

image

that my app is still running long after I performed the gesture although the app is suspended. The app doesn’t appear in ALT+TAB or WINDOWS+TAB so from a user’s perspective it’s gone but the process is still there and so if I was debugging it then the debugger remains attached.

The app is doing a suspend/resume rather than a terminate/launch in response to this gesture on Windows 8.1.

If I want to actually close the app down I have to drag the app to the bottom of the screen and then hold for a moment until the app’s logo appears and then the app seems to exit and the Visual Studio debugger comes back to me after around 10 seconds or so. Alternatively, maybe I’ll just get used to hitting ALT+F4 or ending the session from Visual Studio itself.

There are tonnes more changes in Visual Studio’s debugger for Windows Store Apps – some initial posts that are good to follow through on are below;

Code Editor Changes

As I was navigating around the blank template, I did notice some changes to the code editor. There are lots of these changes and I don’t think that I’ve come across them all yet but I noticed that the magic mapping scrollbar is back (if you right mouse and turn it on);

image

and I also wanted to try out “Peek Definition” – I can remember quite a few years ago talking about the introduction of the “Code Definition” window in Visual Studio and I always kind of liked it but it was perhaps a bit intrusive and especially in recent times when I’ve sometimes been working on smaller screens.

I do like “Peek Definition” though. There’s not much code to try it out with in a blank project but I can just pick out a symbol, hit ALT+F12 and peek that definition inline;

image

and what’s really nice is that I can go crazy and continue that navigation into more symbols – e.g. maybe I’m now curious as to what the heck an AppBar is having spotted that a Page has a BottomAppBar;

image

and those little radio buttons circled towards the top right me cycle back/forth between the Page definition and the AppBar definition.

The other thing that I noticed while navigating this blank project was the CodeLens features telling me (in my case) about what references are made to a particular class/member but there’s quite a lot more to CodeLens and it looks pretty cool in a team environment (I think it’s a VS Ultimate only feature though). There’s more info at;

CodeLens Features – http://msdn.microsoft.com/en-us/library/dn269218(v=vs.120).aspx

but, for me, in this particular project I’m seeing what references are made to a particular symbol – e.g.;

image

and I can hover and then navigate to those references;

image

There are lots more code editor changes – these are just the ones I sought out and/or encountered while looking at this project although I’ll probably encounter some more as I flick further through the template…

Template Changes

There’s not meant to be a whole lot in a blank application template but, even so, there are a few changes between the VS2012 template and the VS2013 ones. Here’s the 2 project structures side-by-side with VS2012 on the left and VS2013 on the right;

imageimage

Not a whole lot of difference there except the Assets have been named to follow the scaling convention in the VS2013 project. The other thing to notice is that the references are to different versions of .NET and WinRT;

image

image

and the other noticeable difference is that the Common folder has gone and with it so has StandardStyles.xaml. If you’ve been following this story you’d know that StandardStyles.xaml on Windows 8.1 was a place where (in every single project) you’d find a tonne of styles that were used (or could be used) in the project. Styles like BasicTextStyle, HeaderTextStyle and so on.

You’d find that those styles depended on brushes and the like which weren’t actually defined in StandardStyles.xaml. Brushes such as ApplicationForegroundThemeBrush and those came from a single place in the system somewhere over in the equivalent of “C:\Program Files (x86)\Windows Kits\8.0\Include\Winrt\Xaml\Design\generic.xaml”.

I always found this a bit odd – here was what seemed like a different approach being taken to two files that seemed to have similar purposes and it felt to me almost as though the templates were saying “Hey, you can hack around with StandardStyles.xaml if you like but don’t mess with generic.xaml”.

I never did. I never altered StandardStyles.xaml (other than perhaps to uncomment some of the styles that were commented out) and, instead, just used the styles that were present there or based styles on them.

Regardless, that file is gone in the VS2013 project. But if I look into a XAML file like MainPage.xaml

image

and if I was to hack the XAML temporarily I can still use a style like HeaderTextBlockStyle;

image

It’s not going to be visible on the screen but I find that as I type XAML into that editor for possibly the first time ever it feels like I am typing at my usual typing speed (I type quite quickly) and Visual Studio does not seem to be lagging behind as it tries to provide some form of IntelliSense on my XAML. Does this scale to big XAML files? No idea at the moment but it feels very different in this “Hello World” blank template example.

The other thing (which I have highlighted on the screen) is that I get IntelliSense on looking up my static resources here. That is – you can see that I’m getting auto-complete on the HeaderTextBlockStyle so Visual Studio clearly knows that I’m looking for a StaticResource and it’s clearly parsed the available resource files and is giving me the right set of options. That’s very nice and, although I haven’t got to it yet, I think the editor can also do more in this area like providing completion on data-bindings (where the editor can see the shape of the object providing the DataContext).

There’s an article on XAML editor improvements up on the Visual Studio Blog;

XAML Editor Improvements in Visual Studio 2013

and I’d particularly welcome the inclusion of XAML code snippets (I can see that being particularly useful for shortening long demos) – I was a bit surprised to see that there’s no code-snippets yet packaged in Visual Studio 2013 so I thought I’d try one out and made a quick “Grid” snippet;

  1. <CodeSnippets 
  2.     xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet&quot;> 
  3.     <CodeSnippet Format="1.0.0"> 
  4.         <Header> 
  5.             <Title>Basic Grid</Title> 
  6.         <Shortcut>grid</Shortcut> 
  7.             <SnippetTypes> 
  8.                 <SnippetType>Expansion</SnippetType> 
  9.             </SnippetTypes> 
  10.  
  11.         </Header> 
  12.         <Snippet> 
  13.             <Code Language="Xaml"> 
  14.                 <![CDATA[  
  15.             <Grid>  
  16.                 <Grid.RowDefinitions>  
  17.                 </Grid.RowDefinitions>  
  18.                 <Grid.ColumnDefinitions>  
  19.                 </Grid.ColumnDefinitions>  
  20.             </Grid>  
  21.         ]]> 
  22.             </Code> 
  23.         </Snippet> 
  24.     </CodeSnippet> 
  25. </CodeSnippets> 

which worked out ok – I’m not sure there’s any way to repeat something in a snippet so I guess I’d probably also write a simple “gridrow” and “gridcol” snippet and then I could create grids pretty quickly from the editor.

Going back to that HeaderTextBlockStyle style that I was using, that article highlights another very nice new feature that I can use from the editor which is “go to definition” in XAML files for resources (and also for bindings, properties and so on). If I go and double click on the HeaderTextBlockStyle to highlight it and then right mouse;

image

Then I can do a “Go To Definition” from here to find out where that resource is located and Visual Studio opens up generic.xaml and I can see that here’s the definition of the style (in one place rather than in every project that uses it);

image

and I can see that this is defined near the bottom of the file ( from the map scrollbar on the right ) and I can also see that this style is BasedOn another style called BaseTextBlockStyle so, of course, I can go and hit an F12 on that and jump to the definition of that style and so on. I’m very glad to see VS picking this sort of thing up.

That generic.xaml file is coming from the same place as it was for a Windows 8.0 application with, as you’d expect, the 8.0 part of the file path replaced with an 8.1 path instead.

I wanted to see how smart this might be so I wrote myself a little class;

    class MyClass
    {
        public MyClass()
        {

        }
        public Brush MyBrush { get; set; }
    }

and then defined one of these as a resource in my XAML file;

    <Page.Resources>
        <local:MyClass x:Key="myKey">
            <local:MyClass.MyBrush>
                <SolidColorBrush Color="Red"/>
            </local:MyClass.MyBrush>
        </local:MyClass>
    </Page.Resources>

and then highlighted the MyBrush property in the editor;

image

and then hit F12 and Visual Studio jumped to the property in the code in exactly the way that I hoped it might. A fairly simple test so I wondered whether I could take that a step further and try “peek definition” here. Could I do ALT+F12 to see that definition inline? The answer seemed to be “no” so maybe that’s not possible when you’re in the XAML editor and you’re asking the C# editor to peek itself onto the screen and start showing a definition?

Back to The Template Changes

It’s easy to get distracted here so back to the template changes. I see no difference in the App class built by App.xaml and App.xaml.cs other than there’s no longer an inclusion of StandardStyles.xaml and the only difference I see between MainPage.xaml and MainPage.xaml.cs is that in the VS2012 project template an empty override for OnNavidatedTo seemed to be included in the template whereas on Visual Studio 2013 it doesn’t look to be.

Adding a Basic Page

Usually I’ve built Windows 8.0 apps by starting from the blank application template and then adding various pieces to it as/when I’ve needed them. Quite often I’ve added pages to the project by using the “Add New Item” dialog box and choosing to add basic pages.

image_thumb33

I thought I’d do that in both the VS2012 edition and the VS2013 Preview edition and see what the changes are there because it brings in a bunch of extra code that wouldn’t otherwise be present in the blank project template (although it is present in the other templates like grid and so on).

I did this for both VS2012 and VS2013 Preview and in the preview I noticed a new option that can be added to a project;

image_thumb35

I’d like to know more about that so I’ll return to it in a later post but going back to adding a basic page to each project there’s a couple of differences. To support a new basic page, Visual Studio 2012 adds these files to my project;

image_thumb36

and Visual Studio 2013 adds these;

image_thumb37

The most obvious thing here is that some things appear to have gone;

  • BindableBase – this is an implementation of INotifyPropertyChanged and I’m not 100% sure why VS2012 added it when you added a basic page because I’m not sure that it was used at all by the basic page or any of the dependencies.
  • LayoutAwarePage.cs – this was a class derived from Page which did some bits and pieces to drive state transitions for things like snapped states. Your newly added basic page then derived from this but the way in which this kind of view management is done has changed in Windows 8.1 and so the templates have also changed and LayoutAwarePage is no longer included. It’s worth saying that this class had a private, ObservableDictionary class within it.
  • RichTextColumn.cs – not 100% sure why Visual Studio 2012 included this because, again, I can’t find any dependency on it from the basic page.
  • BooleanNegationConverter – this is a fairly standard converter and, again, I can’t find any dependency on it from the basic page.

In the VS 2013 project the ObservableDictionary class has come across in its own source file but we have a couple of new bits – the RelayCommand and the NavigationHelper. I thought I’d try and unpick the basic page to see how these work in 2013 rather than trying to do a line-by-line difference with 2012.

Firstly, the RelayCommand is just an implementation of ICommand so there’s nothing too magical going on there and the XAML of the basic page (as below) uses binding to set up a Command on an AppBarButton so that’s perhaps why bringing in this page now needs some implementation of ICommand (would be nice to see one in .NET given that we’ve been using this for many years now).

Opening up that BasicPage1.xaml I find;

<Page
    x:Name="pageRoot"
    x:Class="App1.BasicPage1"
    DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:common="using:App1.Common"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Page.Resources>
        <common:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
        <!-- TODO: Delete this line if the key AppName is declared in App.xaml -->
        <x:String x:Key="AppName">My Application</x:String>
    </Page.Resources>

    <!--
        This grid acts as a root panel for the page that defines two rows:
        * Row 0 contains the back button and page title
        * Row 1 contains the rest of the page layout
    -->
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.ChildrenTransitions>
            <TransitionCollection>
                <EntranceThemeTransition/>
            </TransitionCollection>
        </Grid.ChildrenTransitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="140"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!-- Back button and page title -->
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="120"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <AppBarButton x:Name="backButton" Icon="Back" Height="95" Margin="10,46,10,0"
                          Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageRoot}" 
                          Visibility="{Binding IsEnabled, Converter={StaticResource BooleanToVisibilityConverter}, RelativeSource={RelativeSource Mode=Self}}"
                          AutomationProperties.Name="Back"
                          AutomationProperties.AutomationId="BackButton"
                          AutomationProperties.ItemType="Navigation Button"/>
            <TextBlock x:Name="pageTitle" x:Uid="APP_TITLE" Text="{StaticResource AppName}" Style="{StaticResource HeaderTextBlockStyle}" Grid.Column="1" 
                       IsHitTestVisible="false" TextWrapping="NoWrap" VerticalAlignment="Bottom" Margin="0,0,30,40"/>
        </Grid>
    </Grid>
</Page>

I don’t think this is a change from VS 2012 but I must admit that I do find the way in which the DataContext is being set for this Page to be a bit unusual. Instead of setting the DataContext property for the page to be an instance of a view model, we data-bind the DataContext value to a property on page itself called DefaultViewModel. It feels a bit like swapping one property value for another property value. Regardless, bindings will be resolved by digging into the Page.DefaultViewModel unless a more local DataContext is defined.

For a page called “basic page” I tend to think that this RelativeSource=Self binding is a bit esoteric – it’d be more usual to me to define a separate ViewModel class and put an instance of that as the DataContext.

Looking at the code behind file, the DefaultViewModel property is set up to point to an instance of ObservableDictionary so whether you’d go via this route would depend on whether you want to put a strongly typed ViewModel into the DataContext or whether you like this idea of pulling values from a dictionary.

For me, I’d prefer the strongly typed view model approach and I somewhat wish that Visual Studio would do more to steer and provide tooling for this along perhaps with help for managing those ViewModels and their data through the suspend/resume lifecycle management that needs to happen in a Windows 8 Store app. The PRISM framework does some of this and something similar (or even PRISM itself) would be a great addition to the default templates/framework (in my opinion Smile).

Then there’s the resources section that wants to define a resource called AppName with a comment telling you to remove it if this is already defined. I’d probably prefer to have that name stored in a string constant that is then referenced from the XAML and I find it odd that neither the blank nor the grid template (and possibly none of the others) come with some minimal set of string resources set up for the developer to use. I’ll return to that in a follow on post as it’s something that I think the Windows Phone project system does nicely for you but the Windows Store project system seems to skirt around a little.

There’s then a TextBlock which is going to display that AppName resource with a particular style.

Finally, there’s an AppBarButton whose Command is bound to NavigationHelper.GoBackCommand and that binding is connected via ElementName where the named element is the Page itself. The Visibility of that button is bound to the AppBarButton’s own IsEnabled property so that the button appears/disappears when the Command returns true/false from its CanExecute property.

I’m not sure on that binding. It’s saying that the BasicPage class needs to have a NavigationHelper property on it which has an ICommand property named GoBackCommand. Does this belong on the page?

The NavigationHelper is a new class that wasn’t present in the VS 2012 templates and it works with the SuspensionManager which was. The code-behind file for a basic page does a few things;

  1. Initialises the BasicPage1.DefaultViewModel to be an empty ObservableDictionary. This is going to act as the DataContext for the whole page as discussed above.
  2. Creates a new NavigationHelper instance and makes it available via the BasicPage1.NavigationHelper property.
  3. Wires up NavigationHelper.LoadState and NavigationHelper.SaveState event handlers to empty handlers on the BasicPage1 class. Those handlers are passed navigation parameters and some Dictionary<string,object> into which to store/retrieve state values.
  4. Overrides OnNavigatedTo and OnNavigatedFrom and delegates them by calling methods with the same name (and arguments) on the NavigationHelper class.

So we have a Frame and the Frame navigates to a Page and the Page then has a NavigationHelper which looks like;

image_thumb39

and so the NavigationHelper can answer questions like CanGoBack but it does it by asking the Frame. It also takes responsibility for handling key/mouse input that is requesting forward/backward navigation by passing those on to the Frame as well. The NavigationHelper needs telling as a page is navigated to/from and in those methods it talks to the SuspensionManager to reserve, load, save state for the page. It also fires events back into the Page to ask it to load/save state (which I find a bit circular).

The whole process is likely to run something like this;

  1. App starts up, creates its Frame and registers it with the SuspensionManager. SuspensionManager reserves a slot in its dictionary for the Frame and stores the details of that slot back on the Frame itself in a dependency property. It also adds the Frame to a list so that it can get back to it. One thing to say here is that this all seems to be based around the idea that an app may have many Frames but I wonder how many apps actually do?
  2. App navigates to BasicPage1. This page creates a NavigationHelper at construction time and as the page is OnNavigatedTo it calls the NavigationHelper.OnNavigatedTo to let the NavigationHelper know what’s going on.
  3. The NavigationHelper.OnNavigatedTo fires its LoadState event either passing the navigation parameter and either a null state dictionary or, in the case where the page has been navigated to previously and has already saved items into a state dictionary that dictionary will be passed back to the page.
  4. The LoadState handler in the page fires and it sets itself up from the navigation parameter and potentially from the state dictionary passed to it as well.

The step I find a bit odd in there is Step 2. The Page tells the NavigationHelper that it is being navigated to so the NavigationHelper then fires an event back into the same page to tell it to load its state? I might be missing something but it feels a bit complex to me.

At some point, the page is likely to be navigated away from either by the user or it can be caused by the app being suspended which involves the SuspensionManager walking its list of Frames and grabbing state for them including their navigation history. Either way;

  1. The Page.OnNavigatedFrom will be called which will call the NavigationHelper.OnNavigatedFrom which will fire an event back into the page asking it to SaveState.
  2. The Page will store its state information into the dictionary passed to it.
  3. In the case of a suspension, the SuspensionManager will persist that out to disk ready for restore at a later point (or, at least, it will if someone remembers to call SuspensionManager.SaveAsync() at the time of suspension – there’s a blank OnSuspending handler in App.xaml.cs setup for you to do just that).

I’m not sure whether I’d make use of some/all of this approach if I was trying to keep code out of my Views and also keep my Views and ViewModels so that they have no particular dependency on each other. I’d have to think a little around whether I would be able to make use of the NavigationHelper without adding something to it like PRISM does with its INavigationAware ViewModels which allows for those ViewModels to participate in picking up navigation parameters and also saving/restoring state at the point of suspend/resume.

The “problem” for me with this approach is that we have a lot of classes with knowledge of the Frame (i.e. the Page, the NavigationHelper and the SuspensionManager) and also a generic ViewModel is not going to be able to easily get hold of a NavigationHelper instance if it wants to drive navigation.

Closing

That’s a quick look around the blank XAML template in Visual Studio 2013 Preview – mostly using it as a way of talking about other new things as part of navigating around the template. It turned out to be a lot more involved than I was expecting with lots of diversions along the way – I’ll also poke around in the updated Grid template before moving on to other things including some of the topics that dropped out as part of writing this post.