Application Insights for WPF Application

2019-01-21 19:46发布

There is a WPF application written in Visual Studio. Can I add Application Insights to this WPF app? I would like to know how many times a button/tile is clicked. Since there are multiple installations of the same application, I would like to know which button was clicked how many times from which user/installation. Can this be done with Application Insights?

Thanks Avanti

3条回答
老娘就宠你
2楼-- · 2019-01-21 20:30

https://azure.microsoft.com/en-us/documentation/articles/app-insights-windows-desktop/

An official link from Microsoft on how to add Application Insights to a Windows Forms application. From the link:

In Azure - portal.azure.com

  1. Create an Application Resource. ::New / Developer Services / Application Insights.
  2. Notice the instrumentation key generated, grab a copy and set it aside, we'll need it when we configure your application.

In Your Application

  1. NuGet - Add 'Application Insights API'
  2. Configure your TelemetryClient.

I'm using MvvmCross in a WPF application, on startup I create a single TelemetryClient that I re-use throughout the application.

var telemetryClient = new TelemetryClient();
telemetryClient.InstrumentationKey = "your key here from Azure";
telemetryClient.Context.Session.Id = Guid.NewGuid().ToString();
telemetryClient.Context.User.AccountId = Username;
telemetryClient.Context.Component.Version = Settings.Default.Version; 
telemetryClient.TrackEvent("Application Start");
Mvx.RegisterSingleton<TelemetryClient>(telemetryClient);
  1. Record an event/screen/exception, etc

Any time 'something happens' I'll resolve the TelemetryClient and record the event. This is just like any other Application Insights implementation with regards to tracking and recording.

As an example -

//Resolve the telemetry client
readonly TelemetryClient telemetryClient = Mvx.Resolve<TelemetryClient>();

//Record a page View with some extra information
var pageviewTelemetry = new PageViewTelemetry("Observations");
pageviewTelemetry.Properties.Add("Breadcrumb", breadcrumb);
telemetryClient.TrackPageView(pageviewTelemetry);

//Track an event
var eventTelemetry = new EventTelemetry("Observation Saved");            
eventTelemetry.Properties.Add("Saved Observation", observation);
telemetryClient.TrackEvent(eventTelemetry);

//Track an exception
try
{
  // do work here
}
catch (Exception ex)
{
    telemeteryClient.TrackException(ex);
}
  1. Flush on Application Exit

Application Insights for Windows Desktop applications does not automatically gather/send anything. As a developer one needs to force a flush at application exit.

private void PowerButton_OnClick(object sender, RoutedEventArgs e)
{
    var tc = Mvx.Resolve<TelemetryClient>();
    if (null != tc)
    {
        tc.Flush(); // only for desktop apps
    }            
    Application.Current.Shutdown();            
}

Or setup an RxTimer to flush on a schedule...I decided to flush every 30 minutes:

var observable = Observable.Interval(new TimeSpan(0, 0, 30, 0));
observable.Subscribe(_ =>  Application.Current.Dispatcher.Invoke(new Action(() =>
{
    var tc = Mvx.Resolve<TelemetryClient>();
    if (null != tc)
    {
        tc.Flush(); // only for desktop apps
        Console.WriteLine("Flush TC");
    }
})));

FYI - As of 0.17.0 of the Application Insights API NuGet Package if you are offline the flush call doesn't hang, but appears to. Online, the call completes immediately, offline there is a solid 5 second pause before the call completes.

查看更多
在下西门庆
3楼-- · 2019-01-21 20:34

While not listed as a supported app type this means there isn't default telemetry data collected/sent to application insights nor is there support for adding AI/creating an application insights resource. That being said it is possible to add to your WPF with a few manual steps so that you can track the specific scenarios you mention (like a button/tile click).

-From Visual studio add the "Application Insights API" NuGet to the project (.11 is the latest today).

This will add the Application Insights API reference and create an application insights configuration file to your project.

The applicationinsights.config file needs to be updated with your instrumentation key as follows:

<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings" schemaVersion="2014-05-30">
    <TelemetryChannel>
        <DeveloperMode>false</DeveloperMode>
    </TelemetryChannel>
    <TelemetryModules>
        <Add Type="Microsoft.ApplicationInsights.Tracing.DiagnosticsTelemetryModule, Microsoft.ApplicationInsights"/>
    </TelemetryModules>
    <InstrumentationKey>**your-instrumentation-key-guid**</InstrumentationKey>
</ApplicationInsights>

To create an application insights instrumentation key login to your azure subscription. https://portal.azure.com Click + to create an Application Insights resource. Then choose the properties tile on the application insights blade and copy the Instrumentation key and add it to your applicationinsights.config file. Now in your WPF app you can use the Application Insights sdk as described here: http://blogs.msdn.com/b/visualstudioalm/archive/2014/10/21/application-insights-sdk-0-11-0-prerelease.aspx

your events will be visible in the diagnostic search blade which can be selected on the application insights blade.

Note: telemetry is batched locally for 1 min before being sent to the service unless > 500 telemetry events are queued at which point they are sent.

查看更多
Animai°情兽
4楼-- · 2019-01-21 20:45

Application Insights (AI) for desktop applications is being deprecated in favor of HockeyApp. It's not overly mature yet, but it works (events essentially reach the same place AI events go).

For example, here's how it looks in RoslynPad (a WPF C# Editor):

using Microsoft.HockeyApp;


//In your initialization method:
var hockeyClient = (HockeyClient)HockeyClient.Current;

hockeyClient.Configure(HockeyAppId)
    .RegisterCustomDispatcherUnhandledExceptionLogic(OnUnhandledDispatcherException)
    .UnregisterDefaultUnobservedTaskExceptionHandler();

var platformHelper = (HockeyPlatformHelperWPF)hockeyClient.PlatformHelper;
platformHelper.AppVersion = _currentVersion.ToString();

hockeyClient.TrackEvent("App Start");

//sometime later:
hockeyClient.TrackEvent("Something happened");

EDIT Looks like the following NuGet package is required in order for this to work properly: https://www.nuget.org/packages/HockeySDK.WPF.TelemetryWorkaround (see https://github.com/bitstadium/HockeySDK-Windows/pull/88).

查看更多
登录 后发表回答