What is new in Windows 8.1 for file access: managing user libraries

August 08, 2013
Windows 8 WinRT File System
 

Libraries continue to play important role in Windows Store app development, even though they are hidden by default in Windows 8.1. Moreover, a new class called StorageLibrary is introduced in WinRT to help managing user libraries.

StorageLibrary provides methods and events to add and delete folders within the libraries, to monitor library changes. It supports Documents, Music, Pictures and Videos libraries. Custom libraries are not supported and apps have to declare corresponding capabilities to access standard libraries.

How to add new folder to Pictures library


// Get StorageLibrary object, throws exception when Pictures library capability isn't declared
StorageLibrary library = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
   
// Ask user to select folder to add
StorageFolder newFolder = await library.RequestAddFolderAsync();

RequestAddFolderAsync() shows a new specialized file picker where users can select folder to add to Pictures library:

Add folder picker

In this case, SkyDrive camera roll folder was selected:

Libraries

How to remove folder from Pictures library

StorageLibrary.RequestRemoveFolderAsync() let applications to remove folders from the libraries. Unlike RequestAddFolderAsync(), RequestRemoveFolderAsync() does not provide any UI. Developers have to implement folder selection logic by themselves, for example by using folder picker or StorageLibrary.Folders.

The following code demonstrates removing of the SkyDrive camera roll folder added in the previous example:


StorageLibrary library = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);

StorageFolder folder = library.Folders.FirstOrDefault(x => x.Name == "SkyDrive camera roll")

if (folder != null)
{
   bool deleted = await library.RequestRemoveFolderAsync(folder);
   // …
}

RequestRemoveFolderAsync method displays the following question:

Remove folder

and removes the folder if action is approved.

Removed folder

Monitoring libraries

Since the selected library can be modifies outside of app (by user or another app), StorageLibrary provides DefinitionChanged event to let applications to track changes in the list of folders.

In addition, StorageLibrary.SaveFolder provides the default save folder for the library.

 

Windows 8.1, where are my Libraries?

July 24, 2013
Windows 8
 

If you are an active user of Windows Explorer Libraries, you will be surprised by the default view of Windows 8.1 Explorer

Windows Explorer

The Libraries section is gone and all the standard folders (Documents, Music, Pictures, etc.) are displayed under This PC. Fortunately, Libraries were not removed from this release of Windows, they are just hidden by default.

To bring Libraries back, open Folder Options dialog (View tab->Options) and select "Show libraries" option – this option is new for Windows 8.1.

Folder Options

It will return back the Libraries section in the Explorer’s navigation pane.

Windows Explorer

 

Documents Library capability and Visual Studio 2013

July 05, 2013
Windows 8 WinRT File System
 

Documents Library capability has been a source of confusion for app developers from the first days of Windows Store. This capability can be easily set through App Manifest editor to enable the app to access user’s Documents library through WinRT API. Although it perfectly works during development, enabled Documents Library capability means almost automatic failure of the Store certification process for the affected app, when the app is submitted using non-company account.

So, look what is missed in Visual Studio 2013 Preview App Manifest UI:

App Manifest

Documents Library capability is gone and all attempts to access this folder will generate exceptions:

Documents Library access

However, this capability is gone just from the UI, you still can open appxmanifest source and manually add the capability. The result will probably be the same as before – failure of certification for individual developers, so you better stay away from this trick. Microsoft strongly recommend against using Documents Library capability, suggesting Folder and File Pickers instead.

 

Displaying About, Settings and other Flyouts using Prism for Windows Store

June 22, 2013
Windows 8 WinRT C#
 

1. Windows Store apps made easy with Prism and Prism project templates
2. Views, ViewModels and navigation
3. Configuring Prism using Unity or Ninject
4. Displaying About, Settings and other Flyouts

Windows Store apps use Flyouts for Login and Settings forms, About dialogs and for displaying other temporary information. While HTML5/JS developers experience the comfort of using native WinJS.UI.Flyout control, XAML developers have to use third-party controls.

Prism for Windows Store provides infrastructure for displaying and managing Flyout dialogs in a simple way.

Register Settings Charm commands

According to the Windows Store design guidance, it is recommended to use Settings Charm for providing access to apps’ setting and About dialog. Apps have to register commands by providing titles and command handlers (a function that will be invoked when command is clicked).

Create a new project using Prism Unity app template and open App.xaml.cs. App’s base class – MvvmAppBase – defines virtual method GetSettingsCharmActionItems and we are going to override it to register About and Settings commands.


sealed partial class App : MvvmAppBase
{
    ...
	
    protected override IList GetSettingsCharmActionItems()
    {
        return new List
                   {
                       new SettingsCharmActionItem("Settings", SettingsCommandHandler),
                       new SettingsCharmActionItem("About", AboutCommandHandler)
                   };
    }

    private void SettingsCommandHandler()
    {
        // TODO
    }

    private void AboutCommandHandler()
    {
        // TODO
    }
}

Registration is done and if you will start the app, you will see two new commands in Setting Charm.

Setting Charm

However, command handlers are still empty and before implementing them, we need to introduce visual elements to show.

Add About dialog

Use Add New Item dialog and add Flyout View with name AboutFlyout to Views folder. The created view is empty and you can modify it to present any information you need. For example, the following code makes it nicer and displays app’s title and version.


<prism:FlyoutView 
	x:Class="FlyoutDemoApp.Views.AboutFlyout"
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	xmlns:prism="using:Microsoft.Practices.Prism.StoreApps"
	xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
	xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
	prism:ViewModelLocator.AutoWireViewModel="True"
	mc:Ignorable="d">

    <Border BorderBrush="{StaticResource FlyoutBorderBrush}"
            BorderThickness="1,0,0,0">
        <Grid Background="{StaticResource FlyoutBackground}">
            <Grid.RowDefinitions>
                <RowDefinition Height="80" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>

            <Grid Background="{StaticResource FlyoutHeaderBackground}">
                <StackPanel Orientation="Horizontal" Margin="40, 32, 0, 13">
                    <Button Command="{Binding GoBackCommand}"
                            Margin="0,3,0,0"
                            Style="{StaticResource FlyoutBackButtonStyle}" />
                    <TextBlock Margin="10,0,10,0"
                               Style="{StaticResource FlyoutHeaderText}"
                               Text="About" />
                </StackPanel>
            </Grid>

            <TextBlock Text="{Binding AppTitle}" Style="{StaticResource CaptionFlyoutTextStyle}" 
                       Grid.Row="1" Margin="40,40,10,10"/>
            <TextBlock Text="{Binding AppVersion}" Style="{StaticResource BasicFlyoutTextStyle}" 
                       Grid.Row="2" Margin="40,0,10,10"/>

        </Grid>

    </Border>
</prism:FlyoutView>

Once the Flyout is ready, we need to create corresponding View Model. Note the bindings in the code above: the target View Model needs to provide GoBackCommand command and properties to display title and version.

View Model

Use Flyout View Model template to create AboutFlyoutViewModel class in ViewModes folder. It will generate the View Model with predefined methods for the Flyout lifetime management.


public class AboutFlyoutViewModel : BindableBase, IFlyoutViewModel
{
    private Action _closeFlyout;
    private Action _goBack;

    public Action CloseFlyout
    {
        get { return _closeFlyout; }
        set { SetProperty(ref _closeFlyout, value); }
    }

    public Action GoBack
    {
        get { return _goBack; }
        set { SetProperty(ref _goBack, value); }
    }

    public void Open(object parameter, Action successAction)
    {
    }
}

The following code introduces fields required for the About Flyout.


public class AboutFlyoutViewModel : BindableBase, IFlyoutViewModel
{
    ...
	
    public ICommand GoBackCommand { get; private set; }

    public AboutFlyoutViewModel()
    {
        GoBackCommand = new DelegateCommand(() => GoBack());
    }

    public string AppTitle
    {
        get { return "Flyout Demo"; }
    }

    public string AppVersion
    {
        get
        {
            var version = Package.Current.Id.Version;
            return String.Format("Version {0}.{1}", version.Major, version.Minor);
        }
    }
}

The ViewModelLocator magic links View and View Model for us, all what we need to do is to show the Flyout.

Command handlers

Return to App class and change AboutCommandHandler to show About Flyout: FlyoutService uses the same convention as ViewModelLocator and NavigationService and automatically discover required type based on the provided Flyout ID.


private void AboutCommandHandler()
{
    FlyoutService.ShowFlyout("About");
}

Now we are done with coding – it is demo time

About Flyout

Described technique can be used to display Setting, Login, Privacy or any other types of Flyouts.

 

Configuring Prism for Windows Store using Unity or Ninject

June 21, 2013
Windows 8 WinRT C#
 

1. Windows Store apps made easy with Prism and Prism project templates
2. Views, ViewModels and navigation
3. Configuring Prism using Unity or Ninject

Manual registration of ViewModels with ViewModelLocator is dull and error prone – you can always forget to register new class or copy-paste incorrect definition.

Fortunately, the configuration process can be automated by using dependency injection container, for example Unity or Ninject.

Setting up Unity

When you are starting a new app, you have an option to create a fully configured Unity-based Prism app. My demo was created using the blank Prism app template and I am going to modify the code to introduce Unity.

First, use NuGet to add Unity to the project, create an instance of UnityContainer in App class.

NuGet Unity


private readonly IUnityContainer _container = new UnityContainer();

Than you can modify OnInitialize() method to register NavigationService in Unity container and override Resolve() function to link Unity with Prism framework.


using Microsoft.Practices.Prism.StoreApps;
using Microsoft.Practices.Unity;
using System;
using Windows.ApplicationModel.Activation;

namespace PrismUnityApp
{
	sealed partial class App : MvvmAppBase
	{
		private readonly IUnityContainer _container = new UnityContainer();

		public App()
		{
			this.InitializeComponent();
		}

		protected override void OnLaunchApplication(LaunchActivatedEventArgs args)
		{
			NavigationService.Navigate("Main", null);
		}

		protected override void OnInitialize(IActivatedEventArgs args)
		{
			_container.RegisterInstance(NavigationService);
		}

		protected override object Resolve(Type type)
		{
			return _container.Resolve(type);
		}
	}
}

That is it. From now on Unity will take care about ViewModels resolution and creation. New pages will not require configuration changes.

Setting up Ninject

To use Prism with Ninject you need the same steps as in case of Unity – add Ninject package, register NavigationService and link container with Prism type resolver.

NuGet Ninject


using Microsoft.Practices.Prism.StoreApps;
using Microsoft.Practices.Prism.StoreApps.Interfaces;
using Ninject;
using Windows.ApplicationModel.Activation;

namespace PrismNinjectApp
{
	sealed partial class App : MvvmAppBase
	{
		private IKernel _ninjectKernel = new StandardKernel(); 

		public App()
		{
			this.InitializeComponent();
		}

		protected override void OnLaunchApplication(LaunchActivatedEventArgs args)
		{
			NavigationService.Navigate("Main", null);
		}

		protected override void OnInitialize(IActivatedEventArgs args)
		{
			_ninjectKernel.Bind().ToConstant(NavigationService);
		}

		protected override object Resolve(System.Type type)
		{
			return _ninjectKernel.Get(type);
		}
	}
}

 

Prism for Windows Store: Views, ViewModels and navigation

June 20, 2013
Windows 8 WinRT C#
 

1. Windows Store apps made easy with Prism and Prism project templates
2. Views, ViewModels and navigation

Previously described application is unrealistically simple. In reality, your apps will include more than one page and you will need some navigation mechanism to help users to browse between these pages.

Adding new pages

In addition to the project templates, Prism extension provides several item templates – Page View, View Model, Model and others.

Extensions and Updates

Use "Add New Item" dialog to add new Page View and View Model to Views and ViewModels folders correspondingly. Name them DetailsPage and DetailsPageViewModel.

Extensions and Updates

Next step is to set new DetailsPageViewModel as a data context for the DetailsPage. You can setup context manually, but Prism provides a handy ViewModelLocator class to do it semi-automatically. Why not fully automatically? Because you still need to setup ViewModelLocator.AutoWireViewModel property for DetailsPage.


<prism:VisualStateAwarePage 
    x:Name="pageRoot"
    x:Class="PrismApp.ViewModels.DetailsPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:PrismApp.ViewModels"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:prism="using:Microsoft.Practices.Prism.StoreApps"
    mc:Ignorable="d"
    prism:ViewModelLocator.AutoWireViewModel="True">
    
    ...

</prism:VisualStateAwarePage>

How it works

For wiring Pages with ViewModels Prism framework uses a convention over configuration approach. Class names as well as Views and ViewModels folders are parts of this convention.

By setting AutoWireViewModel for DetailsPage to true we instruct ViewModelLocator to search DetailsPageViewModel in ViewModels folder. If such class is found, Prism will construct it and use as a data context for the DetailsPage.

Sounds logical, but let us look at the DetailsPageViewModel code.


using Microsoft.Practices.Prism.StoreApps;
using Microsoft.Practices.Prism.StoreApps.Interfaces;

namespace PrismApp.ViewModels
{
    public class DetailsPageViewModel : ViewModel
    {
        private INavigationService _navigationService;

        public DetailsPageViewModel(INavigationService navigationService)
        {
            _navigationService = navigationService;
        }
    }
}

The class does not have default parameterless constructor, will Prism be able to construct the object? Actually no: if you will try to run the code as it is, ViewModelLocator will throw an exception telling us that an appropriate constructor was not found.

As you may expect, there is a way to instruct Prism which constructor to use. We can override App. OnInitialize method and properly configure ViewModelLocator.


using Microsoft.Practices.Prism.StoreApps;
using PrismApp.ViewModels;
using PrismApp.Views;
using Windows.ApplicationModel.Activation;

namespace PrismApp
{
    sealed partial class App : MvvmAppBase
    {
        public App()
        {
            InitializeComponent();
        }

        protected override void OnLaunchApplication(LaunchActivatedEventArgs args)
        {
            NavigationService.Navigate("Main", null);
        }

        protected override void OnInitialize(IActivatedEventArgs args)
        {
            ViewModelLocator.Register(typeof(MainPage).ToString(), 
                                      () => new MainPageViewModel(NavigationService));
            ViewModelLocator.Register(typeof(DetailsPage).ToString(), 
                                      () => new DetailsPageViewModel(NavigationService));
        }
    }
}

Navigation

With the object provided in constructor and implementing INavigationService interface, navigation is easy.


using Microsoft.Practices.Prism.StoreApps;
using Microsoft.Practices.Prism.StoreApps.Interfaces;

namespace PrismApp.ViewModels
{
    public class MainPageViewModel : ViewModel
    {
        private INavigationService _navigationService;

        public MainPageViewModel(INavigationService navigationService)
        {
            _navigationService = navigationService;
        }

        public void GoToDetails()
        {
            _navigationService.Navigate("Details", null);
        }

        ...
    }
}

Navigation service use the same Views/ViewModels convention as ViewModelLocator. First parameter in Navigate() function defines target page name, service constructs full class name by adding "Page" suffix. Second parameter allows you to pass some data to the next page.

This concludes Prism Views and ViewModels discussion. Next post will talk about additional configuration techniques.

 

Windows Store apps made easy with Prism and Prism project templates

June 19, 2013
Windows 8 WinRT C#
 

Prism library from Microsoft patterns & practices team is well known among WPF and Silverlight developers. It provides guidance for developing maintainable client software, helps with MVVM pattern implementation and facilitates good design practices, such as separation of concerns and loose coupling.

Recently, P&P team presented a version of Prism for Windows Runtime. This version of Prism is mainly focused on MVVM, navigation and app lifecycle management. Optimized for WinRT, it also supports such Windows 8-specific features as setting and search flyouts.

The following steps will help you to start Windows Store app development using Prism library.

Where to get started

Prism for Windows Runtime is available as a NuGet package (Prism.StoreApps), but there is a simpler approach for starting - use Prism project templates. Prism project templates is a separate product developed as by a third-party developer and distributed as a VisualStudio extension.

Install Prism project templates

From Tools menu open "Extensions and Updates" dialog and search online for Prism for the Windows Runtime Templates, install it.

Extensions and Updates

New Project

Installed extension adds two new project templates:

  • Prism App
  • Prism App using Unity.

New Project

Select Prism App to create single-page Windows Store app configured to use Prism. It will include the following pieces:

  • App class derived from Prism’s MvvmAppBase
  • MainPage with VisualStateAwarePage as a base class
  • MainPageViewModel with pre-configured navigation service

Project

For simple app this is it. ViewModel implements INotifyPropertyChanged interface and is automatically wired with View using ViewModelLocator.AutoWireViewModel property:


<prism:VisualStateAwarePage
    x:Class="PrismApp.Views.MainPage"
    xmlns:prism="using:Microsoft.Practices.Prism.StoreApps"
    prism:ViewModelLocator.AutoWireViewModel="True"
    ... >
...
</prism:VisualStateAwarePage>

Therefore, you can start populating ViewModel with data and presenting it on View. For example


public class MainPageViewModel : ViewModel
{
    private string _title;
    public string Title
    {
        get { return _title; }
        set { SetProperty(ref _title, value); }
    }

    ...
}

However, not all Store apps are so simple and the following posts will demonstrate you more advanced features of Prism.

 

My DevTeach presentation slides

June 02, 2013
async .NET C# Talk Windows 8 WinRT
 

Last week I had the pleasure to present my “Deceptive simplicity of async and await” talk at DevTeach 2013. This year DevTeach celebrates 10th anniversary and I am proud to be part of this milestone.

Abstract: Understanding of asynchronous model is an essential knowledge for development of quality Windows Store apps. This session dives deep into implementation details of async and await C# keywords and provides information about common pitfalls and mistakes of async pattern use and the ways to avoid them.

Slides are available on SlideShare

 

Using Open Data in mobile apps: lessons learned

April 06, 2013
Windows 8 Practices Open Data
 

What is Open Data and why to use it?

Open Data is any information the government agencies and municipalities collect for their own needs but then offer for others to use. Open Data is usually available in machine-readable formats and can be used as it is or be a part of third party solutions, including commercial products.

By using Open Data or combining different sources of data, developers can enrich functionality of their mobile and Web applications. For example, food safety inspection results can be used by dinner planning app to provide better recommendation about restaurants to visit.

While all good practices for working with remote data sets are relevant for Open Data as well, there are some specifics, as I learned developing my Open Data apps for Windows Phone and Windows 8.

Importance of data caching

Cache for Open Data is not just a traffic saver for users on metered networks, but also a way to improve app’s usability. By displaying cached data first and downloading (and then presenting) most recent data asynchronously, startup time for app can be reduced significantly.

Most of Open Data sources have well defined update interval, for example daily, every Thursday, etc. Knowing these intervals, developers can tune cache lifetime to minimize unnecessary data requests.

To simplify building of network-optimized Windows 8/Windows Phone apps developers can use already existing libraries, like AgFX or Akavache.

Speaking of data caching and updating, an important point to remember is the modern app lifecycle. Mobile application can stay suspended for days and when app is resumed this is developer’s responsibility to update UI if new data is available.

Error handling

Most of the times, government and municipal Open Data services are quite reliable. However, if they are down and application is not able to retrieve new data, it should not result in application crash. Instead, application can use cache to display last available information and notify user about temporary unavailability of the service.

Application should indicate whether data is outdated and when it was retrieved.

Complex data sources

When application works with multiple data sources, custom Web or Cloud server can be used to merge or correlate data and expose it through simplified Web API. Same approach is useful when data is published in form of Excel or Word documents – parsing files on server and exposing data via HTTP.

Obviously, publishing of Excel files is the easiest approach for data owners, but it adds unnecessary complexity for data consumption by mobile apps. When necessary data is published as Excel spreadsheet only, developers should try to contact corresponding Open Data curators and request data in alternative formats.

Licensing

Open Data is free to use and usually licensed with just a few conditions. These conditions may vary from agency to agency bust the most common requirement is to acknowledge data source by providing some statement like “Contains public sector Datasets made available under the City of Toronto's Open Data License”.

This statement presented in your app rises citizens’ awareness about Open Data initiatives and increases chances of publishing additional datasets, so make it visible!

 

Building Secure Windows Store Apps

March 19, 2013
Windows 8 Practices
 

Application security is a topic of continuous interest and attention. Modern applications are expected to be robust, predictable and respectful of users’ privacy. To help developers build safer Windows Store apps, several new security features have been added to Windows 8 and Visual Studio 2012.

However, while these new features reduce some security risks, it is important for developers to understand and follow the best practices for working with sensitive data and for intellectual property protection.

Read my post exploring the best security practices and new security features of Windows 8 on Canadian Developer Connection blog: http://blogs.msdn.com/b/cdndevs/archive/2013/03/19/building-secure-windows-store-apps.aspx