Application Insights in Windows Phone 8.1 Silverlight app, first steps

Update! Microsoft has decided to kill the support for Application Insights for Mobile Apps and recommends switching to HockeyApp platform, which has much worse pricing options and not ready support for app analytics and not ready support for UWP apps. I am REALLY disappointed with this decision, because I’ve already integrated App Insights in about 7 of my apps and I was really satisfied with the results I am getting.


Application Insights (AI) is a new Azure-based analytics service available for variety of platforms like ASP.NET, J2EE, Android, iOS and Windows/Phone, and because I started having recently problems with my current analytics service Flurry I decided to replace in one of my Windows Phone 8.1 Silverlight apps Flurry with AI, for the start.

In this article I’ll cover the basic setup of Application Insights in Windows Phone app and also cover few specific problems that I ran into and I had to solve myself.

First steps

tl;dr for adding Application Insights to WP app follow Application Insights for Windows Phone and Store apps 🙂

Or these steps, first on Azure:

  1. For using AI you need to have Microsoft Azure account, if you don’t have one, you can start Free one-month trial.
  2. On Azure Portal create new AI instance using Create -> Developer Services -> Application Insights.
  3. Here choose a name for the AI instance, application type (ASP.NET, Windows Phone, iOS, etc.), resource group and subscription. Note AI is available in Free Tier as well for small apps so you don’t need to pay a single cent for using itVisual Studio Application Insights Pricing.
  4. Once you create your AI instance, click on Settings and here on Properties. Here copy your INSTRUMENTATION KEY which serves as unique ID of your AI instance in your app.

Now lets open Visual Studio to connect your new AI instance with your Windows Phone app.

  1. Open your Windows Phone 8.1 Silverlight app solution either in VS2013 or VS2015. Note VS2015 has built-in support for managing AI. In VS2013 you can install AddIn to get similar features, but from what I experienced this AddIn in VS2013 did not worked at all, it was throwing strange exceptions when creating new projects with AI or adding AI to existing project, so I highly recommend using VS2015 RC.
  2. In your project open NuGet and search for Microsoft.ApplicationInsights.WindowsApps and install it. Current stable version of AI for WP in NuGet is 0.17.
  3. Now open the new config file ApplicationInsights.config and here add here add your instrumentation key into this tag:
  4. The last step is adding reference to the TelemetryClient into your app so the AI is actually started somewhere, and here comes the first problemI had no idea how and where to initialize the telemetry client. It’s not mentioned anywhere in the Application Insights for Windows Phone and Store apps, maybe it’s in subsequent articles, but I haven’t searched any further.

AddOn vs Manual Steps

When adding the Microsoft.ApplicationInsights.WindowsApps NuGet package to your project it tries to modify your App.xaml.cs file with the initialization calls. The thing is it somehow does not work even when I tested it with new clean project. Not sure, where’s the problem, really.

Since the manual guide failed in the last step, I tried the other way for initializing my project with AI – the automated way. In VS2015 it’s possible to just right click your project and click on Add Application Insights Telemetry… which adds all required NuGet packages and initialization calls automatically. This added all packages in WP8.1 Silverlight project but not the initialization calls.

I’ve tried it again this time on WP8.1 XAML project and it worked adding this code the the App.xaml.cs file:

/// <summary>
/// Allows tracking page views, exceptions and other telemetry through the Microsoft Application Insights service.
/// </summary>
public static Microsoft.ApplicationInsights.TelemetryClient TelemetryClient;
public App()
TelemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();

And when launched it works, as expected!

WP8.1 Silverlight App Initialization

So I figured out I’ll do the same in WP8.1 Silverlight project, and here comes the other tricky part. When I added the same calls to App.xaml.cs to the top of the constructor, the app crashes on NullReferenceException when calling the TelemetryClient constructor.


I tried to search some insight regarding this issue on Google and StackOverflow, but with no success. I was actually surprised there were no tutorials yet from WPdevs solving this problem, or maybe I am having problem no one else had?

So the solution was simple, I started JetBrains dotPeek disassembler and checked the Stack Trace where this crash happened and discovered in about 5 minutes the root cause:


