Azure SDK for .NET Samples

Explore practical examples of using the Azure SDKs to build cloud-native applications.

Application Insights Custom Events (C#)

This sample demonstrates how to send custom events to Azure Application Insights using the Azure SDK for .NET. Custom events allow you to track specific user interactions or application activities not covered by standard telemetry.

Scenario: Tracking a Button Click

Imagine a web application where users can submit a form. We want to track when the submit button is clicked as a custom event.

Prerequisites

  • An Azure subscription.
  • An Azure Application Insights resource configured for your application.
  • .NET SDK installed.

C# Code Sample

First, ensure you have the necessary NuGet package installed:

dotnet add package Microsoft.ApplicationInsights

Here's the C# code to send a custom event:


using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using System;

public class ApplicationInsightsService
{
    private readonly TelemetryClient _telemetryClient;

    public ApplicationInsightsService(string instrumentationKey)
    {
        if (string.IsNullOrEmpty(instrumentationKey))
        {
            throw new ArgumentNullException(nameof(instrumentationKey));
        }
        // Configure the instrumentation key
        TelemetryConfiguration.Active.InstrumentationKey = instrumentationKey;
        _telemetryClient = new TelemetryClient();
    }

    public void TrackSubmitButtonClick()
    {
        // Track a custom event
        _telemetryClient.TrackEvent("SubmitButtonClick");

        // You can also add properties to the event for more context
        _telemetryClient.TrackEvent("SubmitButtonClick", new Dictionary<string, string>
        {
            { "ButtonLocation", "UserProfileForm" },
            { "ClickedByUserRole", "Admin" }
        });

        // It's a good practice to flush pending telemetry to ensure it's sent
        _telemetryClient.Flush();
        Console.WriteLine("Custom event 'SubmitButtonClick' tracked.");
    }

    // Example of tracking a more complex event
    public void TrackDataProcessingComplete(string dataType, int processedItems)
    {
        _telemetryClient.TrackEvent("DataProcessingComplete", new Dictionary<string, string>
        {
            { "DataType", dataType }
        },
        new Dictionary<string, double>
        {
            { "ItemsProcessed", processedItems }
        });

        Console.WriteLine($"Custom event 'DataProcessingComplete' tracked for {processedItems} {dataType} items.");
    }
}

// Example Usage:
public class Program
{
    public static void Main(string[] args)
    {
        string instrumentationKey = Environment.GetEnvironmentVariable("APPLICATIONINSIGHTS_INSTRUMENTATIONKEY");
        if (string.IsNullOrEmpty(instrumentationKey))
        {
            Console.WriteLine("Please set the APPLICATIONINSIGHTS_INSTRUMENTATIONKEY environment variable.");
            return;
        }

        var appInsightsService = new ApplicationInsightsService(instrumentationKey);

        // Simulate a button click
        appInsightsService.TrackSubmitButtonClick();

        // Simulate data processing completion
        appInsightsService.TrackDataProcessingComplete("CustomerRecords", 150);
    }
}
                

Explanation

1. TelemetryClient: This is the core class for sending telemetry data to Application Insights.

2. Instrumentation Key: You need to provide your Application Insights resource's instrumentation key. It's best practice to load this from configuration or environment variables.

3. TrackEvent(): This method is used to send custom events.

  • The first parameter is the event name (e.g., "SubmitButtonClick").
  • Optional parameters allow you to add custom properties (string key-value pairs) and metrics (double key-value pairs) for richer analysis.

4. Flush(): Ensures that any telemetry still in the buffer is sent immediately. This is particularly important in short-lived console applications.

Where to Find Your Instrumentation Key

You can find your Application Insights instrumentation key in the Azure portal:

  1. Navigate to your Application Insights resource.
  2. In the "Overview" blade, locate the "Instrumentation key" field.
  3. Copy the key and set it as an environment variable named APPLICATIONINSIGHTS_INSTRUMENTATIONKEY or manage it securely through your application's configuration.