XAML Playground
about XAML and other Amenities

New e-book published

2014-02-10T12:31:42+01:00 by codeblock

Silverlightshow has published today another ebook creted wrapping up a number of articles I wrote in the previous months. The title may sounds ambitious:

Windows 8.1: The new less-known features that will improve your work

The ebook contains 12 chapters made of a collection of arguments that are not mainstream when thinking to Windows 8.1 features. It actually speaks about a number of featurs that has benne added to the most recent release of the platform but that are not really known. Here is the list of chapters:

  • Chapter 1: Behaviors SDK - Part #1
  • Chapter 2: Behaviors SDK - Part #2
  • Chapter 3: Exploring new controls (Hub, CommandBar, Flyouts and Pickers)
  • Chapter 4: Location-aware apps - Part #1: What's new in geolocation
  • Chapter 5: Animations and transitions
  • Chapter 6: Location-aware apps - Part #2: Working in background
  • Chapter 7: Play with Bluetooth Rfcomm
  • Chapter 8: Application Views improvements
  • Chapter 9: Improved device interactions
  • Chapter 10: Alarm and Lock screen call toasts
  • Chapter 11: Create a PDF Viewer with new PDF API
  • Chapter 12: The Windows Search API

The role of Behaviors and UserControls in the MVVM paradigm

2014-02-10T04:30:00+01:00 by codeblock

It is a well known fact that the Model-View-ViewModel pattern is a must when you develop with a XAML-related technology. By now, there are plenty of frameworks, toolkits and tools that imagesupports this programming model and also HTML/Javascript technologies are fast moving towards this architectural pattern using specific libraries like KnockoutJS and AngularJS. 

All in all, the aspects of MVVM programming have been consolidated and it is often clear what goes in the View and what goes in the ViewModel but, as usual, there are a number of degrees of gray between the white and the black and often you meet limits that need a workaround that violates the pureness of the pattern. So please notice that it is not a pretty formal matter, but the violation always takes inside of our architecture some dirty tricks that make it hard to understand, maintain and evolve in the future.

It's here that two actors enter the scene. They are named Behaviors and UserControls. Also if I've merged them into the same argument, they cover very different aspects. Behaviors are much more logic-related and are used to share a common "behavior" (that may have also a visual impact) to a number of different elements. UserControls instead are visual components and they are better to encapsulate visual elements thet should work in a coordinated way.

When do I need a Behavior or a UserControl?

When you work in a MVVM application, most of the time is spent moving data from a local or remote service to a couple of properties, connected to the user interface, and then collecting commands that indicates the actions accomplished by the user. Into the ViewModel you are completely abstracted by the user interface that consumes your properties. I usually pay attention to property names to avoid UI-related names. My view models never have properties called "Visible" or "Opened" because these imply a someway hard-coupling between the meaning of the name and what it happens in the user interface.

It may seem it suffices, but unfortunately, there are a number of cases that you have to switch on or off some special effect in the user interface and it is really hard to get it working only on the basis of a simple property that changes its value. It may be an animation, a fading effect, an item that appear or disapper, or also something that changes it shape suddenly. For all of these and other cases, you may need to write some UI-logic that does the dirty work, but the viewmodel is not the right place to put it.

Let do an example: UserControl

Let say you have to build a registration form. It is really simple to create a similar form and it is all about binding correctly properties together. But there is a subtle problem. the PasswordBox has a property that can't be subject to data binding. So, it is required to work around the problem. In this case, using a user control let you create a piece of code that receive the PasswordChanged event and updates a DependencyProperty.

   1: public partial class BindablePasswordBox : UserControl
   2: {
   3:     bool suspended = false;
   4:  
   5:     public static readonly DependencyProperty PasswordProperty =
   6:         DependencyProperty.Register(
   7:             "Password",
   8:             typeof(string),
   9:             typeof(BindablePasswordBox),
  10:             new PropertyMetadata(string.Empty, new PropertyChangedCallback((s, e) => ((BindablePasswordBox)s).OnPasswordChanged())));
  11:  
  12:     public BindablePasswordBox()
  13:     {
  14:         InitializeComponent();
  15:         this.thePasswordBox.PasswordChanged += thePasswordBox_PasswordChanged;
  16:     }
  17:  
  18:     private void thePasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
  19:     {
  20:         try
  21:         {
  22:             suspended = true;
  23:             this.Password = this.thePasswordBox.Password;
  24:         }
  25:         finally
  26:         {
  27:             suspended = false;
  28:         }
  29:     }
  30:  
  31:     private void OnPasswordChanged()
  32:     {
  33:         if (!suspended)
  34:         {
  35:             this.thePasswordBox.Password = this.Password;
  36:         }
  37:     }
  38:  
  39:     public string Password
  40:     {
  41:         get { return (string)GetValue(PasswordProperty); }
  42:         set { SetValue(PasswordProperty, value); }
  43:     }
  44: }

This control isolate the logic required to create the property and update it. The “suspended” field is used to avoid cyclic updates between the Password property of the PasswordBox and the same property of the user control. Once you have created the control, you can use it into the Views and use the databinding to connect the password to the viewmodel.

   1: <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
   2:     <local:BindablePasswordBox Password="{Binding Password, Mode=TwoWay}" />
   3:     <ProgressBar Minimum="0" Maximum="100" Value="{Binding Complexity}" HorizontalAlignment="Stretch" Height="5" />
   4: </StackPanel>

In this example I've imagined that the viewmodel cheks the password complexity avery time it changes and updates a percentage scale in the Complexity property. The progressbar gives a visual representation of this value but this is only matter of user interface.

Going with a Behavior

Behavior have been added to the XAML family after their inclusion in the Blend SDK 3.0. Immediately they become a first class tool to support development with MVVM, just because they are able to encapsulate a piece of code that can be easily reused. The probably most common usage of behaviors is the EventToCommand trigger that is used to map element events to viewmodel commands, but with a minimum of effort they can improve your MVVM programmi of a number of degrees.

imageLet say we have to build a IP configuration form. In this form we have a field where we can set the IP address if it is not acquired by a DHCP server. The field appear as the figure on the side

Once you select the dropdown list value ad "DHCP", the textbox on the side may behave in very different ways. We can hide it or also it can be disabled. The viewmodel should not be never aware of this fact. It only have a property the contains the IP Address and the IPMode (0 = DHCP, 1 = Manual).

To implement a reusable logic we can use a behavior here. Is should be the most generic so it wraps the FrameworkElement class:

   1: public class ShowHideBehavior : Behavior<FrameworkElement>
   2: {
   3:     public static readonly DependencyProperty ValueProperty =
   4:         DependencyProperty.Register(
   5:             "Value",
   6:             typeof(string), 
   7:             typeof(ShowHideBehavior), 
   8:             new PropertyMetadata(null, (s, e) => ((ShowHideBehavior)s).OnValueChanged()));
   9:  
  10:     public string Value
  11:     {
  12:         get { return (string)GetValue(ValueProperty); }
  13:         set { SetValue(ValueProperty, value); }
  14:     }
  15:  
  16:     public static readonly DependencyProperty ValidValueProperty =
  17:         DependencyProperty.Register(
  18:             "ValidValue",
  19:             typeof(string),
  20:             typeof(ShowHideBehavior),
  21:             new PropertyMetadata(null));
  22:  
  23:     public string ValidValue
  24:     {
  25:         get { return (string)GetValue(ValidValueProperty); }
  26:         set { SetValue(ValidValueProperty, value); }
  27:     }
  28:  
  29:     public bool HideWhenInvalid { get; set; }
  30:  
  31:     private void OnValueChanged()
  32:     {
  33:         if (AssociatedObject != null)
  34:         {
  35:             if (HideWhenInvalid)
  36:                 this.AssociatedObject.Visibility = object.Equals(this.Value, this.ValidValue) ? Visibility.Visible : Visibility.Collapsed;
  37:             else
  38:                 this.AssociatedObject.IsEnabled = object.Equals(this.Value, this.ValidValue);
  39:         }
  40:     }
  41: }

The behavior has a Value property that contains the value specified for the target combo box and a ValidValue that indicates the value for which the element is visible/enabled. Also there is a HideWhenInvalid property that let the developer choose if the control should be disabled or hidden. The followinf XAML uses the behavior:

   1: <StackPanel Orientation="Horizontal">
   2:     <ComboBox x:Name="cboMode" Width="100" SelectedIndex="{Binding IPMode}">
   3:         <ComboBoxItem>DHCP</ComboBoxItem>
   4:         <ComboBoxItem>Manual</ComboBoxItem>
   5:     </ComboBox>
   6:     <TextBox Width="200" Margin="8,0,0,0">
   7:         <i:Interaction.Behaviors>
   8:             <local:ShowHideBehavior HideWhenInvalid="true" Value="{Binding SelectedIndex, ElementName=cboMode}" ValidValue="1" />
   9:         </i:Interaction.Behaviors>
  10:     </TextBox>
  11: </StackPanel>

The logic, encapsulated in this way, is highly reusable and we can also implement a number of properties that allow the customization of behavior across different applications. Additionally, the ViewModel is completely separated from an aspect that is a question specific to the presentation and not to the business logic.

How to choose?

So the question now is: Should I use an UserControl or a Behavior? Unfortunately this question does not have a simple and unique answer. At the proof of facts, there are many cases where the solution are overlapped and you should choose on the basis of your personale feel, or better, on the basis of your project goals. My rules of thumb are the following:

First of all a behavior: It is really much more easy to implement a behavior than a user control if you need to do something more than extracing a chunk of XAML. Behavior are also much more reusable then UserControls and they can be parametrized easily.

