[Xamarin] How to access user’s contacts ?

March 10th, 2014 | Posted by Tom in .NET | Article | Windows Phone | WPF - (0 Comments) | Read: 446

In my previous article about Xamarin, I’ve explained a way to access user’s contact by using the ManagedQuery API. Even if the code is working fine, you may think that it can be a bit “hard” to understand, when the only goal is to query the contacts.

Today, I’ll talk about Xamarin.Mobile, a library that exposes some APIs to access user’s contacts, user’s position and to allow you to, easily, take a picture in your application. The interesting point here is the fact that the API is available for iOS, Android and Windows Phone.

To use Xamarin.Mobile, you need to download the binaries. Thanks to the Components Store available (something that’s a bit similar to Nuget), you can get them easily:

image image

After you hit the “Add to App” button, the component is downloaded and the reference is added to your project:

image image

Once the reference is added, the first step is to add the following “using”:

using Xamarin.Contacts;

Now, by using the AddressBook class, we are able to access to the user’s contacts and we can use LINQ, which provides a more easier and comfortable syntax:

var addressBook = new AddressBook(this);
if (!await addressBook.RequestPermission())
{
    // We don't have the permission to access user's contacts: check if the READ_CONTACTS has been set
}
else
{
    var companyContacts = addressBook.Where(c => c.Organizations.Any(o => o.Name == "Infinite Square"));
    if (companyContacts.Any())
    {
        foreach (var contact in companyContacts)
        {
            var lastName = contact.LastName;
            var firstName = contact.FirstName;
            var thumbnailBitmap = contact.GetThumbnail();
        }
    }
}

As you can see, the code is really easy to understand and maintainable!

 

If you want to know more about Xamarin.Mobile (or just check how does it work), feel free to go to Github, where you’ll be able to find the sources: https://github.com/xamarin/Xamarin.Mobile

 

Happy (Xamarin) coding!

Recently, I was talking with one of my good friend, Matthieu, who explained me how he uses, in WAQS, some Nuget packages to add commands to the PowerShell console. As I like this idea, I decide to take a look at it and it’s really powerful!

So let’s see how it works and let me show you a preview of what you can do :)

Creating the Nuget package

This is the main (but mandatory) step you’ll need to do. For that, I decided to use the tool Nuget Package Explorer that let you to create your package, edit its metadata, add some dependencies, etc.

image

Once you created your package (it’s as simple as click on New –> File), you need to specify what you’ll put in your package. In our case, we want to add some commands to the PowerShell console so we need a script that will run every time a solution/project is opened so we have to add some content to the file init.ps1:

image

We could have choose to put our code in the file install.ps1 but the content of this file is only executed when the Nuget package is installed and not when user open your project in a new instance of Visual Studio (because, in that case, there is no install to perform as the package is already installed). As we want our commands to be always available (not only when the package is installed), we need to use init.ps1 (thanks Matthieu for the trick).

On that file, we’ll perform 2 actions: first, we’ll remove all the previous versions of the module we are developing then we’ll import it (using a module is not always needed but it’s a good thing to split your code in smaller files):

param($installPath, $toolsPath, $package)

foreach ($_ in Get-Module | ?{$_.Name -eq 'VSExtensionsModule'})
{
    Remove-Module 'VSExtensionsModule'
}

Import-Module (Join-Path $toolsPath VSExtensionsModule.psm1)

If the first step is not mandatory (unlike the second one), I recommend you to use it because it’ll prevent your package to be loaded more than 1 time! For the second step, it’ll just import our module to the PowerShell console so now, let’s take a look at the content of that module.

Adding commands to the PowerShell console

Our use case is simple: we want a PowerShell command that will allow us to count, in our project, all the files of a particular extension provided on IntelliSense by the files located on the root folder of the project (yes, I know this is not perfect but it’s just for the demo):

image

To do that, we need to register some code to tell PowerShell to show IntelliSense when user press the Tab key:

Register-TabExpansion 'Get-FilesCount' @{
    'extension' = { Get-Extensions | foreach { $_ } }
}

This code can be read as: “when the user write the command Get-FileCount and press the Tab key, use the method Get-Extensions to get the list of all available extensions and display them on screen”. So the next interesting point is to look at the Get-Extensions method:

function Get-Extensions()
{
    $extensionsList = New-Object Collections.Generic.List``1[string]

    $project = Get-Project
    $projectPath = [System.IO.Path]::GetDirectoryName($project.FullName)

    foreach($file in [System.IO.Directory]::GetFiles($projectPath))
    {
        $fileExtension = [System.IO.Path]::GetExtension($file)
        #$fileExtension = $fileExtension.Substring(1)

        if(!$extensionsList.Contains($fileExtension))
        {
            $extensionsList.Add($fileExtension)
        }
    }

    return $extensionsList
}

This method first starts by creating a generic list of string (List<string>) that will be used to store the list of all extensions. Then, by using the Get-Project method, we get the current active project in Visual Studio and, with the Path.GetDirectoryName method, we retrieve the path to the directory of that project! Then, we iterate through all the files of the folder (be careful here because we don’t use a recursive method) and we get the extension of all the files. That’s all, we are now able to display, on the IntelliSense, the list of all the extensions:

image

Ok so now that the IntelliSense is here, we just need to finish to implement the Get-FilesCount method:

function Get-FilesCount($extension)
{
    $project = Get-Project
    $projectPath = [System.IO.Path]::GetDirectoryName($project.FullName)

    $toExclude = @("\bin", "\obj")

    $files = New-Object Collections.Generic.List``1[string]

    GetFiles $projectPath $toExclude $files

    if($extension -eq $null)
    {
       Write-Host "There are "$files.Count" files on the project."
    }
    else
    {
       $count = 0

       foreach($file in $files)
       {
           if ($file.ToLowerInvariant().EndsWith($extension))
           {
                $count++
           }
       }

       Write-Host "There are "$count" files with the extension '"$extension"' on the project."
    }
}

function GetFiles($path, [string[]]$exclude, $files)
{
    foreach ($item in Get-ChildItem $path)
    {
        if ($exclude | Where { $item.FullName.Contains($_) }) { continue }

        if (Test-Path $item.FullName -PathType Container)
        {
            GetFiles $item.FullName $exclude $files
        }
        else
        {
            $files.Add($item.FullName)
        }
    }
}

The content of the method is pretty simple: we use a recursive method to get all the files from the project and we display the number of files available (or the number of files corresponding to a particular extension).

Finally, we need to export the method of the module:

Export-ModuleMember Get-FilesCount

Once the package is installed on the project, we can use the method in the console:

image

This example might be a bit naive so let’s take a look at a more real sample.

A better example: Get-ImagesFileSizes

This time, we’ll build a better command, that will be used to display the list of all the image’s files (and their size) in your project.

Again, we’ll support the IntelliSense:

Register-TabExpansion 'Get-ImagesFileSizes' @{
    'extension' = { Get-ImagesExtensions | foreach { $_ } }
}

The Get-ImagesExtensions is a simple method (it could be possible to build a more complex one, that display the extension of the image’s files available in the project):

