Category Archives: .NET

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:
    <InstrumentationKey>{your.key}</InstrumentationKey>
  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.

bug1

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:

bug2

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 🙂

How to deploy your own NuGet server on Azure Website in 15 minutes

Let’s imagine this typical scenario: You are an indie developer or a company developing apps in Visual Studio. You have already developed and use several own useful libraries across various projects. Right now you are maintaining each of these libraries in separate Git/TFS repository and adding these libraries as submodules to your projects. Because these libraries are hierarchically dependent one on another, it’s quite hard to maintain the dependencies and changes properly. You’ve thought about packaging these libraries as separate NuGet packages, but adding them to public nuget.org gallery is not an option since these libraries contain private knowhow.

In this article I’ll demonstrate, how to deploy your own NuGet Server on free instance of Azure Website, secure it with Basic HTTP Authentication, setup this new server so it can be used from Visual Studio, easily create automatic PowerShell scripts for deploying these libraries as NuGet packages to your server, use these NuGet packages in your projects and also how to achieve all this in just couple of minutes!

Continue reading

File IO Best Practices in Windows and Phone apps – Part 1. Available APIs and File.Exists checking

Working with files is one of the most common tasks when developing any Windows Phone or Windows apps. In this mini-series of articles I’ll show you available APIs in all Windows Phone and Windows versions, caveats when doing task such as checking if specific file exists, getting target file, reading writing data from/to files and also how to effectively extract data from ZIP files, and more.

In the first part of this series I’ll discuss available File IO APIs in Windows Phone 8, 8.1 Silverlight, 8.1 XAML, Windows 8 and 8.1 platforms and benchmark all available methods for testing, if target file in Local Folder exists, or not. To my great surprise, the performance of methods in StorageFolder API is dramatically different across different platforms and it’s not a good idea to use single approach everywhere.

Continue reading

Xbox 360 Controller API for Windows Store apps

In Windows Store apps for Windows 8.1 there are four basic input methods – touch, mouse, stylus and keyboard. In most of scenarios these input methods are all you need, but in case you want to offer more natural experience for controlling games on Windows 8.1, you can also add support for Xbox 360 and Xbox One controllers.

In this dev article I’ll show you, how to use in any C#/XAML app or game for Windows 8.1 the Xbox 360 Controller API, how to detect presence of such controller and how to poll for current state of all buttons.

Continue reading

How to debug most common memory leaks on WP8

When developing Windows Phone application, which is more complex than just 3 screens and couple lines of text, you’ll probably face the well-known problems of memory leaks. Even when using modern platform as Windows Phone 8, without pointers, with Garbage Collector, IntelliSense and everything, it is still quite easy to experience memory leaks in your apps.

In this article I’ll go through 3 most common problems that are causing leaks when developing Windows Phone apps: Images, abandoned Pages and leaks in native controls. I’ll also shown you simple trick, how to find your leaks early in the development and not two weeks before project deadline 🙂

Continue reading

Shared localization for Windows Phone 8 and Windows 8 apps using Portable Class Libraries

When developing Windows Phone 8 or Windows 8 app for more wider audience, you need to think about the localization. Unfortunately the localization on each platform uses completely different approach:

On Windows Phone 8:

  • Standard resx files with strings for each language are used.
  • The default language, for instance “en”, has localization in file without any suffix, typically just AppResources.resx.
  • Other languages uses files with culture specific suffix, like AppResources.de.resx, AppResources.cs.resx, etc.
  • For supporting non-default languages it’s required to check the additional languages in WMAppManifest.xml file and in the project settings as well
  • Localization in XAML is done typically via databinding to viewmodel class, that has instance of AppResources class, typically:
  • <TextBlock Text=”{Binding Loc.AppTitle, Source={StaticResource Localization}}“/>
  • in AppResources.resx:   |   AppTitle   |   Hello world!   |
  • For accessing the localized string programatically you can use:
  • string text = AppResources.AppTitle;
  • Globalization and localization for Windows Phone

On Windows 8(.1)

  • Windows 8 uses for localization new file types ending with .resw, but actually they use completely equal structure as WP8 .resx files.
  • Each file must be placed in a separate folder, for instance English localization should be placed in Strings/en/Resources.resw, German localization in Strings/de/Resources.resw
  • There are no automatically generated Designer.cs files for these resw files, but you can create manually ResourceLoader class for returning localized strings.
  • In Windows 8 the localization of Controls in XAML is done differently. Rather than assigning directly values using databinding, you just name each localizable control with x:Uid property and then add entry for localizing such property directly into resw file:
  • <TextBlock x:Uid=”TextBlock1″ Text=”DesignTimeText”/>
  • in AppResources.resw:   |   TextBlock1.Text   |   Hello world!   |
  • For accessing the localized string programatically you can use:
  • ResourceLoader resourceLoader = new ResourceLoader();
    string text = resourceLoader.GetString(“TextBlock1.Text”);
  • Application resources and localization sample (Windows 8.1)

As you can see, the recommended localization uses completely different approach in Windows Phone 8 and Windows 8. Sharing resx files using links, or even copying them or renaming is just not feasible to maintain. Beside these obvious differences, there are even other caveats:

  • Accessing localized strings in Windows 8 projects programatically is really cumbersome and you can make simply error, because you have no direct compile time check, that “TextBlock1.Text” actually exists in the resw file.
  • You cannot share any localized XAML code between Windows Phone 8 and Windows 8, because of the different localization method

Let’s see, how to solve this mess once and for all

Continue reading

Pro WP8 AppBar management with AppBarUtils

When developing apps for Windows Phone 8, every developer needs to know how to create and manage the App Bar. The problem is you cannot use databindings and/or localization in App bar buttons and menu items, you also cannot bind the colors or enabled state or even use commands bound to the buttons.

Most apps I’ve seen uses tedious programmatic initialization in code, repetitive entering of same resource values, or even not localized App bar at all. But there is an easy solution – the AppBarUtils library.

With this library you can use databinding for all AppBar properties, use Commands, even use dynamic app bar content for currently selected pivot/panorama item or your own state like logged-in/logged-out user. Let’s see, how to do it.

Continue reading

Logging with log4net in SharePoint

It’s actually pretty easy – I spend several hours looking for right answers how to use log4net logging properly in custom WSS feature/web part. I found several guides on Internet mostly containing points as:

  • modify manually your web.config
  • add loading script to your global.asax page
  • add manually log4net library into SafeControls
  • restart IIS app pool after the installment

Actually you don’t need anything from this list, it’s much simpler…

Continue reading