Alex Golesh's Blog About Silverlight Developmenthttp://blogs.microsoft.co.il/alex_golesh
if (You.InterestedIn(new string[] {"Windows Phone", "XAML", ".NET Developing", "CSharp"})) Console.WriteLine("Welcome to my blog!");else Console.WriteLine("Where do you want to go today?");Wed, 02 Apr 2014 20:10:30 +0000en-UShourly1http://wordpress.org/?v=4.1.1What’s New in Windows Phone 8.1- Porting WP8 apps to WP8.1 (Part 5 out of 5)http://blogs.microsoft.co.il/alex_golesh/2014/04/02/whats-new-in-windows-phone-8-1-porting-wp8-apps-to-wp8-1-part-5-out-of-5/
http://blogs.microsoft.co.il/alex_golesh/2014/04/02/whats-new-in-windows-phone-8-1-porting-wp8-apps-to-wp8-1-part-5-out-of-5/#commentsWed, 02 Apr 2014 20:10:30 +0000http://blogs.microsoft.co.il/alex_golesh/?p=2751171So, you got a WP8.0 app and looking on WP8.1. This post is about to show how to port existing app to WP8.1 and which options are available.

First of all let’s discuss the options:

1. Keep using Silverlight/Keep WP8.0 app

Pros: No porting work required. Will run on WP8.1 (app compatibility), still runs on earlier Windows Phone devicesCons: Will not take advantage of new platform capabilities, cannot enable targeting of Windows

2. Use SL for WP8.1:

Pros: Some work required – take care of breaking changes. Enables existing Silverlight app to take advantage of nearly all new APIs and new platform capabilitiesCons: Will not enable targeting of Windows AND will not run on Windows Phone 8 devices

3. Use WinRT XAML platform:

Pros: Enables targeting of Windows and Windows Phone while takes full advantage of new APIs and platform capabilities. App enjoys better performance & reduced memory useCons: Most porting work required – can be considered as app re-developed almost from scratch AND will not run on Windows Phone 8 devices

Keeping existing WP8.0

Existing WP8.0 apps will keep working without any change on WP8.1. Existing WP8.0 app that doesn’t need to add any new WP8.1 features do not need to upgrade. Such an app will run on WP8.0 and up.

Porting WP8.0 app to WP8.1 Silverlight app

Probably the easies way to leverage new features. Visual Studio provides upgrade command in project menu:

The wizard adds logos/splash screen images and modern application manifest which should be used for app settings related to “modern” features. With this, the project still has WMAppManifest. After such upgrade (and fixing breaking changes) the app will run in modern Silverlight app host which means that there will be platform behavior changes and the app must be adjusted.

Such an app will have an access to many WP8.1 APIs (for example background tasks, data roaming, share contract, geolocation and geofencing, etc.) while still working as “good old” Silverlight app and using Silverlight’s version of XAML. It will also have access to the APIs not available to WinRT apps (such as background agents, lock screen background provider, lens, alarms and reminders, etc.).

Such an app will run only on WP8.1 and up.

Porting WP8.0 app to WP8.1 WinRT app

This approach requires considerably more efforts than simply running wizard. It requires to re-create the UI, change the APIs used to create the business logic and in some cases even change the app flow/features set as not all features accessible from WinRT apps. The benefit of such approach is that the app have high level of code convergence and slightly lover level of XAML convergence and (with some UI changes) will be able to target both WP8.1 and Win8.1 platforms.

The main differences (and thus work required to port the app) will be in the following areas:

* Application manifest/Tile changes: migrate WMAppManifest data into modern application manifest, create differently sized assets for the tiles and splash screen, update code related to the Tiles and Toasts in the app to use modern Tile/Toast templates.

* UI updates to fit form factor devices: recreate XAML using modern controls and take an advantage of new and updated controls. XAML for simple controls (such as Buttons, TextBlock, ListBox) will be exactly the same and this similarity could be up to 80% of existing XAML UI. New controls (such as DatePicker, TimePicker, ProgressRing, Hub, etc.) will require additional efforts in terms of how and when to use them in ported app. Some outdated controls (such as Panorama, LongListSelector) must be replaced with modern alternatives (Hub, ListView, GridView, etc.) and might require not only XAML changes but also code behind changes.

* Future updates/changes to better serve user on specific platform: some futures from Silverlight platform didn’t made into WinRT and have no alternatives, some didn’t made into WinRT but have alternatives. Such features (for example Silvelright’s ShareLinkTask, ShareStatusTask, PhotoChooserTask) must be replaced with WinRT alternatives (Share Contract, File Pickers) and for sure will require to develop different code than in Silverlight app.

To benefit most from this work, it is recommended to use Universal app template that enables to create the app for WP8.1 and Win8.1 platforms and reuse most of the code. Note: Universal app project creates two independent AppX packages for submission to the Windows Phone Store and Windows Store.

The app created as WP8.1 WinRT app will run only on WP8.1 and up. If developed as Universal app, it could also compile and run on Windows 8.1 devices.

That’s it for now

Stay tuned,

Alex

]]>http://blogs.microsoft.co.il/alex_golesh/2014/04/02/whats-new-in-windows-phone-8-1-porting-wp8-apps-to-wp8-1-part-5-out-of-5/feed/0What’s New in Windows Phone 8.1- New features overview (Part 4 out of 5)http://blogs.microsoft.co.il/alex_golesh/2014/04/02/whats-new-in-windows-phone-8-1-new-features-overview-part-4-out-of-5/
http://blogs.microsoft.co.il/alex_golesh/2014/04/02/whats-new-in-windows-phone-8-1-new-features-overview-part-4-out-of-5/#commentsWed, 02 Apr 2014 20:09:59 +0000http://blogs.microsoft.co.il/alex_golesh/?p=2751167With convergence, WP8.1 received many interesting feature from Windows 8.x. In this post I will overview some of them:

Geofencing

Geofencing APIs enables scenarios such as notifications when the device enters or leaves an app-specified geographic region. This makes possible app scenarios such as displaying a reminder when the user arrives at home or notifying the user of deals at stores in area he is currently. Let’s see how to setup the geofence an respond on the geofencing events. First of all, the app must declare a “Location” capability in application manifest:

