Prism for Xamarin Forms – An overview (Part 1)

Even if I understand that it may not be the right technology for every project, I’m a huge fan of Xamarin Forms. As you’ll probably know if you follow my blog, I’m a Windows Developer and Xamarin Forms allows me to use basically all my current skills (XAML, binding, MVVM, etc.) to create applications also for other popular mobile platforms like iOS and Android. Additionally, it gives me the chance (like with native Xamarin) to take advantage of platform specific features and, at the same time, to maintain a user experience which is coherent with the look & feel of the operating system.

I’ve recently used Xamarin Forms to create a porting for Android of my simple Qwertee Shirts app and the advantage was clear: I was able to reuse most of the backend code I’ve already wrote for the UWP version and my XAML knowledge but, at the end, I got an application that fully embraced, from a UI point of view, the new Material Design created by Google, so it doesn’t look “alien” like it often happens with cross platform applications based on other cross platform technologies.

Screenshot_2016-08-20-12-10-58 Screenshot_2016-08-20-12-11-19

However, I’m not only a Windows Developer, but also a MVVM enthusiast and I’ve blogged about this topic multiple times, covering multiple platforms and frameworks. If you’re new to the MVVM pattern, I suggest you to start from this post and move on with the rest of the series. As such, the first thing I did when I decided to resume working with Xamarin Forms to port my app was looking for the best way to reuse my MVVM knowledge to develop the project and, as usual, the choice was hard. In this case, it was even more complicated because Xamarin Forms, compared to other XAML technologies like WPF or UWP, is pretty new, so it was hard to find in the beginning a choice that completely satisfied me.

Don’t get me wrong, if you remember my posts about learning the MVVM pattern, you’ll know that I’m a huge fan of the flexibility offered by MVVM Light and Laurent Bugnion did a superb job to introduce typical MVVM concepts (like binding and commands) in platforms that don’t natively support them, like Android and iOS. However, Xamarin Forms is a bit different than standard Xamarin: it already offers the concepts we need to leverage the MVVM pattern, like binding, data context, dependency properties, behaviors, etc. In this scenario, MVVM Light is still a great choice but, however, you still have to reinvent the wheel to solve many common scenarios you have to deal with when you’re developing a XAML app, like handling navigation, getting access to navigation events in a ViewModel or passing parameters between one page to the other.

Even do it on purpose, right before starting my porting I saw a tweet by Brian Lagunas, one of the MVPs behind the Prism project, announcing a new version of Prism specific for Xamarin Forms. Just to refresh your mind, Prism is a MVVM framework that, originally, was created by the Patterns & Practices division by Microsoft and that, some times ago, has been turned into an open source project driven by the community. Prism has always been a great choice to implement the MVVM pattern in XAML based applications, but sometimes you may have faced the risk to make the project over complicated just to follow its naming conventions and rules (like the requirement of having a bootstrapper to initialize it, despite the fact that XAML based application already have a startup class called App).

After completing the porting, I’ve found myself very satisfied with the Prism approach for Xamarin Forms, so I’ve decided to share my experience with you, hoping that it will get you up & running quicker when you start working on a new Xamarin Forms project.

Creating the first project

The easiest way to create a Xamarin Forms project based on Prism is to use its own Visual Studio extension, that you can download from the Visual Studio Gallery. After you’ve installed it, you will find in Visual Studio a new section called Prism, with various templates for each supported technology. The template we’re interested into is called Prism Unity App (Forms):

prism1

Actually, this template has even an advantage over the standard Xamarin Forms template. As you can see from the image below, it allows you to choose which platform you want to target when you create your project, while the default Xamarin Forms template automatically creates a project for each supported platforms (Android, iOS, Windows Phone 8.1, Windows 8.1, UWP), even if you aren’t interested in targeting one of them.

Project Wizard

After you’ve hit the Create project, you will end up with a standard Xamarin Forms solution: one Portable Class Library and one specific project for each platform you’ve chosen. Additionally, the Portable Class Library will already contain:

  • A Views folder, where to place your pages. The template includes a default one, called MainPage.xaml
  • A ViewModels folder, where to place your ViewModels. The templates includes a default one, called MainPageViewModel.cs.
  • An App class already configured to initialize the Prism infrastructure.

Here is how your default project will look like:

prism2

To demo Prism for Xamarin Forms, I’m going to create a simple client for TrackSeries, a TV Show website created by my great friends and colleagues Adrian Fernandez Garcia and Carlos Jimenez Aliaga.

Let’s start from the beginning and see which references have been automatically added by the template to the project:

prism3

As you can see, other than the standard Xamarin Forms NuGet package, Prism requires two packages: a Core one (which is in common across every platform) and a Forms one (which, instead, contains the specific helpers and services for Xamarin Forms). By default, the standard template leverages Unity as dependency injection container, so you’ll find installed also a bunch of other packages like Unity, Prism.Unity.Forms and CommonServiceLocator. However, if you don’t like Unity, Prism for Xamarin Forms offers some additional packages to integrate other popular dependency injection containers, like Ninject or Autofac.

The App class

One of the biggest changes compared to the old Prism versions is the removal of the bootstrapper concept, which was a dedicated class of the project that took care of initializing all the Prism infrastructure. Xamarin Forms (as every other XAML technology) already has an initializer class: the App one, which is included in the Portable Class Library, so the team has decided to leverage it instead of asking to the developer to create a new one. By default, this class inherits from the Application class. To properly support Prism, we need to change this and let the App class inherit from the PrismApplication one by:

  • In the App.xaml file, adding a new identifier for the namespace Prism.Unity and replacing the root Application node with the PrismApplication one.
<?xml version="1.0" encoding="utf-8" ?>
<prism:PrismApplication xmlns="http://xamarin.com/schemas/2014/forms"
                        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                        xmlns:prism="clr-namespace:Prism.Unity;assembly=Prism.Unity.Forms"
                        x:Class="InfoSeries.App">

</prism:PrismApplication>
  • In the App.xaml.cs file, we need to change the default inheritance from Application to PrismApplication.
public partial class App : PrismApplication
{
    public App(IPlatformInitializer initializer = null) : base(initializer) { }

    protected override void OnInitialized()
    {
        InitializeComponent();

        NavigationService.NavigateAsync("MainPage");
    }

    protected override void RegisterTypes()
    {
        Container.RegisterTypeForNavigation<MainPage>();
    }
}

Additionally, the App class has three distinctive features:

  • It has a base constructor, which takes an IPlatformInitializer object as parameter.
  • It has a method called OnInitialized(), where we initialize the Forms infrastructure (by calling the InitializeComponent() method) and we trigger the navigation to the main page of the app (we’ll see later in details how navigation works).
  • It has a method called RegisterTypes(), which is where we register in the dependency injection container (in this case, Unity) every page and every service required by our application.

The IPlatformInitializer parameter is null by default, but it can be leveraged in case you need to register in the dependency container some specific classes that exists only in a platform specific project. You will find, in fact, that every platform specific project has its own custom initializer class (AndroidInitializer for Android, UwpInitializer for UWP, etc.) which, however, by default has an empty implementation of the RegisterTypes() method. Here is, for example, how the MainPage.xaml.cs of the UWP project looks like:

public sealed partial class MainPage
{
    public MainPage()
    {
        this.InitializeComponent();

        LoadApplication(new DeepNavigation.App(new UwpInitializer()));
    }
}

public class UwpInitializer : IPlatformInitializer
{
    public void RegisterTypes(IUnityContainer container)
    {

    }
}

Connecting Views and ViewModels

As you should already know if you have some previous experience with MVVM , the key to make the pattern working is to connect the ViewModel with its own View through binding. The only difference in a Xamarin Forms app compared to a Windows app is that the property to define the context is called BindingContext and not DataContext. Prism makes use of a simple naming convention to automatically assign a ViewModel to its View:

  • The XAML page should be stored into a folder of the project called Views
  • The ViewModel should be stored into a folder of the project called ViewModels and it needs to have the same name of the page plus the suffix ViewModel (so, for example, the ViewModel connected to the MainPage.xaml will be called MainPageViewModel).

As you can see, this is the exact infrastructure that the Prism template has created for us. Every page that we add to our application needs to be registered in the container, so that we can properly handle the navigation. To register it, we can leverage the RegisterTypes() method of the App class and use one of the methods offered by the Container called RegisterTypeForNavigation<T>, where T is the type of the page. In the starting template, we have just one page called MainPage, so it’s the only one that is automatically registered when the application starts. Here you can notice probably one of the biggest differences between Prism and other MVVM frameworks. With other toolkits, you are used to register in the container only the ViewModels and, eventually, all the services related to them. With Prism, instead, you just register the page’s type: it’s up to Prism to automatically register in the container also the ViewModel connected to the View. As you can see in the sample code, in fact, we have registered the MainPage class and not the MainPageViewModel one.

If you aren’t a fan of the naming convention approach, you aren’t forced to use it: in fact, the RegisterTypeForNavigation() method has another variant, which signature is RegisterTypeForNavigation<T, Y>(), where T is the page’s type and Y is the ViewModel’s type we want to set as BindingContext. So, for example, if you want to connect your MainPage to a ViewModel called MyCustomViewModel, it’s enough to register it using the following code:

protected override void RegisterTypes()
{
    Container.RegisterTypeForNavigation<MainPage, MyCustomViewModel>();
}

In the OnInitialized() method you can see a preview of how navigation works by default: every time you call the RegisterTypeForNavigation<T> method, Prism registers into the NavigationService a reference to that page using, as key, a string with the same type name. As such, since our page’s type is MainPage, we need to pass the string “MainPage” as parameter of the NavigateAsync() method to trigger the navigation to that page. If, by any chance, we want to override this behavior, we can pass as parameter of the RegisterTypeForNavigation<T>() a custom string and use it for the subsequent navigations, like in the following sample, where we have replaced the key “MainPage” with the “MyCustomPage” one.

public partial class App : PrismApplication
{
    public App(IPlatformInitializer initializer = null) : base(initializer) { }

    protected override void OnInitialized()
    {
        InitializeComponent();

        NavigationService.NavigateAsync("MyCustomPage");
    }

    protected override void RegisterTypes()
    {
        Container.RegisterTypeForNavigation<MainPage>("MyCustomPage");
    }
}

However, in the next posts we’ll see more details about how to handle navigation in a more advanced way.

The ViewModel

One of the features I’ve appreciated most of Prism for Xamarin Forms is that it doesn’t require us to do any change in XAML page to support it (for example, there are other MVVM frameworks which require you to change the ContentPage type with a custom one). You will only find, in the MainPage.xaml file, a specific Prism attribute, as property of the ContentPage entry, called ViewModelLocator.AutowireViewModel:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
             x:Class="InfoSeries.Views.MainPage"
             Title="MainPage">
  <StackLayout HorizontalOptions="Center" VerticalOptions="Center">
    <Label Text="{Binding Title}" />
  </StackLayout>
</ContentPage>

This property takes care of connecting the View with the ViewModel: when it’s set to true, the ViewModel will be automatically set as BindingContext of the View if we have respected the naming convention previously described. However, one of the changes introduced in Prism 6.2 is that this property isn’t required anymore, unless you want to explicitly disable the naming convention by setting it to false. The standard template adds it to give a more complete sample, but you can safely remove it.

A key feature offered by every MVVM framework is a class to use for our ViewModels to give quick access to the most used features, like the implementation of the INotifyPropertyChanged interface. Prism doesn’t make any exception and it offers a class called BindableBase, which our ViewModels can inherit from:

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

    public MainPageViewModel()
    {

    }
}

Thanks to this class, whenever we need to create a property that implements the INotifyPropertyChanged interface (so that it can propagate its changes through the binding channel), we can simply use the SetProperty() method in the setter of the property. This method will take care of storing the value and, at the same time, sending a notification to all the controls that are in binding with this property that its value has changed, so they need to update their layout.

The sample app created by template does exactly this: it creates a property called Title, which is connected through binding to a Label control in the XAML page. Whenever we change the value of the property, we will see the UI updated in real time. To be honest, the sample app shows also something different: it sets the value of the Title property in a method called OnNavigatedTo() and it parses some parameters. We’re going to see how this approach works more in details in the next post.

In the next post

In this post we have just scratched the surface and we understood the basic concept behind a Xamarin Forms application created with Prism. In the next post we’ll see some more advanced concepts, like handling navigation in a ViewModel or registering additional services in the dependency container.

Posted in Xamarin | Tagged , , , | Leave a comment

Integrating Facebook in a Universal Windows app

Facebook is, without any doubt, one of the most popular social networks out there. There are many reasons why we would integrate their services into a mobile application: to make the login process easier, to allow sharing some content, to post something on the user’s timeline. I’ve already covered in the past on this blog how to integrate Facebook in a Windows or Windows Phone application. In this post we’re going to see how to achieve this goal in a Universal Windows app for Windows 10 using a new Facebook SDK released by a Microsoft team on GitHub a while ago. Specifically, we’re going to see how to retrieve the main information about the logged user and how to interact with the Graph APIs, the set of REST APIs provided by Facebook to access to their services.

Let’s start!

Configuring the app

The first step to start using the Facebook SDK is registering the app on the Facebook Developer Portal: every mobile or web app which uses the Facebook APIs needs to be connected to an app registered on the Facebook portal. Without this step, Facebook won’t authorize us to perform any operation. Let’s point our browser to https://developers.facebook.com/ and choose to register a new app.

newapp

As you can see, the Windows platform isn’t listed by default, so you have to choose to perform a basic setup with the link at the bottom.

facebook2

The next step will ask you to set a display name (typically, it’s the same name of your application), an optional namespace (which acts as unique identifier for your app) and the category. In the end, press the Create App ID button. At the end of this step, your Facebook app will be created and ready to be configured. Now we need to add support to the Windows platform: we do it in the Settings section, which we can find in the menu on the left. In this page we’ll find the Add platform link, as highlighted in the below image:

facebook3

When you click on the link, this time, you’ll find an option called Windows App in the list. After you’ve chosen it, the following section will appear in the Settings page:

facebook4

In our case, since it’s a Universal Windows app, we need to fill the Windows Store SID field; feel free to ignore the Windows Phone Store SID [BETA] field, since it applies only to old Silverlight apps for Windows Phone.

The SID is the unique identifier that the Windows Store assigns to our application when we associate it using the Store menu in Visual Studio. However, we don’t have to do it in advance to properly register the app on the Facebook portal. It’s enough to use the WebAuthenticationBroker class to retrieve this information: in case the app isn’t associated yet, we’ll retrieve a temporary value which is enough for our tests. Here is how to retrieve the SID in a Universal Windows app:

string sid = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString(); 

You have to take note of this value: the simplest approach is to use the Debug.WriteLine() method to print the value in the Visual Studio’s Output Window.

Here is how a SID looks like:

ms-app://s-1-15-2-2031376880-2039615047-2889735989-2649504141-752107641-3656655002-2863893494/ 

This is the value we need to to put into the Windows Store SID field of the Facebook portal. However, we need to remove the ms-app:// prefix and the ending /. So, based on the previous sample, the SID we would need to add in the developer’s portal is:

s-1-15-2-2031376880-2039615047-2889735989-2649504141-752107641-3656655002-2863893494

The last thing to do is to take note of another information provided by Facebook: the App ID, which will need later during the login phase. You can find it in the main dashboard of your app, as you can see in the following image:

clip_image002

 

Now we’ready to move on and write some code.

Integrating the library

The next step is to integrate the library into your app. Unfortunately, it isn’t available on NuGet, so you’ll need to download the whole project and compile it together with your app. The SDK is available on GitHub, so there are two ways to get it:

  1. Using the Download ZIP button, to download a zipped file with the whole content of the repository.
  2. Cloning the repository on your computer using GIT.

Personally, I suggest using the second approach: this way, you’ll be able to quickly get any update released by the team and keep your app always up-to-date. There are many ways to do it: you can choose the one you prefer, based on your experience with Git. The easiest one is to use the tools integrated in Visual Studio. Let’s see how:

  1. Open Visual Studio.
  2. Open the Team Explorer window. If it isn’t already available in your Visual Studio configuration, look for it in the View menu.
  3. You will find a section called Local Git repositories. Press the Clone button and set:
    1. In the first field, the URL of the GitHub repository, which is https://github.com/microsoft/winsdkfb
    2. In the second field, the local path on your computer where you want to save the project.
  4. Now press the Clone button: Visual Studio will download all the files in your local folder. Any time, by using Solution Explorer, you’ll be able to access to this repository and, by using the Sync button, to download the latest version of the source code from GitHub.

git

Now that you have the library, you can add it to your Visual Studio solution that contains your Universal Windows app, right click on it, choose Add existing project and look for one of the projects of the Facebook SDK you’ve just cloned on your computer:

  1. If it’s a Universal Windows app for Windows 10 (so based on UWP), you need to add the project located at FBWinSDK\FBSDK-UWP\FBSDK-UWP\FBSDK-UWP.vcxproj
  2. If it’s a Windows Store app for Windows 8.1, you need to add the project located at FBWinSDK\FBWinSDK\FBWinSDK.Windows\FBWinSDK.Windows.vcxproj
  3. If it’s a Windows Store app for Windows Phone 8.1, you need to add the project located FBWinSDK\FBWinSDK\FBWinSDK.WindowsPhone\FBWinSDK.WindowsPhone.vcxproj

The last step is to right click on your app’s project, choose Add reference and, from the Projects section, look for the Facebook project you’ve just added. Now you’re finally ready to write some code.

The login phase

The authentication to Facebook services is handled, as for many others similar services, using the oAuth protocol: the user will never share his credentials directly in the app, but inside a Web View which content is provided directly by the service’s owner (Facebook, in this case). If the credentials are accepted, Facebook wil return to the app a token, which we’ll need to perform any operation against the Facebook APIs. This approach improves the user’s security: a malicious developer won’t be able to access, in any case, to the user’s credentials.

The Facebook SDK we’ve added to our project makes easier to handle the login process: the Web View and the auhtentication will be handled directly by the library, which will return us automatically all the info about the logged user and a set of APIs to interact with the Graph APIs.

Here is the full login procedure:

private async void OnLogin(object sender, RoutedEventArgs e)
{
    FBSession session = FBSession.ActiveSession;
    session.WinAppId = Sid;
    session.FBAppId = AppId;

    List<string> permissionList = new List<string>();
    permissionList.Add("public_profile");
    permissionList.Add("email");

    FBPermissions permissions = new FBPermissions(permissionList);
    var result = await session.LoginAsync(permissions);
    if (result.Succeeded)
    {
        //do something
    }
}

The first step is to retrieve the current session, by using the static property FBSession.ActiveSession. If we haven’t completed the login procedure yet, this property will be empty: in this case, we need to move on and continue the login procedure.

The first important properties to set are WinAppId and FBAppId. The first one is the SID of the application, the one we have previously retrieved using the GetCurrentApplicationCallbackUri() method of the WebAuthenticationBroker class. FBAppId, instead, is the App Id that we have noted before from the Facebook’s developer portal. The next step is to define which kind of operations we want to do with the Facebook APIs, by using the permissions mechanism. You can find the complete list of available permissions in the documentation https://developers.facebook.com/docs/facebook-login/permissions

