Code Monkey home page Code Monkey logo

blazorapplicationinsights's Introduction

Connect with me

Anurag's GitHub stats Top Langs

Active Projects

KubeUI - Kubernetes User Interface

GitHub Repo stars GitHub forks GitHub top language GitHub all releases GitHub pull requests

BlazorApplicationInsights - Application Insights for Blazor web applications

GitHub Repo stars GitHub forks GitHub top language Nuget (with prereleases) GitHub pull requests

YamlDotNet.System.Text.Json - Allows YamlDotNet to de/serialize System.Text.Json objects

GitHub Repo stars GitHub forks GitHub top language Nuget (with prereleases) GitHub pull requests

KubernetesCRDModelGen - Kubernetes CustomResourceDefinition Model Generator for .NET

GitHub Repo stars GitHub forks GitHub top language Nuget (with prereleases) GitHub pull requests

OIDC-Guard - OpenID Connect (OIDC) & OAuth 2 API Server for securing Kubernetes Ingress

GitHub Repo stars GitHub forks GitHub top language GitHub pull requests

ingress-nginx-validate-jwt - Enables Kubernetes ingress-nginx to validate JWT tokens

GitHub Repo stars GitHub forks GitHub top language Docker Pulls GitHub pull requests

BlazorInteropGenerator - Blazor Interop Generator

GitHub Repo stars GitHub forks GitHub top language Nuget (with prereleases) GitHub pull requests

TSDParser - C# TypeScript Definition Parser

GitHub Repo stars GitHub forks GitHub top language Nuget (with prereleases) GitHub pull requests

JsonPathLINQ - JsonPath to LINQ Expressions

GitHub Repo stars GitHub forks GitHub top language Nuget (with prereleases) GitHub pull requests

Inactive Projects

ACR-SyncTool - Command line tool to synchronize Docker Image Registries to private Azure Container Registries

GitHub Repo stars GitHub forks GitHub top language Nuget (with prereleases) GitHub pull requests

AutoSPInstallerOnlineGithubPage - AngularJS front end of http://AutoSPInstaller.com

GitHub Repo stars GitHub forks GitHub top language GitHub pull requests

BlazorFileSaver - Blazor Component wrapper for FileSaver.js

GitHub Repo stars GitHub forks GitHub top language Nuget (with prereleases) GitHub pull requests

BlazorTable - Blazor Table Component with Sorting, Paging and Filtering

GitHub Repo stars GitHub forks GitHub top language Nuget (with prereleases) GitHub pull requests

blazorapplicationinsights's People

Contributors

bonbor avatar bradfallows avatar c-owens avatar hakenr avatar honzabejvl avatar ivanjosipovic avatar lucapisano avatar renovate-bot avatar renovate[bot] avatar rogihee avatar shutterquick avatar tariqalsoahmed avatar tdashworth avatar vertonghenb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

blazorapplicationinsights's Issues

SetAuthenticatedUserContext calls wrong api function

I believe the IApplicationInsights.SetAuthenticatedUserContext method calls the ClearAuthenticatedUserContext script function instead of the correct function. I am not able to set authenticated user context.

how to use with blazor server

i have heard that this works with blazor server but how to do that when the install says that i need to add to index.html but blazor server does not have an index.html file in the project.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/cicd.yml
  • actions/checkout v4
  • actions/setup-dotnet v4
  • actions/checkout v4
  • actions/setup-dotnet v4
  • cycjimmy/semantic-release-action v4
  • actions/upload-artifact v4
nuget
global.json
  • dotnet-sdk 8.0.300
samples/BlazorApplicationInsights.Sample.Components/BlazorApplicationInsights.Sample.Components.csproj
samples/BlazorApplicationInsights.Sample.Wasm/BlazorApplicationInsights.Sample.Wasm.csproj
samples/BlazorApplicationInsights.Sample.Wasm6/BlazorApplicationInsights.Sample.Wasm6.csproj
samples/BlazorApplicationInsights.Sample.WebApp/BlazorApplicationInsights.Sample.WebApp.Client/BlazorApplicationInsights.Sample.WebApp.Client.csproj
samples/BlazorApplicationInsights.Sample.WebApp/BlazorApplicationInsights.Sample.WebApp/BlazorApplicationInsights.Sample.WebApp.csproj
src/BlazorApplicationInsights/BlazorApplicationInsights.csproj
  • JetBrains.Annotations 2023.3.0
tests/BlazorApplicationInsights.Tests/BlazorApplicationInsights.Tests.csproj
  • coverlet.collector 6.0.2
  • xunit.runner.visualstudio 2.8.1
  • xunit 2.8.1
  • Moq 4.20.70
  • Microsoft.Playwright 1.44.0
  • Microsoft.NET.Test.Sdk 17.10.0
  • Microsoft.Extensions.Logging 8.0.0
  • Microsoft.Extensions.Configuration.Abstractions 8.0.0
  • FluentAssertions 6.12.0

  • Check this box to trigger a request for Renovate to run again on this repository

Unable to use SetAuthenticatedUserContext method in Blazor Server

I am getting following error when I am trying to use SetAuthenticatedUserContext in Blazor Server application to record logged in user details after successful Azure AD authentication.
Can anyone please suggest a solution for this or is Blazor Server not supported ?
Screenshot 2023-02-16 at 12 45 43 PM

Correlation with api requests

Big thankyou for this project - up and running really quickly and working great.

One thing I would like to figure out is how to correlate api requests made through an HttpClient instance with the back end telemetry. I'm assuming nothing is baked in for this just yet (not seeing any headers on outbound requests) but wonder if you had any thoughts on what would be necessary to get this working before I roll my sleeves up :)

Internal exception not visible

Hi,

When logging an exception with an internal exception I can't see the internal exception in Application Insights:

How exception is thrown in Blazor WASM client:

var invalidOperationException = new InvalidOperationException("TEST INNER");
throw new NotImplementedException(ExceptionMessage, invalidOperationException);

Do you have any plans to improve the logging so the information about the internal exception is also visible in Application Insights?

Best Regards,
Anders Havn

Feature Request: Get User and Session IDs

It would be useful to be able to retrieve the user/session IDs so that I can provide them in error messages.

It looks like they are stored in cookies by default but I guess that is flexible.

I am happy to add this if you'd accept?

Value cannot be null. (Parameter 'jsRuntime')

I am using .NET RC1 Blazor WebAssembly hosted app

Getting the following Error.

crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Value cannot be null. (Parameter 'jsRuntime')
System.ArgumentNullException: Value cannot be null. (Parameter 'jsRuntime')
at Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(IJSRuntime jsRuntime, String identifier, Object[] args)
at BlazorApplicationInsights.ApplicationInsights.TrackEvent(String name, Dictionary`2 properties)
at GetInLineV6New.Client.Pages.Index.OnInitializedAsync() in C:\Users\admin\source\repos\GetInLineV6New\GetInLineV6New\Client\Pages\Index.razor.cs:line 25
at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()

Index.razor

protected override async Task OnInitializedAsync()
    {
       
        await AppInsights.TrackEvent("My Event from Index Page");  //Line 25
}

Add nonce to script tag for content-security-policy (CSP)

At the moment I need to add "https://*.monitor.azure.com" to my script-src allow-list for my content-security-policy to work which i want to avoid. Has anyone modified the JS to add a nonce attribute to the external JS link? I can add one here to allow the inline script fine.

image

image

Exception when starting in debug

My implementation is almost verbatim for the example. Only major difference is that my App.razor is wrapped in a <CascadingAuthenticationState> component and the <ApplicationInsightsComponent> is outside of it.
Microsoft.JSInterop.JSException: Could not find 'appInsights' in 'window'.

If I reload the page, the error goes away.

Receiving Unhandled Exception when using BlazorApplicationInsights with Azure AD SSO Integration on login callback

I have a small application using .Net 5 and Blazor Webassembly and using Azure AD SSO for authentication. When the login authentication completes and issues the callback to the app it is generating the following exception. It appears that a response from the login callback is not being handled in the BAI well. The authentication process is still successful but generates a client messages that needs to be dismissed, so this is not a blocking issue but is a distraction in the user flow. Also the authentication process did not generate this unhandled message prior to adding in the BAI client side logging.

I am attaching the logs from the client side and an image from the developer tools console.

unhandled_exception.log

image

Any thoughts on resolving this?

Setting the cookie

Your code offers two examples to set the cookie programatically
app.MapFallbackToFile("index.html", new StaticFileOptions()
{
OnPrepareResponse = ctx =>
{
ctx.Context.Response.Cookies.Append("ai_connString", app.Configuration["ApplicationInsights:ConnectionString"]);
}
});

This is not an option for me because the required libraries are not available in my project.

The second option:

**In the hosting platform

Inject a Cookie called "ai_connString" with the ConnectionString URL Encoded**

Is there an example of how to do this?

  1. How do I get the configuration settings from javascript?
  2. How do I inject the cookie?

If this is hosted in Azure does that mean it has to be done from Azure? During dev ops? It is just unclear to me what is meant by this.

Broken Set Role scenario

#32 broke SetRoleScenario.

In my opinion, it is bad practice to use IJSRuntime outside of OnAfterRenderAsync. It blocks blazor-server scenarios and adds complexity to WebAssemblyPrerendered mode.

#36 Please take is PR just as a proposal/idea of how to go around this problem.

It allows a consumer to configure OnBlazorInsightsInit callback that is executed during the first OnAfterRenderAsync of ApplicationInsightsComponent

Unhandled exception rendering component: Cannot read property 'push' of undefined

First of, thanks for this awesome project.

Just now we started getting the following error in the browser. I assume it's an azure issue since your site https://blazorapplicationinsights.netlify.app/ is experiencing same error upon load.

blazor.webassembly.js:1 crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Cannot read property 'push' of undefined
TypeError: Cannot read property 'push' of undefined
at Object.m. [as addTelemetryInitializer] (https://blazorapplicationinsights.netlify.app/:10:3524)
at Object.addTelemetryInitializer (https://blazorapplicationinsights.netlify.app/_content/BlazorApplicationInsights/JsInterop.js:32:21)
at https://blazorapplicationinsights.netlify.app/_framework/blazor.webassembly.js:1:9805
at new Promise ()
at Object.beginInvokeJSFromDotNet (https://blazorapplicationinsights.netlify.app/_framework/blazor.webassembly.js:1:9773)
at _mono_wasm_invoke_js_marshalled (https://blazorapplicationinsights.netlify.app/_framework/wasm/dotnet.3.2.0.js:1:171294)
at do_icall (:wasm-function[6049]:0x10f8b1)
at do_icall_wrapper (:wasm-function[1896]:0x50b6a)
at interp_exec_method (:wasm-function[1120]:0x2588e)
at interp_runtime_invoke (:wasm-function[5655]:0xf7391)
Microsoft.JSInterop.JSException: Cannot read property 'push' of undefined
TypeError: Cannot read property 'push' of undefined
at Object.m. [as addTelemetryInitializer] (https://blazorapplicationinsights.netlify.app/:10:3524)
at Object.addTelemetryInitializer (https://blazorapplicationinsights.netlify.app/_content/BlazorApplicationInsights/JsInterop.js:32:21)
at https://blazorapplicationinsights.netlify.app/_framework/blazor.webassembly.js:1:9805
at new Promise ()
at Object.beginInvokeJSFromDotNet (https://blazorapplicationinsights.netlify.app/_framework/blazor.webassembly.js:1:9773)
at _mono_wasm_invoke_js_marshalled (https://blazorapplicationinsights.netlify.app/_framework/wasm/dotnet.3.2.0.js:1:171294)
at do_icall (:wasm-function[6049]:0x10f8b1)
at do_icall_wrapper (:wasm-function[1896]:0x50b6a)
at interp_exec_method (:wasm-function[1120]:0x2588e)
at interp_runtime_invoke (:wasm-function[5655]:0xf7391)
at System.Threading.Tasks.ValueTask`1[TResult].get_Result () <0x2044730 + 0x0002c> in :0
at Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync (Microsoft.JSInterop.IJSRuntime jsRuntime, System.String identifier, System.Object[] args) <0x1fbf840 + 0x000e4> in :0
at BlazorApplicationInsights.ApplicationInsights.AddTelemetryInitializer (BlazorApplicationInsights.ITelemetryItem telemetryItem) <0x1fbedb0 + 0x000dc> in :0
at BlazorApplicationInsights.Sample.Program+<>c.

b__0_1 (BlazorApplicationInsights.IApplicationInsights applicationInsights) <0x1fbe658 + 0x00116> in :0
at BlazorApplicationInsights.ApplicationInsights.InitBlazorApplicationInsightsAsync (Microsoft.JSInterop.IJSRuntime jSRuntime) <0x1fbba58 + 0x000ec> in :0
at BlazorApplicationInsights.ApplicationInsightsComponent.OnAfterRenderAsync (System.Boolean firstRender) <0x1fbb458 + 0x000e4> in :0
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask (System.Threading.Tasks.Task taskToHandle) <0x20073c8 + 0x000ca> in :0
f.printErr @ blazor.webassembly.js:1

Blazor (self-hosted) WASM - SetInstrumentationKey

Thanks for this great plugin.

I'm programmatically setting the instrumentation key in the program.cs file using applicationInsights.SetInstrumentationKey method.
Using your BlazorApplicationInsights.Sample project; set the index.html's instrumentationKey = "" and add the following line to the AI section in program.cs

await applicationInsights.SetInstrumentationKey("AI KEY GOES HERE");

This works, however I can see an HTTP 400 error to a url "https://dc.services.visualstudio.com/v2/track" in the console.

image

The only reference I can find in the solution to this Url is in BlazorApplicationInsights.Tests project. If I remove the project, the error goes away. If I bring the project back in, the error returns.
Could you investigate?

The details of the error are below. Note that the Nuget release v2.1 is affected by this problem from what I can see too.

image

Instrument.js:97
image

To replicate this error, modify your index.html and set instrumentationKey: "".

    <script type="text/javascript">
        !function (T, l, y) { var S = T.location, k = "script", D = "instrumentationKey", C = "ingestionendpoint", I = "disableExceptionTracking", E = "ai.device.", b = "toLowerCase", w = "crossOrigin", N = "POST", e = "appInsightsSDK", t = y.name || "appInsights"; (y.name || T[e]) && (T[e] = t); var n = T[t] || function (d) { var g = !1, f = !1, m = { initialize: !0, queue: [], sv: "5", version: 2, config: d }; function v(e, t) { var n = {}, a = "Browser"; return n[E + "id"] = a[b](), n[E + "type"] = a, n["ai.operation.name"] = S && S.pathname || "_unknown_", n["ai.internal.sdkVersion"] = "javascript:snippet_" + (m.sv || m.version), { time: function () { var e = new Date; function t(e) { var t = "" + e; return 1 === t.length && (t = "0" + t), t } return e.getUTCFullYear() + "-" + t(1 + e.getUTCMonth()) + "-" + t(e.getUTCDate()) + "T" + t(e.getUTCHours()) + ":" + t(e.getUTCMinutes()) + ":" + t(e.getUTCSeconds()) + "." + ((e.getUTCMilliseconds() / 1e3).toFixed(3) + "").slice(2, 5) + "Z" }(), iKey: e, name: "Microsoft.ApplicationInsights." + e.replace(/-/g, "") + "." + t, sampleRate: 100, tags: n, data: { baseData: { ver: 2 } } } } var h = d.url || y.src; if (h) { function a(e) { var t, n, a, i, r, o, s, c, u, p, l; g = !0, m.queue = [], f || (f = !0, t = h, s = function () { var e = {}, t = d.connectionString; if (t) for (var n = t.split(";"), a = 0; a < n.length; a++) { var i = n[a].split("="); 2 === i.length && (e[i[0][b]()] = i[1]) } if (!e[C]) { var r = e.endpointsuffix, o = r ? e.location : null; e[C] = "https://" + (o ? o + "." : "") + "dc." + (r || "services.visualstudio.com") } return e }(), c = s[D] || d[D] || "", u = s[C], p = u ? u + "/v2/track" : d.endpointUrl, (l = []).push((n = "SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)", a = t, i = p, (o = (r = v(c, "Exception")).data).baseType = "ExceptionData", o.baseData.exceptions = [{ typeName: "SDKLoadFailed", message: n.replace(/\./g, "-"), hasFullStack: !1, stack: n + "\nSnippet failed to load [" + a + "] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: " + (S && S.pathname || "_unknown_") + "\nEndpoint: " + i, parsedStack: [] }], r)), l.push(function (e, t, n, a) { var i = v(c, "Message"), r = i.data; r.baseType = "MessageData"; var o = r.baseData; return o.message = 'AI (Internal): 99 message:"' + ("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) (" + n + ")").replace(/\"/g, "") + '"', o.properties = { endpoint: a }, i }(0, 0, t, p)), function (e, t) { if (JSON) { var n = T.fetch; if (n && !y.useXhr) n(t, { method: N, body: JSON.stringify(e), mode: "cors" }); else if (XMLHttpRequest) { var a = new XMLHttpRequest; a.open(N, t), a.setRequestHeader("Content-type", "application/json"), a.send(JSON.stringify(e)) } } }(l, p)) } function i(e, t) { f || setTimeout(function () { !t && m.core || a() }, 500) } var e = function () { var n = l.createElement(k); n.src = h; var e = y[w]; return !e && "" !== e || "undefined" == n[w] || (n[w] = e), n.onload = i, n.onerror = a, n.onreadystatechange = function (e, t) { "loaded" !== n.readyState && "complete" !== n.readyState || i(0, t) }, n }(); y.ld < 0 ? l.getElementsByTagName("head")[0].appendChild(e) : setTimeout(function () { l.getElementsByTagName(k)[0].parentNode.appendChild(e) }, y.ld || 0) } try { m.cookie = l.cookie } catch (p) { } function t(e) { for (; e.length;)!function (t) { m[t] = function () { var e = arguments; g || m.queue.push(function () { m[t].apply(m, e) }) } }(e.pop()) } var n = "track", r = "TrackPage", o = "TrackEvent"; t([n + "Event", n + "PageView", n + "Exception", n + "Trace", n + "DependencyData", n + "Metric", n + "PageViewPerformance", "start" + r, "stop" + r, "start" + o, "stop" + o, "addTelemetryInitializer", "setAuthenticatedUserContext", "clearAuthenticatedUserContext", "flush"]), m.SeverityLevel = { Verbose: 0, Information: 1, Warning: 2, Error: 3, Critical: 4 }; var s = (d.extensionConfig || {}).ApplicationInsightsAnalytics || {}; if (!0 !== d[I] && !0 !== s[I]) { var c = "onerror"; t(["_" + c]); var u = T[c]; T[c] = function (e, t, n, a, i) { var r = u && u(e, t, n, a, i); return !0 !== r && m["_" + c]({ message: e, url: t, lineNumber: n, columnNumber: a, error: i }), r }, d.autoExceptionInstrumented = !0 } return m }(y.cfg); function a() { y.onInit && y.onInit(n) } (T[t] = n).queue && 0 === n.queue.length ? (n.queue.push(a), n.trackPageView({})) : a() }(window, document, {
            src: "https://js.monitor.azure.com/scripts/b/ai.2.min.js",
            ld: -1,
            crossOrigin: "anonymous",
            cfg: {
                instrumentationKey: "",
                disableFetchTracking: false,
                enableCorsCorrelation: true,
                enableRequestHeaderTracking: true,
                enableResponseHeaderTracking: true
            }
        });
    </script>

Then add the SetInstrumentationKey line below into your program.cs file.

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

    // Added this line =>
    await applicationInsights.SetInstrumentationKey("AI KEY GOES HERE");    

    await applicationInsights.AddTelemetryInitializer(telemetryItem);
});

Launch app and check console.

TaskCanceled exception when navigation occurs too fast

When a user enters and exits a page very fast, a TaskCanceledException is fired by NavigationManager_LocationChanged
image
Before a fix is published, as a workaround, we can surround ApplicationInsightsComponent with ErrorBoundary, like this
<ErrorBoundary> <ApplicationInsightsComponent /> </ErrorBoundary>

Missing Name Field on RemoteDependency

Hi,
I'm getting a bad request (400 error code) response from applications insights servers when I try to add a RemoteDependency.

It is reporting this error:
Field 'name' on type 'RemoteDependencyData' is required but missing or empty. Expected: string, Actual: undefined"}],"appId":"087e40d6-a306-4eeb-9c79-2b3115ce0440"

TrackTrace and PageviewData are working well.

Regards,
Juan

Change to LogException parameters

Hi - When trying to update from 0.7.1 to 1.1.1, I noticed that properties was removed as a parameter in LogException, in favor of a CorrelationUid. I was using the properties parameter to log our stack trace and other exception info. Will I just have to call LogEvent with the properties object passed in now, or is there some other way to handle this break?

Here's the change I'm referencing:
image

Ability to set cloud role name

For those of us using a single application insights across multiple apps it would be helpful to have the ability to set the cloud role name via builder.Services.AddBlazorApplicationInsights(); or another method.
I am not sure the best way to do it for this project honestly but it is something I'd love to have :)

The current way to do this in non blazor wasm projects is to add an ITelemetryInitializer like so

public class AppInsightsTelemetryInitializer : ITelemetryInitializer
    {
        public void Initialize(ITelemetry telemetry)
        {
            telemetry.Context.Cloud.RoleName = nameof(OneMarket.Srv.Api);
        }
    }

EasyPrivacy filter blocks js.monitor.azure.com and causes error to be shown

Browser extensions that are filtering for privacy scripts (like the EasyPrivacy script that's used by UBlockOrigin) will cause the script that's placed in the index.html file to cause an error:
Microsoft.JSInterop.JSException: Could not find 'appInsights.trackPageView' ('appInsights' was undefined).

I've tracked this down to the:
"https://js.monitor.azure.com/scripts/b/ai.2.min.js", script getting blocked.

Are you able to improve that function to accommodate for the blocking of that script?
Maybe a try-catch that logs error to console rather?

Fails with browsers that prevent third party tracking (Brave)

After adding this into our application I noticed that we are getting the following errors in console with Brave browser:
image

I suspect this will also happen with other extensions since Application Insights is considered a tracking application.

I don't have any problem with this, but this library needs to be able to detect this state and

  1. Handle the exception
  2. Stop trying to submit telemetry from Blazor

image

I will work through trying to handle this on my own, but wanted to get this issue filed for awareness

Everything working but TrackEvent?

I have implemented everything exactly as shown from the Install section.

I can see events when I refresh my page in the app. I am getting page hits, dependencies and all of the built in app insights data.

I wrote a very simple method to track a custom event on the main page that is already sending good page data to insights. It executes with no error but I don't see any custom events in the app insights portal. I also don't see this custom event being sent to appinsights in the developer network calls. Have I missed a configuration step?

private async Task TrackEvent()
{
await AppInsights.TrackEvent("My Event");
await AppInsights.Flush();
}

protected override async Task OnInitializedAsync()
{
await TrackEvent();
}

Renovate Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

github-actions
.github/workflows/cicd.yml
  • actions/checkout v4@3df4ab11eba7bda6032a0b82a6bb43b11571feac
  • actions/setup-dotnet v3
  • cycjimmy/semantic-release-action v4
nuget
global.json
  • dotnet-sdk 7.0.200
src/BlazorApplicationInsights.Sample/BlazorApplicationInsights.Sample.csproj
  • Microsoft.AspNetCore.Components.WebAssembly.DevServer 7.0.0
  • Microsoft.AspNetCore.Components.WebAssembly 7.0.0
src/BlazorApplicationInsights.Tests/BlazorApplicationInsights.Tests.csproj
  • coverlet.collector 6.0.0
  • xunit.runner.visualstudio 2.5.4
  • xunit 2.6.2
  • Moq 4.20.69
  • Microsoft.Playwright 1.40.0
  • Microsoft.NET.Test.Sdk 17.8.0
  • Microsoft.Extensions.Logging 7.0.0
  • Microsoft.Extensions.Configuration.Abstractions 7.0.0
  • FluentAssertions 6.12.0
src/BlazorApplicationInsights/BlazorApplicationInsights.csproj
  • Microsoft.AspNetCore.Components.Web 7.0.0
  • Microsoft.AspNetCore.Components 7.0.0
  • Microsoft.AspNetCore.Components.Web 6.0.1
  • Microsoft.AspNetCore.Components 6.0.1
  • JetBrains.Annotations 2023.2.0

  • Check this box to trigger a request for Renovate to run again on this repository

Conflict with BlazorMonaco

I'm building an Blazor dotnet 6 project with BlazorApplicationInsight. This packages runs fine until I install package BlazorMonaco. Monaco is created by Microsoft and you can run visual code in the browser with javascript. BlazorMonaco is created by somebody else. When I use both packages, then application insight creates a request with the following body:

Screenshot 2022-01-22 at 13 03 18

Message: SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)
Stacktrace: SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)Snippet failed to load [https://js.monitor.azure.com/scripts/b/ai.2.min.js] -- Telemetry is disabledHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109Host: /Endpoint: https://dc.services.visualstudio.com/v2/track

This crash happens also local at my development machine.

I tried the following solutions but it didn't work:
-> Change some security headers
-> Change the order of the javascript files
-> Different way to set the instrumentationKey
-> More little stupid things

But nothing changed the result.

Index.html in the end of the head tag

    <!-- Extern packages -->
    <link href="_content/BlazorMonaco/lib/monaco-editor/min/vs/editor/editor.main.css" rel="stylesheet" />
    <script type="text/javascript">!function (T, l, y) { var S = T.location, k = "script", D = "instrumentationKey", C = "ingestionendpoint", I = "disableExceptionTracking", E = "ai.device.", b = "toLowerCase", w = "crossOrigin", N = "POST", e = "appInsightsSDK", t = y.name || "appInsights"; (y.name || T[e]) && (T[e] = t); var n = T[t] || function (d) { var g = !1, f = !1, m = { initialize: !0, queue: [], sv: "5", version: 2, config: d }; function v(e, t) { var n = {}, a = "Browser"; return n[E + "id"] = a[b](), n[E + "type"] = a, n["ai.operation.name"] = S && S.pathname || "_unknown_", n["ai.internal.sdkVersion"] = "javascript:snippet_" + (m.sv || m.version), { time: function () { var e = new Date; function t(e) { var t = "" + e; return 1 === t.length && (t = "0" + t), t } return e.getUTCFullYear() + "-" + t(1 + e.getUTCMonth()) + "-" + t(e.getUTCDate()) + "T" + t(e.getUTCHours()) + ":" + t(e.getUTCMinutes()) + ":" + t(e.getUTCSeconds()) + "." + ((e.getUTCMilliseconds() / 1e3).toFixed(3) + "").slice(2, 5) + "Z" }(), iKey: e, name: "Microsoft.ApplicationInsights." + e.replace(/-/g, "") + "." + t, sampleRate: 100, tags: n, data: { baseData: { ver: 2 } } } } var h = d.url || y.src; if (h) { function a(e) { var t, n, a, i, r, o, s, c, u, p, l; g = !0, m.queue = [], f || (f = !0, t = h, s = function () { var e = {}, t = d.connectionString; if (t) for (var n = t.split(";"), a = 0; a < n.length; a++) { var i = n[a].split("="); 2 === i.length && (e[i[0][b]()] = i[1]) } if (!e[C]) { var r = e.endpointsuffix, o = r ? e.location : null; e[C] = "https://" + (o ? o + "." : "") + "dc." + (r || "services.visualstudio.com") } return e }(), c = s[D] || d[D] || "", u = s[C], p = u ? u + "/v2/track" : d.endpointUrl, (l = []).push((n = "SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)", a = t, i = p, (o = (r = v(c, "Exception")).data).baseType = "ExceptionData", o.baseData.exceptions = [{ typeName: "SDKLoadFailed", message: n.replace(/\./g, "-"), hasFullStack: !1, stack: n + "\nSnippet failed to load [" + a + "] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: " + (S && S.pathname || "_unknown_") + "\nEndpoint: " + i, parsedStack: [] }], r)), l.push(function (e, t, n, a) { var i = v(c, "Message"), r = i.data; r.baseType = "MessageData"; var o = r.baseData; return o.message = 'AI (Internal): 99 message:"' + ("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) (" + n + ")").replace(/\"/g, "") + '"', o.properties = { endpoint: a }, i }(0, 0, t, p)), function (e, t) { if (JSON) { var n = T.fetch; if (n && !y.useXhr) n(t, { method: N, body: JSON.stringify(e), mode: "cors" }); else if (XMLHttpRequest) { var a = new XMLHttpRequest; a.open(N, t), a.setRequestHeader("Content-type", "application/json"), a.send(JSON.stringify(e)) } } }(l, p)) } function i(e, t) { f || setTimeout(function () { !t && m.core || a() }, 500) } var e = function () { var n = l.createElement(k); n.src = h; var e = y[w]; return !e && "" !== e || "undefined" == n[w] || (n[w] = e), n.onload = i, n.onerror = a, n.onreadystatechange = function (e, t) { "loaded" !== n.readyState && "complete" !== n.readyState || i(0, t) }, n }(); y.ld < 0 ? l.getElementsByTagName("head")[0].appendChild(e) : setTimeout(function () { l.getElementsByTagName(k)[0].parentNode.appendChild(e) }, y.ld || 0) } try { m.cookie = l.cookie } catch (p) { } function t(e) { for (; e.length;)!function (t) { m[t] = function () { var e = arguments; g || m.queue.push(function () { m[t].apply(m, e) }) } }(e.pop()) } var n = "track", r = "TrackPage", o = "TrackEvent"; t([n + "Event", n + "PageView", n + "Exception", n + "Trace", n + "DependencyData", n + "Metric", n + "PageViewPerformance", "start" + r, "stop" + r, "start" + o, "stop" + o, "addTelemetryInitializer", "setAuthenticatedUserContext", "clearAuthenticatedUserContext", "flush"]), m.SeverityLevel = { Verbose: 0, Information: 1, Warning: 2, Error: 3, Critical: 4 }; var s = (d.extensionConfig || {}).ApplicationInsightsAnalytics || {}; if (!0 !== d[I] && !0 !== s[I]) { var c = "onerror"; t(["_" + c]); var u = T[c]; T[c] = function (e, t, n, a, i) { var r = u && u(e, t, n, a, i); return !0 !== r && m["_" + c]({ message: e, url: t, lineNumber: n, columnNumber: a, error: i }), r }, d.autoExceptionInstrumented = !0 } return m }(y.cfg); function a() { y.onInit && y.onInit(n) } (T[t] = n).queue && 0 === n.queue.length ? (n.queue.push(a), n.trackPageView({})) : a() }(window, document, {
            src: "https://js.monitor.azure.com/scripts/b/ai.2.min.js",
            ld: -1,
            crossOrigin: "anonymous",
            cfg: {
                instrumentationKey: "",
                disableFetchTracking: false,
                enableCorsCorrelation: true,
                enableRequestHeaderTracking: true,
                enableResponseHeaderTracking: true
            }
        });
    </script>

Index.html in the end of the body tag.

    <!-- Extern packages -->
    <script type="text/javascript" src="lib/bootstrap/js/bootstrap.js"></script>
    <script type="text/javascript" src="js/extern/smartlook-def.js"></script>
    <script type="text/javascript" src="_content/BlazorMonaco/lib/monaco-editor/min/vs/loader.js"></script>
    <script type="text/javascript">require.config({ paths: { 'vs': '_content/BlazorMonaco/lib/monaco-editor/min/vs' } });</script>
    <script type="text/javascript" src="_content/BlazorMonaco/lib/monaco-editor/min/vs/editor/editor.main.js"></script>
    <script type="text/javascript" src="_content/BlazorMonaco/jsInterop.js"></script>
    <script type="text/javascript" src="_content/BlazorTable/BlazorTable.min.js"></script>

    <!-- App packages -->
    <script type="text/javascript" src="_framework/blazor.webassembly.js"></script>
    <script type="text/javascript">navigator.serviceWorker.register('service-worker.js');</script>
    <script type="text/javascript" src="_content/Microsoft.Authentication.WebAssembly.Msal/AuthenticationService.js"></script>

    <!-- Extern packages -->
    <script type="text/javascript" src="_content/BlazorApplicationInsights/JsInterop.js"></script>

Program.cs

            builder.Services.AddBlazorApplicationInsights(async applicationInsights =>
            {
                await applicationInsights.SetInstrumentationKey(InstrumentationKey);
                await applicationInsights.TrackPageView();
            });

_Imports.razor

@using BlazorApplicationInsights
@using BlazorMonaco

App.razor
<ApplicationInsightsComponent />

Do you have idea's how to identify the problem or maybe even fix it? Did you have this problem with other packages as well?
At the moment I have no idea's anymore how to tackle the problem.

I created other test projects. When I installed both packages, then the same problem will be there again.

My blazor project is here if you need it: Blazor Project
My website to see the errormessage: Mad-World.nl

If you have questions, then I would like that to hear.

Default configuration breaks Google Analytics tracking

In library description, in Install section there is sample snippet how to configure SDK in javascript.

There is setting enableCorsCorrelation which is set to true. In Application Insights SDK default for this setting is false. If enableCorsCorrelation is set to true, this can break CORS requests or fail OPTION requests made by the application.

For example using suggested configuration will break Google Analytics tracking with following error:

Access to XMLHttpRequest at 'https://www.google-analytics.com/j/collect?v=1&_v<removedforprivacy>' from origin 'https://www.<removedforprivacy>' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Sample installation script should set enableCorsCorrelation to false or omit it.

AppInsights.TrackEvent() generates name "not_specified"

When I use the below implementation, App Insights registers the event with name = "not_specified"

            await AppInsights.TrackEvent("MyEvent", new Dictionary<string, object>()
            {
                { "customProperty", "customValue" }
            });

I believe this is because the javascript needs named parameters, but I'm not sure.

I was able to fix it by defining a class for this:

        public class AppInsightsObject
        {
            public string name { get; set; }
            public Dictionary<string, object> properties { get; set; }
        }

And then I passed it in like this:

            await JSRuntime.InvokeVoidAsync("appInsights.trackEvent", new AppInsightsObject()
            {
                name = "MyEvent",
                properties = new Dictionary<string, object>()
            {
                { "customProperty", "customValue" }
            }
            });

This DID work. I'm not sure I want to submit a full PR, let me know.. ๐Ÿ˜‰

Question: Filtering certain fetch calls

Hi,

I have a project which is using SignalR. Every time one of the hubs disconnect, the failed fetch gets logged and it bloats my application insights. It also logs every failed attempt to reconnect to the server.

Just wondering if it would be possible to filter out these calls and stop them from being logged as they are of no use to me.

Thanks,
Moe.

Your .dependabot/config.yaml contained invalid details

Dependabot encountered the following error when parsing your .dependabot/config.yaml:

The property '#/' did not contain a required property of 'update_configs'
The property '#/' contains additional properties ["updates"] outside of the schema when none are allowed
The property '#/version' value 2 did not match one of the following values: 1

Please update the config file to conform with Dependabot's specification using our docs and online validator.

SetEnableAutoRouteTracker Sets the Wrong Property

Hello! I am wanting to use this library but with auto route tracking turned off.

However, it looks like there may be a bug. In BlazorAppInsightsConfigBuilder.cs, the property ShouldAddLogger is set instead of ShouldSetEnableAutoRouteTracking:

public BlazorAppInsightsConfigBuilder SetEnableAutoRouteTracking(bool state)
{
ShouldAddLogger = state;
return this;
}

Is this a bug or am I missing something? I would be happy to create a PR for this but this is unfortunately a full blocker fo us using this library at the moment.

Thanks!

WASM or Server Side?

Is this package for Blazor WASM or ServerSide or both? Please mention in explicitly in readme.md

Error with the instrumentation Key in Program.cs

Hi I copy the sample in my program.cs

var configuration = builder.Configuration.Build();
var appInsightKey = configuration["ApplicationInsights:Key"];
//builder.Services.AddBlazorApplicationInsights();

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

            await applicationInsights.SetInstrumentationKey(appInsightKey);
            await applicationInsights.LoadAppInsights();
            await applicationInsights.AddTelemetryInitializer(telemetryItem);
        });

And I get this error in the console

crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Could not find 'blazorApplicationInsights.setInstrumentationKey' ('blazorApplicationInsights' was undefined).
Error: Could not find 'blazorApplicationInsights.setInstrumentationKey' ('blazorApplicationInsights' was undefined).
at https://localhost:44367/_framework/blazor.webassembly.js:1:1287
at Array.forEach ()
at e.findFunction (https://localhost:44367/_framework/blazor.webassembly.js:1:1247)
at b (https://localhost:44367/_framework/blazor.webassembly.js:1:2989)
at https://localhost:44367/_framework/blazor.webassembly.js:1:3935
at new Promise ()
at Object.beginInvokeJSFromDotNet (https://localhost:44367/_framework/blazor.webassembly.js:1:3908)
at Object.w [as invokeJSFromDotNet] (https://localhost:44367/_framework/blazor.webassembly.js:1:64232)
at _mono_wasm_invoke_js_blazor (https://localhost:44367/_framework/dotnet.5.0.6.js:1:190800)
at do_icall (:wasm-function[10596]:0x194e4e)
Microsoft.JSInterop.JSException: Could not find 'blazorApplicationInsights.setInstrumentationKey' ('blazorApplicationInsights' was undefined).
Error: Could not find 'blazorApplicationInsights.setInstrumentationKey' ('blazorApplicationInsights' was undefined).
at https://localhost:44367/_framework/blazor.webassembly.js:1:1287
at Array.forEach ()
at e.findFunction (https://localhost:44367/_framework/blazor.webassembly.js:1:1247)
at b (https://localhost:44367/_framework/blazor.webassembly.js:1:2989)
at https://localhost:44367/_framework/blazor.webassembly.js:1:3935
at new Promise ()
at Object.beginInvokeJSFromDotNet (https://localhost:44367/_framework/blazor.webassembly.js:1:3908)
at Object.w [as invokeJSFromDotNet] (https://localhost:44367/_framework/blazor.webassembly.js:1:64232)
at _mono_wasm_invoke_js_blazor (https://localhost:44367/_framework/dotnet.5.0.6.js:1:190800)
at do_icall (:wasm-function[10596]:0x194e4e)
at Microsoft.JSInterop.JSRuntime.d__15`1[[System.Object, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
at Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(IJSRuntime jsRuntime, String identifier, Object[] args)
at BlazorApplicationInsights.ApplicationInsights.SetInstrumentationKey(String key)
at Cardinal.Software.Cif.UI.App.Program.<>c__DisplayClass0_0.<

b__1>d.MoveNext() in C:\Users\lprada\Dropbox\DATA\Cardinal\CONS\CIF\cardinal-software-cif-ui\src\Cif.UI.App\Program.cs:line 53
--- End of stack trace from previous location ---
at BlazorApplicationInsights.ApplicationInsights.InitBlazorApplicationInsightsAsync(IJSRuntime jSRuntime)
at BlazorApplicationInsights.ApplicationInsightsComponent.OnAfterRenderAsync(Boolean firstRender)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)

If I use builder.Services.AddBlazorApplicationInsights(); then it works perfect.

Load instrumentation key from appsettings or code

Do you have any plans to add support for loading the instrumentation key from appsettings, or from the app startup code? Looking at ways to avoid having to create copies of index.html for different deployment environments and interested if you had considered this and / or had any ideas about how best to tackle it?

ReferenceError: appInsights is not defined

I am getting the following Error

I am using .NET 6 RC1 Web Assembly Hosted Project

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: appInsights is not defined
      ReferenceError: appInsights is not defined
          at Object.addTelemetryInitializer (https://localhost:5001/_content/BlazorApplicationInsights/JsInterop.js:32:9)
          at https://localhost:5001/_framework/blazor.webassembly.js:1:3297
          at new Promise (<anonymous>)
          at Object.beginInvokeJSFromDotNet (https://localhost:5001/_framework/blazor.webassembly.js:1:3271)
          at Object.At [as invokeJSFromDotNet] (https://localhost:5001/_framework/blazor.webassembly.js:1:58349)
          at _mono_wasm_invoke_js_blazor (https://localhost:5001/_framework/dotnet.6.0.0-rc.1.21451.13.js:1:193753)
          at wasm://wasm/00945eda:wasm-function[2590]:0x8073e
          at wasm://wasm/00945eda:wasm-function[2310]:0x68ada
          at wasm://wasm/00945eda:wasm-function[7015]:0x17bca9
          at wasm://wasm/00945eda:wasm-function[6830]:0x172e4f
Microsoft.JSInterop.JSException: appInsights is not defined
ReferenceError: appInsights is not defined
    at Object.addTelemetryInitializer (https://localhost:5001/_content/BlazorApplicationInsights/JsInterop.js:32:9)
    at https://localhost:5001/_framework/blazor.webassembly.js:1:3297
    at new Promise (<anonymous>)
    at Object.beginInvokeJSFromDotNet (https://localhost:5001/_framework/blazor.webassembly.js:1:3271)
    at Object.At [as invokeJSFromDotNet] (https://localhost:5001/_framework/blazor.webassembly.js:1:58349)
    at _mono_wasm_invoke_js_blazor (https://localhost:5001/_framework/dotnet.6.0.0-rc.1.21451.13.js:1:193753)
    at wasm://wasm/00945eda:wasm-function[2590]:0x8073e
    at wasm://wasm/00945eda:wasm-function[2310]:0x68ada
    at wasm://wasm/00945eda:wasm-function[7015]:0x17bca9
    at wasm://wasm/00945eda:wasm-function[6830]:0x172e4f
   at Microsoft.JSInterop.JSRuntime.<InvokeAsync>d__16`1[[System.Object, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
   at Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(IJSRuntime jsRuntime, String identifier, Object[] args)
   at BlazorApplicationInsights.ApplicationInsights.AddTelemetryInitializer(TelemetryItem telemetryItem)
   at Program.<>c.<<<Main>$>b__0_2>d.MoveNext() in C:\Users\admin\source\repos\GetInLineV6New\GetInLineV6New\Client\Program.cs:line 63
--- End of stack trace from previous location ---
   at BlazorApplicationInsights.ApplicationInsights.InitBlazorApplicationInsightsAsync(IJSRuntime jSRuntime)
   at BlazorApplicationInsights.ApplicationInsightsComponent.OnAfterRenderAsync(Boolean firstRender)
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)

Here is my app.razor

<ApplicationInsightsComponent />
<CascadingAuthenticationState>
       <CascadingBlazoredModal>
<Error>
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
            <FocusOnNavigate RouteData="@routeData" Selector="h1" />
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p role="alert">Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</Error>
 </CascadingBlazoredModal>
</CascadingAuthenticationState>

Here is the program.cs

using XXXXXXXV6New.Client;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Blazored.LocalStorage;
using XXXXXXV6New.Client.Services;
using Blazored.Modal;
using Serilog;
using Syncfusion.Blazor;
using Microsoft.AspNetCore.Components.Authorization;
using Serilog.Core;
using Serilog.Events;
using System.Diagnostics;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.AspNetCore.Components;
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http.Connections;
using System.Net.Http;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.Configuration;
using System.Configuration;
using Serilog.Sinks;
using Toolbelt.Blazor.Extensions.DependencyInjection;
using BlazorApplicationInsights;
using System.Collections.Generic;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");

builder.Services.AddBlazoredLocalStorage();


builder.Services.AddScoped<AppState>();
builder.Services.AddScoped<PageTransferDisplayMessage>();
builder.Services.AddScoped<OrgService>();
builder.Services.AddScoped<CustomHttpService>();

builder.Services.AddSpeechSynthesis(); // <- Add this line.

builder.Services.AddBlazoredModal();
builder.Services.AddSyncfusionBlazor();
builder.Services.AddLogging(configure => configure.AddSerilog());

builder.Services.AddTransient<CustomHttpMessageHandler>();

builder.Services.AddHttpClient("default", client =>
{
    client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);
})
.AddHttpMessageHandler<CustomHttpMessageHandler>();

//https://awesomeopensource.com/project/IvanJosipovic/BlazorApplicationInsights
builder.Services.AddBlazorApplicationInsights(async applicationInsights =>
{
    var telemetryItem = new TelemetryItem()
    {
        Tags = new Dictionary<string, object>()
            {
                { "ai.cloud.role", "XXXXXXXNewV6" },
                { "ai.cloud.roleInstance", "XXXXXXXNewV6" },
            }
    };

    await applicationInsights.AddTelemetryInitializer(telemetryItem);
});

builder.Services.AddAuthorizationCore();

builder.Services.AddScoped<CustomAuthenticationStateProvider>();
builder.Services.AddScoped<AuthenticationStateProvider>(provider => provider.GetRequiredService<CustomAuthenticationStateProvider>());

Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense('')

var levelSwitch = new LoggingLevelSwitch();
levelSwitch.MinimumLevel = LogEventLevel.Information;

//TelemetryConfiguration.Active.InstrumentationKey = builder.Configuration["ApplicationInsights:InstrumentationKey"];

var loggingConfig = new LoggerConfiguration()
    .Enrich.FromLogContext()
    .MinimumLevel.ControlledBy(levelSwitch)
    .Enrich.WithProperty("Source", "BlazorWebAssembly")
    .Enrich.WithProperty("AppName", "XXXXXXXV6")
    .Enrich.WithProperty("InstanceId", Guid.NewGuid().ToString("n"))
    // .MinimumLevel.
    // .WriteTo.BrowserHttp(controlLevelSwitch: levelSwitch)
    //.WriteTo.Console() Not supported on Blazor Wasm as there is no console, it runs in the browser.
    .WriteTo.BrowserConsole();
    //.WriteTo.BrowserHttp($"{builder.HostEnvironment.BaseAddress}ingest", controlLevelSwitch: levelSwitch);
   // .WriteTo.ApplicationInsightsTraces(TelemetryConfiguration.Active);
//.WriteTo.BrowserHttp(endpointUrl: Environment.GetEnvironmentVariable("SEQ_URL") ?? "http://localhost:5341"),   //http://5.9.10.113/67073040/send-serilog-requests-to-http-endpoint
// .CreateLogger();

Log.Logger = loggingConfig.CreateLogger();

builder.Services.AddSingleton<LoggingLevelSwitch>(levelSwitch);

Serilog.Debugging.SelfLog.Enable(msg =>
{
    Console.WriteLine("Error in Serilog " + msg);
    //Debugger.Break();
});

builder.Services.AddSingleton<HubConnection>(sp => {
    var navigationManager = sp.GetRequiredService<NavigationManager>();
    return new HubConnectionBuilder()
      .WithUrl(navigationManager.ToAbsoluteUri("/XXXXXXXneHub"))
      .WithAutomaticReconnect()
      .Build();
});

await builder.Build().RunAsync();

SetInstrumentationKey doesn't appear to be working (Gives 'Please provide instrumentation key')

I checked out your Sample project and just replaced the cfg in index.html with an empty object.
Like so: cfg: {}

Then I went into Program.cs, removed the telemetry, and added SetInstrumentationKey

builder.Services.AddBlazorApplicationInsights(async applicationInsights =>
{
    await applicationInsights.SetInstrumentationKey("MyKeyHere");
    await applicationInsights.LoadAppInsights();
});

but I keep getting this warning in the browser
Failed to initialize AppInsights JS SDK for instance appInsights - Please provide instrumentation key

If I replace it directly in the index.html it works fine, but I'm trying to get the key from the appsettings since that's what gets replaced in my deployment scripts.

I tried with both the original .NET Core version the library was written in, and also the one I'm using (5.0.4), but the problem appears in both.

Unable to add ApplicationInsightsComponent to App.razor

Hi I just did everything like in the Readme but I am stuck with adding the component to the app.razor file.
I am getting this error in the browser console:

Error: Microsoft.JSInterop.JSException: Could not find 'appInsights.trackPageView' ('appInsights' was undefined).
Error: Could not find 'appInsights.trackPageView' ('appInsights' was undefined).
    at https://localhost:44378/dev-mijn/_framework/blazor.server.js:1:497
    at Array.forEach (<anonymous>)
    at s.findFunction (https://localhost:44378/dev-mijn/_framework/blazor.server.js:1:465)
    at E (https://localhost:44378/dev-mijn/_framework/blazor.server.js:1:2611)
    at https://localhost:44378/dev-mijn/_framework/blazor.server.js:1:3499
    at new Promise (<anonymous>)
    at Ft.beginInvokeJSFromDotNet (https://localhost:44378/dev-mijn/_framework/blazor.server.js:1:3480)
    at Ft._invokeClientMethod (https://localhost:44378/dev-mijn/_framework/blazor.server.js:1:75072)
    at Ft._processIncomingData (https://localhost:44378/dev-mijn/_framework/blazor.server.js:1:72696)
    at Ft.connection.onreceive (https://localhost:44378/dev-mijn/_framework/blazor.server.js:1:67009)
   at Microsoft.JSInterop.JSRuntime.InvokeAsync[TValue](Int64 targetInstanceId, String identifier, Object[] args)
   at Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(IJSRuntime jsRuntime, String identifier, Object[] args)
   at BlazorApplicationInsights.ApplicationInsights.TrackPageView(String name, String uri, String refUri, String pageType, Nullable`1 isLoggedIn, Dictionary`2 properties)
   at BlazorApplicationInsights.ApplicationInsightsComponent.NavigationManager_LocationChanged(Object sender, LocationChangedEventArgs e)
   at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__128_0(Object state)
   at Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext.ExecuteSynchronously(TaskCompletionSource completion, SendOrPostCallback d, Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext.ExecuteBackground(WorkItem item)

I have added the service like this to my startup :
services.AddBlazorApplicationInsights();
And added it to the top of my App.razor file.

Anyone any idea how I can fix this? I have no clue. I will try debugging this meanwhile

Gracefully handle lack of App Insights (due to adblocker, etc)

Most ad blockers out there block telemetry scripts like AI. This package should gracefully handle the case where App Insights is blocked or otherwise couldn't be loaded and do nothing, rather than throwing (user-visible) errors on every page load, e.g.:

crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: appInsights is not defined
      ReferenceError: appInsights is not defined
          at Object.setInstrumentationKey (https://localhost:5001/_content/BlazorApplicationInsights/JsInterop.js:71:9)

Exception is not logged properly

In the ApplicationLogger when there is an Exception the exception is logged as a string, while it should properly split the Error in a Mesaage and a Stacktrace. Also, the eventId could be set as the Id in the trackException.

Blazor server how to set user who is logged in

in the instructions there is a section that uses a RemoteAuthenticatorView component and sets the user
in blazor server using azure ad i have not been able to find a way to impliment that.

does anyone have a way to do this ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.