PhoneApplicationService is here used before it’s initialized in App.xaml.cs, rookie mistake 🙂
PhoneApplicationService is defined as a service object in App.xaml and it’s available only after the InitializeComponent(); call. When I placed the TelemetryClient constructor before it, then PhoneApplicationService.Current is null. When placing it after InitializeComponent();, it works.

The summary

First create your Application Insights instance on Azure, then add the Microsoft.ApplicationInsights.WindowsApps NuGet package to your app, configure instrumentation key in ApplicationInsights.config and last create instance of TelemetryClient in your app.

If you are Windows Phone developer – in WP Silverlight app you need to place the TelemetryClient constructor after the InitializeComponent(); call, otherwise it will crash right after start.

If you are Windows developer targeting new Universal Apps platform, you can place the TelemetryClient constructor right in the top of App constructor with no problems. That’s because PhoneApplicationService is not used here.

And if you are by any chance Application Insights developer:

  • Make sure all tutorials contain required steps regarding TelemetryClient constructor placement.
  • Place the critical sections throwing NullReferenceException into try-catch, or just check if it’s null, and tell the user in Exception message where should the TelemetryClient constructor be placed
  • Revise all NuGet packages so that they place TelemetryClient constructor on proper places and if it’s not possible to place it, notify user.

At the end Application Insights now work in my Windows Phone 8.1 Silverlight app, maybe I’ll publish another blogpost later after I gather some useful analytics data 🙂

Using ResW File Code Generator in Visual Studio 2015

When developing apps for Windows 8.1, Windows Phone 8.1 or Universal Windows apps, the recommended approach for app localization is to use .resw resource files located in Strings/[culture code]/Resources.resw path. This approach is quite similar to the previous .resx localization system used in .NET/Silverlight apps with one big difference – there is no generated code-behind file now that you can use for compiletime-safe access of localized strings. If you want to get the string named “ListHeader”, you need to access it like this:

var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
var str = loader.GetString("ListHeader");

As you can see this is not exactly convenient.

Simple solution for this problem is to use the ResW File Code Generator extension for Visual Studio. All you need is download the ReswCodeGen.VSPackage.vsix file and install it.

Now when you open properties of any .resw file in your app and enter ReswFileCodeGenerator in the Custom Tool field, the code behind file will be created automatically. It’s also possible to define the namespace of the generated class using the Custom Tool Namespace field.



Now it’s possible to access the string ListHeader like this:

var str = Vlak.Resources.AppResources.ListHeader;

Not just this is much shorter to use, it’s also safer. If you now rename the property to ListTitle or delete the string from resources, the app won’t compile, which is good, because you know immediately that the string is not in resources anymore. With the original approach using loader.GetString the app would launch but throw an exception when accessing the no longer present string.


ResW File Code Generator in Visual Studio 2015

Installing the addon to Visual Studio 2012 or Visual Studio 2013 is supported out of the box. The problem, is when you want to install this addon to Visual Studio 2015 – it won’t work using the available installer. Update, new version of ResW File Code Generator for Visual Studio 2015 was released just day after my article, strange coincidence 🙂

Luckily there is a simple fix for this:

  1. Download the ReswCodeGen.VSPackage.vsix addon, rename it to and extract it as a zip file.
  2. Open the extension.vsixmanifest file in any text editor.11 
  3. Change the line
    InstallationTarget Version=”[11.0,12.0]”
    InstallationTarget Version=”[14.0]”
    and save the file.
  4. Pack again the content of the folder as a zip archive and name it ReswCodeGen.VSPackage.vsix22 
  5. Now if you double click the new ReswCodeGen.VSPackage.vsix installer, it will install as expected into Visual Studio 2015 just like the original installer in Visual Studio 2013.

That’s all, simple solution for better productivity when developing localized Windows Store apps that you can start using right now even in Visual Studio 2105!

tl;dw Build 2015 – App Lifecycle: From Activation and Suspension to Background Execution and Multitasking in Universal Windows Apps

My too long; did not watch summary of another Build 2015 session I watched: App Lifecycle: From Activation and Suspension to Background Execution and Multitasking in Universal Windows Apps

Note this session covers quite advanced scenarios. I’ve only summarized new features in Windows 10 API here. For better understanding watching the full session is highly recommended.