function Get-ImagesExtensions()
{
    $imagesExtensionsList = New-Object Collections.Generic.List``1[string]

    $imagesExtensionsList.Add(".png")
    $imagesExtensionsList.Add(".jpg")
    $imagesExtensionsList.Add(".jpeg")
    $imagesExtensionsList.Add(".bmp")
    $imagesExtensionsList.Add(".gif")

    return $imagesExtensionsList
}

Finally, we need to implement the Get-ImagesFileSizes method. This method will be quite similar to the previous one byt, this time, we’ll access to the Length property of the file:

function Get-ImagesFileSizes($extension)
{
    $project = Get-Project
    $projectPath = [System.IO.Path]::GetDirectoryName($project.FullName)

    $toExclude = @("\bin", "\obj")

    $files = New-Object Collections.Generic.List``1[string]

    GetFiles $projectPath $toExclude $files

    if($files.Count -gt 0)
    {
        if($extension -eq $null)
        {
           foreach($file in $files)
           {
               Write-Host $file ":" (Format-FileSize((Get-Item $file).Length))
           }
        }
        else
        {
            $filesWithExtension = ($files | Where { $_.ToLowerInvariant().EndsWith($extension) })
            if($filesWithExtension.Count -gt 0)
            {
                foreach($file in $filesWithExtension)
                {
                    Write-Host $file ": " (Format-FileSize((Get-Item $file).Length))
                }
            }
            else
            {
                Write-Host "Sorry, there are no image(s) with the following extension" $extension
            }
        }
    }
    else
    {
        Write-Host "Humm.... Looks like there are no images on your project :)"
    }
}

The interesting point here is the Format-FileSize method that he use to format the file size to a human readable value:

#
# Source: http://superuser.com/questions/468782/show-human-readable-file-sizes-in-the-default-powershell-ls-command
#
function Format-FileSize()
{
    param ([int]$size)

    if ($size -gt 1TB)
    {
        [string]::Format("{0:0} Tb", $size / 1TB)
    }
    elseif ($size -gt 1GB)
    {
        [string]::Format("{0:0} Gb", $size / 1GB)
    }
    elseif ($size -gt 1MB)
    {
        [string]::Format("{0:0} Mb", $size / 1MB)
    }
    elseif ($size -gt 1KB)
    {
        [string]::Format("{0:0} Kb", $size / 1KB)
    }
    elseif ($size -gt 0)
    {
        [string]::Format("{0:0} b", $size)
    }
    else
    {
        ""
    }
}

When installed and used on the project, the extension works fine:

image

image

 

As you can see, using Nuget/PowerShell to extend the PowerShell console is really easy (if we omits the fact that you may need to learn the PowerShell :) and you can do a lot of more complex things (dynamically adding resources, create base files for a View/ViewModel in XAML projects, etc.). If you want to learn more, I suggest you to look in WAQS, you’ll have a good overview of what’s possible to do!

 

Happy coding!

Early 2014, the Patterns & Practices teams at Microsoft released a new version of the Prism library, dedicated to the creation of business apps using C# and XAML on Windows 8.1 (a version for Windows 8 already existed since 2013, the team “just” updated the version to add the support of Windows 8.1).

In this article, we’ll provide the basics to use Prism to create a Windows Store application so let’s start !

Architecture

Here is the diagram of a typical Windows Store application that is developed using the Prism library:

 Logical architecture of a Windows Store business app that uses Prism

As you can see, this is a standard architecture: MVVM to separate the concerns of presentation, presentation logic, and model, a data access layer using repositories and some Services proxies to retrieve the data, etc. The good part is that some elements are directly provided by Prism (ViewBase, ViewModelBase, ViewModelLocator, Event Aggregator, etc.) so, you just have to provide the XAML code (View), the logic code (ViewModel) and the business objects (Model).

Creating the application

Creating the application is the same as creating any Windows Store application (File –> New Project) but, once Visual Studio has finished to create the project, you need to add reference to the following Nuget packages:

  • Prism.StoreApps: this is the class library that provides MVVM support with lifecycle management, and core services to a Windows Store app (see here for the list of all the features provided)
  • Prism.PubSubEvents: the Portable Class Library that contains classes that implement event aggregation (again, check here to see the class contains on the library)

image

Once this is done, derive the App class from the MvvmAppBase class, to allow your application to support the MVVM pattern and the core services (navigation, events aggregation, etc.):

sealed partial class App : MvvmAppBase

Don’t forget to change the base class of the file App.xaml too or you’ll get compile errors:

<storeApps:MvvmAppBase
    x:Class="DemoPrism.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:DemoPrism"
    xmlns:storeApps="using:Microsoft.Practices.Prism.StoreApps">

</storeApps:MvvmAppBase>

The MvvmAppBase class is an abstract class that define one method that need to be implemented: OnLaunchApplication. This method is used to perform the initial launch of the application so this is where we’ll define the page that’ll be launched on start:

protected override Task OnLaunchApplication(LaunchActivatedEventArgs args)
{
    NavigationService.Navigate("MainPage", null);

    return Task.FromResult<object>(null);
}

This method need to return a Task object so you can use Task.FromResult to return an empty task. To don’t have conflicts with the initial overridden methods, don’t forget to delete the OnLaunched and OnSuspending methods.

The code use the NavigationService property, which is Navigation Service that we can use to perform navigation within the application. Unfortunately, if you try to run this code, you’ll get the following exception:

SNAGHTML2de0d500

Indeed, by default, Prism use a particular convention for the Views: they need to be placed on the “Views” folder. In my case, I used to have the following structure on my applications:

image

So I have a “Views” folder but this folder contains sub-folders containing the big features of the application. So I need to find a way to tell the Prism library to look for the views on that sub-folders. And this can be done by overriding the GetPageType method of the MvvmAppBase class:

protected override Type GetPageType(string pageToken)
{
    var subPageToken = pageToken.Substring(0, pageToken.Length - pageToken.IndexOf("Page", StringComparison.Ordinal));

    var assemblyQualifiedAppType = this.GetType().GetTypeInfo().AssemblyQualifiedName;
    var pageNameWithParameter = assemblyQualifiedAppType.Replace(this.GetType().FullName, this.GetType().Namespace + ".Views.{0}.{1}");
    var viewFullName = string.Format(CultureInfo.InvariantCulture, pageNameWithParameter, subPageToken, pageToken);
    var viewType = Type.GetType(viewFullName);

    return viewType;
}

Now, if I execute the code, the application loads correctly and the page is displayed:

image

Registering services using Dependency Injection

This is not a mandatory steps but Prism has been a long time co-worker of Dependency Injection tools like Unity. So let’s start by adding the Nuget package of your choice (here, I’ll use Unity):

image

Then, declare a Unity container to register and resolve types and instances:

private readonly IUnityContainer _container = new UnityContainer();

You can then override the OnInitialize method of MvvmAppBase to register types and perform any other initialization:

