Monday, 22 May 2017

Storing the AppInsights key in web.config

When working with Application Insights your configuration has a unique key value called the instrumentation key, or more commonly the iKey, which is the unique value that AppInsights uses to associate any telemetry output from your code with the appropriate bucket of data within Azure. It’s just a GUID and is available in the Azure portal. typically this is defined inside the ApplicationInsights.Config file as follows…

<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
  ...
  <InstrumentationKey>00000000-0000-0000-0000-000000000000</InstrumentationKey>
</ApplicationInsights>

This GUID needs to contain the value from within your azure subscription. So far so good. The problem (such as it is) is that for a whole host of reasons I’d rather define this key within the web.config rather than a separate configuration file, as this makes managing keys much easier. If I’m deploying straight to Azure, I’d like to define app settings in Azure so as to override this value for my live environment. Or, if I were using Octopus deploy, I’d like to be able to define a variable and have a different value per environment (Test/Staging/Live and so on). Using the ApplicationInsights.Config file for this makes life a lot more difficult than it needs to be.

Now, I’ve looked at loads of suggestions as to how to overcome this issue – but none (other than the one I’m about to present here) worked for me. Your mileage might vary however. What I wanted was a simple way to write some code in order to read the iKey from my web.config, such that I could roll out my website and have the appropriate key updated for me. In order to do this I had to pull out my trusty copy of .NET Reflector and look at the code. I found a number of posts in the web that suggesting updating the value of TelemetryConfiguration.Active.InstrumentationKey, but regardless of where I set this it didn’t work.

During my spelunking through the code I did find that it’s possible to override the value from the ApplicationInsights.Config file with an environment variable – that being APPINSIGHTS_INSTRUMENTATIONKEY. If this value is defined on the machine you release on then fine, you’re in business. I can see that this is a decent option if you own the hardware that this is running on as someone from IT can login, set the value, and be done with it. But who owns servers these days? I wanted something that was effectively “zero-touch”, and environment variables are not exactly that – nor did I want to write a .ps script that would set this, so I headed out to find another option.

Initialization

In my web project I’d used the defaults for App Insights, which updated my web.config to add the following HTTP module into the processing pipeline…

<system.web>
  <compilation debug="true" targetFramework="4.5.2" />
  <httpRuntime targetFramework="4.5.2" />
  <httpModules>
    <add name="ApplicationInsightsWebTracking"
type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
  </httpModules>
</system.web>

Looking at this module, it called TelemetryConfiguration.Active (a static method) that constructs the telemetry configuration and, by default, reads it from the ApplicationInsights.Config file. From there it then reads the .config data and constructs all of the “plug-ins”, initializes the lot, and that then starts emitting trace data. The initialization of the the plug-ins is done with this section of code from the TelemetryConfigurationFactory class…

private static void InitializeComponents(TelemetryConfiguration configuration, TelemetryModules modules)
{
    InitializeComponent(configuration.TelemetryChannel, configuration);
    InitializeComponents(configuration.TelemetryInitializers, configuration);
    InitializeComponents(configuration.TelemetryProcessorChain.TelemetryProcessors, configuration);
    if (modules != null)
    {
        InitializeComponents(modules.Modules, configuration);
    }
}

So, it configures the telemetry channel (where the telemetry goes), then the initializers and so on. I had a thought – what if I were to add a new class into this initialization phase which would read the iKey from web.config, then I’d be able to plug this into the pipeline and I’d be sorted.

The Code

I came up with this trivially simple class…

public class InstrumentationKeyTelemetryInitializer : ITelemetryModule
{
    public void Initialize(TelemetryConfiguration configuration)
    {
        var iKey = ConfigurationManager.AppSettings["ApplicationInsights:iKey"];

        if (!string.IsNullOrEmpty(iKey))
        {
            configuration.InstrumentationKey = iKey;
        }
    }
}

All it does is read from the .config file and, if the ApplicationInsights:iKey value has been defined, that’s used as the instrumentation key. I then updated my web.config to add on this new app setting…

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    ...
  </configSections>
  <appSettings>
    ...
    <add key="ApplicationInsights:iKey" value="4246A9AC-B3E8-473B-B75D-65DE6B2EEED6"/>
  </appSettings>
</configuration>

That’s not a real key by the way, I just made up a GUID. To plug this in I then altered the ApplicationInsights.Config file to add this new class to the TelemetryModules element…

