CHAPTER 9
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.
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
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.
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
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
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
Behind the scenes, this class will use the following singleton instance of TelemetryConfiguration:
Code Listing 8: TelemetryConfiguration Singleton Instance
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.
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.
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.

Figure 34: Solution Configurations
For this example, suppose we have the following instrumentation keys:
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
|
<!-- 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)
|
<!-- 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.
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
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.