Using Caliburn Micro with Universal Windows app – Binding and actions

In the previous post we’ve learned how to properly set up Caliburn Micro in a Universal Windows app. In this post we’re going to recap all the most important naming conventions that can be used to connect our data to the user interface.

Connecting a property in the ViewModel to a control in the View

The simplest way to connect a property in the ViewModel to a control in the View is using binding. Let’s say you have a ViewModel defined in the following way:

namespace CaliburnDemo.ViewModels
{
    public class MainPageViewModel : PropertyChangedBase
    {
        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                NotifyOfPropertyChange(() => Name);
            }
        }
    }
}

You can notice two things:

  • PropertyChangedBase is the simplest class offered by Caliburn Micro to support the propagation of properties: this way, every time we change the value of the property in the ViewModel, the control that is placed in binding with the property will update its visual layout to reflect the changes.
  • NotifyOfPropertyChange() is the method to call to propagate the change to the UI.

You can connect the property Name to the View using the standard binding approach, like in the following sample:

<TextBlock Text="{Binding Name}" />

Otherwise, you can use the Caliburn Micro naming conventions, which requires to give to the control (using the x:Name property) the same name of the property in the ViewModel you want to connect. In the previous sample, you would have simply defined the TextBlock control in the following way:

<TextBlock x:Name="Name" />

When you use this naming convention, automatically the property called Name in the ViewModel will be bound to the Text property of the TextBlock control. In addition, it will be a two-way binding and every change of the source will be reflected to the target and vice versa immediately. This means that if you’re using a TextBox, for example, every time the user presses a key the updated string will be sent to the ViewModel.

Performing an action

Another common scenario while developing a Windows app is performing an action: for example, the user presses a button and you want to perform an operation. In MVVM, this is typically achieved using commands, which are a way to define an action without being constrained by using the events exposed by the control. Event handlers, in fact, can be managed only from in code behind: you can’t subscribe, for example, to the Click event exposed by a button in a class different than the code behind one (like a ViewModel).

Caliburn Micro offers a simple naming convention to achieve this result: give to the control the same name of the method that is defined in the ViewModel.

Let’s say that you have a Button control which is defined in the following way:

<Button Content="Conferma" x:Name="Confirm" />

Since the name of the control is Confirm, when it’s pressed it will trigger a method with the same name defined in the ViewModel, like in the following sample:

public void Confirm()
{
    Greetings = string.Format("Hello, {0}!", Name);
}

One of the features offered by the command approach is that you’re able to define if the action can be executed or not; the cool thing is that the control that is connected to the action will automatically change its visual status accordingly. The most common example is a page that acts as a form, that the user can fill: until all the fields are filled, the button to send the form should be disabled.

This goal is achieved by creating a boolean property in the ViewModel, which name should be the same of the method plus the prefix Can. In the previous example, to control the method Confirm() we need to create a property called CanConfirm, which should return true or false, based on the condition we need to manage.

For example, let’s say that if the Name property is empty, the action should be disabled. We can achieve this result by defining the CanConfirm property in the following way:

public bool CanConfirm
{
    get { return !string.IsNullOrWhiteSpace(Name); }
}

There’s just one thing missing: every time the Name property changes, we need to evaluate again the CanConfirm property. We can achieve this result simply by calling the NotifyOfPropertyChange()  also for the CanConfirm property every time the value of the Name property changes, like in the following sample:

private string name;
public string Name
{
    get { return name; }
    set
    {
        name = value;
        NotifyOfPropertyChange(() => Name);
        NotifyOfPropertyChange(() => CanConfirm);
    }
}

This way, as soon as the Name property is not empty, the Button control that is connected to the Confirm() method will be enabled; otherwise, it will stay in the disabled state.

One of the best new features in Windows Phone Store apps is that now the Application Bar (managed using the CommandBar control) fully supports binding: this means that you can use the same exact naming convention also with the AppBarButton control, like in the following sample:

<Page.BottomAppBar>
    <CommandBar>
        <CommandBar.PrimaryCommands>
            <AppBarButton Icon="Accept" Label="Confirm"
                         x:Name="Confirm" />
        </CommandBar.PrimaryCommands>
    </CommandBar>
</Page.BottomAppBar>

 

Since the name of this button is Confirm, the method with the same name defined in the ViewModel will be called when the user will tap it.

Advanced actions management

The previous naming convention works fine when it comes to manage the standard command connected to the control, like the Click event for a Button. But what if you need to manage some extra events? Let’s say, for example, that you want to manage the DoubleTapped event, which is triggered when the button is tapped twice. In this case, you can use a special Caliburn Micro class called Message, which allows to attach a method to any event exposed by the control.

First, you need to add the Caliburn Micro namespace in the Page definition in the XAML:

<Page
    x:Class="MoviesTracker.Views.MainPageView"
    xmlns:viewModels="using:MoviesTracker.ViewModels"
    xmlns:micro="using:Caliburn.Micro"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

</Page>

Then you can use the attached property Attach exposed by the Message class, like in the following sample:

<Button Content="Conferma" x:Name="Confirm" micro:Message.Attach="[Event DoubleTapped] = [Action Confirm]" />

The Attach property requires a value split in two parts, each of it defined inside square brackets. The first one is marked with the keyword Event and it requires the name of the event we want to manage (in our case, DoubleTapped). The second one, instead, is marked with the keyword Action and it’s the name of the method defined in the ViewModel that should be triggered when the event is raised.

One cool thing is that you can pass some special values to name of the action, which can be used to pass a parameter to the method in the ViewModel. Let’s see a real example with the ListView control, which is one of the new and powerful Windows Runtime controls to display collection of items:

<ListView ItemTemplate="{StaticResource OnlineMoviesTemplate}"
ItemsSource="{Binding Movies}"
IsItemClickEnabled="True"
SelectionMode="None"
micro:Message.Attach="[Event ItemClick] = [Action GoToDetail($eventArgs)]" />

The ListView control offers a new way to manage the list that is useful when you don’t really want to provide a way to select items, but you just need to redirect the user to a detail page to see more information about the selected item. You can achieve this result by setting the SelectionMode property of the control to None and the IsItemClickEnabled one to True. This way, every time the user will select an item from the list, the selection won’t be triggered, but a specific event called ItemClick will be invoked: in the parameter of the event handler you’ll get the item that has been selected.

The previous sample shows you a powerful special value that can be very useful in this scenario: the GoToDetail() action is invoked with the parameter $eventArgs. This way, the method in the ViewModel will receive the parameter of the event, exactly like if we are managing it in the code behind using an event handler. Here is how the GoToDetail() method in the ViewModel looks like:

public void GoToDetail(ItemClickEventArgs args)
{
    Movie selectedMovie = args.ClickedItem as Movie;
    _navigationService.NavigateToViewModel<DetailMovieViewModel>(selectedMovie.Id);
}

 

The parameter’s type we receive is exactly the same as we would have used the event handler in code behind: in this case, it’s ItemClickEventArgs. The sample shows you how it’s easy to use it to retrieve the needed information, in this case the selected item, which is stored inside the ClickedItem property. This sample is taken from my Movies Tracker application, so we’re dealing with a collection of movies: this method retrieves the selected movie and redirects the user to the detail page. For the moment, ignore the NavigationService usage: we’re going to talk about it in another post.

Another cool thing in Caliburn is that, in the bootstrapper, you can create your own special parameters to use with the Attach property. For example, let’s try to add the following line of code in the Configure() method of the App.xaml.cs file:

MessageBinder.SpecialValues.Add("$clickeditem", c => ((ItemClickEventArgs)c.EventArgs).ClickedItem);

By using the MessageBinder class, we are telling to Callburn Micro that we want to create a new special parameter called $clickeditem, which will be connected to the ClickedItem property of the ItemClickEventArgs class. This way, we can change the ListView definition in XAML in the following way:

 

<ListView ItemTemplate="{StaticResource OnlineMoviesTemplate}"
ItemsSource="{Binding Movies}"
IsItemClickEnabled="True"
SelectionMode="None"
micro:Message.Attach="[Event ItemClick] = [Action GoToDetail($clickeditem)]" />

As you can see, we changed the name of the parameter we pass to the action: it’s now called $clickeditem, which is the same name we defined in the bootstrapper using the MessageBinder.

By applying this change we can simplify the GoToDetail() method we’ve defined in the ViewModel:

public void GoToDetail(Movie movie)
{
    _navigationService.NavigateToViewModel<DetailMovieViewModel>(movie.Id);
}

Thanks to the new parameter we’ve created, the method will directly receive the value of the ClickedItem property: Caliburn Micro is able to apply the cast for you, so we can simply define the parameter’s type as Movie and the framework will take care of converting the ClickedItem property in the expected value.

There are also some other special parameters in Caliburn Micro, like $dataContext (to get access to the DataContext of the control that invoked the action) or $source (which is a reference to the control that invoked the action). You can find the list of all the available parameters in the official documentation.

Wrapping up

In this post we’ve learned the basic naming conventions and how to manage actions in a Universal Windows app with Caliburn Micro. In the next post we’ll see some advanced scenario which have changed in this new version of Caliburn Micro, like navigation.

In the meanwhile, you can play with the sample project.

Caliburn Micro 2.0 in Universal Windows apps – The complete series

  1. The project setup
  2. Binding and actions
  3. Navigation

Samples available on GitHub

Posted in Windows 8, Windows Phone | Tagged , , | 2 Comments

Using Caliburn Micro with Universal Windows app – The project setup

One of the most important features that was added in Windows Phone 8.1 is the native Windows Runtime support: this new approach opened the doors to Universal Windows app, a new way to write applications for Windows and Windows Phone so that you can share most of the code. One of the biggest limitations in the Microsoft world, in the past, was that, despite the fact that Windows 8 and Windows Phone 8 have always shared many similarities (the application lifecycle, the isolated storage, the navigation approach, etc.), you ended to write two different applications, due to the many differences within the APIs implementation.

Windows Phone 8.1 has finally brought real convergence between the two platforms: there are still some differences, but you’ll be able to share most of the code and the logic between the two applications.

In the Universal Windows app world, using the MVVM (Model-View-ViewModel) pattern is a natural choice: splitting the logic and the user interface is the first rule to keep in mind when it comes to reuse the same logic in two different applications. The Universal Windows app project offers multiple ways to share code also using code behind, but it’s not an ideal solution: dealing with event handlers and having direct access to the controls makes hard to think the app as a combination of multiple aspects (the logic, the UI, etc.).

If you regularly follow my blog, you should have already learned to use Caliburn Micro in a Windows Phone application and to master all the powerful naming conventions and services that it offers to the developers. If you haven’t followed my previous tutorials, don’t worry: we’ll do a recap of the things to know in the next posts.

What does it change when it comes to use Caliburn Micro in a Universal Windows app? Not so much, indeed: the approach is always the same. The major difference is about the bootstrapper, which is the class that takes care of configuring in the proper way all the services needed by Caliburn Micro: we’re going to define it, in fact, in a different way than we did in Windows Phone 8.0, due to the differences between the two runtimes (Silverlight in Windows Phone 8.0, Windows Runtime in Windows Phone 8.1).

Let’s start from the beginning and see how to setup a Universal Windows app with Caliburn Micro.

Setting up the project

Caliburn Micro has been recently upgraded to version 2.0, which fully supports Universal Windows app projects. The first step is, as usual, adding Caliburn Micro to the solution. It’s important to highlight that Universal Windows app aren’t a real application: in the end, you’re going to have two different projects, that will produce two separate packages, one for Windows 8.1 and one for Windows Phone 8.1. The major difference with a regular project is that, as part of the solution, you’ll find a shared project, which contains all the stuff (code, user controls, resources, assets, etc.) that will be shared among the two applications.

As a consequence, you can’t add a reference to an external library directly to the shared project: you’ll have to add Caliburn Micro in both projects, using NuGet. Just right click on each of them, choose Manage NuGet packages and look for a package called Caliburn Micro (this is the package reference on NuGet’s website).

The bootstrapper

Caliburn Micro isn’t a toolkit, but a framework: it means that, other than the basic helpers to implement MVVM in an application (like a class to support INotifyPropertyChanged), it offers also a series of services and classes that can help the developers to solve specific scenarios of the platform you’re working on. For example, since we’re talking about Window and Windows Phone, it offers helpers to manage the application’s lifecycle, the sharing feature, the navigation, etc.

As a consequence, Caliburn Micro needs to configure all these helpers when the application is started: this task is demanded to the bootstrapper, which is a special class that takes care of everything. In Caliburn Micro, the boostrapper does more than that: it takes care also of setting up the application itself. For this reason, the bootstrapper totally replaces the App class. The biggest difference between Windows Phone 8.0 and 8.1 is that, instead of using a separate class as bootstrapper and cleaning the App class by deleting all the initialization methods, we’re going to effectively replace the App class, by using another one called CaliburnApplication.

This means that the definition of the App class will change from this:

<Application
    x:Class="MoviesTracker.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

</Application>

to this:

<micro:CaliburnApplication
    x:Class="CaliburnDemo.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:micro="using:Caliburn.Micro">

</micro:CaliburnApplication>

As you can see, we’ve replaced the Application class with the CaliburnApplication one. The second step is to change the code behind (defined in the App.xaml.cs file): we’re going to remove every event handler defined in the class and we will replace it with the following code.

namespace CaliburnDemo
{
    public sealed partial class App
    {
        private WinRTContainer container;

        public App()
        {
            InitializeComponent();
        }

        protected override void Configure()
        {
            container = new WinRTContainer();

            container.RegisterWinRTServices();

            container.PerRequest<MainPageViewModel>();
        }

        protected override void PrepareViewFirst(Frame rootFrame)
        {
            container.RegisterNavigationService(rootFrame);
        }

        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            DisplayRootView<MainPage>();
        }

        protected override object GetInstance(Type service, string key)
        {
            return container.GetInstance(service, key);
        }

        protected override IEnumerable<object> GetAllInstances(Type service)
        {
            return container.GetAllInstances(service);
        }

        protected override void BuildUp(object instance)
        {
            container.BuildUp(instance);
        }
    }
}

First, the App class won’t inherit anymore from the Application class. Then, we have a series of methods that are used to setup the container, called WinRTContainer: Caliburn Micro uses the dependency injection approach, which means that dependencies are resolved at runtime and not at compile time. When the application starts, it registers in the container the ViewModels and the different services we’re going to use (both the standard ones and the custom ones made by us): then, when we’re going to use one of them, we’ll simply add a parameter in the constructor of the ViewModel; the container will take care of “injecting” the concrete implementation of the classes into the ViewModel. This approach is very helpful when we want to support design time data, which is a way to display fake data in the application when we’re designing the user interface with Visual Studio or Blend. We’ll talk more deeply about design time data in a separate post.

In the boostrapper definition there are two important methods: typically, they’re the only ones you’re going to modify during the development. The first one is called Configure(): it takes care of initializing the container and the Caliburn Micro services. You’re going to use it also to initialize your custom services and your ViewModels: every time you’ll add a new page to the application (which, typically, in the MVVM world means adding a new ViewModel), you’ll have to register the ViewModel inside the container in this method.

The second important method is OnLaunched(), which is invoked when the application starts: its important task is to redirect the user to the main page of the application. This operation is achieved by calling the DisplayRootView<T>() method, where T is the page that needs to be loaded first.

Now you’re all set: the application will automatically starts to use the Caliburn Micro services and to support the naming conventions. Let’s see now how to define the structure of our project.

Connecting a ViewModel with the View

When you work with MVVM, you are able to connect the ViewModel to the View thanks to the DataContext property: the ViewModel is set as data context of the View, so that you are able to access to commands and properties defined in the ViewModel using binding.

In Caliburn, this connection is made possible using the following convention:

  • View and ViewModel should have the same name, but with different suffix: View in case of the View, ViewModel in case of the ViewModel. For example, a page called MainPageView and a class called MainPageViewModel are connected.
  • The View should be defined in a namespace which ends for Views and the ViewModel should be defined in a namespace which ends for ViewModels. This goal is typically achieved by grouping the files in folders: just create a folder called Views, in which you’re going to place all the pages, and a folder called ViewModels, in which you’re going to place all the ViewModels.

Where are we going to create all the required files? As we know, the shared project allows to share more or less everything between Windows 8.1 and Windows Phone 8.1: not only code, but also entire XAML pages. However, it’s not the best approach: sharing the logic is correct, but Windows and Windows Phone (despite the fact that they share many similarities) offers a difference experience to the user. For this reason, the best approach is to keep the Views separated, but sharing the same ViewModel. The following image shows you how to structure a Universal Windows project with Caliburn Micro: the ViewModels folder is defined inside the shared project, while the Views folders belong to every specific project.

image

Coming soon

In this post we’ve learned how to setup Caliburn Micro in a Universal Windows app and how to define the structure of the project, so that we’re able to easily connect Views and ViewModels. In the next posts we’ll see how to use the most common naming conventions in order to properly connect the user interface with the data that we’re going to display to the user.

Meanwhile, you can play with the following sample project.

Caliburn Micro 2.0 in Universal Windows apps – The complete series

  1. The project setup
  2. Binding and actions
  3. Navigation

Samples available on GitHub

Posted in Windows 8, Windows Phone | Tagged , , | 8 Comments

Windows Phone 8.1: a lap around the new development features

Don’t get fooled by the version number: Windows Phone 8.1 isn’t just a minor update, but it’s a totally new version of our favorite operating system, both for users but, most of all, for developers. At a first glance, you may think that it’s the usual Windows Phone you already know, with its tiles and the familiar user interface. However, under the hood, there’s a huge number of new features that turns greatly improve the platform’s quality and experience.This new version was awaited since a long time and, finally, yesterday Microsoft has revelead it during the BUILD’s keynote, the most important Microsoft conference that is running in these days in San Francisco.

Since, if you’re reading this post, you’re probably a developer, let’s start by talking about all the new features that you probably care most about. Be prepared, because this is probably one of the longest posts I’ve ever wrote Smile

Welcome Windows Phone Store apps!

If you’ve ever tried to develop an application that targets both Windows Phone and Windows 8 you would have discovered that sharing code between the two platforms is not that easy: despite the fact that, under the hood, you can find the same framework, which is the Windows Runtime, there are a lot of features that are implemented using different classes and methods (like tiles, push notifications or the XAML controls). Windows Phone 8.1 changes everything, by sharing almost all the APIs and features that have been introduced in Windows 8. For this reason the new SDK has added a new kind of applications called Windows Phone Store apps: basically they are the same as Windows Store apps, but for Windows Phone, since they share almost all of the features and APIs. If we have already developed one or more Windows Store apps you’ll find yourself at home: application lifecycle, background tasks, XAML controls, etc. are exactly the same you can find in Windows 8.1. Also the package delivered by Visual Studio isn’t a XAP anymore, but it’s an AppX package, which contains a new manifest file called Package.appxmanifest.

For this reason Visual Studio now offers also a new template to create Universal Windows apps, which makes the life easier to developers that are willing to create an application that targets both Windows 8.1 and Windows Phone. This template includes two different projects for the two platforms, plus a new shared project: all the code we include will be automatically shared with the other projects, using the linked files approach. This means that the files that are part of the shared project are physically stored just in one location, but they are added as link to the other projects. This approach was already available in the past and it was, indeed, one of the strategies to share as much code as possible between a Windows Store app and a Windows Phone app: the difference is that, if in the past you were forced to use a lot of tricks and workarounds (like conditional compilation symbols) due to the many differences between the two frameworks, now everything is much easier, since the two runtimes are basically the same. This way you’ll be able to write your application’s logic just once and you’ll have just to take care to create two different user interfaces, due to the user experience’s differences between the tablet / pc world and the smartphone one (if this doesn’t mean that you won’t be able to reuse the same XAML code at all).

Another cool announcement related to Universal Windows apps is that, in the future, they’ll be able to run also on XBox One, bringing full convergence across all the screens: tablets, smartphones, computers and TVs.

The Windows Phone Store apps are completely based on the Windows Runtime, XAML included: we don’t have to deal anymore with the managed XAML available in Windows Phone 8, which was still based on Silverlight, but now we can work with native XAML, which offers much better performances. However, there’s a downside: due to the many differences, you won’t be able to automatically upgrade your existing Windows Phone applications to the new framework in the same way like, for example, you do now when you want to migrate a Windows Phone 7 app to Windows Phone 8. There are many reasons, like:

  • The Windows Phone Store apps only support the new Windows Runtime APIs: as a consequence, all the old Silverlight APIs (like background tasks, tiles management, network interaction, ecc.) are no longer working.
  • The new native XAML is based on a set of namespaces and controls which is different from the Silverlight ones: many controls, like Panorama or LongListSelector, are not available anymore and they need to be replaced.
  • The application lifecycle and the navigation framework offered by the Windows Phone apps are very different from the Silverlight ones.
  • Since the Windows Phone Store apps are no longer based on the .NET framework, all the third party libraries that still relies on it won’t work anymore. We’ll need to use specific versions of the libraries that can target the Windows Runtime (however, most of the libraries that are available for the Windows Store apps will work just fine).

If you’re already a Windows Phone developer, don’t panic! Microsoft didn’t leave you behind, but they’ve also updated the Silverlight runtime with the new 8.1 APIs and features, by introducing the Windows Phone Silverlight 8.1 apps. This means that you’ll be able to right click on an existing Windows Phone 8.0 project and choose the option Upgrade to Windows Phone 8.1: this way, you’ll be able to use almost all the new APIs (including the Windows Runtime’s specific ones, like the new background tasks or contracts) without losing the compatibility with your existing codebase. Of course, this approach has some downsides: it will be harder to share code with a Windows Store app (since the XAML, the application lifecycle, the navigation framework, etc. will continue to be different) and you’ll lose most of the performance improvements offered by the new runtime.

It should be clear, now, that Windows Phone 8.1 is totally compatible with Windows Phone 7.1 / 8.0 applications: you’ll need to update your application to 8.1 only if you’re planning to make use of some of the new features. Of course, the new 8.1 apps can be launched only on 8.1 devices: if you want to keep the compatibility with Windows Phone 8.0 and, at the same time, use the new 8.1 features you’ll have to maintain and publish two different projects. However this time, unlike it happened with Windows Phone 8.0, it’s just a temporary requirement: since Windows Phone 8.1 is going to be available as a free update to every Windows Phone 8 device on the market, in the long term you won’t be needed anymore to keep two versions of the same project, since eventually every user will be able to use just the 8.1 version.

In the end, the Windows Runtime has added a new important feature: WinJS support. Exactly like you can do nowadays with Windows Store apps, you have the chance to develop native applications (and not just simple web applications that are rendered using a WebBrowser control) using HTML and Javascript thanks to a library called WinJS, which grants access to all the Windows Runtime APIs and features using Javascript as a programming language, in replacement of C#, VB.NET or C++, and HTML as a design language, in replacement of XAML. At the same time, Microsoft has announced that WinJS is being released as an open source and cross platform library on GitHub.

Which framework should I choose?

Probably now, after reading about the coexistence of two frameworks, you were wondering which one you should choose to develop a Windows Phone 8.1 application. The first thing to consider is if you’re planning to develop a new app or to upgrade an existing one: if it’s the first case, the Windows Phone Store apps are, for sure, the most interesting path to take. If you’ve never developed a Windows Store app there will be a starting learning curve, since you’ll have to know and master all the differences with the old approach when you have to deal with lifecycle, navigation, background activities, etc. However, in the end you’re going to develop an application that can be easily ported to Windows 8.1 and that can take advantage of the new performance improvements introduced by the Windows Runtime.

On the other hand, if you already have an existing application and you just want to make use of some of the new Windows Phone 8.1 feature, the simplest path to take is to keep using the Silverlight framework: this way you’ll be able anyway to make use of the new features without having to rewrite the application from scratch. Then, in the future, when Windows Phone apps will take off and the number of supported libraries will increase, you may evaluate to migrate your existing application to the new runtime.

However, there’s another series of things that are important to keep in mind when you have to make this choice: there is a list of features that, for timing and resources issues, the team wasn’t able to make available in both frameworks. For this reason, if you choose to develop a Windows Phone app, you won’t be allowed to:

  • Use the APIs to interact with the clipboard
  • Define your app as a lock screen provider, so that it can change the lockscreen’s wallpaper
  • Define your app as a ringtone provider
  • Use Alarm and Reminders
  • Develop a Lens App (which are photographic apps that can be integrated with the native camera app)
  • Keep an app running under the lock screen
  • Use the Continuous Background Tracking APIs, that can be used to continuosly track the user’s position even when the app is not in foreground
  • Use VoIP APIs
  • Use the CameraCaptureTask, which is the chooser that can be used to take a picture with the native camera app and import into your application

On the other side, if you develop a 8.1 application using the Silverlight framework you won’t be able to:

  • Use the old APIs to manage background audio. You will have to migrate to the new Windows Runtime APIs or keep your application as a Windows Phone 8.0 app
  • Make use of the new XAML framework, which is able to fully support devices with different screen sizes
  • Use the new XAML controls, like Hub or GridView
  • Use the new APIs to edit videos
  • Use the new Visual Studio tools for profiling and coded UI tests

It should be clear now that the framework’s choice can’t be based just on the type of application (new or existing one) but also on the features you want to use: if, for example, you’re developing a Lens App or an images catalogue app which acts as a lock screen provider, you’ll be forced to develop a Windows Phone Silverlight 8.1 app.

New Stores shared experience

Thanks to the Universal Windows apps ,both Windows 8 and Windows Phone stores introduce a new shared experience for our apps: we’ll be able to publish the two versions of our app on both stores but, since they’ll share the same application identifier, the user will be able to buy it just once and install it on all his devices. In addition, you’ll be able to share settings and in-app purchases between your Windows Phone and Windows Store app.

New development tools and emulator

The Windows Phone 8.1 SDK is completely aligned with the latest Microsoft development technologies: the SDK, in fact, is based on Visual Studio 2013 which, for the occasion, has been updated to the Update 2 RC release. There are also many improvements with the emulator: the first thing to mention is that now it’s able not just to simulate different resolutions, but also different screen sizes. This scenario is becoming more and more important every day, since in the mobile market you can find devices with very different screen sizes: from small devices, like the Lumia 620 (3.8 inches) to phablets, like the Lumia 1520 (6 inches). Now, in the debug dropdown menu, other than the usual indicator about the supported resolution (like WXGA, WVGA, 1080p, etc.) you’ll find also the screen size, as you can see in the following image.

image6_thumb3

The second news is connected to the touch screen simulation: finally we’re able to simulate multi touch gestures (like pinch to zoom) also using the mouse, while previously the only way to do that was using a touch screen device.

The third and last new feature is connected to the additional tools that are bundled with the emulator: Windows Phone 8.0 introduced some nice tools to simulate geo location or accelerometer. Windows Phone 8.1 has added to the list:

  • A tool to simulate the type and the network speed (Wi-Fi, 2G, 3G, etc.)
  • A tool to simulate push notifications: we won’t have anymore to send real push notifications from a server application to test if our Windows Phone app correctly manages them
  • A tool to simulate the SD card: we can set up a folder and make the emulator thinks that it’s a removable card, so that we can test the new APIs to read and write data from a SD card
  • A tool to create emulator’s snapshot: the Windows Phone emulator automatically resets itself when it’s closed, including all the data we’ve created (installed apps, storage, etc.). With this new feature we’ll be able to create checkpoints of a specific status and restore them in a second time.

image1_thumb2

 

Another news connected to Visual Studio is a new manifest file, which is now included in the project’s root and it’s called Package.appxmanifest: it’s very similar to the Windows Store apps one and, other that supporting features that should already be familiar to Windows Phone developers, like assets and capabilities managements, we can find new sections like Declarations, which can be used to set up the contracts and the various extensibility points of the application. Another new important feature that we can find in the manifest file is the ability, for the user, to install our application on a SD card: as developers, we are able to disable or enable this feature.

image4_thumb3

The new Windows Phone 8.1 features for developers

It would be almost impossible to deeply analyze all the new Windows Phone 8.1 features, since the list is too big. In this post I will just highlight the most important ones.

Application lifecycle and navigation framework

The Windows Phone Store apps’ lifecycle is the same supported by the Windows Store apps and it has many differences with the old one offered by the Silverlight framework. Under the hood, the architecture is very similar: the application, when it’s suspended, gets “frozen”, which means that every thread and operation is aborted; this way, the application will keep using just memory, but all the other resources (hardware sensors, CPU, etc.) will be released. Without a warning, the operating a system is able to kill a suspended application, in case the left memory is not enough to allow the user to open new applications: as developers, we are required to manage this scenario (which in Windows Phone 8.0 was called tombstoning) to properly save and load the application’s state, so that the user can act like if the application has never been terminated. The main difference with the old approach is that now applications are always suspended: if the user presses the Back button in the first page of the app, it won’t be closed anymore but just suspended, like if he has pressed the Start button. This means that the system, regardless of the way the user will open back the application (using the task switcher, tapping on the tile in the Start screen, etc.), will always resume the previous instance (unless he has explicitly closed the application tapping on the X icon that is displayed in the task switcher).

image8

The other big difference with the previous runtime is the navigation framework: as a standard behavior, the Back button doesn’t automatically redirect anymore the user to the previous page of the app, but to the previous app in the operating system’s stack. If we want to keep the previous navigation approach we need to intercept the Back button and redirect the user to the previous page: by default, the new Visual Studio templates include some code snippets that will take care of this scenario for you. Another new feature connected to the navigation framework is that the NavigationService class is now gone and it has been replaced by the Frame one, which represents the page’s container of the application and, thus, it offers all the methods to move the user from one page to the other. One of the biggest advantages of this class is that it’s not connected anymore the old Silverlight approach, which was based on Uris and, as a consequence, it allowed us to carry only textual parameters from one page to the other: now we are able to exchange also complex objects.

Another new important feature is that Windows Phone now fully support the contracts approach, which are a way to extend our applications and integrate them in the operating system. One of the most useful contracts is called sharing and it allows developers to create apps that are able to share a content to another app (in this case, we talk about sharing source apps) or to receive a shared content from another app (in this case, we talk about sharing target apps). The contracts approach introduce a new behavior in the application lifecycle: the app can be opened not just by the user, but also from another app; exactly like we do in Windows Store apps, the App.xaml.cs file is able to manage all the entry points of our application

image9

If you decide to keep using the Silverlight framework, no one of the just explained features will apply to you: the Back button will continue to redirect the user to the previous page within your app and, if it’s pressed in the main page, it will close it. The only difference is that, now, Fast App Resume is enabled by default: the suspended instance of your application will be always resumed, regardless of the entry point.

The new XAML features

The new XAML runtime includes a lot of new controls and features, which are aligned to the Windows Store app ones: for this reason, the Windows Phone Toolkit is not needed anymore for Windows Phone apps, since all the controls are now included in the Windows Runtime. We can split the controls in three different categories:

  • Common: these are the controls that have the same visual layout and behavior on both platforms, like Button, TextBlock and TextBox
  • Optimized: these are the controls which have the same behavior, but a different visual layout to match the platform’s guidelines. The DatePicker controls is a sample of this category: the behavior is the same on both platorms (it can be used to choose a date), but on Windows 8 it’s rendered as a series of dropdown menus, while on Windows Phone 8.1 it’s displayed in a new page.
  • Signature: these are the unique controls that are available only on one platform or that are available on both, but with a completely different layout and behavior. The Pivot control is part of the first category, since it’s available just in Windows Phone. The AppBar control, instead, is part of the second one: it’s available on both platforms, but with a completely different implementation.

The biggest advantage of this approach is that we’ll be able to reuse the same XAML on both platforms: by using UserControls we’ll be able to share not just the logic, but also part of the user interface between the Windows Phone and the Windows Store app.

The new XAML runtime includes also many new changes when you have to deal with signature controls:

  • The Panorama control has been removed and replaced by the Hub one
  • The application bar is now implemented using the AppBar control, which supports two kind of commands: PrimaryCommands and SecondaryCommands. In Windows Store apps the difference between the two categories is referred to the position of the commands (on the left or on the right of the screen); in Windows Phone apps, instead, we can distinguish between icons (the PrimaryCommands controls replace the old ApplicationBarIconButton ones) and menu items, which are displayed only when the application bar is expanded (in this case the SecondaryCommands controls replace the old ApplicationBarMenuItem ones). Another important news, especially if you work with the MVVM pattern, is that now the AppBar control fully supports binding, both to define properties and commands.
  • Windows Phone 8.0 introduced a new control called LongListSelector to manage grouped data collections (like the hub People, for example, groups the list of contacts by the first letter of the name). However, it wasn’t really simple to use: one of the biggest limitations was the requirement to create a new class to manage the grouping, instead of allowing us to work directly with the original data collection. Now the LongListSelector has been removed and replaced by two controls that should already be familiar by the Windows Store apps developers: GridView and ListView. These controls, other than being optimized to manage large collections of data, help us to simplify the code needed to manage grouping. In addition, they support the semantic zoom concept, which has been added in Windows 8 and can be used to quickly see all the available groups and jump from one to the other.

image2_thumb5

The other big news connected to the XAML runtime is the new layout management: Windows Phone Store apps don’t have anymore a fixed layout that is automatically scaled according to the phone’s resolution, but they uses a fluid layout, that is able to adapt to any resolution and any screen size, exactly like the Windows Store apps do to properly support at the same time small tablets and big monitors.

All the new XAML features mentioned in this section are available just for the Windows Phone Store apps: the Silverlight apps keep using the old XAML frameworks and, as a consequence, you won’t find the new controls.

Dealing with local data: the storage APIs

Windows Phone 8.0 did a first attempt to unify the storage APIs with the Windows Runtime ones, by introducing classes like LocalStorage, StorageFolder and StorageFile. Windows Phone 8.1 completes this unification, by supporting all the features and APIs that were still missing in Windows Phone 8.0. The most important features are:

  • A new way to manage settings
  • A new storage called TemporaryStorage, which can be used for caching purposes: the storage’s content, in fact, is automatically erased by the operating system
  • A new storage called RoamingStorage, which has a limited size (100 KB) but which content is automatically synced with all the other devices that are have been configured with the same Microsoft Account (regardless if they’re Windows Phone devices or Windows 8 tablets or computers).

Another important new feature is the capability to access to all the data that is stored in the multimedia library of the user: thanks to the KnownFolders class (which offers different storage’s types, like PicturesLibrary, MusicLibrary and VideosLibrary) you’ll be able to access (both for reading and writing purposes) to all the user’s pictures, videos and audio tracks. The same limitation has been removed also when you want to deal with the SD card that is supported by some devices: now you’ll be able to read and write data on the external memory. In the end, in Windows Phone 8.1 we are able to better manage and import file from other applications or from the phone, by using the FileOpenPicker and FileSavePicker classes.

image7

 

Geolocalization and geofencing

The biggest new feature introduced in Windows Phone 8.1 connected to the geo location services is geofencing support, which was already introduced in Windows 8.1: with the new APIs you’ll be able to define an area on the map and, when the user walks into it, your app will be notified, even if it’s not running thanks to a new kind of background task. There are a lot of scenarios that can make use of this new feature: let’s think about an application connected to a commercial activity, that can notify to the user all the promotions that are running in the shop he has just walked in.

The new geolocation APIs offers also a complete unification with the Windows 8.1 ones: the only exception is with the maps controls which has two different implementations at the moment. In Windows 8.1, in fact, you still have the Bing Maps control, while in Windows Phone you can use the Here Maps one, which uses the Nokia services.

Tile, notifications and notification center

Windows Phone 8.1 introduces big news in the tiles management: instead of the original 3 templates available in Windows Phone 8.0, now you have access to the full catalog of 40 templates that are available in the Windows Runtime and that are shared with Windows 8.1. The new templates are much more flexible than the old ones: now you can manage multiple images, text lines or badges. The tile architecture is the same we’ve learned with Windows Phone 8.0: every tile is represented by a XML layout, which contains all the properties that define the visual layout of the tile. The difference is that, now, the templates are shared with the Windows Store apps and automatically adapted to the platform: in case there are some properties that can’t be rendered on one of the two platforms, they will simply be ignored. The same applies for toast notifications: the code to define a toast is exactly the same, but the visual layout they will look very different between Windows Phone 8.1 and Windows 8.1.

An important difference to highlight between the old and the new approach is that the XML layout is used for any scenario: in Windows Phone 8.0 XML was required just for push notifications, while in a background agent or within the app you were able to use classes like ShellTile and ShellToast. In Windows Phone 8.1, instead, tiles and toasts are are always represented using XML data: you’ll need to manipulate the XML document to set the different tile properties, like in the following example.

