Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application Insights

I have two projects: one is MVC4 application and another is output type class library.

I want to make the second project (the class library one) an insights communication layer.

The code compiles and the server runs normally.

public static void SaveMetric(string title, double value, 
    string azureKey, Dictionary<string, string> properties = null)
{
    try
    {
        TelemetryClient telemetry = new TelemetryClient();
        telemetry.InstrumentationKey = azureKey;
        telemetry.TrackMetric(title, value, properties);
    }
    catch (Exception ex)
    { 
        var a = "";
    }
}

The problem start's when I call the telemetry.TrackMetric function. This code returns the error:

"Object reference not set to an instance of an object."(System.NullReferenceException).

Is it possible to use Microsoft Insights in a class library project? And if it is, what am I doing wrong?

like image 317
Ricardo Rocha Avatar asked Oct 30 '22 21:10

Ricardo Rocha


1 Answers

I recently upgraded to 1.2.0 and ran into the same problem. In addition to the standard setup, my code was overriding the instrumentation key in the ApplicationInsights.config with one stored in the web.config. This was done via the global.asax - Application_Start. The code works fine locally, but bombs out when deployed to Azure.

It turns out it was a problem of how I was accessing the web.config. I had to switch my code from using WebConfigurationManager to ConfigurationManager.

This Application_Start code:

Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.InstrumentationKey = System.Web.Configuration.WebConfigurationManager.AppSettings["MyInstrumentationKey"];

changed to this:

Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.InstrumentationKey = System.Configuration.ConfigurationManager.AppSettings["MyInstrumentationKey"]; 
like image 148
shane carvalho Avatar answered Nov 11 '22 13:11

shane carvalho