Next, the good idea is to check access status to the Geolocator:

try

{

//Get geolocator

geolocator = new Geolocator();

//Optionally

await geolocator.GetGeopositionAsync().AsTask(token);

}

catch (UnauthorizedAccessException)

{

//...

}

This code ensures that user enabled location services and helps adjust app flow in case he doesn’t. Please note, that app can still set up a Geofence without location permissions but it won’t receive any notifications until the permissions have been enabled.

Setting up a geofence is pretty easy – every app has a collection of geofences identified by Id and defined by region of interest. In addition, the geofence definition contains properties such as MonitoredStates (which indicate what geofence events you want to receive notifications for), DwellTime (indicates how long the user must be in or out of the defined area before the enter/exit events are triggered), StartTime (indicates when to start monitoring the geofence) and others.

//Define how long user should be in or our of area of interest before the event is raised

var dwellTime = TimeSpan.FromSeconds(5);

//Create a new object and add it to the collection of geofences

var geofence = new Geofence(id, geocircle, mask, false, dwellTime);

GeofenceMonitor.Current.Geofences.Add(geofence);

Geofence object supports different types of areas – in the code snippet above I used a circular area, but you can define rectangular area (GeoboundingBox), series of geographic points (Geopath) or even single geographic point (Geopoint).

Also, it could be a good practice to check the presence of specific geofence in the geofences collection as they are preserved between application sessions by system-wide GeofenceMonitor component. The geofences are not removed from the collection automatically and must be manually removed by the app.

When geofence is added to the collection, the app could subscribe to the state changes and read the report from the reports:

//Each report conteains info about new state, position and geofence object

var state = report.NewState;

var geofence = report.Geofence;

if (state == GeofenceState.Entered)

//App logic...

elseif (state == GeofenceState.Exited)

//App logic...

}

});

}

Geofencing could be debugged via new WP emulator – I will talk about the emulator later in this post.

Sharing

Additional new feature supported on WP8.1 form Win8.x s Sharing. While the UI is different as WP doesn’t support charms, the API is the same. To share from the app, simply. It is initiated by the following line of code:

//Call this to get an exception if the background task completed event has reported an error

args.CheckResult();

Debug.WriteLine("Task completed succesfully");

//...

}

catch

{

Debug.WriteLine("Task failed");

//...

}

}

Visual Studio comes handy when need to debug the background tasks as it provides a simulation of lifecycle events and background tasks through the “Debug Location” menu and helps to simulate the trigger that launches the background task under the debugger:

Push Notifications, Tiles and Toasts

WP8.1 supports different type of push notifications depending on the technology used to develop the app. If the app is SL8.1 app, the dev can choose “good-old” WP approach using MPN (Microsoft Push Notification Server) or opt-in newer WNS (Windows Notification Server) approach which is shared with Win8.1. This selection is done in WPAppManifest – the old portion of SL8.1 phone app:

This selection influences which types of tiles will be supported by the app. The MPN selection will leave the app with WP8.0 compatible tiles selection (Flip, Cycle and Iconic) and related APIs. The WNS selection will force the app to use WinRT tiles and APIs.

If the app is WinRT app, then only WNS push notifications are supported. WNS supports delivering Toasts, Tiles, Badges and Raw XML push notifications exactly like on Win8.1.

Working with either MPN or WNS and preparing the app to work with either one of them will follow exact pattern of WP8.0 app (for MPN) or Win8.x app (for WNS). For full info, please refer to the relevant APIs/documentation.

While MPN tiles/toast selection are not changed from WP8.0, the WNS tiles and toasts are converged with Win8.1. Let’s overview the the converged toasts and tiles and how to create manage them on WP8.1.

Toasts & Action Center

Technically, WP8.1 supports all toast templates from Win8.1, but since the toast notification is presented differently on the device all templates being rendered the same. It means that regardless to the selected toast template form ToastTemplateType enum, user will be presented with the same standard WP toast experience:

The toast could be raised from active app, push notification or while running in background task. Following is the sample of how to show toast notification from the running app:

In addition to simply showing the notification, WP8.1 enables app to manage them through Action Center. Action Center enable app to show/present up to 20 notifications and persist them up to 7 days in the Action Center. In the Action Center user can chase the notification (tap to open the app) and remove notification (single, all, group).

Developer can manage app notifications by adding a new notification, removing or replacing existing notification, grouping and tagging notifications for easy management, set an expiration time on the notification and send a “Ghost” notification which is shown only as an icon in Action Center but not pops up as regular toast. The following code snippet shows how to manage the notifications from the app:

//Specify a "Ghost" mode - this notification will be shown only as an icon and not as popup

toast.SuppressPopup = true;

//Show the toast

ToastNotificationManager.CreateToastNotifier().Show(toast);

//...

//Remove all app notifications

ToastNotificationManager.History.Clear();

//Remove specific notification by the tag

ToastNotificationManager.History.Remove("Sample_toast");

//Remove specific notification by the tag from specific group

ToastNotificationManager.History.Remove("Sample_toast", "Blog Post");

//Remove all notifications from the group

ToastNotificationManager.History.RemoveGroup("Blog Post");

The “Ghost” notification produced from the code above looks like the following:

To show tiles the app must be set as “Toast capable” in the application manifest:

Tiles & Badges

The tile feature is more “visually” converged, share about 40 tile templates with Win8.1 platform but still have some minor UI differences to support native WP UX.

First, WP still supports only 3 sizes of the tiles – this means that Square 310×310 (aka Huge) tile is not supported on WP.

Next, while the APIs are exactly the same, the presentation of the tiles is different. For example “peek” animation on WP presented as flip animation, “Image collection” on WP looks exactly like Cycle tile, “Block” looks like Iconic tile.

Lastly, badges shown show platform specific UI and WP doesn’t support all badge types, but only numbers and “alert” + “attention” glyphs.

The code below shows how to update main app tile using new converged templates:

//Create a tile XML -- could be create using different approaches such as TileTemplateType enum, NotificationExtensions from Win8 SDK, etc.

Secondary tiles use the same templates and same APIs as on Win8.1 and produce same type of visuals as described above.

Finally, WP8.1 supports periodical tile updates. It requires some web-based resource that generates tile response and could be used by the app for periodic tile update. Tile update frequency set in application manifest, similarly to Win8.1:

Note: this tile update mechanism could be used also to update the app’s tile on install as the tile will be updated right after installing the app with such declaration in application manifest.

WP Emulator & Tools

New version of WP SDK brings improved WP emulator and few changes/improvements in the tools. What’s new there?

First of all – many different WP 8.1 emulator images:

Next – new project templates, that help to create either Silverlight or WinRT apps:

The solution includes phone-specific app, windows-specific app and shared part that will be compiled in both projects. This shared project can include XAML and code files, assets, folders, etc. The code in “Shared” project is not a portable library code, but full WinRT code to be compiled with target app similarly to source file linking.

While editing shared code, the VS provides scope switch so the same file could be “seen” using target-platform definitions such as constants, platform-specific references, conditional compilation symbols, etc:

To distinguish between two platforms in shared code file the project defines a conditional compilation symbols:

WINDOWS_APP for Win8.1

WINDOWS_PHONE_APP for WP8.1

In such case the context switch described above helps to visually distinguish between active/inactive code

Same switch exists also in XAML editor:

In addition to editor improvements, the SDK supplies new set of developer tools, that can help with fine tuning the app:

The tools are working with either emulator or real device and can monitor specific areas of the app:

By default new emulator image has quite few apps pre-installed, but still not full OS image as on the real device:

That’s it for new features brief overview. Next time I will be showing how to update existing WP8.0 app to WP8.1.

Stay tuned,

Alex

]]>http://blogs.microsoft.co.il/alex_golesh/2014/04/02/whats-new-in-windows-phone-8-1-new-features-overview-part-4-out-of-5/feed/0What’s New in Windows Phone 8.1- App Lifecycle and Navigation (Part 3 out of 5)http://blogs.microsoft.co.il/alex_golesh/2014/04/02/whats-new-in-windows-phone-8-1-app-lifecycle-and-navigation-part-3-out-of-5/
http://blogs.microsoft.co.il/alex_golesh/2014/04/02/whats-new-in-windows-phone-8-1-app-lifecycle-and-navigation-part-3-out-of-5/#commentsWed, 02 Apr 2014 20:07:44 +0000http://blogs.microsoft.co.il/alex_golesh/?p=2751135This post focuses on App Lifecycle and Navigation changes in WP8.1 XAML (aka as WinRT or Windows Phone Sore apps) apps and how they different from SL8.1 apps.

App Lifecycle

WP8.1 apps very similar lifecycle to Windows Store apps. This lifecycle is somewhat different from SL8.1 apps that mostly follows the WP8.0 apps lifecycle. Let’s review the WP8.1. lifecycle:

1. User taps app icon (in apps list or main screen) to run the app. Similarly to Win8.x the app is launched and Application.OnLaunched event is raised. As in Win8.x, it has LaunchActivatedEventArgs that helps to understand how the app was launched (ActivationKind) and previous execution state (ApplicationExecutionState).

2. When user navigates away from the app (incoming call or by clicking Windows/Search/Back key) the app receives OnSuspending even and then suspended in memory.Noted something interesting in this statement? The app is suspended when user press Back key! This is different from SL apps that by default will navigate back in app stack when Back key is pressed and terminated when user navigates back from first page in the app. This default behavior in WP8.1 apps is overrideable and I will show how to override it in next part of the post.

3. When user returns to the app (by tapping app icon on the app list or main screen, clicking the Back button or using app switcher) the app is resumed and can react by subscribing on Resuming event to restore the working state if needed.Noted something interesting in this statement? The app is resumed when user taps app icon instead of running new instance as it was in WP8.0. Also, app will get additional OnLaunched event in this case and ApplicationExecutionState will be “Running” so you can adjust your business logic. Note: This behavior affects also SL8.1 apps: a SL8.1 app is always resumed when launched, instead of replacing any running instance.

4. Apps can be closed by user using app switcher:In this case when app will be launched again the ApplicationExecutionState will be “ClosedByUser”.

5. The app can be terminated by the system – if the system runs short of memory it will use the priority system to determine which app to terminate. In this case when app will be launched again the ApplicationExecutionState will be “Terminated”.

To deal with app state while suspending/resuming the Frame provides [Get/Set]NavigationState methods that helps to deal navigation state.

Navigation

WP8.1 XAML apps adopt Win8.x navigation model of navigating by type rather than by Uri. This helps to identify potential navigation problems on compilation stage instead of discovering them at the runtime. Basic navigation between the pages looks like the following:

Frame.Navigate(typeof(MainPage), optionalNavigationArguments);

Note: optionalNavigationArguments parameter is an object that can be passed between the pages. This parameter can be retrieved at OnNavgatedTo event hander as NavigationEventArgs.Parameter.

Every page provides a set of functions to deal with navigation events such as OnNavigatedTo, OnNavigatedFrom, etc. In addition, the Frame provides standard set of navigation functions such as CanGoBack, GoBack, CanGoForward and GoForward that can be used to navigate between the pages in the app.

In previous versions of WP the Back key used to navigate back in stack of app pages and when first page is reached to navigate from the app and terminate it. Inn WP8.1 hardware Back key navigates back to the previous app – not page! This behavior is different from SL8.1 apps when Back key still works the same way it was on previous versions of WP. This behavior can be overridden (and the code is provided by VS template) so WP8.1 apps also navigates back in the pages stack instead of navigating between the apps. The default code provided by tools looks like:

public App()

{

this.InitializeComponent();

this.Suspending += this.OnSuspending;

//Subscribe to the Back keypress event to override default system behavior

HardwareButtons.BackPressed += this.HardwareButtons_BackPressed;

}

//Handles the back button press and navigates through the history of the root frame.

//If the app is at the first/launch page, don't go back and the system will suspend the app

If you need to implement your own Back key navigation logic, modify this code.