Then try an UserControl: If a behavior does not match, as an example because it implies a too complex logic or needs to access properties that are not available, then the UserControl often is the right answer.

It involves generation of elements: In this case the UserControl is much more effective because you can use a base template in XAML and then add the required elements. In this case you can also evaluate a Custom Templated control if you think the code is widely reusable.

Another question is When? When should I understand I need something different than a ViewModel. This question has a much simple answer: When you need to go to your codebehind to implement such a feature, then probably you can write a behavior or an user control.

Conclusion

The examples I've shown in this post are really simple but I hope they give you the right feel about code encapsulation. The main purpose of creating components like user controls and behaviors should be the reuse of their logic, but there are a number of reasons why it is a good idea to use them also for non-reusabel features since they unplug your logic by the viewmodel.

WP8: New Emulators images released

2014-01-03T12:37:09+01:00 by codeblock

Some new emulator images are now available for the download. These new images - a total of 9 - covers the Windows Phone 8.0 Updates 2 (8.0.10322) and 3 (8.0.10492 or higher). They are freely downloadable from the Microsoft website from the links below:

Windows Phone SDK 8.0 Update for Windows Phone 8.0.10322
http://www.microsoft.com/en-us/download/details.aspx?id=39711

Windows Phone SDK 8.0 Update 3 Emulators
http://www.microsoft.com/en-us/download/details.aspx?id=41559

Both the updates requires at least Visual Studio 2014 Update 4 or Visual Studio 2013 RTM. They are targeted to the test of applications on the correspondent platform updates. Particularly the Update 3 enables the support for large screen devices (1080p). Here is the complet list of images:

Update 2
Windows Phone Emulator 8.0 (10322) WVGA
Windows Phone Emulator 8.0 (10322) WVGA 512 MB
Windows Phone Emulator 8.0 (10322) WXGA
Windows Phone Emulator 8.0 (10322) 720p

Update 3
Windows Phone Emulator 8.0 Update 3 WVGA
Windows Phone Emulator 8.0 Update 3 WVGA 512 MB
Windows Phone Emulator 8.0 Update 3 WXGA
Windows Phone Emulator 8.0 Update 3 720p
Windows Phone Emulator 8.0 Update 3 1080p

Take note that you must have the Windows Phone 8.0 already installed before to intalls the updates.

XPG Toolkit – Notification Library 1.0.5114.0 released

2014-01-02T21:28:29+01:00 by codeblock

During the writing of my last article for Silverlightshow where I’ve explained the new Alarm and Lock screen call Toast notifications, I found useful a small set of classes to generate the XML that I’ve created to build the notification. This short xml chunk must be created for Tile, toasts and badges and also if the framework has an method made to return the empty template is always something of boring.

Using some classes and an xmlSerializer I’ve finally arranged to make the creation of the xml simple as a breeze, and I’ve taken some time during my winter holidays to consolidate the toolset and complete it with tile and badge notifications. It definitely taken something more than a little time due to the fact that tile templates are really a lot of types…

So at the end the library has about 164 classes and is enforced by 136 unit tests made to ensure that the output template does not changes whit future developments. Together with the templates I’ve also created a couple of utility classes, supporting dependency injection, that enable the send of notifications with very few lines of code. Here is and example:

   1: INotificationManager manager = new NotificationManager();
   2:  
   3: manager.PublishToast(new Toast
   4:     {
   5:         Duration = "long", 
   6:         Launch = "12345",
   7:         Audio = new ToastAudio{
   8:             Loop = true,
   9:             Source = "ms-winsoundevent:Notification.Looping.Alarm2"
  10:         },
  11:         Visual = new ToastVisual
  12:         {
  13:             Binding = new ToastText01
  14:             {
  15:                 Text1 = "Alarm!"
  16:             }
  17:         },
  18:         Scenario = new AlarmScenario
  19:         {
  20:             CanDismiss = true,
  21:             CanSnooze = true
  22:         }
  23:     },
  24:     DateTimeOffset.Now.AddMinutes(1), 
  25:     TimeSpan.FromMinutes(1), 
  26:     5);

For a full explanation of the library please refer to this page that will be continuously updated with the new features I’ll add in the future. Feel free to contact me to suggest new features of to make me aware of bugs.

Here are the download links:

Package on nuget: https://www.nuget.org/packages/XPG.Toolkit.Notifications/1.0.5114

Download: http://www.xamlplayground.org/downloads/xpg-toolkit-notifications-1.0.5114.0-bin.zip (83kb)

WP8: A utility class to call choosers using async/await

2013-10-18T15:50:55+01:00 by Andrea Boschin

The relatively recent introduction of async/await keywords in C# has been an important news to help people solve theri problems with the intrisic asynchronous programming model tha comes from the roots of Silverlight. As I often pointed, the asynchronous model is much more effective, but it usually makes the code hard to be wrote and to be understood. with the async/await keywords, all the hard work is done under the hoods by the compiler but there are still a number of cases where these keywords are not directly applicable. One of these is the call of Choosers in Windows Phone 8, where we do not have the needed handles to use this tecnique but we still need to rely on a "Completed" event handler. Let me say that the goal of this post is to avoid the following code:

   1: public void ChoosePhoto()
   2: {
   3:     PhotoChooserTask pct = new PhotoChooserTask();
   4:     pct.ShowCamera = true;
   5:     pct.Completed += HandlePhotoChooseCompleted;
   6:     pct.Show();
   7: }
   8:  
   9: private void HandlePhotoChooseCompleted(object sender, PhotoResult e)
  10: {
  11:     // do what you want with choosen photo
  12: }

Getting the result in a separate method make the code hard to be understand and, in this case, also does not correctly unhook the eventhandler causing additional work for the garbage collection. A complete and effective solution should be much more complex and require the use of member fields in a class. The desire of every progremmer is to call the same this way:

   1: var photo = await DeviceServices.ChoosePhoto(true);

After some tryies I'm able to create the DeviceServices class and inside of it I've created a single method that is able to call every chooser, not only the PhotoChooserTask. Please remember that this applies to the Choosers only, because Launchers does not have a common base class and, actually, the do not require a similar approach since they do not returns any result.

As a careful investigation, a chooser is made of two classes working together: The "chooser" that is a class derived from ChooserBase<T> and a "result" that may be a TaskEventArgs or a class derived from it. So we can declare the following method and be sure it apply to every existing chooser:

   1: private static Task<K> InvokeChooser<T, K>(Action<T> initCallback = null)
   2:     where K : TaskEventArgs
   3:     where T : ChooserBase<K>, new()
   4: {
   5:     // launch chooser here
   6: }

These two classes exposes all the required handles to create, run and retrieve the result from the chooser. The sole problem is in the options specific for the chooser. For this purpose the initCallback method is invoked with the instance of the chooser to let the caller set the options. Here is the full body of the method:

   1: private static Task<K> InvokeChooser<T, K>(Action<T> initCallback = null)
   2:     where K : TaskEventArgs
   3:     where T : ChooserBase<K>, new()
   4: {
   5:     TaskCompletionSource<K> tcs = new TaskCompletionSource<K>();
   6:     T chooser = new T();
   7:     
   8:     if (initCallback != null)
   9:         initCallback(chooser);
  10:     
  11:     EventHandler<K> handler = null;
  12:     
  13:     handler = (s, e) =>
  14:     {
  15:         chooser.Completed -= handler;
  16:     
  17:         if (e.Error != null)
  18:             tcs.SetException(e.Error);
  19:         else
  20:             tcs.SetResult(e);
  21:     };
  22:     
  23:     chooser.Completed += handler;
  24:     chooser.Show();
  25:     
  26:     return tcs.Task;
  27:     }

Let me explain. First of all, an instance of the TaskCompletionSource<T> class is created. This class wraps a task that is returned to the caller to be awaited. This task ends when the SetResult, SetException or SetCancelled methods are called. Then the chooser is created from the generic type, the instance is passed to the initialization callback. After this part the code creates an event handler and, using a lambda expression, it attach a method to handle the result. Finally the chooser is shown and the task is returned.

Inside the lambda expression, the first action is to detach the event handler. This clean every reference to the handler and leave the instance free to be finalized. On the basis of the result (success or failure) the SetException and SetResult methods are a called. This ends the await and eventually returns the result or the exception.

The next is to use this method to create some chooser-specific methods that let the user easily specify the arguments. Here is the ChoosePhoto method:

   1: public static async Task<Stream> ChoosePhoto(bool showCamera = true)
   2: {
   3:     var r = await DeviceServices.InvokeChooser<PhotoChooserTask, PhotoResult>(
   4:         t =>
   5:         {
   6:             t.ShowCamera = showCamera;
   7:         });
   8:  
   9:     return r.ChosenPhoto;
  10: }

In my class I've created a number of these methods, and all of them are targeted to the specific chooser they use. This method collects the hard part into a single and clean solution exposing a bunch of clear methods that simplify the developer life. Here is the full code you can cut & paste in your projects:

/// <summary>
/// Implement services to connect to device
/// </summary>
public static class DeviceServices
{
/// <summary>
/// Chooses the photo.
/// </summary>
/// <param name="showCamera">if set to <c>true</c> [show camera].</param>
public static async Task<Stream> ChoosePhoto(bool showCamera = true)
{
var r = await DeviceServices.InvokeChooser<PhotoChooserTask, PhotoResult>(
t =>
{
t.ShowCamera = showCamera;
});

return r.ChosenPhoto;
}

/// <summary>
/// Chooses the address.
/// </summary>
public static async Task<NamedValue<string>> ChooseAddress()
{
var r = await DeviceServices.InvokeChooser<AddressChooserTask, AddressResult>();
return new NamedValue<string> { DisplayName = r.DisplayName, Value = r.Address };
}

/// <summary>
/// Chooses the email.
/// </summary>
public static async Task<NamedValue<string>> ChooseEmail()
{
var r = await DeviceServices.InvokeChooser<EmailAddressChooserTask, EmailResult>();
return new NamedValue<string> { DisplayName = r.DisplayName, Value = r.Email };
}

/// <summary>
/// Chooses the phone number.
/// </summary>
public static async Task<NamedValue<string>> ChoosePhoneNumber()
{
var r = await DeviceServices.InvokeChooser<PhoneNumberChooserTask, PhoneNumberResult>();
return new NamedValue<string> { DisplayName = r.DisplayName, Value = r.PhoneNumber };
}

/// <summary>
/// Saves the phone number.
/// </summary>
/// <param name="phoneNumber">The phone number.</param>
public static async Task SavePhoneNumber(string phoneNumber)
{
var r = await DeviceServices.InvokeChooser<SavePhoneNumberTask, TaskEventArgs>(
t =>
{
t.PhoneNumber = phoneNumber;
});
}

/// <summary>
/// Saves the email.
/// </summary>
/// <param name="emailAddress">The email address.</param>
public static async Task SaveEmail(string emailAddress)
{
var r = await DeviceServices.InvokeChooser<SaveEmailAddressTask, TaskEventArgs>(
t =>
{
t.Email = emailAddress;
});
}

/// <summary>
/// Invokes the chooser.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="K"></typeparam>
/// <param name="initCallback">The initialize callback.</param>
private static Task<K> InvokeChooser<T, K>(Action<T> initCallback = null)
where K : TaskEventArgs
where T : ChooserBase<K>, new()
{
TaskCompletionSource<K> tcs = new TaskCompletionSource<K>();
T chooser = new T();

if (initCallback != null)
initCallback(chooser);

EventHandler<K> handler = null;

handler = (s, e) =>
{
chooser.Completed -= handler;

if (e.Error != null)
tcs.SetException(e.Error);
else
tcs.SetResult(e);
};

chooser.Completed += handler;
chooser.Show();

return tcs.Task;
}
}

Hoping this helps!

Windows 8.1 available for the download

2013-10-17T05:40:00+01:00 by codeblock

Windows-8-1Today the new update to the Windows 8 operating system is available for the download. It adds a number of new features for the end user and for the developer. Together with the upgrade Microsoft released a number of upgrades for built-in apps that comes together with the operating system.

The update will be available directly from the Store app or as an ISO image. Some trouble may affect users that already installed the public preview using the ISO image. In this case it is required to return back toe the Windows 8 before installing the new 8.1. Differently, if you have installed the preview from the store, the upgrade should work effectively but all the apps must be reinstalled at the end.

There are important new features in user experience: the availability of new tile sizes that now have small, square, wide and large size, powering up the notifiations on this important surface. Now the operating system supports more than two apps on the screen at the same time, and the user is able to choose the size of each app. Skydrive become the official and integrated cloud media; the user can choose to automatically save contents to the cloud and see them sync between different devices.

For the developer the news are huge. Other to the toolset enhancements related to the previous news, it now has also a number of new features.

  • Many xaml improvements for developers
  • A Hub control that simplify the creation of hub-applications
  • A new set of tools for location and geofencing
  • News in share and search contracts
  • New types of toast notifications (alarm and lock screen)
  • Support for Appointments and Contacts
  • Enhanced bluetooth support that includes RfComm
  •  

Review: One week with Lumia 925

2013-10-03T23:04:28+01:00 by Andrea Boschin

WP_20131003_004During last 7 days I had the pleasure of having a Nokia Lumia 925, thanks to the #ilmiolumia program by Nokia Italy. I've subscribed in this page http://slpg.org/18V9Rdj (Italy only I suppose) and few days later they called me because I've been selected to have a try with this device.

When the device arrived and I unpacked it, I have to confess a little delusion. I really would want to have a try with a Lumia 1020, with its amazing 41mp camera, so when I discovered the device was a Lumia 925, I was little disappointed. Few moments later, keeping it in my hands for a little, just before to switch it on, I realized it is really a nice device, really light in weight, and with a stylish line. It immediately captured my love for minimal design with its metal body that appear so attractive for eyes.

The Lumia 925, differently from other Lumia smartphones, like 820, 920 and also the 1020, is externally a device tailored for business man, for the elegant woman that needs to have a phone beautiful and attractive when in the hands but light and invisible when in the pocket or in the purse.

When it is switched on it present the familiar tiles of Windows Phone 8, with a number of applications already on board. Entering the live id I use for my 820, it automatically synchronized apps and data. The operation taken some minutes to complete but at the end I found everything I need, with the exception of tiles positioning that has been completely lost. Also I had to remove some applications that the device is unable to synchronize just because the have a newset version already installed.

I've explored the device for a few and I found that the power of its 1,5 ghz dual core processor makes the navigation very fluid and the applications really fast and stepless. The CPU is exactly the same as my 820 and definitely it is perfect for device features. The device has 16GB on board memory but, and this is a bad note, is haven't a slot for memory expansion. WP_20130928_11_56_21_Smart16GB may appear a huge amount of memory but when you start storing some music and pictures the main memory can rapidly become little. In my 820 the 8GB main memory I only use for apps is insufficient and, due to a strange memory management by the operating system, it refuses to install some memory-hungry applications (e.g. some games). Given you may use half the size to store your files, the remaining half could suffer of the same problem. In my opinion the best would be to have equipped the device with 32gb or alternatively with an SSD slot.

Finally I focused my attention to the very interesting part of the device. The 8,7mp camera. When you start with camera, the default application is disappointing but, after a few you discover two apps that boosts its power to the max. Nokia Smart Camera and Nokia Pro Camera are able to take the maximum advantage from th camera. The first, Nokia Smart Camera, is interesting to take action shots because is able to shoot a fast sequence of images and then elaborate to find the best one or play with moving subjects. The image of me on the side is taken and elaborated with this software. It wp_ss_20131003_0014shows an enjoying effect that shows the shoot sequence. The image is completely customized on board of the phone an it may be modified easily in a secondary time.

The smart cam is beautiful and you will enjoy your friends with your shoots. A much more interesting use is to take sport actions where multiple sequential shoots can help to choose the imagethat better represents the moment. But for an exigent person it is someway trivial.

For such people the Nokia Pro Cam is for sure a dream made reality while it puts in your hands a really professional camera, with a really fast as the light shoot speed. The software gives a number of tuning trimmers, with an effective user interface. You can tune flash, zoome, ISO, shooter speed and exposure. But the very surprising is the ability to manipulate the focus the enables the deep field effect.

wp_ss_20131003_0024The phone made me very satisfied along the week I used it. It is for sure a wonderful device and it made me forget the powerfulness of the Lumia 1020. I'm still attracted by this device due to the 41mp camera that I suppose should add much more control to camera, but watching ad the balance of features, the Lumia 925 is almost the perfect device for who wants a powerful device, with a amazing camera that is able to shoot in low light conditions and make wonderful photograps, but he also wants a compact, light and stylish phone to be used for professional activities. The operating system is to me a great companion for such people, thaks to the integration with work environment thanks to Office hub and a huge number of apps.

My congrats to Nokia for its best device ever, waiting for an hoped "Lumia 1025" (?) that mixes the huge 41mp camera together with the class of the 925.

From a "Class Library" to a "WinRT Component": Deal with inheritance

2013-09-26T23:32:39+01:00 by Andrea Boschin

If you ever tryed to take a class library written in C# for a Windows Store app and act on the "Output Type" dropdown list to convert it to a Windows Runtime Component, you have been probably discouraged by the huge number of errors this, apparently simply action, generates. If your library is something more complex than some basic classes and it has been writing with object orientation in mind, the conversion to a WinRT Component is far far away to be a simple task.

To fully understand the reason, you have to keep in mind the lower target, this component has, that is Javascript. So now, you have to try to think to the wonderful toolset you have in your hands when you write in C# and ask yourself what is the corresponding construct in Javascript.

Let do some examples: Generic Types? they do not exist in Javascript.  Inheritance? It's only simulated in Javascript. Types are limited to a restricted set, the language only supports arrays, and the asynchronous model is something of really different in Javascript.

All these things can't be used in a WinRT component. Precisely, they can be used inside a component, but they can't be exposed to other languages than C# because the projection engine is not able to convert them to Javascript's corresponding constructs.

With these posts I'd like to show how to convert, relatively easily, an existing library, made with the full toolset of C#, in a fully functional WinRT component without wasting lot of time rewriting the most of the library.

Let start from something: Flickr Tools

During my last talk in Venice, I had to present a lab about sharing contracts. In this talk I had the need of creating a simple Windows Store app on the basis of I've presented the arguments. To have an interesting and functional application I've created a simple class library, that is able to call Flickr APIs to retrieve some photographs for the purposes of the presentation. The library, called XPG.FlickrTools has been written with the full usage of inheritance, generics, and types, without any caution for the Javascript side of the story. It simply did not have any interest to me in that moment.

Then after the lab have been done, taken by curiosity I've tried to convert the library to a WinRT component and I found a number of errors:

image

I known that the task is not only to take a dropdownlist down, but the number of errors (15 at the start, but they only hide a greatest number) was totally unexpected. So, my very first task in the conversion have been to convert each class to "internal", to simply hide them to the projection engine. I think it should be the very first step in every conversion because it remove all the errors and let you act one step at the time

This task does not suffice to remove all the errors. Infact, a WinRT component needs to contains almost a public type to be a real component. Differently it generates at least the following:

"Input module must contain at least one public type that is located inside a namespace. The only types found inside namespaces are private."

Now let me introduce the concept to apply to start the conversion. It is really true you are not able to use inheritance in classes so something like this is not legal in a WinRT component:

   1: public class FlickrSearch : FlickrPagedCall
   2: {
   3:     // omissis
   4: }

This is because you need to declare the FlickrSearch class and each other public type "sealed", so you implicitly cut off the inheritance. Once FlickrPagedCall is sealed, the FLickrSearch class cannot inherits from it. Fortunately, inheritance is supported in interfaces so this code is perfectly legal:

   1: public interface  IFlickrSearch : IFlickrPagedCall
   2: {
   3:     // omissis
   4: }

To fully take advantage of this I have to recall that an "internal" type cannot be instantiated by an external assembly, but it can cross the boundaries of the assembly where it have been created if it implements a public interface to handle it. So, I have simple to make the internal component implement the public interfaces. Let start creating an interface for each type it has to be projected:

   1: internal class FlickrSearch : FlickrPagedCall, IFlickrSearch 
   2: { }
   3:  
   4: internal class FlickrPagedCall : FlickrCall, IFlickrPagedCall 
   5: { }
   6:  
   7: internal class FlickrCall : IFlickrCall
   8: { }

Doing this task requires some kind of careful. In my library I have nine classes that needs to be converted to interfaces. First I added an interface to each class prepending an "I" to the class name. Then I added the interface to the implementation list of the corresponding class:

   1: public interface IFlickrCall
   2: {
   3: }
   4:  
   5: internal abstract class FlickrCall : IFlickrCall
   6: {
   7: }

Then I take care of inheritance at the interface level, adding the correct base interface to each interface I previously defined. At the moment I leave the interfaces empty just because taking care of methods may be slightly complicated, so I prefer to make the library free of errors before the next steps.

I need to be really careful when classes have some special inheritance list. In my case the FlickrResponse class implements "IEnumerable<FlickrPhoto>". IEnumerable generic classes are perfectly legal in winRt components but they have to espose public types and not internal ones. So this:

   1: internal sealed class FlickrResponse : IEnumerable<FlickrPhoto>
   2: {
   3: }

May be converted to this:

   1: public interface IFlickrResponse : IEnumerable<IFlickrPhoto>
   2: {
   3: }
   4:  
   5: internal sealed class FlickrResponse : IEnumerable<IFlickrPhoto>, IFlickrResponse
   6: {
   7: }

Obviously you need to convert to the right interface all the places where a concrete class is returned. In this case the FlickrPhoto class is converted to the corresponding IFlickrPhoto interface. Upto the total conversion has been completed you should have a number of errors. Simply forget the errors and take the maximum care in conversion. Here another example:

   1: protected async Task<FlickrResponse> Execute(Uri uri)
   2: { }

It becomes:

   1: protected async Task<IFlickrResponse> Execute(Uri uri)
   2: { }

You have also to start adding properties and method to classes declarations.This happens when an object is used inside a method.

At the end the library soud compile again. Now we have a problem: the interfaces cannot be instantiated, just because they are interfaces, not classes... so we need someone that creates classes internally and then return it by interfaces. It is called a "factory".

   1: public sealed class FlickrFactory
   2: {
   3:     public string AppKey { get; private set; }
   4:     public string Secret { get; private set; }
   5:  
   6:     public FlickrFactory(string appKey, string secret)
   7:     {
   8:         this.AppKey = appKey;
   9:         this.Secret = secret;
  10:     }
  11:  
  12:     public IFlickrSearch CreateSearch(string query, int number)
  13:     {
  14:         return new FlickrSearch(query, this.AppKey, this.Secret);
  15:     }
  16: }

After this passage your library should be near to fully compile. Mine has still some issue, but it is not related to the inheritance problem. I'll be back on these additional problems in the next post, speaking about asyncronicity.

Windows Phone 8 Overview (Slides)

2013-06-07T11:55:00+01:00 by codeblock

Here is the slide set from my last talk on Windows Phone 8.

Categories:  
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

#wp8tip: Adapt images to different resolutions

2013-04-23T23:32:03+01:00 by Andrea Boschin

Windows Phone 8 comes with the support of multiple resolutions, that must be supported by new applications to cover all the available devices. As you can understand, it is really important to be able to support these new resolutions seamless, but it may be annoying when we have to deal with a number of images. Indeed, if vector graphics scales directly to all the resolutions, at the sole price of correctly design yout layout, with images you are forced to provide a different size to every resolution, if you want the best result.

To make my life easy, I wrote a simple attached property that enable me to easily specify the path of the image and have it updated with a resolution suffix. It is something similar to which it happens automatically in Windows 8. First of all a mini helper to convert an uri and add the resolution switch the path:

   1: public static class ResolutionHelper
   2:  {
   3:      public static Uri ToCurrentResolution(this Uri uri)
   4:      {
   5:          string uriString = uri.OriginalString;
   6:  
   7:          if (uriString.EndsWith(".jpg") || uriString.EndsWith(".jpeg") || uriString.EndsWith(".png"))
   8:          {
   9:              int dot = uriString.LastIndexOf('.');
  10:              uriString = uriString.Substring(0, dot) + "." + ResolutionHelper.CurrentResolutionString + uriString.Substring(dot, uriString.Length - dot);
  11:              return new Uri(uriString, UriKind.RelativeOrAbsolute);
  12:          }
  13:  
  14:          return uri;
  15:      }
  16:  
  17:      private static string CurrentResolutionString
  18:      {
  19:          get
  20:          {
  21:              if (App.Current.Host.Content.ScaleFactor == 100)
  22:                  return "screen-wvga";
  23:              else if (App.Current.Host.Content.ScaleFactor == 160)
  24:                  return "screen-wxga";
  25:              else if (App.Current.Host.Content.ScaleFactor == 150)
  26:                  return "screen-720p";
  27:              else
  28:                  throw new InvalidOperationException("Unknown resolution");
  29:          }
  30:      }
  31:  }

Once I have this tool class ready, it's easy to imagine to specify an uri to the image source and have it converted on the basis of the current resolution. I've tried a number of solutions but I finally found that writing a simple Attached property is the most simple and effective. Here is the extension:

   1: public class AutoScale : DependencyObject
   2: {
   3:     public static readonly DependencyProperty SourceProperty =
   4:         DependencyProperty.RegisterAttached("Source", typeof(Uri), typeof(Image), new PropertyMetadata(null));
   5:  
   6:     public static Uri GetSource(DependencyObject obj)
   7:     {
   8:         return (Uri)obj.GetValue(SourceProperty);
   9:     }
  10:  
  11:     public static void SetSource(DependencyObject obj, Uri value)
  12:     {
  13:         obj.SetValue(SourceProperty, value);
  14:  
  15:         Image image = obj as Image;
  16:  
  17:         if (image != null)
  18:         {
  19:             image.Source = new BitmapImage(value.ToCurrentResolution());
  20:         }
  21:     }
  22: }

The attached property has the advantage of making the trick seamless. Instead of writing the Source property in the XAML, I write tha "local.AutoScale.Source" property and is automatially update the underlying image:

   1: <Image local:AutoScale.Source="/Assets/Images/img.jpg" 
   2:        HorizontalAlignment="Center" 
   3:        VerticalAlignment="Center" Width="300" Height="300"/>

Model View ViewModel with Windows Store Application

2013-03-08T21:20:28+01:00 by codeblock

I reference here the slides from this night talk about the Model View ViewModel in a Windows Store app. The talk and the slides are in Italian but I figure out you can use google translate to get the translation in you language.

Model-View-ViewModel con Windows Store Apps

Thanks to all the people that listened to my presentation and asked me a question about this topic. If you need my help please feel free to contact me via blog contact form.

The “evil” in using “async void”

2013-02-19T01:57:03+01:00 by codeblock

Following a non-NDA session at the MVP Global Summit 2013, the speaker pointed me to an interesting argument that is the usage of “async” with methods returning void. This practice is used many times, more than you expect, and is a potential source of interesting bad issues that can cause unexpected crashes in your apps.

The problem with “async void” versus the opposite “async Task” is that a method declared this way is something like a “fire and forget”, where the fired part is the body of the method and the forget part may be the problem. Let say you have a situation like this:

   1: public void Run()
   2: {
   3:     try
   4:     {
   5:         DoSomething();
   6:     }
   7:     catch(Exception ex)
   8:     {
   9:         DisplayError(ex);
  10:     }
  11: }
  12:  
  13: public async void DoSomething()
  14: {
  15:     throw new Exception("Something gone wrong...");
  16: }

The “DoSomething” method here throws and exception, probably due to an error in its flow. The problem is that, when this method is called, the developer cannot use the “await” because the method is declared as “void”. So, when the exception is thrown, the “Run” method has already exited. The direct result is that the Exception is pushed to the UI Thread and in a Windows Store app this means that the app crashes, without any advice.

This situation is much more common they you expect. consider the Dispatcher.RunAsync method:

   1: Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
   2:     async () =>
   3:     {
   4:         // do something here...
   5:     });

The declaration of the RunAsync method requires a delegate declared as “void”, so when you ask for an async lambda, this is called as in the previous example. An exception in the body of the lambda expression causes exactly and application crash. The soluton is to wrap the RunAsync method is a mathod that returns a Task, so it can be awaited. So please, always avoid using “async void” in your code and you will not drive crazy trying to understand what is going wrong in your app.