IvanJosipovic / BlazorApplicationInsights

Application Insights for Blazor web applications
https://BlazorApplicationInsights.netlify.app
MIT License
189 stars 26 forks source link
application-insights blazor

Demo Nuget (with prereleases) Nuget (with prereleases)

Application Insights for Blazor web applications

Sample Projects

Features

Install on Blazor Web App

Install on Blazor WebAssembly Standalone App

Install on Blazor WebAssembly Standalone App - Manual

TrackEvent

@page "/"

<button class="btn btn-primary" @onclick="TrackEvent">Track Event</button>

@code {
    [Inject] private IApplicationInsights AppInsights { get; set; }

    private async Task TrackEvent()
    {
        await AppInsights.TrackEvent(new EventTelemetry() { Name = "My Event" });
    }
}

Set User Name

@code{ [Parameter] public string Action { get; set; }

[CascadingParameter] public Task<AuthenticationState> AuthenticationState { get; set; }

[Inject] private IApplicationInsights AppInsights { get; set; }

public async Task OnLogInSucceeded()
{
    var user = (await AuthenticationState).User;

    await AppInsights.SetAuthenticatedUserContext(user.FindFirst("preferred_username")?.Value);
}

public async Task OnLogOutSucceeded()
{
    await AppInsights.ClearAuthenticatedUserContext();
}

}


## Set Role and Instance
- Edit Program.cs
```csharp
public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    builder.RootComponents.Add<App>("app");

    builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

    builder.Services.AddBlazorApplicationInsights(config =>
    {
        config.ConnectionString = "{Insert Connection String}";
    },
    async applicationInsights =>
    {
        var telemetryItem = new TelemetryItem()
        {
            Tags = new Dictionary<string, object?>()
            {
                { "ai.cloud.role", "SPA" },
                { "ai.cloud.roleInstance", "Blazor Wasm" },
            }
        };

        await applicationInsights.AddTelemetryInitializer(telemetryItem);
    });

    await builder.Build().RunAsync();
}