<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
  ...
  <TelemetryModules>
    <Add Type="MSADC.AppInsights.InstrumentationKeyTelemetryInitializer, MSADC.AppInsights"/>
    ... other modules here
  </TelemetryModules>
  ...
  <InstrumentationKey>00000000-0000-0000-0000-000000000000</InstrumentationKey>
</ApplicationInsights>

Note that I have specifically set the instrumentation key to zeros, as I can easily spot that in the debug output if it’s wrong. I then ran the app and everything worked fine. Well, it nearly did. My initializer was called, but after all the others – so there were a few telemetry calls that included the “zero” key which was of no use at all. What I realised was that my telemetry initializer had to be the first in the .config file. With that done, everything did indeed work just as expected. The first call I got from the telemetry logging was this…

Application Insights Telemetry:
{
  "name": "Microsoft.ApplicationInsights.Dev.4246a9acb3e8473bb75d65de6b2eeed6.Message",
  "time": "2017-05-22T14:53:56.3869277Z",
  "iKey": "4246a9ac-b3e8-473b-b75d-65de6b2eeed6",
  "tags": {
    "ai.operation.parentId": "Oezb1HoAPP8=",
    "ai.location.ip": "127.0.0.1",
    "ai.cloud.roleInstance": "DESKTOP-6NDCRK5",
    "ai.operation.name": "GET /",
    "ai.operation.syntheticSource": "SDKTelemetry",
    "ai.application.ver": "1.0.0.0",
    "ai.operation.id": "Oezb1HoAPP8=",
    "ai.internal.sdkVersion": "dotnet:2.2.0-54037"
  },
  "data": {
    "baseType": "MessageData",
    "baseData": {
      "ver": 2,
      "message": "AI: Diagnostic message: Performance counters are unavailable {snip!}",
      "properties": {
        "Tags": "API",
        "DeveloperMode": "true"
      }
    }
  }
}

Voila! I have my key used by AppInsights, and I can now setup replacement keys for staging/live in the appropriate tool (in my case Octopus).

Conclusion

This was a bit harder than I’d expected but I got a solution in the end. I can now use this initializer to allow me to define the AppInsights key in a more convenient spot.

I don’t have a code download for this – please feel free to cut & paste the code above into your project, and update the web.config file as required.

251 comments:

«Oldest   ‹Older   201 – 251 of 251
huraira said...

The thought behind tech-infused fashion is to mix the feel of customary fashion with the usefulness and development of technology.Tech-Infused Fashion

Amelia said...

Great tips Nutrition is key for a healthy pup. I always trust Debbies Dog Foodfor my dog’s meals. Check them out

cameronjammy said...

Kshetry And Associates is a trusted law firm in Kolkata, offering expert legal services across various practice areas with a commitment to delivering effective solutions for clients. Law Firm in Kolkata

cameronjammy said...

Kshetry And Associates is the best law firm in Kolkata, offering expert legal services with a proven track record of success in various practice areas. Best Law Firm in Kolkata

shadid-nathifa said...

Informative article! I’ll be sharing this with my network

Amelia said...

Nice information! Thank you. Visit Debbies Dog Food

Amelia said...

Nice blog! Thanks for sharing Visit Debbies Dog Food

Phone shark said...

PhoneShark.ae–The Most Trusted Mobile Repair Company in UAE:

onlineAssignmenthelp said...

Macquarie University is excellent at providing education, but assignment work is stressful. Don't wait until it's too late to worry about deadlines, research, or even formatting worries from The Tutors Help. Our expert writers make sure your assignments are of the highest academic standards and that you achieve top grades.
Therefore, if you require help with Macquarie University assignments, don't hesitate to contact The Tutors Help today and simplify university life!
https://www.thetutorshelp.com/macquarie-university-assignment-help.php

Macquarie University Assignment Help

onlineAssignmenthelp said...

Swinburne University students have challenging academic tasks, but with the right guidance, they can overcome giant battles. Whatever you need assistance with, be it essays, case studies, research papers, or technical assignments, The Tutors Help is here to make you a success.
Don't let homework chase you at night—call The Tutors Help today and enjoy improved grades and a successful learning experience!
https://www.thetutorshelp.com/swinburne-university-assignment-help.php

Swinburne University Assignment Help

onlineAssignmenthelp said...

University of New England provides excellent education but sometimes assignment stressful. You may be having trouble in research, writing, formatting, or comprehending complicated topics; relax; The Tutors Help is here at your fingertips to assist you.
With the help of The Tutors Help, you can submit assignments of better quality within time limit and secure good grades. Assignments need never bother you again—ask for instant UNE assignment help with The Tutors Help!
https://www.thetutorshelp.com/university-of-new-england-assignment-help.php