When pressing Back key on the app’s first/launch page it suspends the current app. This behavior is also different from SL8.1 apps when Back key – in SL8.1 it closes/terminates the app. This behavior is not overridable.

Every page has a NavigationChacheMode property that controls whether a page will be destroyed or cached when app navigates away. By default the value is NavigationCacheMode.Disabled which means that when navigating back to the same page (for example using Back button) the app get a new instance of the page and it must be initialized. This behavior is different from SL8.1 apps where the page is preserved in the history. The override this behavior add the following code snippet to the page:

public MyPage()

{

this.InitializeComponent();

//Require saving the page in cache

this.NavigationCacheMode = NavigationCacheMode.Required;

}

protectedoverridevoid OnNavigatedFrom(NavigationEventArgs e)

{

base.OnNavigatedFrom(e);

//When navigating backwards the page should't be saved in cache so change the NavigationCacheMode

if (e.NavigationMode == NavigationMode.Back)

this.NavigationCacheMode = NavigationCacheMode.Disabled;

}

That’s it for now. Next time I will be talking about new features such as geofencing, sharing using share contract, background tasks, tiles and toasts and many more.

Stay tuned,

Alex

]]>http://blogs.microsoft.co.il/alex_golesh/2014/04/02/whats-new-in-windows-phone-8-1-app-lifecycle-and-navigation-part-3-out-of-5/feed/0What’s New in Windows Phone 8.1- XAML Controls (Part 2 out of 5)http://blogs.microsoft.co.il/alex_golesh/2014/04/02/whats-new-in-windows-phone-8-1-xaml-controls-part-2-out-of-5/
http://blogs.microsoft.co.il/alex_golesh/2014/04/02/whats-new-in-windows-phone-8-1-xaml-controls-part-2-out-of-5/#commentsWed, 02 Apr 2014 20:06:53 +0000http://blogs.microsoft.co.il/alex_golesh/?p=2751132In this post I will show what’s new in controls that can be used in Windows Phone 8.1 (WP8.1) XAML apps (aka WinRT, Windows Phone Store apps). First I will talk about what convergence really means for the controls, then will show phone-only controls that are not available on Win8.x platform and finally will overview changes in AppBar, system tray, etc. Please note that from this post I will be focusing only on WP8.1 XAML features and not on Windows Phone Silverlight 8.1 (SL8.1). Features for SL8.1 will be highlighted specifically.

Converged controls

With convergence story WP8.1 receives many controls from Win8.x apps. About 80% of the controls (and their XAML) is fully converged with Win8.x which means very high code reuse levels for developers. The common controls such as buttons (of all types), text controls, etc. works exactly the same on both platforms. In most case those controls also looks pretty similar on both platforms, though the developer can expect minor visual adjustments in some cases. Some of the controls, while exits on both platforms and supports exactly the same XAML/API looks considerably different to fit the form factor and shows appropriate UI based on the device. The example of such controls are datepicker, timepicker, flyouts.

Flyouts also produce different UI based on the platform. Consider the following code snippet:

<ButtonContent="Flyout"x:Name="btnFlyout1">

<Button.Flyout>

<Flyout>

<StackPanelWidth="250">

<TextBlockText="Header"FontSize="24"Margin="0,0,0,20"

Foreground="CornflowerBlue"/>

<TextBlockText="This is a flyout content with some blah blah blah blah..."

TextWrapping="Wrap"FontSize="16"/>

<ButtonContent="Accept"HorizontalAlignment="Right"Margin="0,20,0,0"

Click="Button_Click_1"/>

</StackPanel>

</Flyout>

</Button.Flyout>

</Button>

and the visuals are:

Windows

Windows Phone

Some controls such as ProgressRing, ToggleSwitch, Hub, etc. are new to WP platform but exists on Win platform.

Phone-only controls

Some of the controls (about 20%) are not converged and are considered as platform-specific. Example of such phone-only controls are ListPickerFlyout, ContentDialog, AutoSuggestBox.

ContentDialog is merely a custom message box that support arbitrary content and can span across part or full screen:

The AutoSuggestBox is a “smart” version of TextBox with suggestions and tuned events:

AppBar, SysTray and others

Last category of the controls that partially converged in terms of XAML/code behind but they looks and behave considerably different based on the platform or platform-specific functionality. In this category falls controls like AppBar – while the XAML is fully compatible between two platforms, they looks slightly different and behave considerably different. For example, the app bar on Win platform has two groups of buttons – PrimaryCommands and SecondaryCommands. On WP platform it “translates” to the buttons visible on app bar (PrimaryCommands) and menu items (SecondaryCommands):

Other differences are that on WP8.1 platform the AppBar is always visible while on Window it is shown by gesture, certain properties and events (IsSticky, Opened, Closed) are ignored on WP8.1, AppBarSeparator is not rendered on WP8.1. While those differences won’t break the code some might do than – for example TopAppBar is not supported on WP and shared code with TopAppBar definition won’t compile for WP platform.

Last in the list is system tray accessibility. While being pure WP control, it considerably changed form SL8.1. In WP8.1 XAML app the SysTray is accessed through Windows.UI.Management.StatusBar.GetForCurrentView() function. It supports async commands to show/hide the UI, changing background and opacity and reports size through Windows.UI.Management.StatusBar.GetForCurrentView().OcculedRect property. In addition it still supports the ProgressIndicator.

That’s it for this post. Next time I will be talking about Application lifecycle and Navigation changes.

Stay tuned,

Alex

]]>http://blogs.microsoft.co.il/alex_golesh/2014/04/02/whats-new-in-windows-phone-8-1-xaml-controls-part-2-out-of-5/feed/0What’s New in Windows Phone 8.1- Platform Convergence (Part 1 out of 5)http://blogs.microsoft.co.il/alex_golesh/2014/04/02/whats-new-in-windows-phone-8-1-platform-convergence-part-1-out-of-5/
http://blogs.microsoft.co.il/alex_golesh/2014/04/02/whats-new-in-windows-phone-8-1-platform-convergence-part-1-out-of-5/#commentsWed, 02 Apr 2014 20:06:12 +0000http://blogs.microsoft.co.il/alex_golesh/?p=2751121Spring time again and it means new (RC) SDK from Microsoft is out to the wild. This time it is long awaited Windows Phone 8.1 SDK RC. In this series of posts I will highlight important features in new SDK and discuss recent changes every Windows Phone developer should know.

This post is about the “keyword” of this SDK release: Platform Convergence

What does it mean to developer?

First of all – new SDK usually means improvements, new features, bug fixes. This SDK is not exception. It brings many new features by merging Windows platforms into one and gives developer more power by enabling (finally) to target Windows and Windows Phone devices in one code base without having too much code differences if any. With great power comes great responsibility and it will be discussed later in the post. Next, it brings “surprise” by introducing new version of Windows Phone Silverlight!

Silverlight 8.1 apps for Windows Phone 8.1

Just a second! Didn’t we said “Platform Convergence”? What Silverlight (“SL”) is doing there? Well – it turns out that Windows Phone 8.1 (“WP8.1”) supports two different runtimes (actually three, but I will not discuss JavaScript apps for Windows Phone 8.1 in my blog posts)! First is Silverlight (the new SL8.1 version). Second is WinRT compatible by 90% with Win8.1 Store apps and very small set or phone-specific APIs. The developer can choose the framework to use when starting new WP8.1 app. Framework selection will determine then the set of available APIs, XAML version, accessible features and app behavior. Let’s see what is in WP8.1 SL so the developer want to consider it as a framework.

First of all, WP8.1 SL apps supports all features that are available for WP8 apps with some breaking changes. In addition SL8.1 adds some new features such as:* Social extensibility for photos – this allows the app to register as a photos provider for contacts in the People hub.* Seamless VoIP call upgrade – this allows the VoIP apps seamlessly upgrade calls from cellular to VoIP when it is supported by both the caller and the callee.* Selected set of WinRT features – this means that developer can use either set of APIs. The partial list of WinRT features accessible from SL8.1 are:

Note, that SL8.1 can choose the platform for push notifications (through app manifest editor) and use either WP8’s MPN or Windows Store WNS push notifications. Next, there is a small set of features that are not available in WinRT but still available through SL. If app relays on some of those features – the choice is obvious.So here is the list of features supported only in SL apps:* Clipboard APIs* Lock screen backgrounds* Ringtone provider* Alarms and reminders* Lens* Bitmaps generation (for example for the Live Tiles) in a Background Task using managed code

Lastly, the amount of breaking changes between WP8 SL and WP8.1 WinRT. The WP8.1 SL is just good old version of SL with set of new features and some breaking changes that help to support new WP8.1 better. From this point of view it is much easier (and faster) to address breaking changes in WP8 app than to convert whole app including XAML (in most cases) to the new WinRT model. Here are few breaking changes that might affect the framework selection:Silverlight/XNA interop is blocked – while it was not officially supported by WP8, it was not blocked so some apps used some XNA functionality. New SL8.1 cannot use XNA at allStatic fields initialization – updates to the CLR now require that static fields that are initialized in the variable declaration must explicitly provide a static constructor, which will cause the system to initialize the static fields. The following example shows how to properly initialize the static variable:

publicclass TheClass

{

//...

publicstatic TheStaticField myStaticField = new TheStaticField();

//...

//This static .ctor is required to initialize the myStaticField properly

static TheClass() {}

//...

}

For the complete list of the breaking changes refer to the official documentation.

Windows Store apps for Windows Phone 8.1

WP8.1 converges with the Windows Store apps platform into a single developer platform that runs the same types of apps. The WP8.1 shares very large APIs set with Windows Store apps. In addition now the platforms share a similar app model and life cycle, a shared toolset and a common XAML UI framework. Naturally there are still some small differences in behavior and supported features between WP8.1 and Windows Store apps. Some of these are the result of timing of the different product cycles, and they may not appear in future releases. Some differences are the result of the different natures of phones and tablets, their sizes, and the way people use them.

Let’s see the main areas of convergence:* App model and app lifecycle – A Wp8.1 app goes through the same app execution states as a Windows Store app and uses the same events to handle launch, activation, and suspension. While this means that app can reuse most of code for saving and restoring state on both form factors, it also means that app behaves considerably different from SL8.1 app that has different lifecycle. In addition to events difference, the WP8.1 exposes different default behavior while user press Back key: the SL app navigates backward in stack (and terminates when last page in back stack is reached) but WP8.1 app being suspended and the system switches to the previous WP8.1 app. To support same Back key navigation behavior as in SL app, the WP8.1 app must override this behavior as follows in the code snippet below:

Note: this functionality is added by default by VS template.* Manifest and App package – the new WP8.1 app manifest file is named Package.appxmanifest (same as Windows Store apps) and shares same designer in Visual Studio. The app is compiled into the APPX package, which is the same for Windows Store apps* XAML – WP8.1 apps uses same version of XAML as Windows Store apps (which is different version of XAML from SL apps)* Notifications – WP8.1 supports notifications stack from Windows.UI.Notifications namespace. They are using same WNS push notification mechanism (and same tile/toast templates) as Windows Store apps. * The programming model for background tasks is the same for WP8.1 and Windows Store apps. This is different from SL8.1 apps which still use WP8 background agents programming model.* Geolocation and Geofencing – new features supported exactly as in Windows Store apps* Background transfer APIs from Windows.Networking.BackgroundTransfer namespace replace the WP8 background transfer service APIs* Background audio is provided by Windows.Media.BackgroundPlayback.MediaPlayer class instead of the Microsoft.Phone.BackgroundAudio.BackgroundAudioPlayer class in WP8* AppBar uses same CommandBar and AppBarButton as Windows Store apps* Windows.Storage APIs incl. roaming support* Share Contract – same contract as Windows Store apps with different UX as WP8.1 doesn’t have charms.* Many other features as Read/Write access to the SD card, Proximity, Security and monetization APIs from Windows Store apps.

For more info about those features please see my blog post here and official documentation.

Universal Windows Apps

