left-icon

Application Insights Succinctly®
by Roberto Albano

Previous
Chapter

of
A
A
A

CHAPTER 9

Writing Your Code

Writing Your Code


In the last chapter, we demonstrated how Visual Studio creates a project that is ready to be used as an Application Insights resource. Now it’s time to gather the points we want to keep track of.

As we have seen, with Application Insights we can register anything that happens in our web application. You can do this programmatically through code, using the available SDKs for most web development languages and frameworks.

In every SDK, there is a standard entry point to register something on our Application Insights resource, and this is the TelemetryClient class.

The TelemetryClient class

To start using the TelemetryClient class, we only need a few lines of code. In the following example, we track an exception.

Code Listing 3: Tracking an Exception Using a TelemetryClient Instance

var ai = new TelemetryClient();

ai.TrackException(ex);

In this example, the first line of code creates a new instance of the TelemetryClient class. It establishes a connection to the Application Insights resource linked by the instrumentation key used.

In the next line, the TrackException method is invoked, passing an exception instance.

With these two lines of code, we can send the entire exception to the Application Insights resource. There we will find all the information related to it, including the origin of the exception, the stack trace, and so on.

As you can see, this example is written in C#, and so it can be executed from the server side. The interesting thing to know is that we can have the TelemetryClient class even on the client side, using the same method, with the same input and output provided.

Tracking methods

Table 7 contains the methods of the TelemetryClient class. Some of these methods are invoked directly using the JavaScript snippet (see the Scripts section).

Table 7: TelemetryClient Methods

Method

Description

TrackAvailability

Sends an AvailabilityTelemetry object with information about the availability of an application

TrackDependency

Sends a DependencyTelemetry object with information about external dependencies called in an application

TrackEvent

Sends an EventTelemetry object for display in Metrics Explorer

TrackException

Sends an ExceptionTelemetry object for display in Diagnostic Search

TrackMetric

Sends a MetricTelemetry object for aggregation in Metrics Explorer

TrackPageView

Sends a PageViewTelemetry object with information about the page viewed in the application

TrackRequest

Sends a RequestTelemetry object with information about a request handled by the application

TrackTrace

Sends a TraceTelemetry object with a trace message for display in Diagnostic Search

Every method sends an instance of a particular class to the Application Insights resource. The instance sent has all the information related to the event or metric to enable tracking. All these methods are overloaded to send the original information as parameters instead of the instance.

To give an example, suppose you have the following variables.

Code Listing 4: Defining Parameters for a RequestTelemetry Instance

var ai = new TelemetryClient();

string name = "myRequest";

DateTimeOffset startTime = new DateTimeOffset(DateTime.Now);

TimeSpan duration = new TimeSpan(0,0,0,0,250);

string responseCode = "200";

bool success = true;

You can track a request by sending an instance of the RequestTelemetry class.

Code Listing 5: Tracking a Request Using TrackRequest with a RequestTelemetry Instance

RequestTelemetry requestTelemetryInstance = new RequestTelemetry(name, startTime, duration, responseCode, success);

ai.TrackRequest(requestTelemetryInstance);

Alternatively, this can be done by sending the values as parameters using an overload of the constructor.

Code Listing 6: Tracking a Request Using TrackRequest with Parameters

ai.TrackRequest(name, startTime, duration, responseCode, success);

The TelemetryConfiguration class

TelemetryConfiguration is another important class to understand. It holds all the information related to the resource of Application Insights that will use the web application.

As stated previously, the instrumentation key is stored in the ApplicationInsights.config file.

You can create an instance of the TelemetryClient class using the default constructor (without any input parameters), or use an overload of it.

In both constructors, the class uses an instance of TelemetryConfiguration to connect to the right Application Insights resource.

If you use the default constructor for TelemetryClient, it implies the usage of a singleton instance of the TelemetryConfiguration class. If you require more than one instance, you must manage your own TelemetryConfiguration instance.

For example, say we create an instance of TelemetryClient using the default constructor.

Code Listing 7: TelemetryClient Instantiation Using a Default Constructor

var ai = new TelemetryClient();

Behind the scenes, this class will use the following singleton instance of TelemetryConfiguration:

Code Listing 8: TelemetryConfiguration Singleton Instance

TelemetryConfiguration.Active

This uses the instrumentation key present in the ApplicationInsights.config file.

However, since InstrumentationKey is a property of this class, we can change this value to connect to a different key. We will discuss this in the next section and see how we can manage different instrumentation keys depending on different scenarios.

Returning to the TelemetryClient class, another constructor accepts an instance of a TelemetryConfiguration class as an input parameter.

Code Listing 9: TelemetryClient Instantiation Using an Overloaded Constructor

TelemetryConfiguration config = TelemetryConfiguration.CreateDefault();

config.InstrumentationKey = "myInstrumentationKey";

var ai = new TelemetryClient(config);

By using this constructor, you have the responsibility to set the correct references for the resource in the configuration class.

Tip: In the previous listing, we used the CreateDefault initializer (that creates an instance starting from the ApplicationInsights.config parameters) due to the long list of properties to initialize by hand using a default constructor.

Using different instrumentation keys for various environments

If you are working on a web application and want to use Application Insights resources to monitor both the debug and the release version of your project, it is recommended that you use two different resources to avoid influencing the production environment with data coming from the development environment.