University of New England Assignment Help

onlineAssignmenthelp said...

UniSA campus life is great but too challenging on the academic front. If assignments are weighing you down, then you've come to the right place. Our expert services ensure that you receive your assignments done within deadlines, achieve good grades academically, and receive higher grades.
Reduce your concern regarding assignments—call The Tutors Help today and receive UniSA assignment professionalism at your doorstep!

https://www.thetutorshelp.com/university-of-south-australia-assignment-help.php
University of South Australia Assignment Help

onlineAssignmenthelp said...

Monash University assignments are tough, but you can do well in your studies with proper guidance. The Tutors Help aims to offer professional guidance to students so they can attain their academic goals without stress.
No more assignment stress! Call The Tutors Help today and receive professional Monash University assignment assistance.
https://www.thetutorshelp.com/monash-university-assignment-help.php
Monash University Assignment Help

onlineAssignmenthelp said...

Bond University students typically have to complete their assignments within given deadlines owing to academic pressure and time constraint. The Tutors Help guarantees quality support and production of quality, well-researched, and plagiarized-free assignments.
We welcome you to contact us at The Tutors Help anytime you desire quality assignment services from our experienced professionals. We can give assurance of academic success with us!

https://www.thetutorshelp.com/bond-university-assignment-help.php


Visit W3Schools.com!

onlineAssignmenthelp said...

Edith Cowan University provides excellent learning experience, but assignments at times become too daunting. If you are looking for professional assistance, The Tutors Help is here to assist you in providing researched, high-quality, and plagiarism-free assignments.
Worry no more with assignments! Contact The Tutors Help today and receive high-quality ECU assignment help to succeed at university.
https://www.thetutorshelp.com/edithc-cowan-university-assignment-help.php

Edith Cowan University Assignment Help

Gautam Mander said...

Nice post!

Fathima Shammas said...

Thank you! 😊✨ Stay tuned for more insightful posts! 🚀📖

Fathima Shammas said...

Thank you! 😊✨ Stay tuned for more insightful posts! 🚀📖
website: https://www.homegram.ae/real-estate-broker-for-rental/

cameronjammy said...

Digital Meta Squad is the best digital marketing agency, delivering innovative strategies, SEO expertise, and data-driven results to help businesses thrive online. best digital marketing agency

cameronjammy said...

Digital Meta Squa expert digital marketing manager crafts data-driven strategies to enhance brand visibility, drive traffic, and maximize online success. digital marketing manager

lara232 said...

Discover premium Italian footwear at Sergio Fabbri, your ultimate destination to shop scarpe crafted with elegance, quality, and timeless style. shop scarpe

lara232 said...

Sergio Fabbri offers a premium selection of borse online, combining Italian craftsmanship with modern elegance for stylish and functional bags available at your fingertips. borse online

Max Kingson said...

i dont see anythig for great information about this seoson visit my site. HVAC Company in North Miami

Max Kingson said...

Property dealers in Lahore specialize in real estate buying and selling, rentals, and investments, offering expert advice and the best property deals for residential and commercial clients.

Aditya Sachdeva Men said...

Discover the versatility of the bush coat, now available at half price! Explore how to style this unique garment for festivals, getaways, and more. Book your Appointment - 93199 39500 / https://www.adityasachdevamen.in/products/stylish-mens-bush-coat-elevate-your-look-with-timeless-fashion
Content Writer & SEO - Jai
All right reserved – Aditya Sachdeva Men https://www.adityasachdevamen.in

onlineAssignmenthelp said...

Brisbane university life may be challenging, but you don't have to face it by yourself. The Tutors Help is your study buddy whom you can trust for the best Brisbane assignment assistance. From difficult subjects to urgent deadlines, we are here to help you.

Chat with The Tutors Help now and make your study life easy and a joyful experience!
https://www.thetutorshelp.com/assignment-help-in-brisbane.php

Assignment Help in Brisbane

onlineAssignmenthelp said...

Assignments are a university student's way of life, but they should not be time-consuming and stressful. With The Tutors Help, you can have professional assistance for your assignment in Perth without wasting your precious time on deadlines and challenging work. We try to provide you with stress-free and effective learning experience.
Seek professional assistance for assignments in Perth by chatting with The Tutors Help today!
https://www.thetutorshelp.com/assignment-help-in-perth.php
Assignment Help in Perth

Services Providing Company said...

Tired of broken fridges and noisy washers taking over? We’re here to save the day with fast appliance fixes and handy solutions! Affordable, friendly, and oh-so-skilled, check out at Appliance repair service albuquerque and let’s get your home running smoothly together!

