Skip to content

Instantly share code, notes, and snippets.

@JakobFerdinand
Created January 24, 2020 09:54
Show Gist options
  • Save JakobFerdinand/43234376798183e23071a3ad09c3a7d2 to your computer and use it in GitHub Desktop.
Save JakobFerdinand/43234376798183e23071a3ad09c3a7d2 to your computer and use it in GitHub Desktop.
ApplicationInsight for .Net Client Applications
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.DependencyCollector;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse;
using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
namespace RZL.DeploymentHelper.Monitoring
{
internal class ApplicationInsightsClient : IApplicationInsightsClient
{
private readonly TelemetryClient _telemetryClient;
private readonly DependencyTrackingTelemetryModule _dependencyTrackingTelemetryModule;
public ApplicationInsightsClient(string instrumentationKey, string liveMetricsApiKey, string userName, string userSId)
{
var configuration = TelemetryConfiguration.CreateDefault();
configuration.InstrumentationKey = instrumentationKey ?? throw new ArgumentNullException(instrumentationKey);
configuration.TelemetryInitializers.Add(new HttpDependenciesParsingTelemetryInitializer());
configuration.TelemetryChannel = new ServerTelemetryChannel
{
DeveloperMode = Debugger.IsAttached
};
#if DEBUG
configuration.TelemetryChannel.DeveloperMode = true;
#endif
var telemetryClient = new TelemetryClient(configuration);
telemetryClient.Context.User.Id = userName;
telemetryClient.Context.User.AccountId = userSId;
telemetryClient.Context.User.AuthenticatedUserId = userSId;
telemetryClient.Context.Session.Id = Guid.NewGuid().ToString();
telemetryClient.Context.Device.OperatingSystem = DeviceInformations.GetWindowsFriendlyName();
telemetryClient.Context.Device.Model = DeviceInformations.GetDeviceModel();
telemetryClient.Context.Device.OemName = DeviceInformations.GetDeviceManufacturer();
telemetryClient.Context.Component.Version = DeviceInformations.GetComponentVersion();
var depModule = new DependencyTrackingTelemetryModule();
depModule.Initialize(configuration);
var perfModule = new PerformanceCollectorModule();
perfModule.Counters.Add(new PerformanceCounterCollectionRequest($@"\Process({Process.GetCurrentProcess().ProcessName})\Page Faults/sec", "PageFaultsPerfSec"));
perfModule.Initialize(configuration);
QuickPulseTelemetryProcessor quickPulseTelemetryProcessor = null;
configuration.TelemetryProcessorChainBuilder
.Use(next =>
{
quickPulseTelemetryProcessor = new QuickPulseTelemetryProcessor(next);
return quickPulseTelemetryProcessor;
})
.Build();
var quickPulse = new QuickPulseTelemetryModule()
{
AuthenticationApiKey = liveMetricsApiKey
};
quickPulse.Initialize(configuration);
quickPulse.RegisterTelemetryProcessor(quickPulseTelemetryProcessor);
foreach (var telemetryProcessor in configuration.TelemetryProcessors)
if (telemetryProcessor is ITelemetryModule telemetryModule)
telemetryModule.Initialize(configuration);
_telemetryClient = telemetryClient;
_dependencyTrackingTelemetryModule = depModule;
}
/// <summary>
/// Get the device Manufacturer and Model that TelemetryClient will report
/// </summary>
public string DeviceDetails => $"{_telemetryClient?.Context.Device.OemName} {_telemetryClient?.Context.Device.Model}";
/// <summary>
/// Instrumentatin Key value assigned to the TelemetryClient
/// </summary>
public string InstrumentationKey => _telemetryClient?.InstrumentationKey;
/// <summary>
/// The OS that the TelemetryClient will report
/// </summary>
public string OperatingSystem => _telemetryClient?.Context.Device.OperatingSystem;
/// <summary>
/// Session key value that has been created for this session
/// </summary>
public string SessionKey => _telemetryClient?.Context.Session.Id;
/// <summary>
/// User key value assigned to the TelemetryClient
/// </summary>
public string UserKey => _telemetryClient?.Context.User.Id;
/// <summary>
/// Version number that the Telemerty client will report
/// </summary>
public string VersionNumber => _telemetryClient?.Context.Component.Version;
public void TrackDependency(string dependencyTypeName, string target, string dependencyName, string data, DateTimeOffset startTime, TimeSpan duration, string resultCode, bool success)
=> _telemetryClient.TrackDependency(dependencyTypeName, target, dependencyName, data, startTime, duration, resultCode, success);
public void TrackEvent(string eventName, IDictionary<string, string> properties = null, IDictionary<string, double> metrics = null)
{
_telemetryClient.TrackEvent(eventName, properties, metrics);
_telemetryClient.Flush();
}
public Task TrackException(Exception exception, IDictionary<string, string> properties = null, IDictionary<string, double> metrics = null)
{
_telemetryClient.TrackException(exception, properties, metrics);
_telemetryClient.Flush();
return Task.Delay(2500);
}
public void TrackMetric(string name, double value, IDictionary<string, string> properties = null)
=> _telemetryClient.TrackMetric(name, value, properties);
public void TrackPageView(PageViewTelemetry pageViewTelemetry)
=> _telemetryClient.TrackPageView(pageViewTelemetry);
public void TrackRequest(RequestTelemetry requestTelemetry)
=> _telemetryClient.TrackRequest(requestTelemetry);
public void TrackTrace(TraceTelemetry traceTelemetry)
=> _telemetryClient.TrackTrace(traceTelemetry);
public void Flush()
=> _telemetryClient.Flush();
public Task DisposeAsync()
{
Flush();
_dependencyTrackingTelemetryModule.Dispose();
return Task.Delay(2500);
}
}
}
using Microsoft.ApplicationInsights.DataContracts;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace RZL.DeploymentHelper.Monitoring
{
public interface IApplicationInsightsClient
{
string DeviceDetails { get; }
string InstrumentationKey { get; }
string OperatingSystem { get; }
string SessionKey { get; }
string UserKey { get; }
string VersionNumber { get; }
void TrackDependency(string dependencyTypeName, string target, string dependencyName, string data, DateTimeOffset startTime, TimeSpan duration, string resultCode, bool success);
void TrackEvent(string eventName, IDictionary<string, string> properties = null, IDictionary<string, double> metrics = null);
Task TrackException(Exception exception, IDictionary<string, string> properties = null, IDictionary<string, double> metrics = null);
void TrackMetric(string name, double value, IDictionary<string, string> properties = null);
void TrackPageView(PageViewTelemetry pageViewTelemetry);
void TrackRequest(RequestTelemetry requestTelemetry);
void TrackTrace(TraceTelemetry traceTelemetry);
void Flush();
Task DisposeAsync();
}
}
    <PackageReference Include="Microsoft.ApplicationInsights" Version="2.12.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.DependencyCollector" Version="2.12.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.PerfCounterCollector" Version="2.12.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.SnapshotCollector" Version="1.3.5" />
    <PackageReference Include="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel" Version="2.12.0" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment