Archive for the ‘ WP8 ’ Category

Windows Phone 8 Development – Localization

WP8 Development Serie

1. Introduction
2. Screen resolutions
3. MVVM
4. Localization (this post)

A while ago I wrote a post about Localization in WP7 and thought we should have a refresh on localization and what is new in Windows Phone 8.

Windows Phone 8 Localization
Windows Phone 8 supports 50 display languages (shipped with the phone depending on market and country/region) and selectable by the user on the language+region section of the Settings page. Windows Phone 7.1 only supported 24 and I bet more languages are coming. WP8 also allows you to build apps that read from right to left.

New Project Templates Have Localization Support Built In

One really nice addition is that every new project you create in Visual Studio 2012 has a class included called LocalizedStrings that provides the developer programmatic access to resources. An instance of this is created in App.xaml, in the Application Resources with the key LocalizedStrings. I might argue on the default names selected, but Microsoft has selected that in our templates, so better stick to it I guess.

Every new project also includes the default resources for the apps neutral language, Resources\App.Resources.resx. Note that some strings are already defined here and it is now up to the developer to create all literals in here to support localization for the default language you choose. All new projects also includes a commented-out code section in MainPage.xaml.cs to setup a localized Application Bar. You make it to simple for us!

resources_default

Accessing String Resources from XAML

Now that we have the “framework” setup to handle localization in our WP8 app we need to databind the Text property of your TextBlock and other controls to the StaticResource  with a key of LocalizedStrings. Binding to resources has always been really simple in Expression Blend, although a bit more complicated in Visual Studio, you really need to know how to type the binding expression etc. Although I don’t think that is a huge problem to most of us developers, but for the UI developers the addition of better support to XAML design in Visual Studio 2012 is always welcome.

To databind to a localized string resource we simply select the element we want to localize, and then click the Rectangle icon next to the property we want to bind to in the Properties Window, in my example the Text property of the Application Title.

resources_binding1

In the dialog that appears we need to select StaticResource in the Binding type drop-down and navigate to App.xaml and select LocalizedStrings (the key for the LocalizedStrings class instance)

It will then provide access to all the string resources, and we can just select what resource string we want to bind to. Very nice!

resources_binding2

Add Support for Additional Languages

By default we have one AppResources file created for us, that is the Neutral Language used by the application. With VS2012 it is super simple to add support for additional languages:

  • Double-click project properties to open the Properties editor
  • On the Application tab
    –  Check each of the languages your app will support
  • Save the Project Properties
    – Visual Studio will now automatically create new AppResource files for each selected language/culture

resources_add_more

Translate the Additional Languages Resource Files

  • Visual Studio adds a resource file for each additional language that the app will support. Each resource file is named using the correct culture/language name, as described in Culture and language support for Windows Phone in the documentation
  • For example:
    – For the culture Swedish, file is AppResources.sv.resx.
    – For the culture German (Germany), file is AppResources.de-DE.resx.
  • Supply appropriate translations in each resource file

Define the Default Language

Now when we have added and let Visual Studio create the resource files for us, all we need to do now is to select what language the app is using as default language. This is also very simple:

  • Double-click WMAppManifest.xml to open the manifest editor
  • On the Packaging tab
    – Set the Default Language to the language of your default resources

This identifies the language of the strings in the default resources file. For example, if the strings in the default resources file are English (United States) language strings, you would select English (United States) as the Neutral/Default Language for the project.

resources_add_more_manifest

Happy Coding!

Windows Phone 8 Development – MVVM

WP8 Development Serie

1. Introduction
2. Screen resolutions
3. MVVM (this post)
4. Localization

I guess most of us know the core concepts of MVVM, so this post will not talk about the pattern itself, but more highlight a new way of defining our properties that are bound in UI. Shortly anyway, binding to properties in XAML requires the properties to implement the INotifyPropertyChanged interface for the UI to automatically reflect changes.

