One of the most powerful features in XAML is design time data support. Let’s say that you have an application that displays some news retrieved from a RSS feed using a ListView or a GridView control. If you try to edit the visual layout of your application using Blend or the Visual Studio designer, you won’t be able to get a preview of the final result: since data is retrieved from a remote service, the ListView will look empty, since the designer isn’t able to load the real data. This scenario makes hard for a designer to have a real preview of the final result or to edit some elements (like the ItemTemplate of the ListView).

Design data is the solution to this problem: it’s basically a way to create fake data, that is loaded only when the View is displayed in Blend or in the Visual Studio designer. Let’s see how to manage this scenario using Caliburn Micro.

The sample app: a simple news reader

As a sample, we’re going to develop a simple news reader, that will read and parse the RSS feed of this blog. The real application will display the real posts from the blog, while the designer will display some fake posts, just to give to designer an idea of the content that will displayed in the page. First, let’s start to set up the real application, using the conventions we’ve learned in the previous posts. The application will have just one View, that will display a list of posts using a ListView control.

First, let’s define a simple class that will map some of the information about the post that we want to display in the page:

public class FeedItem
{
    public string Title { get; set; }
    public DateTimeOffset PublishDate { get; set; }
    public string Description { get; set; }
}

Then, we need to download the RSS feed from the web and convert the XML into a list of FeedItem objects. For this purpose, we’re going to create a separate class, that will take care of processing the RSS feed: we’re going to define a method that will take, as input, the URL of the RSS feed and will return, as output, a collection of FeedItem objects. Here is how the interface of the class looks like:

public interface IFeedService
{
    Task<IEnumerable<FeedItem>> GetNews(string feedUrl);
}

To implement it, we’re going to use one of the new 8.1 APIs, called SyndicationClient: it’s a special HttpClient implementation that is able to download the RSS feed and to automatically parse it, so that you can work with classes and objects instead of raw XML. Here is the implementation:

public class FeedService: IFeedService
{
    public async Task<IEnumerable<FeedItem>> GetNews(string feedUrl)
    {
        SyndicationClient client = new SyndicationClient();
        SyndicationFeed feed = await client.RetrieveFeedAsync(new Uri(feedUrl, UriKind.Absolute));
        List<FeedItem> feedItems = feed.Items.Select(x => new FeedItem
        {
            Title = x.Title.Text,
            Description = x.Summary.Text,
            PublishDate = x.PublishedDate
        }).ToList();

        return feedItems;
    }
}

We use the RetrieveFeedAsync() method, which takes in input the URL of the RSS feed (which is passed as parameter of the GetNews() method), and it will give you in return a SyndicationFeed object, which stores all the information about the feed. What’s interesting for us is the Items collection, which contains all the news that are included in the feed (in our case, the list of all the posts published in this blog). Using LINQ, we convert it into a collection of FeedItem objects, by grabbing the title, the description and the published date of the post.

Now we need to use this class in the ViewModel that is connected to our page. The easiest way would be to simply create a new instance of the FeedService class and to call the the GetNews() method, like in the following sample:

public class MainPageViewModel : Screen
{

    public MainPageViewModel()
    {
    }

    private List<FeedItem> _news;

    public List<FeedItem> News
    {
        get { return _news; }
        set
        {
            _news = value;
            NotifyOfPropertyChange(() => News);
        }
    }

    protected override async void OnActivate()
    {
        IFeedService feedService = new FeedService();
        IEnumerable<FeedItem> items = await feedService.GetNews("http://feeds.feedburner.com/qmatteoq_eng");
        News = items.ToList();
    }
}

However, this approach has some cons. Let’s say that, due to some changes in the requirements, you need to swap the FeedService() class with another implementation, by keeping the IFeedService interface as a base ground. With this approach, you would have to go in every ViewModel in which you’re using the FeedService class and replace the implementation. But wait, there’s a better way to do that: using the dependency injection container provided by Caliburn Micro!

Let’s move to the App.xaml.cs file and, in the Configure() method, let’s register the FeedService, like we did for the different ViewModels:

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

    container.RegisterWinRTServices();

    container.PerRequest<MainPageViewModel>();
    container.PerRequest<IFeedService, FeedService>();
}

The only difference is that, this time, since we have an interface that describes our class, we use another approach: instead of registering just the class (by calling the PerRequest<T>() method), we bind the interface with the concrete implementation, by using the PerRequest<T,Y>() method. Now, to get a reference to the FeedService class in our ViewModel, we simply need to add a new parameter in the constructor, which type is IFeedService, like in the following sample:

public class MainPageViewModel : Screen
{
    private readonly IFeedService _feedService;

    public MainPageViewModel(IFeedService feedService)
    {
        _feedService = feedService;
    }

    private List<FeedItem> _news;

    public List<FeedItem> News
    {
        get { return _news; }
        set
        {
            _news = value;
            NotifyOfPropertyChange(() => News);
        }
    }

    protected override async void OnActivate()
    {
        IEnumerable<FeedItem> items = await _feedService.GetNews("http://feeds.feedburner.com/qmatteoq_eng");
        News = items.ToList();
    }
}

We’ve simply added a parameter in the constructor which type is IFeedService: the dependency injection container will take care of resolving the parameter at runtime, by injecting the real implementation we’ve defined in the App class (in our case, FeedService). This way, if we need to use a different implementation of the IFeedService class, we simpy have to go back to the App class and change the Configure() method we’ve previously defined, instead of having to change the code in every ViewModel that needs to use this class. Now we can simply define our View using a ListView control, to display the posts retireved by the FeedService:

<ListView ItemsSource="{Binding Path=News}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Path=Title}" Style="{StaticResource TitleTextBlockStyle}" />
                <TextBlock Text="{Binding Path=PublishDate}" Style="{StaticResource BodyTextBlockStyle}"></TextBlock>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Now if you run the app (it doesn’t matter if the Windows 8.1 or the Windows Phone 8.1 version) you should see the lists of posts recently published on this blog, downloaded from the following RSS feed: http://feeds.feedburner.com/qmatteoq_eng

image

Using design data

If you try to open your project in Blend or you enable the Visual Studio designer, you’ll notice that the page will be empty: the real FeedService isn’t executed during design time, so you don’t get a chance to see the list of posts. The purpose of our work will be to display a list of fake posts, in case the View is displayed inside the designer.

One thing you should have noticed, while working with Caliburn, is that you don’t get Intellisense while you’re dealing with binding, unlike when you work with other toolkits like MVVM Lights. This happens because you’re not explicitly setting the DataContext of the page: it’s automatically resolved at runtime, by using the specfic Caliburn naming convention. The result is that, when you’re writing the XAML, the View doesn’t know which is the ViewModel that is connected to it. This is a consequence of the design data requirement: we need to tell to the View which is the connected ViewModel, so that it can enable Intellisense and that it can provide design data for us.

Here is how to do it:

<Page
    x:Class="DesignData.Views.MainPageView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:DesignData"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:micro="using:Caliburn.Micro"
    xmlns:viewModels="using:DesignData.ViewModels"
    mc:Ignorable="d"
    d:DataContext="{d:DesignInstance Type=viewModels:MainPageViewModel, IsDesignTimeCreatable=True}"
    micro:Bind.AtDesignTime="True"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <ListView ItemsSource="{Binding Path=News}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Path=Title}" Style="{StaticResource TitleTextBlockStyle}" />
                        <TextBlock Text="{Binding Path=PublishDate}" Style="{StaticResource BodyTextBlockStyle}"></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Page>

First we’ve defined which is the DataContext of the page, but we did it in a different way, by adding the prefix d: this way, we’re telling to the XAML compiler that this value should be used only at design time, while at runtime the application will continue to use the standard DataContext (in our case, the ViewModel assigned by Caliburn). With this definition, basically we’re manually defining what Caliburn automatically does at runtime: we’re telling to the current View that the DataContext class to use is called MainPageViewModel and that supports design time data.

Then, we need to use a special Caliburn attached property, that is able to perform the binding for us at design timed: it’s called Bind.AtDesignTime and its value has to be set to True. Please note that, to get this code working, we need to define two XAML namespaces: the first one (called viewModels in the sample) which points to the project’s folder that contains all our ViewModels (in our case, using:DesignData.ViewModels, where DesignData is the name of the project); the second one (called micro in the sample) it’s the default Caliburn one, which is using:Caliburn.Micro.

After this setup, one thing you’ll immediately notice is that you’ll get Intellisense up and running: if you try to setup a new binding with a control, Visual Studio will propose you one of the properties that have been declared in the ViewModel.

Now it’s time to define the design time data: one important thing to highlight is that this feature, to work properly in Caliburn, requires a parameterless constructor. In our case, it will be different than the standard one (which, instead, contains a parameter which type is IFeedService): in this empty constructor we’re going to set up the fake data, by filling the News collection (the one displayed in the ListView control) with a list of fake posts, like in the following sample.

public class MainPageViewModel : Screen
{
    private readonly IFeedService _feedService;

    public MainPageViewModel(IFeedService feedService)
    {
        _feedService = feedService;
    }

    public MainPageViewModel()
    {
        if (Execute.InDesignMode)
        {
            News = new List<FeedItem>
            {
                new FeedItem
                {
                    Title = "First news",
                    Description = "First news",
                    PublishDate = new DateTimeOffset(DateTime.Now)
                },
                new FeedItem
                {
                    Title = "Second news",
                    Description = "Second news",
                    PublishDate = new DateTimeOffset(DateTime.Now)
                },
                new FeedItem
                {
                    Title = "Third news",
                    Description = "Third news",
                    PublishDate = new DateTimeOffset(DateTime.Now)
                }
            };
        }
    }

    private List<FeedItem> _news;

    public List<FeedItem> News
    {
        get { return _news; }
        set
        {
            _news = value;
            NotifyOfPropertyChange(() => News);
        }
    }

    protected override async void OnActivate()
    {
        IEnumerable<FeedItem> items = await _feedService.GetNews("http://feeds.feedburner.com/qmatteoq_eng");
        News = items.ToList();
    }
}

As you can see, the main code of the ViewModel is the same: we have one constructor, that takes care of initializing the IFeedService object; we have a property called News, which contains a list of FeedItem objects; in the OnActivate() method (that is invoked when the view is displayed) we use the FeedService class to retrieve the list of posts and to display it in the View.

The difference is that now we have a constructor without parameters, in which we initialize a list of fake posts: we manually create some FeedItem objects and we add them to the News collection. Of course, we want to do that only if the View is displayed in the designer: we don’t want to display fake data when the app is running on the phone. For this purpose, we can use a Caliburn class called Execute, which provides some useful properties and methods: for our scenario we can use a property called InDesignMode, which is a simple boolean that is set to true in case the View is displayed inside the designer. We’re goint to add fake data to the News collection only if the value of this property is set to true.

Now, build your project and try to open the designer: you’ll notice that the View won’t be empty anymore, but it will display the fake data we’ve provided.

image

Wrapping up

As usual, I’ve commited all the samples described in this post in my GitHub project (https://github.com/qmatteoq/CaliburnMicro-UniversalApp-Demo), inside the folder called DesignData. Have fun!

Tagged with:  

When you’re developing an application using the MVVM pattern, one of the most common needs is to create a communication channel between two ViewModels or a ViewModel and a View: you need to exchange some data between the two actors, but you don’t have an easy way because everything is decoupled.

Messages are the perfect solution for such scenarios: they’re basically objects, that a class (like a ViewModel) can send using a special messenger; any other class can subscribe to receive such kind of messages and perform an operation when it happens. With this approach, we are able to maintain the fundamental concept of MVVM, which is “separation of concerns”. When a class sends a message, it doesn’t know who will be the receiver: it’s the class that wants to receive the message that needs to act and prepare itself to receive messages.

In Caliburn Micro, this scenario is achieved using one of the built-in services, called EventAggregator: it’s our postman and we’re going to use it to publish and to receive messages.

Let’s see how it works and how to use it in a Universal Windows app.

Sending a message

As a sample scenario, we’re going to develop a simple application with two pages: a main page and a detail page. The detail page will offer a button that will send a message containing some text; the main page will subscribe itself to receive this message and it will display the text on the screen, using a TextBlock control.

I won’t go into the details needed to setup the application and to connect the ViewModel’s properties and actions to the UI: you can see my previous posts, where I explained the basic concepts of a Caliburn Micro application.

The first step to use the EventAggregator is to add a reference to it in our ViewModel: in the same way we did in the previous post for the NavigationService, we need to add a parameter in the constructor of the ViewModel’s class, which type will be IEventAggregator.

public class DetailPageViewModel: Screen
{
    private readonly IEventAggregator _eventAggregator;

    public DetailPageViewModel(IEventAggregator eventAggregator)
    {
        _eventAggregator = eventAggregator;
    }
}

Now that we have a reference to the EventAggregator class, we can manage the button’s click: we’re going to define a method in the ViewModel, that will be invoked when the button is clicked. The purpose of this method is to send a message:

public async void SendMessage()
{
    string message = "This is a simple message";
    await _eventAggregator.PublishOnUIThreadAsync(message);
}

In this sample the message is simply a text: we send a string object by passing it as parameter of the method PublishOnUIThreadAsync() offered by the EventAggregator class. There are multiple ways to send a message: we’ll deal with them later. For the moment, it’s important to know that the PublishOnUIThreadAsync() method simply takes the object passed as parameter and sends it as a message on the UI thread. This means that the receiver class will receive it on the same thread that manages the user interface of the application: it’s perfect for our scenario, since we’re simply going to display the text on the UI.

Receiving a message

There are two steps to register a class to receive a message: the first one requires to use, again, the EventAggregator class. As a consequence, you’ll need to add an IEventAggregator parameter also in the receiver’s ViewModel constructor. The difference is that, this time, we’re going to call the Subscribe() method, that will communicate to our postman that the current class wants to receive messages.

public class MainPageViewModel: Screen
{
    public MainPageViewModel(IEventAggregator eventAggregator)
    {
        eventAggregator.Subscribe(this);
    }
}

As a parameter of the Subscribe() method you need to pass which class is going to subscribe to receive messages: since, in this case, it’s the ViewModel itself, we simply pass the value this, that is a reference to the current class.

The second step is to implement the IHandle<T> interface, where T is the type of message we want to receive: by doing so, you’ll be forced to implemented the Handle() method, which will receive as input the message.

public class MainPageViewModel: Screen, IHandle<string>
{
    private string _text;

    public string Text
    {
        get { return _text; }
        set
        {
            _text = value;
            NotifyOfPropertyChange(() => Text);
        }
    }

    public MainPageViewModel(IEventAggregator eventAggregator)
    {
        eventAggregator.Subscribe(this);
    }

    public void Handle(string message)
    {
        Text = message;
    }
}

Here is a complete sample of the MainPageViewModel class: first, we’ve implemented the IHandle<string> interface, since we want to receive the message sent by the DetailViewModel class, which is a string. Then, we’ve created a method called Handle(), which receives as parameter a string, since it’s the type of message we expect: now we are free to manage the message as we prefer, according to our needs. In the sample, we simply take the string and we assign it to a property called Text, which is connected to a TextBlock control in the View.

If we try this simple application, we’ll see that, if we tap on the button to send the message that we’ve placed in the detail page and then we go back to the main page, the text stored in the message will be successfully displayed on the screen.

Sending and receiving complex messages

In the previous sample we’ve simply sent a string as a message. However, there are situations when using a base type can be too generic: for example, we could have multiple ViewModel registered to receive string messages, but we want that a particular message is received only by a specific ViewModel.

In this case, the solution is easy: the EventAggregator can send not only basic types as messages, but also complex objects. Let’s try to implement the same scenario, but with a different approach: instead of sending a simple string, we’re going to send an object that will store a string.

First, we need to add a new class in our application, that can act as a message. We’re going to call it SimpleMessage:

public class SimpleMessage
{
    public string Text { get; private set; }

    public SimpleMessage(string text)
    {
        Text = text;
    }
}

It’s a simple class, which exposes a string parameter called Text, which is initialized using the constructor. The next step is to send the message, using the same approach we’ve seen before with the EventAggregator class and the PublishOnUIThreadAsync() method: the only difference is that, this time, instead of passing as parametere a simple string, we’re going to send a SimpleMessage object.

public async void SendComplexMessage()
{
    SimpleMessage message = new SimpleMessage("This is a complex message");
    await _eventAggregator.PublishOnUIThreadAsync(message);
}

Now, in the MainPageViewModel, we need to subscribe to receive the SimpleMessage by simply implementing the IHandle<T> interface in the proper way, like in the following sample:

public class MainPageViewModel: Screen, IHandle<SimpleMessage>
{
    private string _text;

    public string Text
    {
        get { return _text; }
        set
        {
            _text = value;
            NotifyOfPropertyChange(() => Text);
        }
    }

    public MainPageViewModel(IEventAggregator eventAggregator)
    {
        _navigationService = navigationService;

        eventAggregator.Subscribe(this);
    }

    public void Handle(SimpleMessage message)
    {
        Text = message.Text;
    }
}

Nothing special to mention: it’s the same approach we’ve used before, the only difference is that this time the Handle() method will receive a real object (which type is SimpleMessage) instead of a simple type.

Sending and receiving messages to the code behind

Another common scenario is the communication between a ViewModel and a View: there are, in fact, certain operations that require direct access to the controls, like starting an animation or invoking a method that is exposed only in code behind. A way to solve this scenarios is using behavior, but sometimes they can be complex to define: sending messages is much easier.

Sending and receiving messages in the code behind is the same we’ve seen before with ViewModels: we send messages using the EventAggregator class and we receive them by implementing the IHandle<T> interface. The only difference is that, in the code behind, we can’t add an IEventAggregator paramter to the constructor: dependency injection works fine only for ViewModels. The solution is to manually interact with the Caliburn container, to explicity ask for an EventAggregator object: to achieve this result, we first need to do a change in the App class since, by default, the container is declared as a private variable, so we can’t use it in another class.

public sealed partial class App
{
   public WinRTContainer container { get; private set; }

   public App()
   {
       InitializeComponent();
   }
}

We’ve simply changed the container’s type from private to public and we’ve turned it into a property. Now, from every class, we can access to the container in the following way:

WinRTContainer container = (Application.Current as App).container;

To explicity ask for an instance of a class registred in the container, we need to use the GetInstance<T> method. Let’s see that we want to receive the SimpleMessage object we’ve sent before in the code behind of the MainPage View. Here is how we can do it:

public sealed partial class MainPageView : Page, IHandle<SimpleMessage>
{
    public MainPageView()
    {
        this.InitializeComponent();

        this.NavigationCacheMode = NavigationCacheMode.Required;

        WinRTContainer container = (Application.Current as App).container;

        IEventAggregator eventAggregator = container.GetInstance<IEventAggregator>();

        eventAggregator.Subscribe(this);
    }

    public void Handle(SimpleMessage message)
    {
        MessageContent.Text = message.Text;
    }
}

As you can see, there aren’t big differences with the previous approach: the class implements the IHandle<SimpleMessage> interface and, as a consequence, it defines the Handle() method which receives, as parameter, a SimpleMessage object. The only difference is that we set up the EventAggregator in another way: after we’ve obtained a reference to the WinRTContainer object, we ask for the EventAggregator instance registered in the container by calling the GetInstance<IEventAggregator>()  method. Then, we proceed as usual, by calling the Subscribe() method passing this as parameter, since we want the actual code behind class to be able to receive messages.

Managing messages in a background thread

One of the new features added in Caliburn Micro 2.0 is the support to send messages in a background thread. This scenario is useful if the receiver class needs to perform intensive operation when the message is received: to avoid impacting on the UI, we can handle the message in a separate thread. Sending a message in a background thread is really easy: just use the PublishOnBackgroundThread() method offered by the EventAggregator class, like in the following sample:

public void SendMessageInBackground()
{
    SimpleMessageInBackground message = new SimpleMessageInBackground("This is a message handled in a background thread");
    _eventAggregator.PublishOnBackgroundThread(message);
}

 

Then, in the receiver class, we’ll handle it in the same way we did in the previous samples: we implement the IHandle<T> interface and we manage the Handle() method in the class. The only difference is that, this time, the Handle() method will be executed on the background thread: we need to remember that, if we need to interact with the View (for example, by changing a control’s property) we need to use the Dispatcher, which takes care of redirecting the operation to the UI thread; otherwise, we will get a cross-thread access exception.

Take a look at the following sample:

public sealed partial class MainPageView : Page, IHandle<SimpleMessageInBackground>
{
    public MainPageView()
    {
        this.InitializeComponent();

        this.NavigationCacheMode = NavigationCacheMode.Required;

        WinRTContainer container = (Application.Current as App).container;

        IEventAggregator eventAggregator = container.GetInstance<IEventAggregator>();

        eventAggregator.Subscribe(this);
    }

    public void Handle(SimpleMessageInBackground message)
    {
        Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            MessageContent.Text = message.Text;
        });
    }
}