protected override void OnInitialize(IActivatedEventArgs args)
{
    _container.RegisterInstance<INavigationService>(NavigationService);
    _container.RegisterType<IEventAggregator, EventAggregator>(new ContainerControlledLifetimeManager());
}

And, to be able to resolve the types, you just need to override the Resolve method:

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

Now, let’s see how we can add the Views and the ViewModels to the application.

Creating a View and its ViewModel

The Views has nothing particular related to the Prism library. You just composed it like you used to do it so this is just XAML content that you defined using Visual Studio or Blend.

To define the ViewModel associated to the view, you can use the ViewModelLocator.AutoWireViewModel property:

xmlns:storeApps="using:Microsoft.Practices.Prism.StoreApps"
storeApps:ViewModelLocator.AutoWireViewModel="true"

Once this property is set to True, the ViewModelLocator will try to instanciate the corresponding ViewModel based on a particular convention: the ViewModels need to be located in the same assembly, in a namespace ended by .ViewModels and the ViewModel name must match the View name and ends with ViewModel. But this is always what you have in your application. Indeed, you can have your ViewModels in a separate assembly or you can have them within the folder containing the views, like I use to have:

image

Fortunately, you can once again change the way Prism is loading your ViewModels, by specifying the ViewModelLocator.SetDefaultViewTypetoViewModelTypeResolver method:

protected override void OnInitialize(IActivatedEventArgs args)
{
    _container.RegisterInstance<INavigationService>(NavigationService);
    _container.RegisterType<IEventAggregator, EventAggregator>(new ContainerControlledLifetimeManager());

    ViewModelLocator.SetDefaultViewTypeToViewModelTypeResolver((viewType) =>
    {
        var subPageToken = viewType.Name.Substring(0, viewType.Name.Length - viewType.Name.IndexOf("Page", StringComparison.Ordinal));

        var assemblyQualifiedAppType = this.GetType().GetTypeInfo().AssemblyQualifiedName;
        var pageNameWithParameter = assemblyQualifiedAppType.Replace(this.GetType().FullName, this.GetType().Namespace + ".Views.{0}.{1}ViewModel");

        var viewFullName = string.Format(CultureInfo.InvariantCulture, pageNameWithParameter, subPageToken, viewType.Name);
        var viewModelType = Type.GetType(viewFullName);

        return viewModelType;
    });
}

Now, if you execute your application and put a breakpoint to the ViewModel’s constructor, you’ll see that the execution is stopped correctly (the ViewModel has been correctly instantiated):

image

Also, thanks to the Dependency Injection we put in place with Unity, we can construct the ViewModel and get, in constructor’s parameters, the type we want to retrieve:

public class MainPageViewModel : ViewModel
{
    private readonly INavigationService _navigationService;
    private readonly IEventAggregator _eventAggregator;

    public MainPageViewModel(INavigationService navigationService, IEventAggregator eventAggregator)
    {
        this._navigationService = navigationService;
        this._eventAggregator = eventAggregator;
    }
}

image

Handling navigation between pages

To handle navigation between pages, Prism library offers to developer the interface INavigationAware (already implemented by the base ViewModel class). This interface exposes 2 methods:

  • OnNavigatedFrom: which is called before the navigation occurred. You can use this method to preserve the state of your data during the navigation
  • OnNavigatedTo: which is called after the navigation to a page is performed. This method can be used to retrieve parameter sent from a page to another page.

So this interface is really helpful if you want to execute navigation to another page within a component which has nothing to do with navigation (like a ViewModel for example!). And to change to another page, we’ll use the methods provided by the INavigationService (that is injected to the ViewModel’s constructor thanks to the dependency injection):

image

Saving properties’ values between the application’s states

As you know, a Windows Store application have different state: Not Running, Running, Suspended and Terminated. This is your job to preserve the properties’ value between the different states of your application so when users are going back to the application, they don’t feel there was a kind of pause (or termination) during the application’s execution.

So let’s take a look at the following example:

private string _mySuperString;

public string MySuperString
{
    get
    {
        return this._mySuperString;
    }
    set
    {
        this.SetProperty(ref this._mySuperString, value);
    }
}

And the dedicated XAML interface:

<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
            VerticalAlignment="Center">
    <TextBox HorizontalAlignment="Center"
             VerticalAlignment="Center"
             Text="{Binding MySuperString, Mode=TwoWay}" />
    <Button Content="Click Me!"
            HorizontalAlignment="Center"
            VerticalAlignment="Center" />
</StackPanel>

If I enter some text on the Textbox, the property will be updated in memory, thanks to the databinding feature. Each time the application is suspended and  terminated by the OS (which determined when to kill suspended apps to retrieve some resources), the text entered in the Textbox is deleted from the memory. To stop that, I can simply add the RestoreState attribute to the property:

private string _mySuperString;

[RestorableState]
public string MySuperString
{
    get
    {
        return this._mySuperString;
    }
    set
    {
        this.SetProperty(ref this._mySuperString, value);
    }
}

image

Now, I can execute the application and simulate a termination done by the OS, by using the Suspend and shutdown feature from the Debug Location toolbar:

image

If I execute the application again, without having to add other code, the MySuperString property will be automatically populated and the user interface will be modified:

image

Of course, you can also add more complex objects to the State to retrieve them later. For that, you’ll need to use the ISessionStateService (which exposes a Dictionary object) that manages the automatic load and save during application exit and startup!

First, to get the ISessionStateService object from your ViewModel, you need to get it injected to the constructor:

public MainPageViewModel(INavigationService navigationService, ISessionStateService sessionStateService)
{
    this._navigationService = navigationService;
    this._sessionStateService = sessionStateService;
}

Don’t forget to register the instance during the app’s initialization:

protected override void OnInitialize(IActivatedEventArgs args)
{
    _container.RegisterInstance<INavigationService>(NavigationService);
    _container.RegisterInstance<ISessionStateService>(SessionStateService);
}

Now, you just need to add your object to the session’s state:

public void SaveToSessionState()
    {
        var users = new List<User> { new User { Id = Guid.NewGuid(), Name = "Thomas LEBRUN" } };

        this._sessionStateService.SessionState.Add("DemoKey", users);
    }

public class User
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

And, finally, you can check (when the user navigated to the ViewModel) if the key exists in the dictionary:

public override void OnNavigatedTo(object navigationParameter, NavigationMode navigationMode, Dictionary<string, object> viewModelState)
{
    base.OnNavigatedTo(navigationParameter, navigationMode, viewModelState);

    if (_sessionStateService.SessionState.ContainsKey("DemoKey"))
    {
        var users = _sessionStateService.SessionState["DemoKey"] as List<User>;
        if (users != null)
        {
            //
        }
    }
}

Now, if you execute the code and simulate an termination of the app, you got a correct execution… or not :)

image

You’ll see that an exception is raised:

image

If you take a look at the details of the exception, you’ll see something familiar if you use to work with data serialization:

image

“Type ‘System.Collections.Generic.List`1[[DemoPrism.Views.Main.User, DemoPrism, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]’ with data contract name ‘ArrayOfUser:http://schemas.datacontract.org/2004/07/DemoPrism.Views.Main’ is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types – for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.”

Indeed, to save the session state, the system will serialize the items and here, we try to serialize a type (User) that is not known by the DataContractSerializer. So we need to teach it all about our custom type(s). This is done by overriding the method OnRegisterKnownTypesForSerialization of the MvvmAppBase class:

protected override void OnRegisterKnownTypesForSerialization()
{
    base.OnRegisterKnownTypesForSerialization();

    SessionStateService.RegisterKnownType(typeof(User));
    SessionStateService.RegisterKnownType(typeof(List<User>));
}

And now, the termination of the app works successfully and when the user navigated to the page, we can check/retrieve the results from the session state:

image

Simple but terribly useful isn’t it ?! Now, let’s see how we can communicate from a component to another one!

Communication between components using the Event Aggregator

Sometimes, you might need to communicate some data from a component to another one. This can be from ViewModelA to ViewModelB, ViewModelA to ViewC, ViewB to ViewA, etc. All this elements have one thing in common: they are not loosely coupled so there are no links between them. So how can we communicate from a component to another one when they are not linked ?

The answer is 2 words: Event Aggregator. This is a design pattern, also known as Publish/Subscribe, which is used to send a message (from the publisher) that is catched by all the subscribers (Martin Fowler talked about the pattern on his blog).

So how does it works ? Well, first, you need to get a reference to the Event Aggregator instance. This can be done through the dependency injection of the ViewModel’s constructor:

public MainPageViewModel(INavigationService navigationService, IEventAggregator eventAggregator, ISessionStateService sessionStateService)
{
    this._navigationService = navigationService;
    this._eventAggregator = eventAggregator;
    this._sessionStateService = sessionStateService;
}

Or thanks to Dependency Injection container you choose to use:

var eventAggregator = UnityServiceHelper.UnityContainer.Resolve<IEventAggregator>();

Then, we need to create the event object that will be sent from the publisher to the subscribers. This object is a simple class that inherits from the PubSubEvent<T> class:

public class SessionStateSavedEvent : PubSubEvent<object>
{
}

Now, we just have to publish an instance of this event. To do so, we’ll use the GetEvent method of the EventAggregator object and we’ll call the Publish method:

this._eventAggregator.GetEvent<SessionStateSavedEvent>().Publish(null);

This method takes in parameter the object you want to send to the subscribers (in our case, we don’t want to use any parameters so we send the null value). Finally, we need to add a handler that will be raised when the event will be catched by the subscriber:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    var eventAggregator = UnityServiceHelper.UnityContainer.Resolve<IEventAggregator>();
    eventAggregator.GetEvent<SessionStateSavedEvent>().Subscribe(OnSessionStateSavedEventSubscribe);
}

private void OnSessionStateSavedEventSubscribe(object obj)
{
    //
}

And voilà! Once the publisher send an instance of our event, all the subscribers will be notified and their handlers will be invoked:

image image

Of course, there are plenty other possibilities when using the Event Aggregator like specifying on which thread the handler will be executed or like filtering which handlers need to be executed:

image

image

 

Prism allows a lot of more (validation of user input, performance optimizations, etc.) but I hope this first overview gave you all you need to take a further look at this very cool library !

 

Happy coding!

 

PS: The source code of the article is available here.

I like to think that I’m open minded enough to look at a lot of things. Recently, I’ve started to look at Xamarin not to start developing apps on Android but just to be able to know the product and I have to say that it’s very interesting. I’ll try to make more posts on it but, for now, let’s take a look that the big picture of it!

 

What is Xamarin ?

 

 Xamarin is a set of tools developers can use to delivers high performance compiled code with full access to all the native APIs so you can create native apps with device-specific experiences. Anything you can do in Objective-C or Java, you can do in C# with Xamarin.

The other good point is that even if you can use Xamarin Studio to develop your app, you can also use Visual Studio and all the other tools you already use for any C# development. This include Team Foundation Server (for the source control) but also plugins like Resharper, GhostDoc, etc.

Finally, to let you share code easily across iOS, Android and Windows Phone, you can also use the Portable Class Library (PCL) to create a core component that will be available on all the platforms (only the GUI part will be specific). The following article give your more details on how to work with the PCL and Xamarin Studio or Visual Studio (if you are already using the PCL on Visual Studio, you’ll see that there are no big differences!).

 

How does it work ?

Xamarin offers 2 mains products: Xamarin.iOS (MonoTouch.dll) and Xamarin.Android (Mono.Android.dll). Both of them are developed on top of Mono, the open source version of the .NET Framework. For those who have been on the .NET community for a long time, you may remembered that Mono project has been initiate by Miguel De Icaza, the co-founder and current CTO of… Xamarin :)

On iOS, a dedicated compiler (AOT: Ahead Of Time) compiles applications written on C# directly to native ARM code.

For Android, the process is similar to the .NET compilation and execution: the source code is compiled to an Intermediate Language (IL) and, when the code is executed on the device, a second compilation (performed Just-In-Time, JIT) compile the IL to native code. This makes sense because Android applications are used to be developed in Java, which has an internal architecture similar to the .NET architecture.

In both case, you don’t have to worry about the memory management, resources allocation, etc.: all is managed, for you, by the runtime delivered by Xamarin.

Once compiled, the Android applications are packaged in a file with the .apk extension. Like XAP files, these files are only ZIP files that contains:

  • The Android manifest file, on binary format (more on that later)
  • The application code (compiled into the file classes.dex)
  • The differents assets included in the package
  • The differents resources (layouts, drawable)
  • The native libraries containing the Mono runtime.

This last point is important. Indeed, an Android application must be deployed with the native libraries for the desired architecture (armeabi, armeabi-v7a, x86). Be careful that your application won’t be able to run on a particular plateform until the dedicated runtime libraries are deployed on it:

image image

Finally, the Android application also contains the Android Callable Wrappers (ACW), which allows you to call managed code from the Android runtime. The full definition of the Android Callable Wrappers can be found online but, basically, this is similar to the Runtime Callable Wrappers (RCW): a proxy object that allows Java (or COM) to allow .NET code, without having to handle the difference of type between the two worlds. On the other side, the Managed Callable Wrappers (MCW) are bridges allowing .NET code to invoke Android code (so this is the opposite of Android Callable Wrappers). Managed callable wrappers are responsible for converting between managed and Android types and invoking the underlying Android platform methods.

 

What tools are available ?

Xamarin has its own IDE, Xamarin Studio, that looks like a lot to Visual Studio (well, to be honest, it’s more like the first version of SharpDevelop but at least, it’s working):

image

But Xamarin Studio can only be used to develop Android applications, not iOS apps:

image

Fortunately, for the .NET developers we are, it’s also possible to use Visual Studio to develop iOS and Andoid applications!

image

Xamarin also come with a lot of emulators that are available through Xamarin Studio and Visual Studio:

image image

There is also a very nice device manager that allow you to manage the different emulators installed:

image image

image

You may notice that I talk/write a lot about Android. This is not that I dont want to try iOS but to be able to test iOS, you need a Mac (with Xamarin.iOS installed on it) to play the role of a proxy between your PC and the target device. Unfortunately, as I don’t have a such device, I’m not able to try and test that part (if a Apple evangelist read my blog and want to offer me a Mac, feel free to him to do so ;-)

The first time you’ll start an Android emulator, you’ll see this message:

image

Trust me, this is true! Indeed, the first time the emulator starts, the IDE need to deploy on it the Mono Shared Runtime and the Platform Framework corresponding to the API level that will be targeted by your application. So, in my case, the initial start was up to 7 minutes ! Of course, once the emulator is started, the deployments are more faster.

 

A first look of the development part

Each page, of an Android application, is represented by an Activity object. This is the equivalent of the Page objects on Windows (Phone) apps. To define the activity that need to be launched on the first start, you need to put the MainLauncher property to true:

[Activity(Label = "AndroidApplication1", MainLauncher = true, Icon = "@drawable/icon")]
public class Activity1 : Activity
{
}

From the point of view of a XAML developer, the development is quite similar. Indeed, on the XAML side, we have the XAML part that defines the UI and the code-behind that corresponds to the app logic. Well, here, this is the same: the activity corresponds to the code-behind part and the XAML part will be associated to the AXML (no, it’s not a typo) files that we will see more in details later.

On the activity, the method OnCreate need to be override to add our own logic. This method is called when the activity is starting so this is where we’ll define our user interface, etc.:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
}

To define the user interface, we can do it using 2 ways:

  1. By using C# code
  2. By using XML code.

The first way consists in building the GUI by code:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    var btn = new Button(this);
    btn.Text = "Hello World!";
    btn.Click += (sender, args) => { };

    SetContentView(btn);
}

image

Even if that works, this is not the most useful way (in particular to create complex UI). So we’ll prefer the XML way.

Each project contains a “Resources” folder that is composed by a set of sub-folders:

  1. Drawable: contains all the resources (images for example) that need to be used in the app
  2. Layout: contains all the layouts that will be designed by the developer
  3. Values: contains all the strings resources available

To add a new view, simply right clic on the Layout folder and select Add –> New item –> Android Layout:

image

The screen that appears offers a visual designer where you can drag and drop controls from the toolbox to create your custom UI:

image

If you click on the “Source” button (located at the bottom of the view), you’ll be able to see the XML representation of the GUI. So, like for the XAML part, the visual designer is just here to serialize the XML content and render it on a surface view:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:minWidth="25px"
    android:minHeight="25px">
    <Button
        android:text="Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button1" />
</LinearLayout>

You may notice the particular syntax used to specify the value of the id property: @+id/button1. This syntax tells the parser to generate a resource with the id indicated so, on the file Resource.Designer.cs (which is refreshed after all builds and which contains all the resources values as strongly type properties) a property is automatically added:

public partial class Id
{
    // aapt resource value: 0x7f050001
    public const int MyButton = 2131034113;

    // aapt resource value: 0x7f050000
    public const int button1 = 2131034112;

    static Id()
    {
        global::Android.Runtime.ResourceIdManager.UpdateIdValues();
    }

    private Id()
    {
    }
}

For the strings values (of the buttons, labels, etc.), you have 2 choices: you can hardcode the value and set it to the dedicated property (for example, the Text property of the button) or you can use a similar principle as the id property. Indeed, here is a valid code to set the text property:

<Button
        android:text="@string/TestButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button1" />

So again, we tell the Android parser to generate a dedicated property to the resources file:

public partial class String
{
    // aapt resource value: 0x7f040001
    public const int ApplicationName = 2130968577;

    // aapt resource value: 0x7f040000
    public const int Hello = 2130968576;

    // aapt resource value: 0x7f040002
    public const int TestButton = 2130968578;

    static String()
    {
        global::Android.Runtime.ResourceIdManager.UpdateIdValues();
    }

    private String()
    {
    }
}

But this time, this is a bit different. The String class contains the property corresponding to the string resources we want to use but we have to define the values of these resources. To do so, we need to open and edit the file Strings.xml which is in the subfolder Values of the folder Resources:

 image

The content of this file is a simple list of key/value:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="Hello">Hello World, Click Me!</string>
    <string name="ApplicationName">AndroidApplication1</string>
    <string name="TestButton">My Super Button!</string>
</resources>

Using this system, it’s easy to create a localized version of your application. In the Resources folder, just add a folder “Values-XX” where XX corresponds to the two-letter language code (if you want to support multiples locales of the same language, add the two-letter region code prefixed by the –r letter, for example: Values-fr-rFR for the French France locale; Values-fr-rCA for the French Canadian locale, etc.):

 image

Add a new XML file on the newly created folder (be sure to set its Build Action property to AndroidResource) and just translate the content:

image  image

OK so now that our user interface is almost finished (eventually using string resources for the different labels), we need to display it! To do that, let’s go back to the code of the activity and just modify the parameter of the SetContentView to use our newly interface:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    // Set our view from the "demolayout" layout resource
    SetContentView(Resource.Layout.demolayout);
}

Again, after finishing the user interface, the parser generates a dedicated property so we can manipulate it:

public partial class Layout
{
    // aapt resource value: 0x7f030000
    public const int demolayout = 2130903040;

    // aapt resource value: 0x7f030001
    public const int Main = 2130903041;

    static Layout()
    {
        global::Android.Runtime.ResourceIdManager.UpdateIdValues();
    }

    private Layout()
    {
    }
}

image

Your view is now display on screen but you may wonder how you can interact with it so you can retrieve user inputs (clicks con button, etc.). For that, you’ll need to use the FindViewById method:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    // Set our view from the "demolayout" layout resource
    SetContentView(Resource.Layout.demolayout);

    var button = FindViewById<Button>(Resource.Id.button1);
}

This method takes in parameter the id of the control you want to manipulate through code (and you can notice, once again, the use of the Resource.Id nested class, which contains all the ids of the graphical elements). Once you get access to the controls, you can manipulate them easily:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    // Set our view from the "demolayout" layout resource
    SetContentView(Resource.Layout.demolayout);

    var button = FindViewById<Button>(Resource.Id.button1);
    button.Click += (sender, args) => SetContentView(Resource.Layout.Main);
}

You may also wonder how to access to some assets resources you can embed on the application. To do so, you have 2 choices. For the image files, you need to put them on the “Drawable” folder. After the build, the file Resource.Designer.cs will be updated (as we seen before). Then, to use your new file, simply use it as before:

<ImageView
        android:src="@drawable/Yoda"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/imageView1" />

Here, for the src property, I access to the Yoda file within the “Drawable” folder:

image image

For the other types of files (text files, sound files, video files, etc.), you need to put them on the Assets folder. Files placed on that folder will have a build definition set to AndroidAsset. To be able to use them, you need to call one of the methods of the Asset API of the AssetManager (Asset.Open, Asset.OpenFd, etc.):

var button = FindViewById<Button>(Resource.Id.button1);
button.Click += (sender, args) =>
{
    var assets = Assets.List(string.Empty);
    if (assets.Any())
    {
        var videoFilename = assets.FirstOrDefault(a => a.EndsWith(".mp4"));
        if (!string.IsNullOrWhiteSpace(videoFilename))
        {
            var fileDescriptor = Assets.OpenFd(videoFilename);

            var player = new MediaPlayer();
            player.SetDataSource(fileDescriptor.FileDescriptor, fileDescriptor.StartOffset, fileDescriptor.Length);
            player.Prepare();
            player.Start();
        }
    }
};

To be able to perform some actions, you might need to set the desired required permissions on the Android Manifest file. To do that, open the properties of your project and select the tab “Android Manifest”:

image

In the previous screenshot, the SEND_SMS permission is selected. So the application is free to write code that will send SMS:

SmsManager.Default.SendTextMessage("0123456789", null, "First SMS from Xamarin", null, null);

Without selected this permission, the code throws an exception (one thing I regret currently about exceptions: we don’t have a lot of information about the exact issue):

image

On the project properties, you can also look at the different options you can change like, for example, the particular platforms for which your application will be available or the API version needed to be able to run your app:

image

Some actions you’ll need perform will not need special permissions, even if you think there are needed. Indeed, let’s re-write the sample to send a SMS (don’t forget to uncheck the dedicated permission):

var phoneNumber = Android.Net.Uri.Parse("smsto:0123456789");
var smsIntent = new Intent(Intent.ActionSendto, phoneNumber);
smsIntent.PutExtra("sms_body", "First SMS from Xamarin");
StartActivity(smsIntent);

If you execute this code, you’ll note that there are no errors/exceptions:

image

But how is it possible, as we don’t select the right permission ?! In fact, this is because this sample use an Intent (Android.Content.Intent):

image

An Intent is a kind of concept that is used to say: “Hey, do the following but don’t do it automatically: use a dedicated application to do that!”. So, basically, it’s not your code that performs the action, it’s another app. An intent generally has two pieces of information associated with it; first, what the intent is (a phone call, a camera ), and second, what data does the intent need (such as a phone number) to perform the intention.

That’s why the following code, which use an Intent, does not need special permissions (although it access special information such battery data):

var filter = new IntentFilter(Intent.ActionBatteryChanged);
var battery = RegisterReceiver(null, filter);
int level = battery.GetIntExtra(BatteryManager.ExtraLevel, -1);
int scale = battery.GetIntExtra(BatteryManager.ExtraScale, -1);

var batteryLevel = Math.Floor(level * 100D / scale);

int status = battery.GetIntExtra(BatteryManager.ExtraStatus, -1);
var isCharging = status == (int)BatteryStatus.Charging || status == (int)BatteryStatus.Full;

// How are we charging?
int chargePlug = battery.GetIntExtra(BatteryManager.ExtraPlugged, -1);
var usbCharge = chargePlug == (int)BatteryPlugged.Usb;
var acCharge = chargePlug == (int)BatteryPlugged.Ac;

 

Access to the user’s contacts

To be able to access to the user’s contacts, it’s pretty easy. We’ll use the ManagedQuery API to query the contact’s properties:

var uri = ContactsContract.Contacts.ContentUri;

string[] projection = { ContactsContract.Contacts.InterfaceConsts.Id, ContactsContract.Contacts.InterfaceConsts.DisplayName, };
var cursor = ManagedQuery(uri, projection, null, null, null);

var items = new List<string>();

if (cursor.MoveToFirst())
{
    do
    {
        items.Add(cursor.GetString(cursor.GetColumnIndex(projection[1])));

    }
    while (cursor.MoveToNext());
}

The API takes in parameters the list of properties you want to retrieve. In the previous code, we load the Id and DisplayName properties and we add the last one on a list of string objects. Of course, when using the ManagedQuery object, it’s possible to filter the results:

var uri = ContactsContract.Contacts.ContentUri;

string[] projection = { ContactsContract.Contacts.InterfaceConsts.Id, ContactsContract.Contacts.InterfaceConsts.DisplayName, };
var cursor = ManagedQuery(uri, projection, null, null, null);

var items = new List<string>();

if (cursor.MoveToFirst())
{
    do
    {
        items.Add(cursor.GetString(cursor.GetColumnIndex(projection[1])));

        var userId = cursor.GetString(cursor.GetColumnIndex(projection[0]));
        var userEmailCursor = this.ManagedQuery(ContactsContract.CommonDataKinds.Email.ContentUri, null, ContactsContract.CommonDataKinds.Email.InterfaceConsts.ContactId + "=" + userId, null, null);
        if (userEmailCursor.Count > 0)
        {
            while (userEmailCursor.MoveToNext())
            {
                var userEmail = userEmailCursor.GetString(userEmailCursor.GetColumnIndex(ContactsContract.CommonDataKinds.Email.InterfaceConsts.Data));
            }
        }

    }
    while (cursor.MoveToNext());
}

Ok so now, we have a list of the contacts stored in memory but we need to find a way to display it on the screen. For that, we’ll replace the base type for the current activity by the ListActivity. This is a particular activity type that expose a ListAdapter object, which allow you to directly displays a list of items on the screen using a particular template:

ListAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, items);

As its name suggests, the SimpleListItem1 display the items using a simple list:

image

If you want to display the items with some Checkboxes, you have just to use SimpleListItemsSingleChoice:

ListAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItemSingleChoice, items);

Which displays the following:

image

So, by changing a simple property, you can change the display of your items! If you want to know which item is clicked by the user, you just have to override the OnListItemClick method (available because we are on a ListActivity):

protected override void OnListItemClick(ListView l, View v, int position, long id)
{
    var item = items[position];

    Android.Widget.Toast.MakeText(this, item, ToastLength.Short).Show();
}

 

Of course, there are a lot of other things that you can do in your applications but I hope this first overview gave you all the pointers you need to start !

Happy (Xamarin) coding!

The FlipView control is very useful to display a set of data and display them with a DataTemplate. But imagine that you need to load 1000000 of customers: you’ll need to load all of them and set the ItemsSource property so the data can be shown. But loaded 1000000 objects in memory is not a very good idea in terms of performance so, let’s take a look at how we could prevent that!

First, you need to add an event handler to the SelectionChanged method of the FlipView:

private async void OnFlipViewSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    await this._viewModel.LoadMoreItemsAsync(this.flipView.SelectedIndex);
}

As you can see, we just call a method of our ViewModel, passing in parameters the current index of the FlipView. So all the magic is in the LoadMoreItemsAsync method of our ViewModel:

private int _offset;

private ObservableCollection<PostViewModel> _posts;
public ObservableCollection<PostViewModel> Posts
{
    get { return this._posts; }
    set { this.SetProperty(ref this._posts, value); }
}

public async Task LoadMoreItemsAsync(int currentIndex)
{
    if (currentIndex > 0)
    {
        var globalIndex = currentIndex % 10;
        var itemIndex = currentIndex - globalIndex;

        if (itemIndex <= 5)
        {
            this._offset = this._offset - 1;

            var rangedPost = await this.GetPostsAsync(this._offset);
            var posts = rangedPost as IList<Post> ?? rangedPost.ToList();
            if (posts.Any())
            {
                for (int i = 0; i <= posts.Count - 1; i++)
                {
                    var post = posts.ElementAt(i);

                    this.Posts.Insert(i, this.CreatePostViewModel(post));
                }
            }
        }
        else if (currentIndex >= this.Posts.Count - 5)
        {
            this._offset = this._offset + 1;

            var rangedPost = await this.GetPostsAsync(this._offset);
            var posts = rangedPost as IList<Post> ?? rangedPost.ToList();
            if (posts.Any())
            {
                foreach (var post in posts)
                {
                    var postViewModel = this.CreatePostViewModel(post);
                    if (postViewModel != null)
                    {
                        this.Posts.Add(postViewModel);
                    }
                }
            }
        }
    }
}

So how this method works exactly ? Well, basically, we load our “pages” by set of 10 items so we just check if we need to add the items at the end of the property bound to the ItemsSource or if we need to insert the items (starting from the index 0). Also, don’t forget to use an ObservableCollection (instead of a simple List) for the property databound otherwise, your GUI won’t be refreshed.

Of course, to make this happened, you need to have a service/backend that accepts to send data/items according to a page index.

Maybe there are other solutions (I’ve haven’t checked yet if ISupportIncrementalLoading can be used, in Windows 8.1, with the FlipView control but as far as I know, it didn’t work on Windows 8) but this one is pretty simple isn’t it ? :)

 

Happy coding!

Ok, I admit the title is a bit long and you may wonder what I’m talking about so let me explain.

On the application I’m working, I use a Listbox to display items and I wanted to start an animation when an item is selected. Of course, I could have simply edit the ListBoxItem style and modify the “Selected” visual state (as explained here) but, in my case, I wanted to be notified when the animation was finished (to redirect the user on another page).

So here is the solution I’ve found. On the SelectionChanged event handler, retrieve the current ListBoxItem:

private async void OnCategoriesSelected(object sender, SelectionChangedEventArgs e)
{
    if (e.AddedItems != null && e.AddedItems.Count > 0 && e.AddedItems[0] != null)
    {
        // The Listbox is bound to a List<Category> so when I get the AddedItems, I know they are of type Category.
        var selectedCategory = e.AddedItems[0] as Category;
        if (selectedCategory != null)
        {
            var listBoxItem = this.CategoriesListBox.ItemContainerGenerator.ContainerFromItem(selectedCategory) as ListBoxItem;
            if (listBoxItem != null)
            {
            }
        }
    }
}

Now that I have the ListBoxItem object, I simply create a Storyboard and begin it:

listBoxItem.RenderTransform = new CompositeTransform();

var swipeAnimation = new DoubleAnimationUsingKeyFrames();
swipeAnimation.KeyFrames.Add(new EasingDoubleKeyFrame
{
    Value = App.RootFrame.ActualWidth,
    KeyTime = KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 250))
});

Storyboard.SetTarget(swipeAnimation, listBoxItem);
Storyboard.SetTargetProperty(swipeAnimation, new PropertyPath("(UIElement.RenderTransform).(CompositeTransform.TranslateX)"));

var sb = new Storyboard();
sb.Children.Add(swipeAnimation);

await sb.BeginAsync();

Of course, feel free to create your custom animation here. Also, the extension method BeginAsync is defined as below:

public static Task BeginAsync(this Storyboard storyboard)
{
    var tcs = new TaskCompletionSource<bool>();

    EventHandler completedEventHandler = null;
    completedEventHandler = (sender, o) =>
    {
        storyboard.Completed -= completedEventHandler;
        tcs.TrySetResult(true);
    };
    storyboard.Completed += completedEventHandler;
    storyboard.Begin();

    return tcs.Task;
}

Now, after the call to the BeginAsync method, I can redirect my user to another page:

await sb.BeginAsync();

this.NavigationService.GoToQuestionsPage(selectedCategory.Id);

Here is a small video of the result:

 

Happy coding!

On Silverlight/Windows Phone, the FluidMoveBehavior can be used to animate the items of a ListBox when user adds or removes an item. But the behavior has no effect when the items are loaded and bound to the Listbox.

Imagine the following C# code corresponding to our ViewModel:

private ObservableCollection<Category> _categories;

public ObservableCollection<Category> Categories
{
    get
    {
        return this._categories;
    }
    set
    {
        this.Set(() => this.Categories, ref this._categories, value);
    }
}

public override async Task OnNavigatedTo(NavigationEventArgs navigationEventArgs, NavigationContext navigationContext)
{
    this.IsBusy = true;

    if (App.Categories == null)
    {
        App.Categories = await ClientServices.ClientServicesLocator.CategoriesService.GetAllCategoriesAsync();
    }

    this.Categories = new ObservableCollection<Category>(App.Categories);

    this.IsBusy = false;
}

And the associated XAML code:

<ListBox x:Name="CategoriesListBox" ItemsSource="{Binding Categories}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"
                       Style="{StaticResource PhoneTextTitle2Style}"
                       FontSize="40"
                       controls:TiltEffect.IsTiltEnabled="True"
                       x:Name="CategoryNameTextBlock" />
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Vertical" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

If you apply the FluidMoveBehavior to the StackPanel of the ListBox and go to the page, you’ll see that the items are all loaded on the same time, with no effect.

To change this, we can replace the ViewModel code with this one:

public Action RefreshCategories { get; set; }

public override async Task OnNavigatedTo(NavigationEventArgs navigationEventArgs, NavigationContext navigationContext)
{
    this.IsBusy = true;

    if (App.Categories == null)
    {
        App.Categories = await ClientServices.ClientServicesLocator.CategoriesService.GetAllCategoriesAsync();
    }

    this.RefreshCategories();
}

As you can see, we no longer use a property of the ViewModel to bind it to the view: we just have an Action property that is raised once the data are loaded. In the code-behind of the page, here is how we use the Action property:

public CategoriesPage()
{
    InitializeComponent();

    this._viewModel = this.DataContext as CategoriesPageViewModel;
    if (this._viewModel != null)
    {
        this._viewModel.RefreshCategories = async () =>
        {
            this.CategoriesListBox.Items.Clear();

            foreach (var category in App.Categories)
            {
                this.CategoriesListBox.Items.Add(category);

                await Task.Delay(100);
            }

            this._viewModel.IsBusy = false;
        };
    }
}

So once the action is raised, we first starts by clearing the items on the ListBox then, for each items we want to add, we add it to the Items property of the control. Then, we make a small pause using Task.Delay, to give some time to the UI to be refreshed!

To get a more clean result, it’s also possible to modify the DataTemplate:

<DataTemplate>
    <TextBlock Text="{Binding Name}"
               Style="{StaticResource PhoneTextTitle2Style}"
               FontSize="40"
               controls:TiltEffect.IsTiltEnabled="True"
               x:Name="CategoryNameTextBlock">
        <TextBlock.Resources>
            <EventTrigger x:Name="LoadEventTrigger"
                          RoutedEvent="Canvas.Loaded">
                <BeginStoryboard>
                    <Storyboard x:Name="FadeIn">
                        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)"
                                                       Storyboard.TargetName="CategoryNameTextBlock">
                            <EasingDoubleKeyFrame KeyTime="0" Value="0.01"/>
                            <EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="1"/>
                        </DoubleAnimationUsingKeyFrames>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </TextBlock.Resources>
    </TextBlock>
</DataTemplate>

When the item is loaded, an animation is raised to change its opacity from 0 to 1. The result of the code can be seen on the first page of the following video (the animation on the second page will be covered in another post):

 

Happy coding!

Recently, I started to work on a Windows Phone application with all the data available through a Website (thanks to HtmlAgilityPack for helping me to parse the webpages).

All the parsing was quite easy but when I wanted to implement the search feature, I wondered how I could do this without any API ? Then, I discovered that the website was using a search form to propose the feature to its users so that was the way !

Here is the HTML code corresponding to the search form on the website:

<form method="post" action="http://www.mysyperwebsite.com/results.html">
    <input type="text" name="keyword" size="25" value="Enter some text..." onfocus="if (this.value=='Enter some text...') {this.value=''}" class="champs">&nbsp;
    <input type="button" onclick="ValidateSearch(this.form)" value="Search" alt="Search">
</form>

As we can see, the form send its data to the URL http://www.mysuperwebsite.com/results.html using the POST method. And that’s all we need to know! Indeed, we’ll do the same thing in our application: we’ll send a POST request to the indicated URL.

For that, we’ll use the HttpClient API and its PostAsync method (you can use the portable version of the HttpClient if you want). The PostAsync method takes in parameters the URI where to post the data and the content to send/post:

image

 

As we mimic the behavior of the form which post content, we’ll use the FormUrlEncodedContent object. This one takes in parameters a list of KeyValuePair, corresponding to the parameters sent by the search form:

var searchParameters = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("keyword", searchText) };

Here is the complete code:

var searchUri = "http://www.mysuperwebsite.com/results.html";
var searchParameters = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("keyword", searchText) };

using (var httpclient = new HttpClient())
{
    using (var content = new FormUrlEncodedContent(searchParameters))
    {
        using (var responseMessages = await httpclient.PostAsync(new Uri(searchUri, UriKind.Absolute), content))
        {
            return await responseMessages.Content.ReadAsStringAsync();
        }
    }
}

And voilà! Now, if you execute this code, it will be the same as if user use the search form.

 

Happy coding (and new year) ! :)

Today, we are going to see a small but useful tip for those who want to prevent a screen to turn off while there is no user activity.

This might be useful, for example, if there are some videos playing on your app: while the video are playing, the user does not interact with the app thus, depending to your power settings, the screensaver can start or the screen can even turn off!

To prevent this case, Microsoft offers the DisplayRequest API. The usage is really simple:

private DisplayRequest _displayRequest;

public void PreventDisplayToTurnOff()
{
    if(_displayRequest == null)
        _displayRequest = new DisplayRequest();

    _displayRequest.RequestActive();
}

public void AllowDisplayToTurnOff()
{
    if (_displayRequest == null)
        _displayRequest = new DisplayRequest();

    _displayRequest.RequestRelease();
}

Even if the usage is really simple, be careful of the following:

  • Use DisplayRequest API only when it’s necessary. Indeed, preventing the screen to start screensaver or to turn off impact battery life!
  • Don’t forget to release each request as soon as possible

Here is a simple helper that, I hope, will help you (this one might not be totally proper but, at least, it works on my case :)):

public class DisplayRequestHelper : IDisposable
{
    private bool _requestActivated;
    private DisplayRequest _displayRequest;

    public void PreventDisplayToTurnOff()
    {
        if (!_requestActivated)
        {
            if (_displayRequest == null)
                _displayRequest = new DisplayRequest();

            _requestActivated = true;
            _displayRequest.RequestActive();
        }
        else
        {
            throw new InvalidOperationException("An active request is already pending.");
        }
    }

    public void AllowDisplayToTurnOff()
    {
        if (_requestActivated)
        {
            if (_displayRequest == null)
                _displayRequest = new DisplayRequest();

            _requestActivated = false;
            _displayRequest.RequestRelease();
        }
        else
        {
            throw new InvalidOperationException("No active request found to be released.");
        }
    }

    public void Dispose()
    {
        try
        {
            if (_displayRequest != null)
            {
                _displayRequest.RequestRelease();
            }
        }
        finally
        {
            _requestActivated = false;
            _displayRequest = null;
        }
    }
}

To use it, just use the Dispose pattern:

using (var helper = new DisplayRequestHelper())
{
    helper.PreventDisplayToTurnOff();
}

This way, you’re sure that the active request are release as soon as possible!

 

Happy coding!

Most of the apps available are used by single users but imagine you want to develop an application that will allow users to switch user accounts. This lead us to, at least, 2 majors issues: how to store the credentials of the users ? How to allow them to easily switch the current user account ?

 

Storing user credentials:

Credential Locker, available through the PaswwordVault class, allows you to add, get or delete credentials for user in a secure way (all passwords are encrypted and cannot be accessed by other users). Other good point: the credentials are roamed with the Microsoft account users will be able to retrieved its credentials from another device without no cost!

To use the PasswordVault, it’s pretty simple:

private void AddCredentials(string userName, string password)
{
    var passwordVault = new Windows.Security.Credentials.PasswordVault();
    passwordVault.Add(new PasswordCredential(AppName, userName, password));
}

private bool CheckCredentials(string userName, string password)
{
    var retVal = false;

    var passwordVault = new Windows.Security.Credentials.PasswordVault();

    try
    {
        var passwordCredential = passwordVault.Retrieve(AppName, userName);
        if (passwordCredential != null)
        {
            retVal = passwordCredential.Password == password;
        }
    }
    catch (Exception)
    {
        // If the passwordvault does not contains the credentials
        retVal = false;
    }

    return retVal;
}

Once added, the credentials can be viewed from the Credential Manager and we can confirmed that roaming is activated:

image

Ok so now that the credentials are saved and we know how we can retrieved them, let’s see how to display a

 

Switch user account:

The AccountsSettingsPane is a new class in Windows 8.1 that let you add the Accounts command to the Settings Flyout. This command is available, for example, on the native mail application:

image  image

To get the entry added to the SettingsPane, simply add the command to the SettingsPage:

image

Then, the AccountsSettingsPane pane is used like the SettingsPane. First, get a reference to the pane of the current view then, add an event handler to the CommandRequested event:

image

Finally, all the magic appears at the end where you add a provider account for your app and, for each credentials that to the app, you add a web account command (specifying which actions user will be able to take when he will select an account):

image

image

During my investigations, I found that Mike Taulty has posted a similar blog post with Azure Mobile Services (available here) where he gives more details about how to handle the deconnection/reconnection (so I’ll not give you more details here, just look at his post).

 

PS: Source code is available here.

 

Happy coding!