What is part of the unified Windows Application Lifecycle?

Suspend and resume
Background execution
Resource management
System triggers and notifications

This application lifecycle model is same across all platforms supported by Windows 10, only with a minor differences based on the device performance, memory, etc.


Application Lifetime – app can be in 1 of 3 states:


Application receives events when transitioning between states, Except: Suspended->NotRunning. This has not changed since Windows/Phone 8.1.


Extended Execution

Previously if user switched from app A to app B, app A was suspended with no way to continue running.
In Windows 10 it’s possible to request Extended Execution from OS.
App must provide reason for extended execution: ExtendedExecutionReason.LocationTracking or SavingData or Unspecified
This is basically the replacement for background location tracking API in Windows Phone 8, that was missing in Windows Phone 8.1.

User can revoke the request for extended execution. Revoked events will have ~1 sec to clean up. Min time is guaranteed but opportunistic afterwards.

private async void OnSuspending(object sender, SuspendingEventArgs e)
    SuspendingDeferral deferral = e.SuspendingOperation.GetDeferral();
    using (ExtendedExecutionSession session = new ExtendedExecutionSession())
        session.Reason = ExtendedExecutionReason.SavingData;
        session.Description = "Upload Data";
        session.Revoked += session_Revoked;
        ExtendedExecutionResult result = await session.RequestExtensionAsync();
        if (result == ExtendedExecutionResult.Denied)
        // Upload Data 
        var completionTime = await UploadDataAsync(session);

Background Execution

Same Background Task API from Windows/Phone 8.1 – extended with new Triggers in Windows 10:



Resource management

Opportunistic Background Tasks: Run for as long as resources are available, No guarantee of execution, ApplicationTrigger, MaintenanceTrigger, DeviceUseTrigger

Default Background Tasks: Guaranteed minimum execution time of 25 secs, Everything else: TimeTrigger, PushTrigger


Opportunistic Background Tasks serve as a replacement for Windows Phone 8 that had no replacement in Windows/Phone 8.1 ResourceIntensiveTasks.


In-Proc Background Tasks

Originally background tasks were executed in separate process – with separate memory cap. In Windows 10 it’s possible to define in-process background tasks – shares memory cap with the host process. This can be defined the Pacakge.appxmanifest.



Socket Trigger Tasks

Apps can have network connectivity and discoverability maintained while suspended or even terminated. Alternative to WNS triggered Tasks

How it works:

In foreground app process: Create/retrieve socket(s), Register background task to be woken up, Give socket to broker service as app is suspending, Take socket back from broker service at any time

On incoming network activity on brokered socket: Background task is triggered, Take socket back from broker service



Background processing is converged with Windows
There are lots of new things you can do
But resources are still limited

tl;dw Build 2015 – Data Binding: Boost Your Apps’ Performance Through New Enhancements to XAML Data Binding

My too long; did not watch summary of a really interesting Build 2015 session about Data Binding: Boost Your Apps’ Performance Through New Enhancements to XAML Data Binding

Windows 10 Universal Apps support new compiled bindings that use {x:Bind} syntax – it’s possible to replace in some scenarios classic DataBindings, that are resolved in runtime using reflection, with new compiled bindings, that are created in compile time against specific DataContext type:

  • Declarative bindings are converted into generated code behind
  • Eliminates need for slow runtime “reflection” operations
  • Code can be inspected and debugged

x:Bind bindings are validated at build time

Performance improvements are clearly visible in lot of benchmarks shown in the session. Both faster page loading and smaller memory footprint.


How to use it – Replace {Binding …} with {x:Bind …}. x:Bind is strongly typed. Mode=OneTime is the default.

Usage in Data Templates:



Resource dictionaries with bindings: Need to have a class, Need to have a code behind, Need to be loaded using their type. Too complicated for tl;dw, better check the session 🙂

x:Phase – progressive rendering for list items.


Another great feature – Binding for Events (finally!)

<Button Click="{x:Bind Model.ManagerProp.Reports[0].Poke}" Content="Poke Employee"/>


Signature needs to:

  • Have no parameters – void Poke() {…}
  • Or match the event parameters – void Poke(object sender, RoutedEventArgs e) {…}
  • Or match event parameters with base types – void Poke(object sender, object e) {…}
  • Overloading is not supported