private void OnSendNotificationClicked(object sender, RoutedEventArgs e)
{
    XmlDocument xml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWideText01);
    XmlNodeList nodes = xml.GetElementsByTagName("text");
    nodes[0].InnerText = "This is the text";

    TileNotification notification = new TileNotification(xml);
    TileUpdateManager.CreateTileUpdaterForApplication().Update(notification);
}

In case you prefer to use a more traditional approach, based on classes and objects, you can find on NuGet a library provided by Microsoft called  NotificationsExtensions. By using it, you’ll be able to change the previous code like the following one:

private void OnSendNotificationClicked(object sender, RoutedEventArgs e)
{
    ITileWideText01 tile = TileContentFactory.CreateTileWideText01();
    tile.TextBody1.Text = "Line 1";
    tile.TextHeading.Text = "Title";

    TileNotification tileNotification = tile.CreateNotification();
    TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);
}

image3_thumb2

This new approach improves a lot the tile and toast management for developers, especially when you have to deal with push notifications. We’ll be able, in fact, to send from a server application (like a cloud service) the same exact notification to Windows Phone and Windows Store apps and they’ll both be able to receive it with success. As a consequence, you probably have already guessed another new important feature introduced in Windows Phone 8.1: push notifications are now sent using the WNS (Windows Notification Service, which is the service used for Windows Store apps) instead of the old MPNS (Microsoft Push Notification Service). The architecture is the same: the application subscribes to receive notifications and receives from the WNS a URL that univocally identifies the channel; server side, when you want to send a notification to the device, you simply send a HTTP request using a POST command do the URL that identifies the channel: the body of the request is the XML data that represents the notifications. This way, you’ll be able to unify the push notifications management in your backend service: we’ll be able to send the exactly same notification to both platforms.

If you already have an existing app which uses push notifications, don’t worry: MPNS is here to stay and you’ll be able to keep using it. However, if you want, you’ll be able to use the new tiles management and the Windows Notification Service also from a Windows Phone Silverlight 8.1 app.

For sure, the biggest new feature (especially from the user point of view) connected to notifications is the action center: by swiping from the top to the bottom of the screen we’ll be able to access to this new screen, which stores all the toast notifications that all your apps have received. The action center fills one of the biggest Windows Phone 8.0 limitations: if the user received a notification while he was distracted and the app wasn’t set up to display notifications on the lock screen or on the tile, the user didn’t have any chance to retrieve it. Now, instead, all the notifications are automatically stored in this new view, grouped by application. As developers, this new feature is completely transparent: automatically, all the toast notifications that are sent to our application will be automatically kept in the action center. However, we have the chance to interact with it thanks to some properties that are exposed by the ToastNotification class (which identifies, as you can imagine, a toast notification): for example, we can define after how much time the notification should disappear from the action center (by using the ExprationTime property) or we can send to the application “ghost notifications” (by setting to true the SuppressPopup property), that are not displayed to the user in the regular way but they are simply stored in the action center. We can also remove notifications generated by our application, by using the ToastNotifcationHistory class.

QuickAction_Default_16X9

Background operations

Windows Phone 7.5 introduced background agents, which are separated projects that contains some code that can be executed periodically from the operating system even when the application is not running. Windows Phone 8.1 improves this area by following, again, the Windows Runtime approach: we’ll keep working with separated projects called background tasks, which offers much more flexibility than the old background agents. Background tasks, in fact, are based on triggers: if background tasks were limited to be executed according to specific time conditions (for example, every 30 minutes), background tasks, instead, can be automatically activated due to a system status change (SystemTrigger, like Internet connection available or not available); when the user walks into a specific are (LocationTrigger, they are connected to the new geofencing APIs); when the app receives a push notification (PushNotificationTrigger); when the device connects or disconnects with another device using Bluetooth (BluetoothSignalStrengthTrigger). If you just need to recreate the old background agent experience don’t worry, you have also some triggers for that, like TimeTrigger (which can be used to peridocailly run the background task, the minimum intervalis 15 minutes) and MaintenanceTrigger (which replaces the ResourceIntensiveTask and can be used to perform long running operations that should be execute only when the phone is charging).

Thanks to Visual Studio improvements, it’s now easier also to test background tasks: in the Debug toolbar now we have a useful dropdown menu that can be used to trigger a background task’s execution anytime we need.

image5_thumb2

There are also some regardless other background scenarios, which, again, have been aligned to the Windows Runtime APIs:

  • Background transfers are now achieved using the BackgroundDownloader and BackgroundUploader classes, which are more flexible
  • You can develop multimedia applications that can reproduce audio in background using a new set of APIs, which area great improvement compared to the old ones

New APIs to interact with other devices

Windows Phone 8.0 added a new set of APIs called Proximity APIs, which can be used to interact with other devices using technologies like NFC and Bluetooth. Windows Phone 8.1 adds a bunch of new features in this category, by introducing support to two new technologies:

  • Bluetooth Low Energy (BLE), which is a new Bluetooth standard that is widely used by many new devices on the market like smart watches, fitness bracelets, medical equipment, etc. Windows Phone 8.0 Update 3 introduced the support to these kind of devices, but just from a user point of view: the phone was able to connect to some of these devices and interact with them. Now, instead, we are able to interact with these devices also from third party applications
  • Wi-Fi Direct, which is a technology that can be used to establish a direct connection between two devices using Wi-Fi

Multimedia

Windows Phone 8.1 introduces a new set of APIs called Media Foundation APIs, which were already part of the full Windows Runtime in Windows 8: you’ll b able to developer advanced applications that are able to manipulate audio and video and to play multimedia content. There’s also a new set of APIs inside the Windows.Media.Editing namespace, which can be used to perform video editing operations: we’ll be able to developer apps that will allow the user to trim, add effects or manipulate videos that have been recorded with the phone.

Inside this category we can find also some new classes that can be used to record the user’s activity on the screen: we’ll be able, for example, to include a recording feature inside our game, so that the user can share his best match with his friends or on social networks.

The new consumer features