onlineAssignmenthelp said...

Studying in Auckland is a simply wonderful experience, but pressure to perform academically can be nerve-wracking. Students need not miss deadlines to complete their assignments and compromise on quality. We help with research, writing, or even editing, our professional team is always ready to assist you.
Worry less about homework—Chat with The Tutors Help today and gain professional homework assistance in Auckland and attain academic success with ease!

https://www.thetutorshelp.com/assignment-help-in-auckland.php

Assignment Help in Auckland

onlineAssignmenthelp said...

Academic success requires effort and good guidance. If you are a Los Angeles student who is struggling with homework, do not worry, you are not alone. The Tutors Help is always available to provide you with their assistance. The experienced tutors here will guide you through difficult lessons and enable you to turn in quality homework as needed.
Never let learning anxiety compromise your forward momentum. Chat with The Tutors Help today and gain access to the best in Los Angeles homework and assignment aid!

https://www.thetutorshelp.com/usa/assignment-help-louisiana.php

Homework and Assignment Help in Los Angeles

onlineAssignmenthelp said...

If you are a Victoriana student, Canada, and your work is proving difficult to accomplish, remember that you don't need to do it by yourself. It could be a difficult subject, a deadline, or just too little time, but The Tutors Help will assist you. We're dedicated to making sure that you pass your studies with ease.
Let us take the pressure off your shoulders. Chat with The Tutors Help today and get top-quality assignment help in Victoria, Canada. We’re here to make your academic journey smoother and more successful!
https://www.thetutorshelp.com/assignment-help-in-victoria.php
Assignment Help in Victoria, Canada

onlineAssignmenthelp said...

Homework and assignment assistance by The Tutors Help is extremely simple:
● Send Your Assignment: Send us the assignment details like topic, word count, deadline, and instruction if any.
● Get a Quote: We provide a genuine and reasonable price quote.
● Relax While We Do the Work: Our writers will begin working on your assignment immediately.
● Get Your Work: Submit your assignment in time and check it. We provide free revision as and when required.
Final Thoughts
In case you are a Toronto-based student with homework or assignment problems, do not panic. You are not alone and assistance is at your fingertips. The Tutors Help is here to provide you with expert assistance, quality assignments, and timely submission.
Let us assist you with your studies and ease your academic tension. Chat with The Tutors Help today for Toronto's finest homework and assignment help!

https://www.thetutorshelp.com/assignment-help-toronto.php

Assignment and Homework Help in Toronto

Ayurveda Tours India said...

thanks for showing interested content
Ayurveda Treatment In Rishikesh
Ayurveda Treatment In Kerala
Ayurveda Treatment In Goa
Ayurveda Retreats In India

onlineAssignmenthelp said...

Assignment takes up a considerable part of your work, but the assignments do not necessarily have to be stressful. If you are in Ireland and require help with assignments, help is at your disposal through The Tutors Help. We are dedicated to your success by helping you through presenting you with superior academic assistance that you can rely on.
Don't let challenging topics or tight timelines stand in your way. Chat with The Tutors Help today and get the best assignment assistance in Ireland — your academic achievement starts here!
https://www.thetutorshelp.com/assignment-help-in-ireland.php

Assignment Help in Ireland

onlineAssignmenthelp said...

As a Riyadh student with coursework or essay issues, you do not have to struggle. Tutors Help is with you in the shape of expert writing services that are affordable, quick, and of superior quality. Our ambition is to make your academic life simpler and more triumphant.
Chat with The Tutors Help today and receive assistance that will ensure you become a success in academics!
https://www.thetutorshelp.com/essay-help-in-riyadh.php

Essay and Coursework Help in Riyadh

huraira said...

In the computerized age, social media has turned into a prevailing power in communication, news distribution, and public talk.Fashions Mag

My Aesthetics said...

This article provided valuable insights; I appreciate the detailed explanation.​ botox nürnberg

onlineAssignmenthelp said...

If you are a student in Austria and struggling to finish your work, worry not. The Tutors Help is here to assist you step by step. If you need assistance in the area of research, writing, or even editing, our experts can be capable of assisting you.
We will assist you in saving time, lowering stress levels, and enhancing academic performance. Chat with The Tutors Assistance today and receive the perfect assignment assistance in Austria!
https://www.thetutorshelp.com/edu/assignment-help-in-austria.php
Assignment Help in Austria


onlineAssignmenthelp said...