Usable on all events, can replace usage of ICommand & EventToCommand behavior. Note does not cover command parameter, or ICommand.CanExecute scenarios

Binding Lifecycle & Performance

Binding initialization done during Loading event

  • Bindings.Initialize() will initialize bindings
  • Can call Bindings.Update() for async data
  • Bindings.StopTracking() to pause tracking, Update() will resume

OneTime binding is cheaper than OneWay

  • Bindings.Update() can be used to update OneTime bindings
  • For lists – consider INCC update of item rather than INPC for property

Not all binding path nodes need to support change notifications

How do I handle:

  • RelativeSource = Self, ElementName = … => x:Bind uses the page/user control as the context, so can use the element name
  • RelativeSource = TemplatedParent => x:Bind is not supported in a control template. Most scenarios should use TemplateBinding instead which is already optimized
  • Source / DataContext => Binding context for {x:Bind} is fixed, and can’t be changed for sub elements unless it’s a template. Options: Use a longer path to get to the data, Add a field/property to page and bind to that

When to use classic binding

  • Duck Typing – same property name on different objects => Text=“{Binding Age}” works for both Person & Wine objects. x:Bind Mitigation: use a base class / interface
  • Dictionary graphs => {Binding} can work with JSON or other dictionary of untyped objects. {x:Bind} doesn’t work without typing information
  • Programmatic binding creation => {x:Bind} doesn’t have the ability to add / remove bindings at runtime
  • Use in a style => {x:Bind} can’t be used in a style for setters etc. It can be used in a DataTemplate defined in the style


tl;dw Build 2015 – Developing Universal Windows Apps in Visual Studio 2015

Another too long; did not watch summary of the Build 2015 session I just watched: Developing Universal Windows Apps in Visual Studio 2015

Developer tools are available nowVisual Studio 2015 RC and Universal Windows App Development Tools

Windows 10 is finally one Universal Windows platform for all device types.

Single project, single package, works across all Windows devices. It’s still possible to use separate package for separate platforms, if required.

Supported operating systems for Universal Windows development – Windows 10, Windows 8.1 and Windows 7 too (in VS 2015 RTM, not yet)



Important Windows 10 project properties:

Target Version – highest API version used in the app. Example, if the app uses API from OS version 10.0.10100 and it’s known that there is breaking change in this API in Windows 10.0.10250, then this package won’t be available on Windows 10.0.10250 and higher until the developer publishes new package for the new API version.

Min Version – min API version required. The package won’t be available on Windows with lower OS version than the MinVersion.


Windows Device Family Extension SDKs – used for accessing platform specific features like phone SIM card features, the vibrator, etc.

Since there is usually only single project and single assembly, it’s not possible to use conditional compilation using #if. Solution: Windows.Foundation.Metadata.ApiInformation, reflection-like API for checking if specific type/method/property is available on current device

if (ApiInformation.IsTypePresent("Windows.Phone.UI.HardwareButtons"))
    HardwareButtons.BackPressed += HardwareButtons_BackPressed;


Developers can create custom Extension SDKs. Currently it’s possible to reference Windows 8.1 libraries in Windows Universal Apps, either from NuGet o directly. In VS2015 RTM it will be possible to reference Windows Phone 8.1 libraries as well.

App Insights – new analytics framework from Microsoft for monitoring app users, sessions, page views, crashes and real time usage, basically better Flurry Analytics 🙂 It’s possible to use custom events for additional telemetry.

How to migrate from Windows/Phone 8.1 to Universal Apps? Typically by creating single new UWP project, using adaptive code for platform specific stuff and platform specific views for different form factors. It’s still possible to have one project for tablet and one for phone (or for Xbox, IoT…) and share code using linked files, or using Portable Class Libraries, or using Shared Code project, it’s up to developer and the target app.

Windows 10 Samples on GitHub


tl;dw Build 2015 – What’s New in XAML for Universal Windows Apps

Here’s my too long; did not watch summary of the Build 2015 session What’s New in XAML for Universal Windows Apps that I just seen.

