In my previous post I’ve described how to use Application Insights and use it within your new web application. Most of us aren’t working in a greenfield project, so new solutions have to be integrated with the old.

The project I’m working on uses log4net for logging messages, exceptions, etc. In order for us to use Application Insights, we had to search for a solution to integrate both. After having done some research on the subject we discovered this wasn’t a big problem.

The software we are working on are Windows Services and Console Applications, so we should not add the Application Insights package for web applications. For these kind of applications it’s enough to just add the core package to your project(s).


Once added, we are creating the TelemetryClient in the Main of the application.

private static void Main(string[] args)
	var telemetryClient = new TelemetryClient { InstrumentationKey = "[InstrumentationKey]" };

	/*Do our application logic*/


You will notice we are setting the InstrumentationKey property explicitly. That’s because we don’t use an ApplicationInsights.config file, like in the web application example and this key has to be specified in order to start logging.

This final flush will make sure all pending messages will be pushed to the Application Insights portal right away.
Now you might not see your messages in the portal right away. We discovered this while testing out the libraries. The reason for this is probably due to some caching in the portal or all messages being handled by some queue mechanism on the backend (assumption on my behalf). So don’t be afraid, your messages will show up within a few seconds/minutes.

After having wired up Application Insights, we still had to add it to log4net. When browsing through the nuget packages we noticed the Log4NetAppender for Application Insights.

After having added this package to our solution, the only thing we had to do is creating a new log4net appender to the configuration.

    <level value="INFO" />
    <appender-ref ref="LogFileAppender" />
    <appender-ref ref="ColoredConsoleAppender" />
    <appender-ref ref="aiAppender" />
<appender name="aiAppender" type="Microsoft.ApplicationInsights.Log4NetAppender.ApplicationInsightsAppender, Microsoft.ApplicationInsights.Log4NetAppender">
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%message%newline" />

This appender will make sure all log4net messages will be sent to the Application Insights portal.

As you can see, adding Application Insights to existing software is rather easy. I would really recommend using one of these modern, cloud based, logging solutions. It’s much easier to use this compared to ploughing through endless log files on the disks or creating your own solution.

Some time ago the Application Insights became available as a preview in the Azure portal. Application Insights helps you monitor the state of an application, server, clients, etc. As said, it’s still in preview, but it’s rather stable and very easy to use and implement in your applications.
The documentation is still being worked on, but with all the getting started guides on the Microsoft site you can kick start your project with it in a couple of minutes.

The main reason for me to dig into Application Insights is because we still had to implement a proper logging solution for our applications which are migrating to the Azure Cloud.  As it happened, Application Insights just became available at the time and because of the tight Azure integration we were really eager to check it out (not saying you can’t use it with non-Azure software of course).

If you want to start using Application Insights, the first thing you will have to do is creating a new Application Insights application. You will be asked what type of application you want to use.


It’s wise to select the proper application type over here, because a lot of settings and measuring graphs will be set for you depending on the choice made over here. For this example I’ll choose the ASP.NET web application. After having waited for a few minutes the initial (empty) dashboard will be shown.


As you can see, the dashboard is filled with (empty) graphs useful for a web application. In order to see some data over here, you need to push something to this portal. To do this, you’ll need the instrumentation key of this specific Application Insights instance. This instrumentation key can be found within the properties of the created portal.


Now let’s head to Visual Studio and create a new MVC Web Application and add the Microsoft.ApplicationInsights.Web nuget package to the project.


This package will add the ApplicationInsights.config file to the web project in which you have to specify the instrumentation key.


The web application is now ready to log data to the Application Insights portal.
You might also want to track some custom events, exceptions, metrics, etc. into the Application Insights portal. To do this, just create a new TelemetryClient to your code and start pushing data. An example is shown below.

public class HomeController : Controller
	public ActionResult Index()
		var tc = new TelemetryClient();

		return View();

	public ActionResult About()
		ViewBag.Message = "Your application description page.";
		var tc = new TelemetryClient();
		tc.TrackTrace("This is a test tracing message.");
		tc.TrackEvent("Another event in the About page.");
		tc.TrackException(new Exception("My own exception"));
		tc.TrackMetric("Page", 1);

		return View();

	public ActionResult Contact()
		ViewBag.Message = "Your contact page.";
		var tc = new TelemetryClient();

		return View();

Running the website an navigating between the different pages (Home, About and Contact) will result in the web portal pushing data to Application Insights. Navigating back to the selected Application Insights portal will show the results in the dashboard.


You can click on any of the graphs over here and see more details about the data. I’ve clicked on the Server Requests graph to zoom a bit deeper into the requests.


As you can see, a lot of data is send to the portal, response time, response code, size. The custom messages, like the exceptions, are also pushed towards the Application Insights portal. You can see these when zooming in on the Failures graph.


As you can see in the details of an exception, a lot of extra data is added which will make it easier to analyze the exceptions.

This post talked about adding the Application Insights libraries to an ASP.NET Web Application via a nuget package, but that’s not the only place you can use this tooling. It’s also possible to add the Application Insights API for Javascript Applications to your application. This way you are able to push events to the portal on the front end. Awesome, right?

Of course there are plenty of other logging solutions available, but Application Insights is definitely a great contender in this space in my opinion.

This is something which has been available in the .NET Framework since, well, forever. I’m talking about encrypting data in the config file of your (web)application. Every time I studied for the Microsoft developer exams I was reminded on this feature and thought “Hey, I really should use this in the next project”. Up until now I’ve never used this feature though.

The project I’m currently working on has some setup which encrypts the the config file when it’s deployed. A great feature, but this means I can’t read and edit the config file anymore. Manually editing the file shouldn’t be done anyway, but reading it would be nice though.

I knew this data could be decrypted also, but not how to do it exactly. Lucky for me this is a really old feature and there are dozens of people who have written something about it. This article on MSDN helped me out the most. I also read the feature had became available in the .NET Framework 2.0, apparently this wasn´t available in version 1.1.

As with most encrypting algorithms you need some kind of seed to create a stronger (and safer) encryption. If I’m not mistaken this method used the machine key of the computer it’s encrypted on. That’s not all too bad, but this means you can’t decrypt the encrypted data on a system with a different machine key.
The linked article says the machine key is stored in %windir%\system32\Microsoft\Protect\S-1-5-18, which probably is right, but I haven’t checked that out as I can’t log in on the server(s).

If you have encrypted the files, or are able to retrieve the machine key, it’s possible to decrypt the data using the aspnet_regiis tool (Visual Studio Prompt).
If you’d want to decrypt the appSettings block of a website in a virtual directory called virtualDir, the following line should suffice:
aspnet_regiis –pd “appSettings” –app “/virtualDir”

I tried this myself and it didn’t work. The following error was thrown:

Failed to decrypt using provider 'DataProtectionConfigurationProvider'. Error message from the provider: Key not valid for use in specified state. (Exception from HRESULT: 0x8009000B) (C:\VRIESJAN\ApplicationDir\Source\CustomerApp\CustomerApp.Presentation\web.config line 104)

This probably had something to do with me not having the correct machine key on my system. Lucky for me the sysadmin could discover the values through IIS Manager so there wasn’t a real loss, but this is exactly the reason why I haven’t implemented such a thing in a solution of mine. It makes reading production data a lot harder.

Vandaag was ik weer eens bezig met het ontwikkelen van een website. Nu wilde ik op deze website graag per pagina de omschrijving en keywords opgeven. Een van de redenen hiervoor is omdat de zoekmachines dit leuker vinden en je zo ook per pagina aan kunt geven wat er op te lezen valt. Om nou niet op iedere pagina dezelfde functie te hoeven implementeren en ik liever niet een BasePage wil gebruiken, aangezien ik al met een Masterpage werk, zocht ik een alternatief. Het mooiste zou zijn om in de masterpage een functie te maken en die vanuit alle child pagina's aan te kunnen roepen. Na even zoeken hoe ik dit kon bewerkstelligen heb ik het antwoord gevonden. Als eerste moet je een methode in je masterpage declareren, ik heb deze public gemaakt, maar ik denk dat protected of internal ook wel zal werken. Zodra dit is gedaan kun de functie vanuit een child pagina aanroepen door de masterpage te casten naar de master-klasse. Dit kan als volgt:
Presentation.Master.JanV ma = this.Master as Presentation.Master.JanV;
Nu kun je met de ma variabele alle methoden en attributen aanroepen die in de masterpage zijn gedefinieerd, bijvoorbeeld als volgt:
ma.SetMetaTags("Description", paginaItem.Omschrijving);
Ter verduidelijking, de methode SetMetaTags heb ik zelf gemaakt in de masterpage. Op deze manier kun je redelijk eenvoudig basis methoden maken zonder gebruik te maken van een tussenpagina waarvan je moet overerven. In mijn geval worden nu extra meta-tags geplaatst, maar je kunt dus ook andere CSS-bestanden plaatsen of een methode in je masterpage plaatsen die (bijna) iedere childpagina gebruikt.

Bij het maken van websites is het belangrijk om op iedere pagina je keywords en description goed in te vullen. Wanneer je dit niet doet, dan kun je straffen krijgen van zoekmachines en dus een lagere ranking krijgen. Momenteel ben ik weer bezig met het maken van verschillende websites, dus wilde ik ook gelijk de meta tags per pagina kunnen invullen. Hoe dit via normale HTML gaat is mij reeds bekend, maar ik wist nog niet hoe het via de code-behind moest in C#. Na een korte zoektocht op Google is mij duidelijk hoe je meta-tags kunt aanmaken. Zelf maak ik gebruik van masterpages. Deze hebben standaard een zogenaamde ContentPlaceHolder in de head en de body van de pagina. Voor het invullen van meta-tags moet er gebruik worden gemaakt van de placeholder welke in de head staat gedefinieerd. In C# kun je gebruik maken van de HtmlMeta. Deze klasse zorgt ervoor dat een meta-tag in de juiste vorm op de pagina verschijnt. Het enige wat je hier aan hoeft mee te geven is de Name en de Content, zodra dat is gedaan kun je de klasse toevoegen aan je placeholder. In mijn geval ziet de code er ongeveer als volgt uit
HtmlMeta hm = new HtmlMeta(); hm.Name = name; hm.Content = content; HeaderPlaceholder.Controls.Add(hm);
Met 4 regels code kun je er dus voor zorgen dat je meta-tags dynamisch worden aangemaakt en je automatisch ook een hogere (of in ieder geval geen lagere) ranking krijgt in de zoekmachines.