Assignments are part of your learning, and they ought not to be scary. You are a Georgia student, and you can leverage our professional help to enhance your writing. You might be struggling to write, need editing assistance, or stuck on a topic that matters but is complex, and we are here to help you.
Don't wait till the eleventh hour. Chat with the The Tutors Help today for the best assignment assistance in Georgia and simplify your academic life!
https://www.thetutorshelp.com/edu/assignment-help-in-georgia.php
Assignment Help in Georgia


onlineAssignmenthelp said...

AutoCad Assignment Help
Need help with your AutoCAD assignment or homework? Get expert guidance to master 2D and 3D drafting, modeling, and design. Whether you're a beginner or advancing your skills, professional AutoCAD tutors can help you understand complex commands, improve accuracy, and complete your projects on time. With step-by-step assistance, you'll learn to create precise technical drawings, architectural plans, and engineering models using industry-standard practices. Support is available for students at all levels, ensuring quality results and improved performance. Don’t stress over deadlines—get reliable AutoCAD assignment help and boost your grades with personalized support tailored to your learning needs.
https://www.thetutorshelp.com/autocad-assignment-help.php
AutoCad Assignment Help

onlineAssignmenthelp said...

Cipd Assignment Help
Achieve high scores with the best CIPD assignment help from The Tutors Help. Our expert writers specialize in CIPD modules and ensure your assignments are well-researched, structured, and aligned with academic standards. Whether you're pursuing we provide tailored support to meet your specific needs and deadlines. With our professional guidance, you’ll gain a deeper understanding of HR concepts and improve your academic performance. Trust The Tutors Help for plagiarism-free, original content and round-the-clock assistance. Get the edge you need to succeed in your CIPD journey—contact us today for reliable and affordable assignment support.
https://www.thetutorshelp.com/cipd-assignment-help.php
Cipd Assignment Help

WEBMOK DIGITAL said...

Great blog Its amazing how author branding services can help writers stand out in a crowded market.

i am also good at blogs and digital marketing my website details are gives below.

website url - https://webmok.in/
contact no- 8684031003

onlineAssignmenthelp said...

If you are a Salalah student having problems with assignments, fret not. The Tutors Help is here to ease your academic journey. With professional guidance, punctual delivery, and low rates, we are your guide to academic success.
Get in touch with us today and receive the best assignment assistance in Salalah—fast, convenient, and hassle-free!
https://www.thetutorshelp.com/edu/assignment-help-salalah.php
Assignment Help Salalah



onlineAssignmenthelp said...

As a Manama student searching for expert assignment assistance, The Tutors Help will be the best option. We are dedicated to guiding you through academic milestones with ease, free of fear. From school assignments to university dissertations, we have full assistance custom-made according to your requirements.
So why not? Let The Tutors Help ease your student life. Chat with us today and benefit from the best assignment assistance in Manama at competitive rates!
https://www.thetutorshelp.com/edu/assignment-help-manama.php
Assignment Help Manama

Phone shark said...

Trusted iPhone repairs | trusted solution for your apple devices | iphone screen repair | screen replacement | battery replacement all at Phoneshark in dubai

EMed Healthtech Pvt. Ltd. said...

Solve problem through Healthcare Technology.

custom healthcare software development company

Anesha said...

Definitely worth a read, I’ll be recommending this to a few of my colleagues as well. https:/filmixcinema.me/movies

My Aesthetics said...

I’m considering Lippen aufspritzen Nürnberg, but I’m a little nervous about possible complications or risks. Has anyone had any issues or found that the results weren’t what they expected? Looking for some honest opinions before moving forward. lippen aufspritzen nürnberg

East Croydon Minicab said...

East Croydon Minicab offers reliable, affordable, and prompt private hire taxi services in and around East Croydon. Whether you're heading to the airport, commuting to work, or exploring the city, our experienced drivers and well-maintained vehicles ensure a comfortable and hassle-free journey. Available 24/7, we specialize in local and long-distance travel, airport transfers, and corporate bookings. With easy online and phone bookings, fixed pricing, and a strong focus on customer satisfaction, East Croydon Minicab is your trusted choice for dependable transportation.

Phone:+4402086862777
Website: https://expresscouriercars.co.uk/east-croydon-station-minicabs

Avlok - AVI International said...

Hi, my name isAvlok. Great blog post! I love how you explained everything so clearly. Definitely looking forward to reading more of your content!

huraira said...

In this in-depth article, we’ll examine what makes Selections Etc therefore fascinating, what types of things you can find.Fashions Mag

«Oldest ‹Older   201 – 251 of 251   Newer› Newest»