Windows Phone 8.1 isn’t just a big update for developers, but also for users: other than being able of make use of all the new features that the application will be able to implement, users will find many new features integrated in the operating system. Here are the most important ones:

  • A new feature called Cortana, which acts both as a vocal assistant (she’s able to interact with the user by voice) and as personal assistant (she’s able to remind you important things, scan your mail to plan your travels, etc.). Plus, third party applications will be able to integrate with it, so that Cortana can search data directly in your application.
  • New start screen customization: now you can set a background image, which is applied to all the transparent tiles with a parallax effect; in addition, you can reduce the tile size, so that you can display a third column even on devices without a big screen.
  • The action center, other than being a container for all the toast notifications received by the applications, gives quick access to the network settings: you’ll be able to quickly enable or disable Wi-Fi, Bluetooth, etc.
  • Complete backup of the phone, including the tile layout on the Start Screen.
  • The Store app has been completely redesigned, to give more visibility to the best applications.
  • Now you can force the Store to check updates for the installed apps or, like in Windows 8, you can enable auto update, so that apps are automatically updated without manual confirm from the user.
  • New Calendar app, with new options (like weather forecast) and a new weekly view.
  • New Camera app, with support for burst mode (the camera takes many photos at once, so that you can choose the best one and discard the others).
  • Internet Explorer 11, which improves support for the latest web standards (HTML5, WebGL, etc.); automatic bookmarks sync with your  Windows 8 pc or tablet; integrated password and download manager; Reading mode, which is able to adapt a page’s layout so that it’s easier to read.
  • New enterprise features: VPN support, better devices management, new policies to decide which apps can be installed from the store, encrypted mails support, Wi-Fi enterprise support, etc.
  • New swipe keyboard, that can be used to insert texts without releasing your finger from the touch screen
  • New Sense applications: Battery Power Sense, to keep track of the battery usage made by every single app; Wi-Fi Sense, to share your Wi-Fi connections with another device; Storage Sense, to keep track of the storage occupied by every app.
  • You can project your phone’s screen on another screen, like a monitor or a TV, both with a wired connection (using the USB cable) and with a wireless one, using Miracast

Wrapping up

As you can see, Windows Phone 8.1 is more than just a simple update: it’s a new starting point, that adds a new and important piece of the puzzle of the Microsoft ecosystem. If you already are a Windows Phone developer, this new release will give you the chance to push your application even further: thanks to the new features, you’ll be able to easily port your application to Windows 8.1, giving you more chances to make money and to increase your number of users.

On the other side, if you already are a Windows Store app developer, you’ll find yourself at home: one of the biggest complaints in the past was that, even if Windows Phone 8 and Windows 8 apps shared many similarities (like the application lifecycle, the user interface approach, etc.) most of them were implemented with totally different APIs. Now, instead, this problem has been fixed and there are only a few scenarios where you won’t find APIs convergence (and, in most of the cases, this happens just because there are some scenarios which don’t make sense both on tablets and smartphones).

And now, let’s share some release dates:

  • During the BUILD’s keynote Microsoft announced also a new update for Windows 8.1, which brings some features that will improve the desktop experience. The update is already available for MSDN subscribers and it will be released on 8th April via Windows Update to every Windows 8.1 device.
  • MIcrosoft will release a Windows Phone 8.1 Preview for existing phones via the Preview for Developers Program during April.
  • Starting from May / June, vendors and operators will start to release Windows Phone 8.1 as an OTA (Over The Air) update to every existing device
  • Later this month Microsoft will also open the Store to accept the submission of Windows Phone 8.1 apps

And here are some links that can be helpful:

We have just scratched the surface! In the upcoming months we’ll have the chance to cover more deeply all the new features and to learn how to implement them in our applications!

Posted in Windows Phone | Tagged | 19 Comments

Windows Phone 8 Development Succinctly: free ebook for developers

I’m happy to announce that, last week, Syncfusion, a popular company among developers for their great suites of controls, has released my new book titled Windows Phone 8 Development Succinctly. It’s a digital free e-book and, in 243 pages, it covers most of the important concepts to develop a Windows Phone application, from the basic ones (like the XAML, the application lifecycle, etc.) to the most advanced ones (like background tasks, geolocalization and speech APIs).

Here is a quick recap of the chapters:

  1. Introduction
  2. The User Interface: Basic XAML Concepts
  3. Core Concepts
  4. Data Access: Storage
  5. Data Access: Network
  6. Integrating with the Hardware
  7. Integrating with the Operating System
  8. Multimedia Applications
  9. Live Apps: Tiles, Notifications, and Multitasking
  10. Distributing the Application: Localization, the Windows Phone Store, and In-App Purchases

The book is distributed by Syncfusion for free, you just have to register and then you’ll be able to download it both in PDF and Kindle format. I hope that the book can be a great resource both for new developers, that want to start learning the basic Windows Phone concepts, and for already skilled developers, that can use the book as a reference for all the APIs and features offered by the platform.

So don’t waste anymore time and head to http://www.syncfusion.com/resources/techportal/ebooks/windowsphone8 to register and download your free copy!

 

Posted in Windows Phone | Tagged | Leave a comment

New GDR3 emulators for Windows Phone Developers

A few days ago Microsoft has finally released a new set of emulators that are aligned with the latest Windows Phone update, GDR3, which is available to developers since a while and that it’s going to be released soon for all the consumers. One of the most important additions is a new emulator image for the new resolution introduced with GDR3, which is 1080p (1080×1920). But there’s an important thing to highlight: resolution and screen size are two different parameters! If a device is using the 1080p resolution, it doesn’t mean that it has a big screen. Take, as example, the Lumia 1320: it features the same resolution of other devices on the market (720p), like the HTC 8X, but it offers a much bigger screen (6 inches).

This means that knowing the device’s resolution isn’t enough: if you want to adapt your application to devices with big screens (by showing, for example, more information), you need to know the real size of the screen. All the emulators included in the SDK simulates a standard device: you can notice, in fact, that the 1080p emulator offers the standard interface with two columns of tiles, while devices like the Lumia 1520 and Lumia 1320 offers three columns of tiles.

And what if you want to optimize your app for bigger screens and you don’t have a real device to play with? Rudy Huyn, the developer behind many famous apps like 6tag or 6sec, has created a simple class that can be used to “fake” the big screen, so that you can test your apps using one of the standard emulators.

Here are two articles that you’ll find useful to adapt your applications:

Happy coding!

Posted in Windows Phone | Tagged | Leave a comment