ViewModel Implementation in Windows Phone 7.1
The old style of implementation was error-prone because of use of “magic strings”. Imagine that you rename/refactor a property name then that will not change the string representation of the property name used and you might end up with bugs that are hard to find.

public class ItemViewModel : INotifyPropertyChanged
 {
    private string _id;
    /// Sample ViewModel property; this property is used to identify the object.
    public string ID
    {
        get { return _id; }
        set {
            if (value != _id)
            {
                _id = value;
                 NotifyPropertyChanged("ID");
            }
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (null != handler)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

ViewModel Implementation in Windows Phone 8.0
New style of implementation – CallerMemberName Attribute.

public class ItemViewModel : INotifyPropertyChanged
 {
    private string _id;
    public string ID
    {
        get { return _id; }
        set { this.SetProperty(ref this._id, value);  }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
    {
        if (object.Equals(storage, value)) return false;
        storage = value;
        this.OnPropertyChanged(propertyName);
        return true;
    }

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var eventHandler = this.PropertyChanged;
        if (eventHandler != null)
            eventHandler(this, new PropertyChangedEventArgs(propertyName));
    }
 }

This is not a huge change, you can still use the old way of literal strings for the property name, although I suggest using the new way to be pragmatic about future rename refactorings.

Happy Coding!

Windows Phone 8 Development – Screen Resolutions

WP8 Development Serie

1. Introduction
2. Screen resolutions (this post)
3. MVVM
4. Localization

This post will focus on the different screen resolutions that are now supported in Windows Phone 8.

3 Screen resolutions
resolutions

Windows Phone 8 supports three different resolutions and the first question that pops into mind is; Do I have to do three different UIs? Well actually no, but you can do custom things when you have different resolutions, but  we as developers work with device independent pixels, the OS applies a scale factor to the actual resolution so that we do not have to worry about that.

Resolution Aspect ratio Scale Factor Scaled resolution
WVGA 800 x 480 15:9 1.0x scale 800 x 480
WXGA 1280 x 768 15:9 1.6x scale 800 x 480
720p 1280 x 720 16:9 1.5x scale, 80 pixels taller (53 pixels, before scaling) 853 x 480

If we would like to do custom UI we can, and we can also select what resolutions the application supports (double-click the WMAppManifest.xaml file and check the Supported resolutions) but if we do not specifically specify supported resolutions, all are supported and the OS handles the scaling.

Images

In most cases, you should supply images targeting the WXGA (1280 x 768) screen

  • WXGA assets are of the highest quality
  • Will automatically scale down on WVGA phones
  • Still look great on 720p (1280 x 720)

Although if we want to give the users maximum user experience then we should consider supplying images with three resolutions.

E.g. Logo.screen-wvga.png, Logo.screen-wxga.png and Logo.screen-720p.png and then at runtime get Application.Current.Host.Content.ScaleFactor to determine the current resolution of the screen on the phone and write custom code to load the correct corresponding image. ScaleFactor returns 100 for WVGA, 160 for WXGA and 150 for 720p.

One common way is to create a resolution helper class

public enum Resolutions { WVGA, WXGA, HD720p };

public static class ResolutionHelper
{
   private static bool IsWvga
   {
      get
      {
         return App.Current.Host.Content.ScaleFactor == 100;
      }
   }

   private static bool IsWxga
   {
      get
      {
         return App.Current.Host.Content.ScaleFactor == 160;
      }
   }

   private static bool Is720p
   {
      get
      {
         return App.Current.Host.Content.ScaleFactor == 150;
      }
   }

   public static Resolutions CurrentResolution
   {
      get
      {
         if (IsWvga) return Resolutions.WVGA;
         else if (IsWxga) return Resolutions.WXGA;
         else if (Is720p) return Resolutions.HD720p;
         else throw new InvalidOperationException("Unknown resolution");
      }
   }
}

Then create a class that uses the above resolution helper to select the correct image.

using System.Windows.Media.Imaging;

    public class MultiResImageChooser
    {
        public Uri BestLogo
        {
            get
            {
                switch (ResolutionHelper.CurrentResolution)
                {
                    case Resolutions.HD720p:
                        return new Uri("Assets/Logo.screen-720p.jpg", UriKind.Relative);
                    case Resolutions.WXGA:
                        return new Uri("Assets/Logo.screen-wxga.jpg", UriKind.Relative);
                    case Resolutions.WVGA:
                        return new Uri("Assets/Logo.screen-wvga.jpg", UriKind.Relative);
                    default:
                        throw new InvalidOperationException("Unknown resolution type");
                }
            }
        }

    }

Then in xaml we can simply use the following expression to bind and get correct image for pixel-perfect result

...
xmlns:h="clr-namespace:DataBoundApp1"

...

<!--Application Resources-->
<Application.Resources>
   <h:MultiResImageChooser x:Key="MultiResImageChooser"/>
</Application.Resources>

...

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
   <Image Source="{Binding BestLogo, Source={StaticResource MultiResImageChooser}}"/>
</Grid>

Splash Screens

To add a splash screen to your project suitable for all resolutions, add a file as content called SplashScreenImage.jpg at 768 x 1280 resolution. This means that the framework automatically scales it to the correct size on different resolution screens. But we can also provide pixel-perfect splash screens for all resolutions, add images with the  following names:

  • SplashScreenImage.Screen-WVGA.jpg
  • SplashScreenImage.Screen-WXGA.jpg
  • SplashScreenImage.Screen-720p.jpg
  • In addition to these images, you must still include the default SplashScreenImage.jpg file

Note that Windows Phone 8 apps starts much faster than WP7.1 apps, so unless you have an app that is unusually slow on loading (might be due to amount of resources needed etc) we should omit the splash screen image. If you decide to use a splash screen, one suggestion is to create an animated splash screen to give the users something more appealing to look at, One way to do this is by creating a Popup control that displays the animation while the app resources are loading. When the app has finished loading, you can hide the Popupcontrol. For more info about animations, see Quickstart: Animations for Windows Phone.

App Icon and Tiles

  • You must supply app icon and tile images sized for WXGA
  • The framework automatically scales to the correct size for WVGA and 720p
Tile size WXGA
Application Icon 100 × 100
Small 159 × 159
Medium 336 × 336
Large 691 × 336

Happy Coding!

Windows Phone 8 Development – Introduction

1. Introduction (this post)
2. Screen resolutions
3. MVVM
4. Localization
5. …
6. …
7. …
8. …
9. …
10. …

This will be the first post of several regarding Windows Phone 8 development. To get started it would be good to get an overview of what is new and what to expect in upcoming posts. So let’s go through most of the features and technologies provided and available for Windows Phone 8 development.

Shared Core

So the first statement that a lot of people has gotten wrong is about “Shared Core”. That Windows Phone 8 has Windows 8 OS and that you can build apps that runs on both Windows 8 and Windows Phone 8.

This is not exactly true. With shared core we mean

  • Some OS components such as the kernel, networking, graphics support, file system and multimedia are the same on both Windows 8 and Windows Phone 8
  • Hardware manufactures work with the same driver model on both platforms
  • Windows Phone 8 now also has support for multi-core and other features like Windows
  • Most important is that this common foundation makes it easier to extend the Windows Phone platform into the future

But where there is a misunderstanding is that shared core does NOT mean

  • that Windows 8 and Windows Phone 8 work against the exact same API

Windows Phone 8 is also said to be backward compatible, meaning all WP7.1 apps will run on WP8, but this is not true either, since all the apps that has used special SDKs, like the Hybrid SDK will not run by default on a WP8 device. So don’t be alarmed if you are missing some of your favorite apps in the Store on your Windows Phone 8 device.

Windows Phone 8 Programming Model

Let’s take a closer look at the Windows Phone 8 Programming Model

  • Windows Phone 8 will use the WinPRT (Windows Phone Runtime) programming model which is a subset of WinRT. This allows a lot of code to actually be shared between the two platforms.
  • We also have access to managed app development targeting WP7.1 and WP8.0
  • Native app dev using WinPRT and Win32
  • Games dev using WP7.1 XNA framework
  • Games dev using Direct3D or DirectX

WP8 Programming Model

managed The .NET API for Windows Phone is the primary managed API used. It contains all the types and APIs from WP7.1 but there as also been a lot of new classes added for Windows Phone 8, like for example, Microsoft.Phone.Wallet and many more…
managedAndNative WinPRT (Windows Phone Runtime) is a subset of the full WinRT with some phone-specific additions. One important part to high-light is that WinPRT is implemented in  C++ and projected into C#, VB.NET and C++ but HTML5/JavaScript projection is not available on Windows Phone 8.
win32Com Win32 and COM API gives you access to native app dev and access to for example:

  • Winsock for low-level networking
  • Camera API
  • and a bunch of COM APIs such as ReadFile, WriteFile and many more…

Note that managed application could call these APIs if we add a native project to the solution, but I don’t think to many projects will need that.

Tile Templates and Tile Sizes

Windows Phone  8 now supports 3 different Tile templates that you can use/support to let users pin your app to the start screen.

tiles

Flip Template, which is similar to what we have in WP7.1 template that flips the tile front to back
Iconic Template (new in WP8) that has a clean iconic design that incorporates Windows Phone Design Principles
Cycle Template (new in WP8). The Cycle Tile template cycles through between one and nine images.

Lock Screen

One new awesome feature is that you can now register your app as a lock screen provider which enables users to select your app to show detailed status on the lock screen. The possibility to select your app as one of the five apps to show quick status as an icon and count. And also select your app as the lock screen background image provider. I see a lot of potential good apps that I would love to be able to get detailed status info from directly on the lock screen. Let’s see if there are some apps that actually use this feature.

Launchers

Windows Phone 8 introduces a few new launchers. Launchers are APIs that helps the user perform common tasks, which means that the users can invoke parts of the phone’s built-in capabilities to perform tasks.

The new launchers in WP8 are:

For a complete list of Tasks available see Windows Phone Dev Center

Maps

One big news is that Bing Maps control has now been set as obsolete/deprecated and the new Maps control is provided by Nokia (although you can still use Bing Maps but it will probably eventually be removed). The new Maps control provided by Nokia is really good and has a lot of good features

  • Vector-based for faster rendering
  • Four cartographic map modes
  • Light and dark color modes
  • Display landmark and pedestrian features

Location and Location Tracking

WinPRT has a new location API that is similar to Windows 8 Location API. The Windows Phone 7.1 .NET Location API is still supported.

We can also implement Background location-tracking apps that
– run continuously in the background when the user navigates away from your app
– enables scenarios such as a Run Tracker, turn-by-turn navigation etc.

Speech

Another really nice feature that existed on WP7 is Speech, but in WP8 we as developers can also add speech support to our apps!

There are two types of voice interactions

  • Voice Commands, that basically allows users to deep-link into your app
  • Speech Recognition and Text-to-Speech APIs

Wallet

  • Credit & Debit  Cards
  • Loyalty & Membership Cards
  • Access Saved Deals
  • Supports NFC ‘Tap to Pay’

More Screen Resolutions

WP8 now supports 3 different screen resolutions

resolutions

More on this in later post regarding what we as developers need to think about to support the different resolutions.

Camera and Photos

  • Lenses
  • New Picture.GetPreviewImage() method to return thumbnail images
  • New Photos extensibility features
  • Background Photo Auto-upload
  • Advanced camera capture APIs for apps that require fine control of the camera

Media

  • Add and remove music files from the users’s collection with SaveSong and Delete methods
  • Each picture saved on the phone will automatically generate two different thumbnail images and be possible to be retrieved by your app
    – A small thumbnail image
    – A preview image that has the same dimensions as the phone’s screen resolution.
    this enables the developers to get better performance when displaying images on the phone
  • There is now also a new PlayStateChangedEventArgs that returns data when the state of the BackgroundAudioPlayer changes. This was very difficult to handle in previous versions and should now enable the developers to create more robust and performing audio apps.

VoIP and Video Chat

  • Incoming VoIP calls work like any other call
  • Integrates with built-in phone features
  • VoIP apps continue to run in the background
  • Available to all developers!

Bluetooth and NFC

  • Create apps that communicate with other phones using Bluetooth technology
  • Bluetooth API enables the following scenarios for Windows Phone 8:
    – App-to-app communication
    – App-to-device communication
  • Proximity API enables:
    – App-to-app connection using Bluetooth technology
    – Establish a Wi-Fi, Bluetooth, or Wi-Fi Direct connection between your app and an instance of your app on a proximate device
    – Send data between devices using NFC.
    – Use a phone to interact with NFC tags

Using NFC developers will now be able to build apps that can easily share data between Windows Phone 8 and a Windows 8 device, can’t wait to see what the community/developers creates!

Networking Enhancements and Changes

  • Windows.Networking WinPRT API
    – New networking API highly compatible with Windows 8
  • Incoming Sockets
    – Supported in both System.Net.Sockets and Windows.Networking.Sockets, which means your app can listen for an incoming network connection
  • Support for IPV6
  • Winsock native API support
    – Helps porting of existing native libraries that use the Winsock API

Storage

Apps can now use the Microsoft.Phone.Storage API to read files from an SD card. More on this in upcoming posts.

Custom Contact Store
  • Create a set of contacts owned exclusively by the app, though visible through the phones built-in Contacts app! How cool isn’t that, although don’t really know what types of apps will use it except apps like Facebook and similar.
  • APIs are provided to create, update, delete, and query the app’s contacts
  • Sync the app’s contact list with a remote list maintained by the app’s cloud service

File and Protocol Associations

This is another really awesome new feature. Apps can now register their own File Associations which means that we can automatically launch your app when a file of the registered type is received as an email attachment or opened in the browser or even through SharePoint. This actually enables App-to-App communications. One app can launch another app by sending it a file of the registered type. If the user opens a file that is associated with your app, this will actually not prevent other apps from registering the same file extensions. How this will actually work in the end is yet to see. A really cool feature but will it be used?

An app can register a protocol that allows your app to automatically launch when another app ‘opens’ a special URI
– Protocol is the first part of the URI, e.g. myprotocol:/ShowItems?ItemID=4711
– App launches another and passes data in the remainder of the launch URI

Windows Phone 8 apps run faster!
In Windows Phone 8 Managed Apps are actually NGEN’d for you (compiled to native) in the Windows Phone Store, which means they will typically start and run faster without any special tasks performed by the developer!! This means that when you build your app in Visual Studio, the code is not compiled into a native image, but into a machine-independent Common Intermediate Language (CIL) binary file (formerly known as Microsoft Intermediate Language, or MSIL) and when you submit your app to the Windows Phone Store, you submit the CIL file and that is converted automatically and optimized to Machine Dependent Intermediate Language, or MDIL. So when the users download your app to their device, it is actually pre-jitted to native image to increase performance!
.
Stuff to know
Other new features we have in WP8 and important stuff we need to know about that I hopefully will cover in upcoming posts are among others
  • In-App Purchase
  • Enterprise App Development
  • Company Hub
  • Converting Apps from 7.1 to 8.0
    – Source Code incompatibilities
    – Binary App Incompatibilities (basically code that behaves differently when run on WP8 compared to WP7.1)
  • Development Tools, Visual Studio tools, Emulator tools, Network Simulations
  • etc…

Hopefully this gives you a good introduction on what new features we have in Windows Phone 8 development and in upcoming posts I will dig in more to give you more meat to the bones!

Happy coding!
%d bloggers like this: