Snippets

This is a collection of code snippets that I find useful. They are not meant to be comprehensive, but rather a quick reference for myself and others.


using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;

namespace Geico.ProductMgmt.FileGeneration.Application.Services;

public static class TelemetryExtensions
{
    public static IDisposable StartOperation(
        this TelemetryClient telemetryClient,
        [CallerMemberName] string operationName = "",
        [CallerFilePath] string callerFilePath = "",
        [CallerLineNumber] int callerLineNumber = 0)
    {
        // Extract just the class name from the file path
        var className = Path.GetFileNameWithoutExtension(callerFilePath);
        var fullOperationName = $"{className}.{operationName}";
        var operation = telemetryClient.StartOperation<RequestTelemetry>(fullOperationName);
        operation.Telemetry.Properties["CallerLineNumber"] = callerLineNumber.ToString();
        return operation;
    }

    // Overload with custom properties
    public static IDisposable StartOperation(
        this TelemetryClient telemetryClient,
        Dictionary<string, string> properties,
        [CallerMemberName] string operationName = "",
        [CallerFilePath] string callerFilePath = "")
    {
        var className = Path.GetFileNameWithoutExtension(callerFilePath);
        var fullOperationName = $"{className}.{operationName}";
        var operation = telemetryClient.StartOperation<RequestTelemetry>(fullOperationName);

        foreach (var prop in properties)
        {
            operation.Telemetry.Properties[prop.Key] = prop.Value;
        }

        return operation;
    }
}