You can achieve this with little effort and only a few lines of code.

Creating and configuring resources

Let’s start creating the Application Insights resources. Of course, we will create two different resources; in this example, we’ll identify these as ai_dev_resource for development and ai_rel_resource for release.

Note: We’ll create this example using an ASP.NET MVC web application and Visual Studio. For different languages and IDEs, there might be an equivalent way.

In this type of application, we have a Web.Config file with all the information about the web application configuration.

Using the solution configurations feature within Visual Studio, we’ll have a debug and a release configuration created by default (but we can have more solution configurations if needed).

For every solution configuration, Visual Studio generates a corresponding configuration file, so having debug and release configurations will result in two XLST files in the Solution Explorer: Web.Debug.config and Web.Release.config. This allows us to transform the Web.config file with the correct parameters for each environment.

Solution Configurations

Figure 34: Solution Configurations

For this example, suppose we have the following instrumentation keys:

  •                     ai_dev_resource      => a11111111-a111-a111-a111-a11111111111
  •                     ai_prod_resource     => b22222222-b222-b222-b222-b22222222222

First, in your Web.config file, you need to add the development instrumentation key in an appSettings key:

Code Listing 10: Instrumentation Key Setting in the Web.config File

<appSettings>

  <!-- Application Insights -DEVELOPMENT- Instrumentation Key -->

  <add key="ApplicationInsightsInstrumentationKey" value=" a11111111-

   a111-a111-a111-a11111111111" />

</appSettings>

Then you must add the other instrumentation key in the Web.Release.config file, with an XML transformation rule, as follows.

Code Listing 11: Instrumentation Key Transformation Setting for Release (Production)

<appSettings>

  <!-- Application Insights -PRODUCTION- Instrumentation Key -->

  <add key="ApplicationInsightsInstrumentationKey" value=" b22222222-

   b222-b222-b222-b22222222222" xdt:Transform="SetAttributes"   

   xdt:Locator="Match(name)"/>

</appSettings>

Using this configuration replacement, you ensure that when you deploy your code in a production environment (by using the release solution configuration), the instrumentation key will have the correct value.

Remember that these settings will not automatically change the instrumentation key at run time. It is only a mode to guarantee that, in every context, the correct key will target the right destination environment. It must be loaded by code, as we will see in the next section.

Assigning instrumentation keys at run time

Once these configurations have been added, we need to understand how to assign the instrumentation key at run time.

Since the Application Insights SDK is very flexible, there is a possibility to change the value of the current resource’s instrumentation key at run time.

To do this, use the Global.asax file and add two lines of code at the end of the Application_Start method of the class inside this file.

Code Listing 12: Customizing Application Insights’ Resource Loading

public class MvcApplication : System.Web.HttpApplication

{

    protected void Application_Start()

    {

        AreaRegistration.RegisterAllAreas();

        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        RouteConfig.RegisterRoutes(RouteTable.Routes);

        BundleConfig.RegisterBundles(BundleTable.Bundles);

        // Load the instrumentation key from the configuration file

        var currentTelemetryKey System.Web.Configuration.

            WebConfigurationManager.

            AppSettings["ApplicationInsightsInstrumentationKey"];                      

        // Assign the instrumentation key to the running resource

        Microsoft.ApplicationInsights.

            Extensibility.TelemetryConfiguration.Active.

            InstrumentationKey = currentTelemetryKey;

    }

}

The last line of code in this method will assign the value of the instrumentation key by reading it from the Web.config file; therefore, if you are in a production environment and using the Release solution configuration, you should have the InstrumentationKey value of the ai_prod_resource resource.

There is another area where you need to make a small change: the JavaScript snippet we talked about in the Scripts section.

In this snippet, instead of using the InstrumentationKey as a fixed value, we will load it using the Razor syntax with the variable we mentioned that holds the key.

Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.
InstrumentationKey

The result is something like this:

Code Listing 13: JavaScript Snippet for Page View Tracking

<script type="text/javascript">

    var appInsights=window.appInsights||function(config){

        function r(config){t[config]=function(){var i=arguments;t.queue.push(function(){t[config].apply(t,i)})}}var t={config:config},u=document,e=window,o="script",s=u.createElement(o),i,f;for(s.src=config.url||"//az416426.vo.msecnd.net/scripts/a/ai.0.js",u.getElementsByTagName(o)[0].parentNode.appendChild(s),t.cookie=u.cookie,t.queue=[],i=["Event","Exception","Metric","PageView","Trace"];i.length;)r("track"+i.pop());return r("setAuthenticatedUserContext"),r("clearAuthenticatedUserContext"),config.disableExceptionTracking||(i="onerror",r("_"+i),f=e[i],e[i]=function(config,r,u,e,o){var s=f&&f(config,r,u,e,o);return s!==!0&&t["_"+i](config,r,u,e,o),s}),t

    }({

        instrumentationKey: "@(Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.InstrumentationKey)"

    });

    window.appInsights=appInsights;

    appInsights.trackPageView();

</script>

Using this code, you will ensure that every HTML page will use the right instrumentation key to track page views.

From now on, you can debug your code using the ai_dev_resource, and without influencing the production environment, which will be monitored by the ai_prod_resource.

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.