XAML UI is the primary native UI Framework for Windows 10 Apps and Services. Lot of new features were added to it with the same goal  – increase the reach and dev opportunity, reduce the cost to deliver apps and decrease loading time and memory footprint.

When creating new Windows 10 project there is now only one universal Windows project template for all platform or devices.

New Native CalendarView control is now available for developers. Touch Friendly, used in Outlook, Calendar popup when tapping the current date in bottom right corner.

Basic controls were updated to match across all platforms. Context menu is now cascading. On Desktop it can go outside the window, which is nice. When invoked by touch, it’s bigger, tailored for the target platform and input type.

When running app on Xbox One overlay rectangles are shown over the active control. It works the way you expect it to work. It runs on Raspberry Pi 2 too, just deployed and it works.

In some controls there were differences between WP and Windows behavior, like in PasswordBox the Show Password icon. In some scenarios both original behaviors were kept with the option to select the right one for your app.

There is both SearchBox and AutoSuggestBox in Windows 10. SearchBox will be likely deprecated in the future.

There is updated Pivot control in Windows 10 that works great on large screens too. Optionally it can work as Tabs too.

New ContentDialog control, like MessageDialog, but you can customize it with your own XAML content.


Simplifying Responsive View Development

New SplitView control – basically a navigation affordance, typically used with the Hamburger button in top left corner.


New AdaptiveTrigger and simplified Setters, no need to use Storyboard + ObjectAnimationUsingKeyFrames + DiscreteObjectKeyFrame just to change single discrete value from A to B.


RelativePanel – the replacement for common pattern – nested panels. Gives better performance in typical scenarios where nested panels are used in ItemTemplates.

Before, nested Grid and StackPanel.


After, with RelativePanel



XAML Performance improvements in Windows 10

If you just take your Windows 8.1 app and run it on Windows 10, it runs faster. If you recompile your Windows 8.1 app to Windows 10, it runs even faster!

New Compiled Bindings – {x:Bind} instead of {Binding}, better performance and memory footprint. Compile time property check, support for binding event handlers.



More details about the Bindings improvements in Windows 10: Data Binding: Boost Your Apps’ Performance Through New Enhancements to XAML Data Binding

Change notification on all Dependency Properties

PerspectiveTransform3D – Composable 3D Transforms (Effects: 3D Rotations, Parallax)

Windowing – Custom chrome, branding, sizing. Used heavily in the Edge browser, you can use it too.

Ink Canvas – Palm rejection, smoothing, high fidelity

Drag and Drop from Desktop to Store apps

Visual Tree Inspector of a running app

tl;dw Build 2015 – Design: UX Patterns for Universal Windows Apps

Another too long; did not watch summary of the Build 2015 session I just watched: Design: UX Patterns and Responsive Techniques for Universal Windows Apps

The goal when controls for Windows 10 apps were designed – single API across all types of devices, screen sizes, input options. But each platform should also get tailored UI experience.

Example – specific Context Menu based on input method mouse vs touch:



Effective pixels – screen sizes are measured in effective pixels that are based on physical screen size, screen resolution and expected distance from the user, keeping the same visual size of elements on all platforms.

effective pixels


Breakpoints – when designing your app there are typically three breakpoints when app layout should change from one to another:
320 epx, the minimum default view -> 720 epx, first breakpoint-> 1024 epx, another breakpoint. This is only example, it’s up to you how you design your app.



Example: Mail app


Universal app patterns – each app screen usually consists of three parts: Content, Navigation buttons and Command buttons

Most common navigation patterns, how content/navigation/commands are placed on a screen, observed in real world apps, not just in Windows Store:

Pivot – typically Contacts app. Useful when navigation between set of pages is common task. Avoid controls with horizontal interaction – Map, ToggleButton. No more than 6 pivot items should be used. In Windows 10 it’s possible to layout all Pivot items next to each other, useful on large screens.

Tabs – typically Twitter app. Variant of pivots with fixed order tabs on top of the screen. Muscle memory for easy content switching. No more than 5 tabs should be used.

Hub – typically Xbox hub. useful for displaying complex pages, lot of content at the same time. Good for content consumption, not for creation. Works good with touch and gamepad.

Master-detail – typically contact detail. Clear hierarchy of list and master content