In addition to API convergence, the Visual Studio supports new type of the apps – Universal Windows Apps. Those apps enable targeting both WP8.1 and Windows Store platforms in a single solution to complement the convergence of the platform itself. The universal apps has three “projects” in the solution – Windows 8.1 app, Windows Phone 8.1 app and Shared code/resources/XAML section that shared across both platforms:

Visual studio helps while writing code in the Shared project, the Visual Studio code editor uses a context that targets one platform or the other. The Intellisense is specific to the context of the code editor – that is, specific to Windows or to Windows Phone:

In addition, the app can also use the #ifdef directive to isolate sections of code that are platform-specific. The constants WINDOWS_APP and WINDOWS_PHONE_APP are predefined by Visual Studio.Lastly, VS helps moving files between Shared/platform specific projects:

For more info about new features in tools please see my blog post here and official documentation.

Decisions, decisions, decisions…

Based on described above the developer must take a decision of which framework to chose. Let’s see some pros and cons of both. For the existing WP8 app:

1. Keep using Silverlight/Keep WP8 app

Pros: No porting work required. Will run on WP8.1 (app compatibility), still runs on earlier Windows Phone devicesCons: Will not take advantage of new platform capabilities, cannot enable targeting of Windows

2. Use SL for WP8.1:

Pros: Some work required – take care of breaking changes. Enables existing Silverlight app to take advantage of nearly all new APIs and new platform capabilitiesCons: Will not enable targeting of Windows AND will not run on Windows Phone 8 devices

3. Use WinRT XAML platform:

Pros: Enables targeting of Windows and Windows Phone while takes full advantage of new APIs and platform capabilities. App enjoys better performance & reduced memory useCons: Most porting work required – can be considered as app re-developed almost from scratch AND will not run on Windows Phone 8 devices

For the new WP8.1 app the decision “matrix” is simpler – if app must support both Windows and WP or doesn’t need Silverlight-only features (as described above) it should take WinRT XAML approach. Otherwise it should use SL approach.

That’s it for now. Next post will show the new and improved XAML controls available for WP8.1 apps.

Stay tuned,

Alex

]]>http://blogs.microsoft.co.il/alex_golesh/2014/04/02/whats-new-in-windows-phone-8-1-platform-convergence-part-1-out-of-5/feed/0Re-targeting Windows 8 apps to Windows 8.1http://blogs.microsoft.co.il/alex_golesh/2013/10/21/re-targeting-windows-8-apps-to-windows-81/
http://blogs.microsoft.co.il/alex_golesh/2013/10/21/re-targeting-windows-8-apps-to-windows-81/#commentsMon, 21 Oct 2013 21:31:09 +0000http://blogs.microsoft.co.il/?p=2751114Windows 8.1 is latest version of Microsoft’s operating system which brings many improvements over Windows 8 released year ago. Windows 8.1 brings updates to the end user experience, support for new types of devices, improves performance and new features which were not available before.

Why re-target?

While Windows 8 apps works on Windows 8.1, the upgraded apps will enjoy better performance even without code changes. In most cases recompiled app will see improvements in startup time (5-30% percent when app uses ListView on the main view), faster panning (up to two times for long lists), lower memory usage (10-20% lower memory consumed by XAML) and HTML editing improvements (15-35% while editing ListView in WinJS-based app). In addition, upgraded apps can take advantage of new features and improved APIs.

So what are the new features which makes the upgrade process worth the time? First, and most “visible” to end-user feature is new tile sizes. Windows 8.1 adds two additional tile sizes (Large Square and Small Square) and enables app to surface more information through new tile templates added to support new tile sizes.

Next big improvement is related to the search experience. New search is powered by Bing and gives you results from your PC, your apps, and the web. Results shown in a clean, graphic view that lets you do things and launch apps right away.

Additional big step toward productivity is multiple apps support. Depending on the screen resolution, end user can have up to four apps on a screen at a time. Windows 8.1 enables the scenarios such as scheduling meetings on calendar while responding to email and take notes in the desktop.

Retarget the App

The process is one-way road, so make sure to make a copy of Windows 8 app. Once re-target complete compile new Windows 8.1 app and note all breaking changes and deprecation API warnings.

Some breaking changes might be related to 3rd party SDKs used in original Windows 8 app. It is up to developer to check for updated version of 3rd party SDKs or replacement SDKs.

Deprecated APIs

The deprecation warnings will not break the compilation (and in most cases will work in upgraded Windows 8.1 app) but developer should consider of changing them with new APIs.

Some APIs which must be considered are:

· Tiles

· AppBar

· ApplicationView

· Flyouts

Some of those features were usually implemented in Windows 8 either as app-specific code or using 3rd party components which might not be available for Windows 8.1. In other cases (such as ApplicationView warnings) the Windows 8.1 introduced features which helps to improved end-user productivity and should be fixed.

Once app compiles without deprecation warnings and runs on Windows 8.1, develop must check the app functionality as some APIs were changed in terms of behavior. This called “quirks” mode – in some cases, while the API signature remain the same the behavior changed and might introduce functional or UI bugs under Windows 8.1.

New Features

Next, it is a time to take advantage of new Windows 8.1. Short list of new features which usually makes sense for many updated apps is:

· New tile sizes – improves the app “visibility” on the Windows main screen and helps surface information to the end user even the app is not actively executed.

· AppBar controls and CommandBar – standardizes the AppBar experience across Windows 8.1 apps, simplifies developer work and enables using standard icons which user is familiar from another apps.

· Flyouts – standardizes the end user experience and reduces development time by reusing exiting controls instead of creating own (often no-standard) UI and behavior.

· “Text” improvements – many “small” additions to XAML controls which helps developer to show header above some (usually input) controls, placeholder text for input controls which helps the end user to understand what is expected in specific field, etc.

· SearchBox – new UI feature which greatly improves the end user experience by adding search into the app (instead of having search experience presented on charm).

· Hub – new navigation pattern which highlights key-item while still presenting groups of items in the app.

· Speech synthesis, People and Appointments, etc. – many features which helps to improve the end user experience and create more integrated apps with Windows 8.1 services.

Once the app is ready, it could be submitted to the Store as Windows 8.1 version of existing app.

It is supported by the Store dashboard automatically and two platform-specific packages will be submitted to the certification as one app. Once certified, Windows 8.1 app version will be available to users running Windows 8.1 and Windows 8 app will be surfaced to users running Windows 8.

Conclusion

Updating the Windows 8.1 app is manual process which makes existing app better. It helps improving app performance by using updated Windows 8.1 APIs and is required step to take advantage of new Windows 8.1 features.

About a week ago I was delivering Windows 8 training and as a part of this course was delivering a sessions about Live Tiles and Windows 8 PLM (PLM = Process Lifetime Management, session which discusses when Windows 8 runs apps and some point about Windows 8 background tasks). The PLM session mentions, that Windows 8 apps are permitted to run background tasks, but they will be executed approximately once in 2 hour and will be getting few seconds of CPU time. I’ve also mentioned, that some apps, which got user permission to run under the lock screen will be able to run the background tasks based on system timer, but those apps will be scheduling to run once in 15 minutes as minimum timeslot between the execution. Right after the PLM session, at the break, one of my students came to me and asked how “clock” live tiles applications (already few published in the Store) are working. I had to admit, that I never saw this apps before and was not aware about them and how do they working. The student pointed out on one of them and after installing the app I saw that the app go a live tile with current clock and it updates the tile once in a minute. I have to admit, I was intrigued…

I checked the app permissions – it used background permissions, but this was not enough to update a tile once in a minute (remember – the minimum timeslot for such apps are 15 minutes). Then (after briefly chatting about this with my friend and colleague from MS DPE) I assumed that app probably uses push notifications. After further thoughts I failed also this option as the app is free and pushing 1440 messages daily per client is way above free limit of push notifications. I double checked myself by disconnecting network connections on my laptop to make sure. The app keep working and updated the tile. And suddenly it hit me – the app uses Scheduled Toast Notifications! It is possible to schedule many future toasts (I don’t remember exact number, but way more than 15 (needed for background service with lock screen permissions) and more than 120 (needed for regular background service). I tried to repro the app and here it is – for the sake of simplicity I didn’t create images of all minutes per day (actually half is enough as analogue clock has the same presentation once in 12 hours). Also I decided to make a sample without background service as for my demo it was not rally needed.

So I’ve create the super simple UI which gets a count number from user:

Clock app schedules the tiles using different tile template and points to images distributed with app. IMO it schedules 60-120 notifications, and every time background task runs adjust slightly the time and reschedules the tiles. I saw few times that the tile “skips” a minute sometime and jumps two minutes or stays on same minute instead of changing an image which makes me thing that at this time background task was running and adjusted an tiles schedule.

Enjoy and stay tuned!

//Alex

]]>http://blogs.microsoft.co.il/alex_golesh/2013/01/28/windows-8-live-tiles-take-2/feed/0What’s New in Windows Phone 8 (8 out of 8)–Wallethttp://blogs.microsoft.co.il/alex_golesh/2012/11/09/whats-new-in-windows-phone-8-8-out-of-8wallet/
http://blogs.microsoft.co.il/alex_golesh/2012/11/09/whats-new-in-windows-phone-8-8-out-of-8wallet/#commentsFri, 09 Nov 2012 02:11:47 +0000http://blogs.microsoft.co.il/?p=1425627Windows Phone 8 adds new interesting feature – the Wallet – which helps users to manage their virtual cards (membership, credit, debit), coupons and use them for in-app and real-world transactions.

The documentation states, that Wallet helps users to:

Collect coupons, credit cards, memberships, loyalty cards, and more in one place.

Manage the payment instruments that they use in the app and music store.

Link items in the Wallet to apps on their phone.

Make contactless transactions, using Near-Field Communication (NFC), in some markets

Wallet exposes APIs which enable developers to create, read, write, and delete in-Wallet items from application. It also enables update items by using agents and interact with the user through messages and custom fields. The application and agents could connect to application’s server side functionality to provide updates about new items, bill availability and update balance of stored Wallet items. Let’s overview how to integrate application with Wallet.

In this post I will overview application with following scenario: free application for “DevCorner Friends” club members, which provides club members with different coupons. In addition the club provides users with debit and credit cards. All those items will be stored in the Wallet.

Note: in sake of simplicity this application will fake server-side functionality.

Getting started

To use any Wallet related functionality the app should specify the following capabilities in the application manifest:

ID_CAP_WALLET – required to use all APIs from Microsoft.Phone.Wallet.

ID_CAP_WALLET_PAYMENTINSTRUMENTS – addition capability required to use PaymentInstrument and OnlinePaymentInstrument classes (credit and debit cards, online payments such as PayPal)

Membership card

As you remember from scenario the app is targeted for club members, so very first operation would be to check membership card in the Wallet:

private WalletTransactionItem LoadMembership()

{

return Wallet.FindItem("membership") as WalletTransactionItem;

}

The following code snippet uses FindItem function from the Wallet object to check for specific item in the Wallet items connected/linked to the application.

Note: we will see more functions provided by Wallet object later in the post.

If card was not found application presents simple UI informing user, that this application could be used only with membership card:

Navigating to purchase page user is presented with standard in-app purchase screen suggesting to pay for membership (to get more info about in-app purchases functionality see my this post):

This app uses standard in-app purchase mechanism to buy membership and fulfills by saving new membership card into the Wallet:

MembershipPage is used to collect information need to create membership card – this includes fields required by the Wallet and custom fields required by our application and/or related server side functionality:

To save collected info we will be using new Task from Microsoft.Phone.Tasks namespace – the AddWalletItemTask:

MessageBox.Show("There were the following errors when saving your membership to the wallet: " + ex.Message);

}

}

The following code snippet uses WalletTransactionItem object, fills the properties (predefined in application such as IssuerName, DisplayName, etc. and user inputs such as CustomerName, BillingPhone, etc.). In addition it uses CustomWalletProperty to extend standard properties with “email” property required by application/server side.

When WalletTransactionItem object is fully initialized the code snippet uses AddWalletItemTask to save new card to the the Wallet:

The result saved into the Wallet:

Clicking on “open app” or message (right upper part, is available) takes user back to the application.

After membership card was purchased and in the Wallet the application should present valued club member with promised coupons/deals.

Deals

As you remember, when user starts the app it checks for membership card presence in the Wallet. If card does exists there the app is going to present the deals available for user:

membershipCard = LoadMembership();

if (null == membershipCard)

{

//Membership is not found, suggest to purchase one

//...

}

else

{

//Membership found

await GetCoupons();

//...

}

Note: In some case it makes sense to do additional checks such as membership card validity, expiration date, etc.

The code snippet above gets PaymentInstrument from the Wallet, binds transactions history ListBox to TansactionHistory object. Lastly, it checks for custom property “BillPosted” (will be added later in case of credit card) and suggest user to pay the bill:

Paying the bill (in case of credit card) is a new page:

Paying bill involves your application’s business logic (probably contacting server side and performing transaction), but after it is done updating the card in the Wallet is simple:

if (currentCard.CustomProperties.ContainsKey("BillPosted"))

currentCard.CustomProperties.Remove("BillPosted");

currentCard.Message = "";

currentCard.DisplayAvailableCredit = "1000";

currentCard.DisplayCreditLimit = 1000.ToString("C");

await currentCard.SaveAsync();

Note: CustomProperties is collection of properties associated with WalletItem which could be used to store application-specific info.

Through the post I presented the screenshots with transactions, messages and also credit card bill. In this last part I will show how to keep your wallet item updated.

Wallet Agent

The WalletAgent is special type of background agent which associated with the application and used by the Wallet to update wallet items. The agent is created as standard Scheduled Task Agent:

Once added, it should be referenced from the main application:

This is special type of agent which executed automatically and doesn’t requires any additional code from user (unlike standard scheduled agent). To implement it, ScehuledAgent must derive form WalletAgent class:

The code snippet above creates new WalletTransaction object and populates it with info to be presented in the Wallet. Based on application’s logic, if card balance less than 100, the code adds new CustomWalletProperty which is used to signal user about new bill availability in the application. In addition, the code snippet uses same Message and MessageNavigationUri properties to show new bill info in the Wallet.

Note: The simplest way to execute/debug WalletAgent is to select “refresh” command of your wallet item:

Now we have a complete application for scenario described at the beginning of the post.

Video of working app:

Sample wallet app

Enjoy and stay tuned,

Alex

]]>http://blogs.microsoft.co.il/alex_golesh/2012/11/09/whats-new-in-windows-phone-8-8-out-of-8wallet/feed/0What’s New in Windows Phone 8 (7 out of 8)–In-App-Purchaseshttp://blogs.microsoft.co.il/alex_golesh/2012/11/07/whats-new-in-windows-phone-8-7-out-of-8in-app-purchases/
http://blogs.microsoft.co.il/alex_golesh/2012/11/07/whats-new-in-windows-phone-8-7-out-of-8in-app-purchases/#commentsWed, 07 Nov 2012 17:26:30 +0000http://blogs.microsoft.co.il/?p=1421986This post talks about new monetization feature in Windows Phone 8 – In-App-Purchases (IAP). According to multiple industry sources (link1, link2, link3) IAP can actually make more money that free/ad-supported application. Let’s see how to add this feature to application. In this post I will show how to build simplest “virtual” shop app. All IAP functionality process allocated in Windows.ApplicationModel.Store namespace.

First let’s understand the terminology associated with IAP process.

Product – something you are selling in application. Unlike Windows 8, in Windows Phone 8 we got two different product types: Durable and Consumable.

Durable – a Product that is purchased once and owned by the user/application.

Consumable – a Product that is purchased and used multiple times. This Product could be purchased again and again when user needs it.

Products are organized into Product List which managed through application’s settings on Dev Center Dashboard.

Purchase – the process of buying a Product.

License – a set of definitions describing the product type, whether it is active and its expiration date. Associated with each Product.

Receipt – a proof of purchase which used to verify that user Purchased the Product.

Fulfillment – the process of giving the user the Product he/she Purchased. Depends on application logic, but must me reported to marketplace. Available only for Consumables and plays key role in Product Purchase process – new Consumable cannot be Purchased again without reporting previous successful fulfillment.

Working with Catalog

Current application licensing info and associated product list is obtained using CurrentApp class. This app provides key functionality of searching catalog (by keyword or productId), purchasing the products and report fulfillments. The following code snippet searches all products by keywords:

In addition to search functionality, CurrentApp class also provides access to full product list which is accessible through CurrentApp.LicenseInformation.ProductLicenses class. Each item in ProductLicenses is an object from ProductLicense class. This class enables querying product state by providing ExpirationDate, IsActive and IsConsumable properties. The following code snippet loads not purchased durables from product catalog:

Working IAP is a server-based commerce. It relies on communication with Microsoft’s backend services to list products, enumerate licenses and process purchases. It may also rely on your servers to deliver purchased in-app products if needed. When purchasing the product (published application) marketplace will perform real transaction with client’s account. In development cycle it is not always possible to deploy application to marketplace (especially as public application). It is possible to deploy application as Beta on marketplace. Beta applications support full IAP mechanism through marketplace with only one difference – although the user experience shows prices as entered into Dev Center, all in-app purchases made from beta apps are free. This approach is strongly recommended once you application is in somewhat ready state. But what to do during initial development stages? Windows 8 provides CurrentAppSimulator class for this work. Unfortunately this functionality didn’t made it into Windows Phone 8. To overcome this, we want to use mock library which closely mimics Store APIs.

To work with this library it must be referenced on all pages which are using Store functionality as follows:

#if DEBUG

using MockIAPLib;

using Store = MockIAPLib;

#else

using Store = Windows.ApplicationModel.Store;

#endif

From now on, to test real marketplace functionality all you need is to compile your app as Release. While the library closely mimics store APIs it must be initiated with as it doesn’t uses server-based information from marketplace. It should be initiated from XML-based product catalog as follows:

Note: in real scenarios it is recommended to get product images from app’s server-side storage as the approach shown in this sample relays on having all possible product images in application package which is not recommended and prevents from extending product list after publishing the app.