This sample is similar to the previous one: in a code behind class we register to receive a message which type is SimpleMessageInBackground. The final result is the same: we display the content of the message in a TextBlock control called MessageContent. The difference, this time, is that we do it using the RunAsync() method of the Dispatcher class, since we’re interacting with a control in the XAML but the message is being handled in a background thread.

That’s all!

In this post we’ve covered all the basic concepts about sending and receiving messages in a MVVM application built with Caliburn Micro 2.0. The last week I’ve decided to publish all the samples connected to this series of post about Caliburn Micro and Universal Windows app on GitHub: the repository is available on https://github.com/qmatteoq/CaliburnMicro-UniversalApp-Demo. You’ll find in the solution, together will all the samples of the previous posts, also a new one about messages.

Tagged with:  

In my everyday job at Funambol I work on an application called OneMediaHub, which is the Windows Phone client for the cloud services offered by the company. The application is built using the MVVM pattern and Caliburn Micro as a framework. Now that the development cycle of the new version of the client is completed, one of my goal before starting working on the new features for the next version is to upgrade Caliburn Micro from the previous version (1.5.3) to the most recent one (2.0).

However, as I discovered by my self, the procedure isn’t so straight forward: Caliburn Micro is a big improvemenet compared to the previous version, but it also includes many breaking changes. In this post I’ll detail the most important ones I had to face during the migration.

Changes in bootstrapper

The boostrapper is the base class that replaces the App one and that takes care of initializing the app, among all the Caliburn services and conventions.

There are two important changes in the boostrapper with Caliburn Micro 2.0:

  • In the previous release, the bootstrapper’s class had to inherit from the PhoneBootstrapper one. Now, instead, the base class has been renamed to PhoneBootstrapperBase.
  • Now, in the constructor of the bootstrapper’s class, you need to call the Initialize() method, while in the previous version it wasn’t required.

Here is a full working initialization of the bootstrapper for Caliburn Micro 2.0:

public class CaliburnBootStrapper : PhoneBootstrapperBase
{
    public OneMediaHubBootStrapper()
    {
        this.Initialize();
    }
}

Thanks to Matteo Tumiat that pointed me in the right direction: without calling the Initialize() method, the app was stuck in the loading phase, without any warning or exception.

Changes in EventAggregator

EventAggregator is the class used to manage messages (which are, in the end, simple objects) that can be sent and received from different classes (like two ViewModels or a ViewModel and a View). This approach helps to create a communication channel between different classes while keeping alive, at the same time, the fundamental MVVM concept of “separation of concerns”. In fact, when a class sends a message, it doesn’t know who’s going to receive it: it’s the receiver class that will simply register itself to handle specific kind of messages.

To send a message in Caliburn Micro 1.5 we used the Publish() method of the IEventAggregator class, that simply dispatched the object using the UI thread. In Caliburn Micro 2.0 this method doesn’t’ exists anymore and it’s been replaced with multiple methods, that support a greater number of scenarios, like sending messages on a background thread, or using the UI thread but in an asynchronous way.

If you want to replace the Publish() method without changing the old behavior (so the message is sent in a synchronous way on the UI thread), you just need to use the new PublishOnUIThread() method.

Otherwise, if you want to improve performances and avoid to overload the UI thread, you can use the new asynchronous version, which is PublishOnUIThreadAsync(): however, by doing this, you’ll need a bit more work to complete the porting; since the metod is asynchronous , you’ll have to add as prefix the await keyword and mark the container method with the async one. But, most of all, you’ll have to verify that you’re correctly managing the asynchronous pattern: for instance, if your method that sends the message is marked as void and it’s not an event handler, you should change it so that it returns a Task, so that it can be correctly awaited by the caller.

private async Task SendMessage()
{
  
    await eventAggregator.PublishOnUIThreadAsync(new SimpleMessage());
  
}

There’s also another useful new method offered by the IEventAggregator class, which is called PublishOnBackgroundThread(): by using it, the Handle() method that will receive it will be executed in a background thread instead of the UI thread. It’s useful when the receiver class needs to perform many CPU consuming tasks when a message is received.

New namespace for the Message class

In my application I found myself multiple times using the Message.Attach attached property, which can be useful to manage in a ViewModel events that are raised by controls in the UI. In the previous Caliburn Micro version, the Message class was define inside the Caliburn.Micro assemply. It means that, to use it, you had added the following namespace in the XAML definition:

xmlns:micro="clr-namespace:Caliburn.Micro;assembly=Caliburn.Micro

Now the assembly that contains the Message class is changed to Caliburn.Micro.Platform: as a consequence, you’ll have to change all your XAML namespaces definition to

xmlns:micro="clr-namespace:Caliburn.Micro;assembly=Caliburn.Micro.Platform"

Managing the application bar

To manage the application bar in a Caliburn way I’ve used in my project a third party component made by Kamran Ayub, called CaliburnBindableAppBar. I’ve talked abut it in details in the following blog post. The problem comes if, like me, you’ve installed the component using NuGet: the available version, in fact, it’s compiled against Caliburn Micro 1.5 and it won’t work if you upgrade your project to Caliburn Micro 2.0. However, the developer has already updated the project: on GitHub you can see that the component already supports Caliburn Micro 2.0, as stated in the changelog. I’ve already contacted the developer and he promised me that he’s going to update the package on NuGet soon; however, if you need to use the updated application bar right now, the solution is simple: just download the project from GitHub and compile it by yourself or add it to your solution.

That’s all!

If you had a similar experience and you found other changes that are worthes to be mentioned, feel free to leave a comment!

Tagged with:  

Let’s continue our journey with Caliburn Micro and Universal Windows app. After talking about the project setup and binding and actions, let’s see how to manage navigation in a Windows and Windows Phone 8.1 app.

The NavigationService

Managing navigation is one of the challengers offered by the MVVM pattern: the Windows Runtime offers a static class called Frame, which exposes the methods needed to perform the navigation. This class is available only in the code behind, since it’s inherited from the Page class, which is the base class from which every application’s page inherits from. Since the ViewModels don’t inherit from the Page class, you won’t be able to directly access to the Frame class. Here comes the NavigationService class, which is a wrapper that can be used to perform navigation duties inside a ViewModel. Using it is really simple: since it’s one of the services that is embedded in Caliburn Micro, it’s automatically registered during the startup (do you remember the RegisterWinRTServices() method that is called in the Configure() method defined in th App.xaml.cs file?).

To get access to the NavigationService, you simply need to add a parameter of type INavigationService to the ViewModel constructor: the container will take care of injecting the concrete implementation of the service at runtime. Here is a sample of a ViewModel that registers the NavigationService:

public sealed class MainPageViewModel: Screen
{
    private readonly INavigationService _navigationService;

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

Now you’ll be able to use the NavigationService across the ViewModel: for example, you can use it in a method that is triggered when a button is clicked. One of the nice things of the NavigationService class is that supports a ViewModel-First approach, which is very useful when you work with the MVVM: you can specify, instead of the page where to redirect the user, the ViewModel that is associated to the page. Caliburn Micro will take care of resolving the correct page and it will perform the navigation. This goal is achieved using the method NavigateToViewModel<T>(), where T is the type of ViewModel where we want to redirect the user.

Here is a sample:

public void GoToDetail()
{
    _navigationService.NavigateToViewModel<DetailPageViewModel>();
}

Managing parameters

One of the most interesting changes included in the Windows Runtime is that navigation isn’t based anymore on uris like in Silverlight: as a consequence, you are able to pass as navigation’s parameters also complex objects, while in Windows Phone 8.0 you were forced to pass only plain data (like texts or numbers). Caliburn Micro 2.0 supports this scenario, simply by accepting a parameter in the NavigateToViewModel<T>() method. Let’s use the same sample we’ve seen in the previous post: we’re going to display a list of movies using a ListView control. When the user taps on one of them, we’re going to use the ItemClick event to redirect him on the detail page.

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

We’ve simply added the object received by the method GoToDetail() as parameter to the NavigateToViewModel<T>() method. Now we have another problem: how to get the parameter in the destination ViewModel? In an application developed without MVVM, we would have used the OnNavigatedTo() method defined in the code behind: the parameter returned by the method contains a property, called Parameter, with the object that has been sent by the source page. But, again, this is a scenario that can be satisfied because the code behind class inherits from the Page class: we can’t say the same for the ViewModel class.

Caliburn Micro uses a naming convention to manage this scenario: you just have to define, in the destination ViewModel, a property called Parameter, which type is the same of the object you’ve passed to the NavigateToViewModel<T>() method. Since, in the previous example, we passed a Movie object, here is how we can setup the DetailPageViewModel class:

public class DetailPageViewModel: Screen
{
    public Movie Parameter { get; set; }

    private string title;

    public string Title
    {
        get { return title; }
        set
        {
            title = value;
            NotifyOfPropertyChange(() => Title);
        }
    }

    protected override void OnActivate()
    {
        Title = Parameter.Title;
    }
}

As you can see, in the DetailPageViewModel class we’ve added a new public property called Parameter, which type is Movie. This way, we’ll be able to access to the Movie object sent by the main page: in this sample, we’re going to display the title of the movie in the page , by assigning it to the Title property. The operation is performed in the OnActivate() method, which is triggered when the page is displayed: it’s one of the navigation events that is offered by the Screen class which, as you may have noticed, is the one all the ViewModels are inheriting from. With this method, we are able to recreate the OnNavigatedTo() event inside the ViewModel.

Managing the back button

One of the biggest differences between Windows Phone 8.0 and Windows Phone 8.1 is the back button management: as a consequence of the alignment with the Windows 8 platform (which doesn’t offer a hardware back key button), the default behavior when the Back button is pressed is to redirect the user to the previous application and not to the previous page. This doesn’t mean that it’s correct, from a user experience point of view, to keep this behavior: the user expects to go back to the previous page of your application when the Back button is pressed. To support the developer to correctly manage this scenario, all the Visual Studio templates for the Universal Windows apps (except the Blank App one) include a class called NavigationHelper, which, among other things, automatically intercepts the Back button pressed event and redirects the user to the previous page of the app.

However, if you’re using Caliburn Micro, you won’t need it: the framework will take care, automatically, of managing the back button for you. In the previous sample, you’ll notice the by pressing the Back button in the detail page, you’ll be correctly redirected to the main page of the app and not the previous application in the OS stack.

Wrapping up

In this post we’ve learned how to properly manage navigation in a Universal Windows app using Caliburn Micro. As usual, you can download a sample project to play with from the following link.

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

Tagged with:  

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

Tagged with:  

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

Tagged with:  

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!

Tagged with:  

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!

 

Tagged with:  

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!

Tagged with:  

For me the first day of the year is always a special day: not only because it’s a day full of hope for the things that are going to come during the year, but also because it’s the day in which, since 2011, my MVP status expires. If you’re not familiar with the MVP, it’s an award gifted by Microsoft to the community leaders for their passion and enthusiasm in sharing their knowledge about Microsoft technologies (in my case, about Windows Phone development). It’s not a “one time” award: you have to earn it every year and to prove that you still deserve it. For me, this time of the year is 1st January: and I’m really happy to say that Microsoft has confirmed his trust in me and renewed my award also for 2014!

2013 has been a crazy year for me as an MVP: 2 summits, the release of my first book, the Windows Phone Week organization, the Italian webinar series with Nokia and much much more. There are so many people to thank for this great year! The first one is, for sure, my wife Angela, that keeps supporting me, even when my activities steal some of the time that we can spend together. Then, in random order:

  • Lorenzo Barbieri, which is not only a friend but he’s also the best supporter (together with the DPE department) of the Windows Phone activities that we organize with the community.
  • Daniele Pagani, Luca De Bernardi and Frangino Lucarini, which are part of the Italian Nokia team that are doing an amazing job in supporting the Italian Windows Phone developers and our activities as Nokia Champions.
  • Desiree Lockwood, the referral for our activities as Windows Phone Development MVPs. She’s an amazing person and she’s doing a terrific job. Without her, the Windows Phone Week (and many other activities) would have been just a crazy idea.
  • The Windows Phone Development’s MVP family (with a special mention to Joost Van Schaik): they’re the living proof that being part of the MVP family doesn’t mean just connecting with great professionals, but also that you can find and meet great friends, even if they live far away from you.
  • Ugo Lattanzi: if today I have the pleasure to be part of the MVP family it’s totally his fault Smile He’s the one that, 5 years ago, made me discover the community world and conviced me to open a blog and to do my first speech about Windows Phone. Everything started right there Smile
  • Roberto Freato and the DotNetLombardia crew, which accepted me as part of the community and involved (and keep involving me) in all their activities.
  • Funambol and my team: I’ve joined the company more than 1 year ago and it has been one of the best things that happened in my life. I met many special people and friends and I love the way the company keeps supporting my community activites. I’m really proud to be part of it!

But, of course, my biggest thank goes to all the developers and communities out there, which keeps supporting and believing in me. I’m looking forward to keep working with you in 2014!

Tagged with:  
Animated Social Media Icons Powered by Acurax Wordpress Development Company