Hamburger – typically Office or Mail apps. used for infrequent navigated items, allows more content to be displayed. On large screen could be expanded by default. Hamburger symbol very common and well known among users. Works best when placed top left  according to usability testing.


6 R’s of responsive content when switching between small and large screen sizes

Resize – when screen gets wider, the content is simply expanded, typically TextBlock

Reflow – similar to Resize, but more columns are added when the screen is wide enough. Easier for large text reading.

Reposition – when screen gets more wide than narrow, content shown previously under the main block is placed on the right of the main block. Great use case for the new RelativePanel control.

Reveal – when the screen is wide enough, additional content block is shown, that was previously hidden or available only on-demand.

Re-architect – similar to Reveal, but panel order is changed when screen is large enough.

Replace – more complex UI change, when the screen get wide enough some controls collapse and some new controls are shown that better suit the new window size.

tl;dw Build 2015 – Introducing the Windows 10 App Model

After watching the session, here’s my too long; did not watch summary of the Build 2015 session Introducing the Windows 10 App Model

What is the Windows App Model? It’s a specification of all processes in the app, how it’s downloaded from Store, deployed, started, communication with the OS, how the app lifetime works, how the app capabilities and access rights are managed, how the app contracts, data roaming, device usage work, and also how the uninstallation process is handled.

Windows 10 app model is same across all supported platforms: IOT->Mobile->PC->Xbox->Hololens.

It also defines new App Model for Classic Windows Apps installed from Store – this is a new thing in Windows 10. It solves problem with registry growth/fragmentation, clean install and uninstall. WinRT virtualizes registry/disk access and enforces App Model Policy – Denied access to Drivers, NT services, Admin elevation, Shell extension. Allowed access to Full API and desktop app lifecycle.

App installationnever regret installing an app. Possible to install apps on removable storage. Opt out for disabling it. Encrypted app data.

Developer unlock for sideloading apps – now in Settings, can be disabled via Domain politics. Limit 20 apps on mobile, unlimited on PC.

MultitaskingIt’s about battery and memory. Turn by turn navigation and Always running app now possible.

App resume politics – now always resume. Old resume policy for old WP7-8 apps. When app is resumed devs need to handle navigation to home screen.

App to App API – URL based activation, communication. Foreground to Foreground communication. Foreground to Background Task (App service) communication with sending data and receiving data in response.

Adaptive Tile Templates – same Tile size but different content based on actual tile size.

Action Center – same look and feel shared across all platforms. Alarms and Reminders working again, can be viewed in Action Center. Action Center Change Trigger for updating Live Tiles when notification is removed.

Universal Data Store – global API for Contacts, Calendar, Email, Messaging. Some limited for selected developers right now.

Summary – reliable app installation and uninstallation, more flexible multitasking, unified navigation model, URI based activation/communication, richer tiles and Action Center


New API in Windows Phone 8.1 Update 2

Windows Phone 8.1 Update 2 v 8.10.15127 finally arrived as the default OS version on new Microsoft Lumia 640 and 640 XL, and again, there is a new hidden API in it, so let’s take a look, if there is anything interesting that we, developers, can use in our apps.

tl;dr The API diff between WP8.1 Update 1 and WP8.1 Update 2 is here on GitHub. Only added/updated Windows.Phone.Notification.Management API – nothing we can use in our apps without special Accessory extension SDK, + new property in PhoneApplicationPage,

Continue reading

How to fix missing Extension SDKs in Windows 10 Universal Apps

When tools for developing Windows 10 Universal Apps were released couple of days ago I started porting one of my apps to find out, what are the changes and possible issues.
First issue I ran into was that I was unable to add Behaviors SDK to my project – the list of Extension SDKs was almost empty:

In Windows/Phone 8.1 project:


In Windows 10 UAP project:


Luckily, there is a workaround, according to Release Notes for the first version of Windows 10 Tools it’s necessary to copy the extension SDKs from the Windows 8.1 Extension SDK location to the universal apps location—that is:

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1\ExtensionSDKs
C:\Program Files (x86)\Microsoft SDKs\UAP\v0.8.0.0\ExtensionSDKs

After restarting Visual Studio 2015 the copied SDKs are then available in the list and you can add it just like before. Done.