It’s imortant to highlight how Facebook doesn’t allow to get access to all the permissions by default. Only the basic ones, like public_profile or email, are automatically allowed. The most advanced ones (like publish_actions that allows to publish a post on behalf of the user) require that the Facebook app passes a review process, where the team will double check the reasons and the use cases for which you’re requesting such permissions. Don’t confuse it with the certification process done by Microsoft when you submit the app on the Store: this review is completely handled by Facebook.

Permissions are defined into a collection of strings, which is passed as parameter when you initialize the FBPermissions object. The last step is to call the LoginAsync() method, passing as parameter the FBPermissions object you’ve just defined. When you call it, if the user has never logged in with your app, the SDK will display a popup, which will embed the Facebook login page, as you can see in the following image:

clip_image004

The user will have to fill his credentials and give to our app the authorization to access to the permissions we’ve required. If everything goes well, the method will return us a FBResult object with the outcome of the operation. The first property we can leverage is called Succeded, which will tell us if the login operation went well or not. In case the answer is yes, we can leverage the User property of the FBSession class to get access to all the public information of the user. The following code stores into a variable the full name of the user:

var result = await session.LoginAsync(permissions);
if (result.Succeeded)
{
    string name = session.User.Name;
}

Interact with the Graph APIs

As mentioned in the beginning of the post, Graph APIs are a set of REST APIs offered by Facebook that we can use to perform many operations, like publishing a post, liking a comment, etc. Let’s see how the SDK can help us to interact with these APIs with a real sample: retrieving the e-mail address of the user. It isn’t one of the information exposed by the public profile, so you won’t find an Email property in the FBUser class, but you’ll need to use the Graph APIs to get it.

As every REST API, an operation is defined by:

  1. An endpoint, which is the URL we need to invoke to interact with the service. In our scenario, we need to use the https://graph.facebook.com/v2.5/me endpoint, followed by the query string parameter fields with the list of information we need. In our case, the full endpoint will be https://graph.facebook.com/v2.5/me?fields=email
  2. A method exposed by the HTTP protocol, to be used in combination with the endpoint. Typically, when we’re retrieving some data we use the GET method; writing operations (like posting a status on Facebook), instead, are performed with the POST method. Our scenario falls in the first category, so we will perform a GET.

The first thing we need is a class which maps the response that we’re going to receive from the API. For this purpose we can use the Graph API Explorer, a tool which we can use to simulate the operations with the Graph APIs and that is available at https://developers.facebook.com/tools/explorer

The tool features an address bar, where we can specify the endpoint and the HTTP method we want to use. After pressing the Submit button, we’ll see in the main windows the JSON response returned by the API. If, for example, we perform a test with the endpoint we’re interested into (/me?fields=email) this is the response we’ll get:

{
  "email": "mymail@mail.com",
  "id": "10203404048039813"
} 

Visual Studio offers a built-in option to convert a JSON data into a class. We just need to add a new class to the project and, once we have opened the file, using the option Paste Special –> Paste JSON as classes which is available in the Edit menu. Visual Studio will generate the following class:

public class UserProfile
{
    public string id { get; set; }

    public string email { get; set; }
}

However, to properly use the Facebook SDK, we need also another element in the class: a static method which is able to deserialize the JSON returned by the service to convert it into a UserProfile object. We create it with the help of the popular JSON.NET library, which we need to install in the project using NuGet (https://www.nuget.org/packages/Newtonsoft.Json/).

This is the complete definition of the class:

public class UserProfile
{
    public string id { get; set; }

    public string email { get; set; }

    public static UserProfile FromJson(string jsonText)
    {
        UserProfile profile = JsonConvert.DeserializeObject<UserProfile>(jsonText);
        return profile;
    }
}

The FromJson() method uses the JsonConvert class to take as input the JSON returned by Facebook and to return, as output, a UserProfile object. To understand why we have created such a method, we need to analyze the code required to interact with the Graph APIs:

private async void OnGet(object sender, RoutedEventArgs e)
{
    string endpoint = "/me";

    PropertySet parameters = new PropertySet();
    parameters.Add("fields", "email");

    FBSingleValue value = new FBSingleValue(endpoint, parameters, UserProfile.FromJson);
    FBResult graphResult = await value.GetAsync();

    if (graphResult.Succeeded)
    {
        UserProfile profile = graphResult.Object as UserProfile;
        string email = profile?.email;
        MessageDialog dialog = new MessageDialog(email);
        await dialog.ShowAsync();
    }
}

The first step is to define the endpoint. It’s important to highlight that the query string parameters can’t be added directly in the URL, but separately using the PropertySet collection, otherwise we will get an exception at runtime. This happens because the SDK, under the hood, automatically sets the base URL for the APis and adds the access token retrieved during the login phase. You can notice it from the fact that we have just set the value /me as endpoint; we didn’t have to specify the full URL with the https://graph.facebook.com/v2.5 prefix.

Using the PropertySet property is quite simple: it’s a collection, where we can add key-value pairs composed by a key (the name of the property, in our case fields) and a value (the property’s value, in our case email). In the next line of code you’ll finally understand why we had to create a FromJson() method inside the UserProfile class: it’s one of the paramters required when we initialize the FBSingleValue object, which is the class exposed by the SDK to interact with the Graph APIs. The other two parameters are the endpoind and the PropertySet collection with the list of parameters.

Now we are ready to perform the request. The FBSingleValue class offers many options, based on the HTTP method we need to use. In our case, since we need to perform a GET operation, we use the GetAsync() method, which will return us a FBResult object. It’s the same type of result we received during the login operation: this means that, also in this case, we can leverage the Succeded property to understand if the operation has completed succesfully or not. The difference is that, this time, we have also a Result property, which contains the result returned by the Graph API. It’s a generic object, since the Graph APIs don’t return a fixed structure; it’s our job to convert it into the type we expect, in this case a UserProfile object.

The rest is up to us and depends by our app’s logic: in the previous sample code, we just show to the user a dialog with the retrieved mail address.

This approach works for every interaction supported by the Graph APIs. What changes between one operation and the other is:

  1. The endpoint
  2. The values to add to the PropertySet collection, based on the parameters required by the API.
  3. The class to map the API’s response.
  4. The method of the FBSingleValue class to call to perform the operation.

For example, if instead of retrieving the user’s mail address we would have wanted to publish a post on the user’s timeline, we would have used the following code:

private async void OnPost(object sender, RoutedEventArgs e)
{
    PropertySet parameters = new PropertySet();
    parameters.Add("title", "Microsoft");
    parameters.Add("link", "https://www.microsoft.com/en-us/default.aspx");
    parameters.Add("description", "Microsoft home page");
    parameters.Add("message", "Posting from my Universal Windows app.");

    string path = "/me/feed";

    FBSingleValue sval = new FBSingleValue(path, parameters, FBReturnObject.FromJson);
    FBResult fbresult = await sval.PostAsync();

    if (fbresult.Succeeded)
    {
        // Posting succeeded
    }
    else
    {
        // Posting failed
    }
} 

The main difference here, other than the endpoint and the parameters, is that we’re dealing with a “write” operation. Consequently, we need to use the POST method of the HTTP protocol, which is translated into the PostAsync() method of the FBSingleValue class. As a reminder, remember that this method won’t work as it is: you’ll need to request the publish_actions permission, which is granted by Facebook only after the app has passed their review.

Wrapping up

In this post we’ve learned how to leverage the new Facebook SDK in a Universal Windows app to interact with the services offered by the popular social network. If you want to learn more, you can refer to the GitHub project (https://github.com/microsoft/winsdkfb) and o the official documentation (http://microsoft.github.io/winsdkfb/). Happy coding!

Posted in Universal Apps, UWP, wpdev | Tagged , , | Leave a comment

Scheduling toast notifications in a Universal Windows app

Toast notifications are, without any doubt, one of the most used techniques when it comes to notify something to the user, even when the app isn’t running. It’s almost impossible not to miss a toast notification: it plays a sound, it’s displayed on the screen, it’s stored in the Action Center and, on the phone, it makes also the device vibrate.

A toast notification is mapped with a XML file, which describes its content and its behavior. The flexibility in defining a toast notification has been vastly improved in Windows 10, since the Universal Windows Platform has added:

  1. More ways to customize the look & feel of the notification. You can add images, multiple lines of text, etc.
  2. Support to interactive notifications. You can add interactive elements (like buttons or text boxes), which can be handled by a background task.

You can learn more about the new features introduced in the Universal Windows Platform regarding toast notification in the following blog post from the team: http://blogs.msdn.com/b/tiles_and_toasts/archive/2015/07/02/adaptive-and-interactive-toast-notifications-for-windows-10.aspx

In this post I would like to focus on the ways you can send a toast notification, specifically on scheduled toasts, since you may find some challenges in implementing them in the proper way.

Sending toast notifications

There are multiple ways to send a toast notification to the user:

  1. Within the app: the Universal Windows Platform includes APIs like ToastNotification and ToastNotificationManager which can be used to send a toast notification when the app is running in foreground.
  2. From a background task: the same APIs can be used also in a background task, so that toast notifications can be sent also when the app isn’t running.
  3. Push notifications: a toast can be sent by a backend and received also when the app isn’t running. In this case, the app subscribes to a service offered by Microsoft (called WNS) and receives back a Url, which identifies the unique channel for that device. When the backend wants to send a push notification to that device, it executes a HTTP POST request to the Url including, in the body, the XML that describes the notification.
  4. Scheduled notifications: by using the same APIs you use within the app you can create a toast notification and schedule it to be displayed at a specific time and date, even if the application isn’t running. This is the scenario we’re going to focus from now on.

Creating a scheduled toast notification

Creating a scheduled toast notification is easy and you leverage the same APIs you would use for a standard toast notification sent by the app or by a background task. Here is a sample code:

private void OnScheduleToast(object sender, RoutedEventArgs e)
{
    string xml = @"<toast>
            <visual>
            <binding template=""ToastGeneric"">
                <text>Hello!</text>
                <text>This is a scheduled toast!</text>
            </binding>
            </visual>
        </toast>";

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);

    ScheduledToastNotification toast = new ScheduledToastNotification(doc, DateTimeOffset.Now.AddSeconds(10));
    ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast);
}

The first step is to define the XML with the toast content. To learn how to define a toast, you can refer to the documentation and you can get some help using Notifications Visualizer, a Windows Store app by Microsoft that is able to give you an instant preview of how a specific XML will be rendered.

snip_20160205175523

Once you have the XML, you need to use it to create a XmlDocument object by calling the LoadXml() method and passing, as parameter, the XML string. Be aware that there are multiple classes called XmlDocument in the Universal Windows Platform: the one required by your scenario belongs to the Windows.Data.Xml.Dom namespace.

The last step is to create a new ScheduledToastNotification object, which is very similar to the basic ToastNotification one. The difference is that, this time, other than the XmlDocument object with the toast definition, you have to specificy also the date and time when the notification will be displayed, using a DateTimeOffset object. In the sample, we’re scheduling the notification to be display after 10 seconds that this code is executed. In the end, we schedule the notification by calling the AddToSchedule() method of the ToastNotifier object, which you can get by calling the CreateToastNotifier() method of the ToastNotificationManager class.

If you don’t like working with XML, you can use the Notifications Extensions library available on NuGet and documented at http://blogs.msdn.com/b/tiles_and_toasts/archive/2015/08/20/introducing-notificationsextensions-for-windows-10.aspx This library gives you a set of classes and methods to create notifications and, under the hood, it takes care of generating the proper XML for you. For example, here is how the previous code looks like using the Notifications Extensions library:

private void OnScheduleToast(object sender, RoutedEventArgs e)
{
    ToastContent toastContent = new ToastContent
    {
        Visual = new ToastVisual
        {
            TitleText = new ToastText
            {
                Text = "Hello!"
            },
            BodyTextLine1 = new ToastText
            {
                Text = "This is a scheduled toast!"
            }
        }
    };

    XmlDocument doc = toastContent.GetXml();

    ScheduledToastNotification toast = new ScheduledToastNotification(doc, DateTimeOffset.Now.AddSeconds(10));
    ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast);
}

Scheduled notifications and locked devices

If you try the previous code on a phone and, before the notification is displayed, you lock it by pressing the power button, you’ll realize that the notification won’t be displayed. As soon as you press the power button again to unlock the phone, you’ll see the notification appearing. What’s happening? The reason is that, by default, apps aren’t allowed to interact with the device when they’re locked, but they require a permission to do that. It’s a typical scenario when you work with background tasks: when you register a new task using the BackgroundTaskBuilder class you define a code similar to the following one:

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    if (BackgroundTaskRegistration.AllTasks.All(x => x.Value.Name != "ToastTask"))
    {
        BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
        builder.Name = "ToastTask";
        builder.TaskEntryPoint = "ToastsTask.CheckAnswerTask";
        builder.SetTrigger(new ToastNotificationActionTrigger());
        var status = await BackgroundExecutionManager.RequestAccessAsync();
        if (status != BackgroundAccessStatus.Denied)
        {
            builder.Register();
        }
    }
    
}

You can notice that, after defining all the properties of the task (like the name, the entry point and the trigger we want to use) we call the RequestAccessAsync() method of the BackgroundExecutionManager class: only if the request isn’t denied, we move on to perform the real registration. The RequestAccessAsync() method makes sure that:

  1. We don’t have too many background tasks registered. On low memory devices, in fact, there’s a maximum number of tasks that can be registered and, if it has been reached, the OS will deny the request.
  2. The background task is granted access to interact with the device also when it’s locked.

As you can see, the second scenario is the one we need also for our scheduled toast notification: without this approval from the OS, we won’t be able to wake up the phone even if it’s locked. However, there’s a catch: the fact that we’re using scheduled toast notification doesn’t mean that we are necessarly using also a background task in our application. The problem is that, if we try to call the BackgroundExecutionManager.RequestAccessAsync() method without having a background task registered, we’ll get an exception.

The workaround is simple: register a fake background task. We don’t even need to add a Windows Runtime Component to our project: we just need to declare, in the manifest file, a fake background task. Open the manifest file of your app, go into the Declarations section and, from the dropdown menu, adds the Background task item. Then choose:

  1. As task type, System.
  2. As entry point, any value (for example, Test). It doesn’t have to be a real entry point for a task, since we won’t try to register the task for real.

snip_20160205175826

That’s all: the declaration in the manifet is enough for our scenario, since it will allow the BackgroundExecutionManager.RequestAccessAsync() method to be execute without any error. Now we just have to call this method when the app is starting, for example in the OnNavigatedTo() method of the page:

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    await BackgroundExecutionManager.RequestAccessAsync();
}

That’s all. Now if you repeat the test of scheduling a notification and locking the phone before it’s displayed, you’ll correctly see the phone waking up and displaying the toast, like if it happens for regular push notifications.

Happy coding!

Posted in Universal Apps, UWP, wpdev | Tagged , | 6 Comments

The MVVM pattern – Design time data

Ok, I’ve broken my promise. I’ve said that the previous post would have been the last one about MVVM, but I’ve changed my mind Smile I realized, in fact, that I didn’t talk about one of the most interesting pros of working with the MVVM pattern: design time data.

Design time data

In one of the posts of the series we’ve talked about dependency injection, which is an easy way to swap the implementation of a service used by ViewModel. There are various reasons to do that: to make refactoring easier, to replace the data source in a quick way, etc. There’s another scenario for which dependency injection can be very useful: helping designers to define the user interface of the application. If this requirement is simple to satisfy when it comes to static data (like the header of a page), which are rendered in real time by the Visual Studio designer, things are a little bit more tricky with dynamic data. It’s very likely that most of the data displayed in the application isn’t static, but it’s loaded when the application is running: from a REST service, from a local database, etc. By default, all these scenarios don’t work when the XAML page is displayed in the designer, since the application isn’t effectively running. To solve this problem, the XAML has introduced the concept of design time data: it’s a way to define a data source that is displayed only when the XAML page is displayed in Visual Studio or in Blend in design mode, even if the app isn’t effectively running.

The MVVM pattern makes easier to support this scenario, thanks to the separation of layers provided by the pattern and the dependency injection approach: it’s enough to swap in the dependency container the service which provides the real data of the app with a fake one, which creates a set of static sample data.

However, compared to the sample we’ve seen in the post about the dependency injection, there are a couple of changes to do. Specifically, we need to detect when the XAML page is being displayed in the designer rather than at runtime and load the data from the correct data source. To do this, we use again one of the features offered by the MVVM Light toolkit, which is a property offered by the ViewModelBase class that tells us if a class is being used by the designer or by the running app.

Let’s see in details the changes we need to do. We’re going to use the same sample we’ve seen in the post about dependency injection, which can be found also on my GitHub repository https://github.com/qmatteoq/UWP-MVVMSamples. The app is very simple: it displays a list of news, retrieved from a RSS feed. In the old post we implemented an interface, called IRssService, which offers a method with the following signature:

public interface IRssService
{
    Task<List<FeedItem>> GetNews(string url);
}

Then, the interface is implemented by two classes: one called RssService, which provides the real data from a real RSS feed, and one called FakeRssService, which provides instead fake static data.

public class RssService : IRssService
{
    public async Task<List<FeedItem>> GetNews(string url)
    {
        HttpClient client = new HttpClient();
        string result = await client.GetStringAsync(url);
        var xdoc = XDocument.Parse(result);
        return (from item in xdoc.Descendants("item")
                select new FeedItem
                {
                    Title = (string)item.Element("title"),
                    Description = (string)item.Element("description"),
                    Link = (string)item.Element("link"),
                    PublishDate = DateTime.Parse((string)item.Element("pubDate"))
                }).ToList();
    }
}

public class FakeRssService : IRssService
{
    public Task<List<FeedItem>> GetNews(string url)
    {
        List<FeedItem> items = new List<FeedItem>
        {
            new FeedItem
            {
                PublishDate = new DateTime(2015, 9, 3),
                Title = "Sample news 1"
            },
            new FeedItem
            {
                PublishDate = new DateTime(2015, 9, 4),
                Title = "Sample news 2"
            },
            new FeedItem
            {
                PublishDate = new DateTime(2015, 9, 5),
                Title = "Sample news 3"
            },
            new FeedItem
            {
                PublishDate = new DateTime(2015, 9, 6),
                Title = "Sample news 4"
            }
        };

        return Task.FromResult(items);
    }
}

Before starting to explore the changes we need to do in the application to support design data, I would like to highlight a possible solution to handle asynchronous operations. One of the challenges in creating fake data comes from the fact that, typically, real services use asynchronous methods (since they retrieve data from a source which may take some time to be processed). The RssService is a good example: since the GetNews() method is asynchronous, it has to return a Task<T> object, so that it can be properly called by our ViewModel using the await keyword. However, it’s very unlikely that the fake service needs to use asynchronous methods: it just returns static data. The problem is that, since both services implement the same interface, we can’t have one service that returns Task operations while the other one plain objects. A workaround, as you can see from the sample code, is to use the FromResult() method of the Task class. Its purpose is to to encapsulate into a Task object a simple response. In this case, since the GetNews() method returns a Task<List<FeedItem>> response, we create a fake List<FeedItem> collection and we pass it to the Task.FromResult() method. This way, even if the method isn’t asynchronous, it will behave like if it is, so we can keep the same signature defined by the interface.

The ViewModelLocator

The first change we have to do is in the ViewModelLocator. In our sample app we have the following code, which registers into the dependency container the IRssService interface with the RssService implementation:

public class ViewModelLocator
{
    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

       
        SimpleIoc.Default.Register<IRssService, RssService>();
        SimpleIoc.Default.Register<MainViewModel>();
    }

    public MainViewModel Main => ServiceLocator.Current.GetInstance<MainViewModel>();
}

We need to change the code so that, based on the way the app is being rendered, the proper service is used. We can ues the IsInDesignModeStatic property offered by the ViewModelBase class to detect if the app is running or if it’s being rendered by the designer:

public class ViewModelLocator
{

    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

        if (ViewModelBase.IsInDesignModeStatic)
        {
            SimpleIoc.Default.Register<IRssService, FakeRssService>();
        }
        else
        {
            SimpleIoc.Default.Register<IRssService, RssService>();
        }

        SimpleIoc.Default.Register<MainViewModel>();
    }

    public MainViewModel Main => ServiceLocator.Current.GetInstance<MainViewModel>();
}

In case the app is being rendered in the designer, we connect the IRssService interface with the FakeRssService class, which returns fake data. In case the app is running, instead, we connect the IRssService interface with the RssService class.

The ViewModel

To properly support design time data we need also to change a bit the ViewModel. The reason is that, when the app is rendered by the designer, isn’t really running; the designer takes care of initializing all the required classes (like the ViewModelLocator or the different ViewModels), but it doesn’t execute all the page events. As such, since typically the application loads the data leveraging events like OnNavigatedTo() or Loaded, we will never see them in the designer. Our sample app is a good example of this scenario: in our ViewModel we have a RelayCommand called LoadCommand, which takes care of retrieving the data from the RssService:

private RelayCommand _loadCommand;

public RelayCommand LoadCommand
{
    get
    {
        if (_loadCommand == null)
        {
            _loadCommand = new RelayCommand(async () =>
            {
                List<FeedItem> items = await _rssService.GetNews("http://wp.qmatteoq.com/rss");
                News = new ObservableCollection<FeedItem>(items);
            });
        }

        return _loadCommand;
    }
}

By using the Behaviors SDK described in this post, we have connected this command to the Loaded event of the page:

<Page
    x:Class="MVVMLight.Advanced.Views.MainView"
    xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
    xmlns:core="using:Microsoft.Xaml.Interactions.Core"
    DataContext="{Binding Source={StaticResource ViewModelLocator}, Path=Main}"
    mc:Ignorable="d">

    <interactivity:Interaction.Behaviors>
        <core:EventTriggerBehavior EventName="Loaded">
            <core:InvokeCommandAction Command="{Binding Path=LoadCommand}" />
        </core:EventTriggerBehavior>
    </interactivity:Interaction.Behaviors>

    <!-- page content here -->

</Page>

However, when the page is being rendered in the designer, the LoadCommand command is never invoked, since the Loaded event of the page is never launched. As such, we have to retrieve the data from our service also in the ViewModel’s constructor which, instead, is executed by the designer when it creates an instance of our ViewModel. However, we need to do it only when the ViewModel is being rendered by the designer: when the app is running normally, it’s correct to leave the data loading operation to the command. To achieve this goal we leverage the IsInDesign property, which is part of the ViewModelBase class we’re already using as base class for our ViewModel:

public MainViewModel(IRssService rssService)
{
    _rssService = rssService;
    if (IsInDesignMode)
    {
        var task = _rssService.GetNews("abc");
        task.Wait();
        List<FeedItem> items = task.Result;
        News = new ObservableCollection<FeedItem>(items);
    }
}

Only if the app is running in design mode, we retrieve the data from the service and we populate the News property, which is the collection connected to the ListView control in the page. Since the GetNews() method is asynchronous and you can’t call asynchronous methods using the async / await pattern in the constructor, you need first to call the Wait() method on the Task and then access to the Result property to get the list of FeedItem objects. In a real application this approach would lead to a synchronous call, which would block the UI thread. However, since our FakeRssService isn’t really asynchronous, it won’t have any side effect.

This sample shows you also the reason why, in case you wanted to make things simpler, you can’t just call the GetNews() method in the constructor also when the application is running: since we’ can’t properly use the async / await pattern, we would end up with unpredictable behaviors. As such, it’s correct to continue calling the data loading methods in the page events that are triggered when the page is being loaded or navigated: since they’re simple methods or event handlers, they can be used with the async and await keywords.

And we’re done!

Now the job is done. If we launch the application, we should continue to normally see the data coming from the real RSS feed. However, if we open the MainPage.xaml page in the Visual Studio designer or in Blend, we should see something like this:

snip_20160116230050

The designer has created an instance of our ViewModel, which received from the dependency container a FakeRssService instance. Since the ViewModel is running in design mode, it will excecute the code we wrote in the constructor, which will retrieve the fake data. Nice, isn’t it? Thanks to this implementation, we can easily see how our collection of news will look like and, if it doesn’t satisfy us, easily change the DataTemplate we have defined in the ItemTemplate property.

As usual, you can find the sample code used in this blog post on my GitHub repository: https://github.com/qmatteoq/UWP-MVVMSamples Specifically, you’ll find it in the project called MVVMLight.Advanced. Happy coding!

Introduction to MVVM – The series

  1. Introduction
  2. The practice
  3. Dependency Injection
  4. Advanced scenarios
  5. Services, helpers and templates
  6. Design time data
Posted in Universal Apps, UWP, wpdev | Tagged , , | Leave a comment

The MVVM pattern – Services, helpers and templates

In this last post of the series about MVVM we’re going to introduce some concepts and libraries that can make your life easier when you develop a Universal Windows app leveraging the MVVM pattern.

Services, services and services

In one of the previous posts we have created a sample app to display a list of news retrieved from a RSS feed. While developing the app we introduced the concept of service: a class that takes care of performing some operations and passing the results to the ViewModel. Services can be useful also to reach another important goal of the MVVM pattern: avoiding writing platform specific code directly in the ViewModel, to make it easier to share them with other platforms or applications. As usual, I prefer to explain concepts with real examples, so let’s start with a new one.

Let’s say that you’re developing an awesome application that needs to display a dialog to the user. By applying the knowledge we’ve learned in the previous posts, you’ll probably end up to create a command like the following one:

private RelayCommand _showDialogCommand;

public RelayCommand ShowDialogCommand
{
    get
    {
        if (_showDialogCommand == null)
        {
            _showDialogCommand = new RelayCommand(async () =>
            {
                MessageDialog dialog = new MessageDialog("Hello world");
                await dialog.ShowAsync();
            });
        }

        return _showDialogCommand;
    }
}

The command shows the dialog using a specific API of the Universal Windows Platform, which is the MessageDialog class. Now let’s say that your customer asks you to port this amazing app to another platform, like Android or iOS, using Xamarin, the cross-platform technology that allows to create apps for all the major mobile platforms using C# and the framework .NET. In this scenario, your ViewModel has a problem: you can’t reuse it as it is in Android or iOS, because they use a different API to display a message dialog. Moving platform specific code in a service is the best way to solve this problem: the goal is to change our ViewModel so that it just describes the operation to do (displaying a dialog) without actually implementing it.

Let’s start by creating an interface, which describes the operations to perform:

public interface IDialogService
{
    Task ShowDialogAsync(string message);
}

This interface will be implemented by a real class, which will be different for each platform. For example, the implementation for the Universal Windows Platform will be like the following one:

public class DialogService: IDialogService
{
    public async Task ShowDialogAsync(string message)
    {
        MessageDialog dialog = new MessageDialog(message);
        await dialog.ShowAsync();
    }
}

On Xamarin Android, instead, you will leverage the AlertDialog class, which is specific from Android:

public class DialogService : IDialogService
{
    public async Task ShowDialogAsync(string message)
    {
        AlertDialog.Builder alert = new AlertDialog.Builder(Application.Context);

        alert.SetTitle(message);

        alert.SetPositiveButton("Ok", (senderAlert, args) =>
        {

        });

        alert.SetNegativeButton("Cancel", (senderAlert, args) =>
        {
        });
        alert.Show();

        await Task.Yield();
    }
}

Now that we have moved the platform specific APIs in a service, we can leverage the dependency injection approach (which I’ve described in a previous post) to use, in the ViewModel, the interface instead of the real class. This way, our command will just describe the operation to perform, demanding to the DialogService class to effectively execute it. With this new approach, the ViewModel will add a dependency to the IDialogService class in the constructor, like in the following sample:

public class MainViewModel : ViewModelBase
{
    private readonly IDialogService _dialogService;

    public MainViewModel(IDialogService dialogService)
    {
        _dialogService = dialogService;
    }
}

Then we can change our command in the following way:

private RelayCommand _showDialogCommand;

public RelayCommand ShowDialogCommand
{
    get
    {
        if (_showDialogCommand == null)
        {
            _showDialogCommand = new RelayCommand(async () =>
            {
                await _dialogService.ShowDialogAsync("Hello world");
            });
        }

        return _showDialogCommand;
    }
}

 

By using the dependency injection approach, the Android application will register in the container the DialogService implementation which uses the Android APIs; vice versa, the Windows 10 application will register, instead, the implementation which uses the UWP APIs. However,now our ViewModel can be shared as it is between the two versions of the application, without having to change it. We can move the ViewModel, for example, in a Portable Class Library, which we can share across the Windows, Xamarin Android, Xamarin iOS, WPF, etc. versions of the application.

To help developers in moving the platform specific code into services, there are many libraries which offer a set of services ready to be used in your applications. One of the best ones, which plays well with MVVM Light, is Cimbalino Toolkit (http://cimbalino.org/), which is specific for the Windows world. Other than many converters, behaviors and helpers classes, it includes a wide set of services to handle storage, settings, network access, etc. All the services are provided with their own interfaces, so that it’s easy to use them with the dependency inection’s approach.

If you want to know more about reusing your ViewModels on different platforms, I strongly suggest you to read this article from Laurent Bugnion, the creator of MVVM Light itself. The tutorial will help you to learn how you can reuse your binding knowledge also on platforms like Android and iOS, which doesn’t support binding out of the box.

Implementing the INotifyPropertyChanged interface in an easy way

In the second post of the series we’ve learned that, to properly support the INotifyPropertyChanged interface, we need to change the way we define the properties in the ViewModel. We can’t use the standard get / set syntax, but in the setter we need to call a method that dispatches the notification to the binding channel that the value has changed. This approach makes the code more “noisy”, since the simple definition of a property requires many lines of code.

Please welcome Fody, a library that is able to change the code you wrote at build time. Fody offers many addons and one of them is called Fody.PropertyChanged. Its purpose is to automatically turn every standard property into a property that, under the hood, implements the INotifyPropertyChanged interface. All you have to do is to decorate your class (like a ViewModel) with the [ImplementPropertyChanged] attribute.

For example, the following code:

[ImplementPropertyChanged]
public class MainViewModel : ViewModelBase
{
    public string Message { get; set; }
}

is converted, during the compilation, into this:

public class MainViewModel: ViewModelBase, INotifyPropertyChanged 
{
    private string _message;

    public string Message 
    {
        get { return _message; }
        set 
        {
            _message = value;
            OnPropertyChanged("Message)
        }
    }
}

This way, you can simplify the code you need to write in your ViewModel and make it less verbose. To use this special attribute, you have to:

  1. Install the package called Fody.PropertyChanged from NuGet (https://www.nuget.org/packages/PropertyChanged.Fody/)
  2. To properly work, Fody requires a special XML file in the root of the project, which describes which is the addon to apply at compile time. The name of the file is FodyWeavers.xml and the content shoudl look like this:
<?xml version="1.0" encoding="utf-8" ?>
<Weavers>
  <PropertyChanged />
</Weavers>

That’s all!

MVVM and Template10

Template10 is a new template, specific for Universal Windows apps development, which has been created to make the developer’s life easier, by providing a cleaner and simpler way to handle the initialization of an app, new controls, MVVM helpers, etc. Template10 is a great starting point also for MVVM apps, since it offers a set of classes that will help you to solve some of the platform specific challenges that may arise during the development, like handling the navigation or the page’s lifecycle. I won’t dig into this topic in this post, since I’ve already talked about it in another post on this blog. If you’re planning to create a Universal Windows app with the MVVM pattern, I strongly suggest you to give it a read and evaluate it.

That’s all folks!

We’ve reached the end of our learning path. I hope you found these series useful to understand the power of the MVVM pattern and that, after reading it, you will try to develop your next application using it. As usual, remember that you can find the samples used as a reference in these posts on GitHub: https://github.com/qmatteoq/UWP-MVVMSamples Happy coding!

Introduction to MVVM – The series

  1. Introduction
  2. The practice
  3. Dependency Injection
  4. Advanced scenarios
  5. Services, helpers and templates
  6. Design time data
Posted in Universal Apps, UWP, wpdev | Tagged , , | Leave a comment