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.

61 comments:

www.rushmyessays.co.uk said...
This comment has been removed by a blog administrator.
Oliver Maurice said...

I think that you should definitely check out this site to get some info on how to write the essay in MLA format. This info will save you lots of troubles in the future

Helen Harper said...

This is a great post. I like this topic.This site has lots of advantage.I found many interesting things from this site. It helps me in many ways.Thanks for posting this again.
https://www.topessayservices.com/123helpme/

WritePaperFor Me said...

I love reading your articles. Thank you very much. Write more- https://writepaperfor.me/ .

PaperCoach. net said...

Nice article thanks for sharing. I write articles if it's interesting to visit my site- Papercoach net reviews.

Nancie L Beckett f said...

Are you feeling lost in this big complicated world of computer programming? Does the very thought of programming makes your heart skip a beat? Get the correct answers and explanations related to it with 24X7assignmenthelp JAVA SCRIPT HOMEWORK HELP so that in future there are no issues associated with it.

LennonJohn said...

Need Computer Programming Assignment Help? We provide Programming Assignment help service in Java, Python, C, C#, Php, C++ programming students assignments , Databases, SQL, HTML etc

domyhomework said...

Get Coding help from the best computer programming assignment help website in USA, UK & Australia. Quick & Best domyhomework computer science homework help

Pro Accounting Support said...

Very nice post, I just stumbled for your weblog and wanted to say that I’ve really enjoyed surfing around your blog posts, as they are highly knowledgeable. Read more QuickBooks Error 3371 and QuickBooks Proadvisor Support.

Assignment Help said...

Great site and a great topic as well I really get amazed to read this. It’s really good.For Assignment Help visit our site AllAssignmentHelp.

Students Assignment Help said...

Hire the writers of Students Assignment Help now, if you are facing difficulties in assignment help Auckland. The writers are expert in their respective field and possess enough knowledge. To hire our writers email us at info@studentsassignmenthelp.com or WhatsApp at +44-755-536-9184

Mihail377 said...

In the healthcare business, nurses are finding that individuals who have pursued an RN-BSN diploma program tend to be times prepared to proceed from traditional patient care to distinct roles in the health care sector. You can read more at http://coursework-writing-service.org/

Ada Smith said...

online stumbled upon online casino advertising, all kinds of slot machines And I was glad to click on the link to see such a cool design and everything is clear where and how to play and what to press merely online casino now this is my favorite site

Nathan William said...

Since this is very important and most students do not take the risk of writing their own CDR report. There hire CDR writing services to get the work done professionally. These services providers have professional and experienced Cdr Australia writers who do the job, correct them and give back a flawless report.
You will need to compose three distinct career episodes, each dealing with a professional project or task handled by you as an engineering professional CDR report writers. This section must have a detailed account of your role and application of problem-solving techniques for those projects.

Praylin S said...

Remarkable article! I really enjoyed the reading experience. Thanks for taking time to share this with us. Looking forward to learn more from you.
C C++ Training in Chennai
C Training in Chennai
Tally Course in Chennai
Tally Classes in Chennai
Embedded System Course Chennai
Embedded Training in Chennai
C C++ Training in Porur
C C++ Training in Adyar

cynthia williams said...

Learned a lot from your post and it is really good. Share more tech updates regularly.
AWS Training in Chennai
DevOps Training in Chennai
Angularjs Training in Chennai
RPA Training in Chennai
Blue Prism Training in Chennai
UiPath Training in Chennai
Data Science Course in Chennai
ccna Training in Chennai
R Programming Training in Chennai

cdraustraliahelp said...

The professional CDR Help Australia writers provide impressive and plagiarism-free quality report writing help online, and you can also download the CDR sample from our website. We also provide CDR Report Writing Help for the engineers at affordable prices. For more details, visit our website or direct mail at- support@casestudyhelp.com

Andrew Robert said...

Informative post! I enjoyed your all post. Thanks for taking the time to share the information with us. Are you looking CDR Writing Services for getting high-quality CDR Australia. In this case, No Worries! Our Experts is here to assist you. They will provide the best CDR Report Australia in the short of time. Also, for more information, you can go to our website.

Andrew Robert said...

Love to provide a significant post. I am waiting for the more new update, and I already read your recent post for many times. I appreciate your work. Thanks for sharing the excellent article. Also, We provide Online Assignment Writing Services in all countries. With the help of our experts, you can get sooner Marketing Assignment Help for getting good grades in your exam.
Also, visit our website:
CDR Report Australia
Economics Assignment Help
Computer Engineering Assignment Help
Case Study Assignment Help
Assignment Writers in Australia
MBA Assignment Help

Sophie Grace said...

Your work is very good and I appreciate you and hopping for some more informative posts tik tok video

Rob Martin said...

Get best Assignment Help by casestudyhelp.com. We have experienced team who provide 24/7 Live Chat with a solution, 100% plagiarism free work, and 100% satisfaction.
Online Assignment Help UAE
Online Assignment Help Australia
Online Assignment Help New Zealand E
Online Assignment Help Malaysia
Canada assignment help experts
Online Assignment Help Singapore
Online Assignment Help USA
Online Assignment Help UK

uae assignment help said...

Are you looking homework helper . then uaeassignmenthelp.com provide you that service. because our expert have analytics skill in essay writing . those have decades years experience. you take assignment help becuase you will skyrocket you grades. you can send an email info@uaeassignmenthelp.com

jenifer irene said...

Such an excellent and interesting blog, do post like this more with more information, this was very useful, Thank you.
Aviation Academy in Chennai
Air hostess training in Chennai
Airport management courses in Chennai
Ground staff training in Chennai

Andrew Robert said...

You are sharing the very informative and great post. It is effortless and easy to understand for me. Thanks for sharing the post. Moreover, we provide writing services for CDR Engineers Australia. For getting extra information about CDR Report Australia, you can visit our website.

Andrew Robert said...

You are sharing delightful post. It is effortless and easy to understand for me. Thanks for sharing the post. Moreover, our team provide Australian Assignment Help for all Australian universities. If you need urgent Online Assignment Help, then you can contact with them.

Domenic Tylor said...

Students need many times to essay help. So we provide essay help online service in Australia. We have many experts to write your essay easily. Experts have more than 15+ years of experience in the writing field. Book now at australiaassignmenthelp.com.

AmandaMorgan said...

You need to know that writing essays are a long and stressful process. It's not the same as to write a few paragraphs or sharing your thoughts. You need to follow some rules. the most difficult is history essay because you need to be well-prepared with this period in history. But the other way to find history essays online. You may read and analyze it and create your own or buy it online.

Dylan Eales said...

Sample Assignment bestows over the college going students with online assignment help. It is a consultancy possessing academic experts providing a number of subject-specific assignment helps. Marketing assignment help, economics assignment help, MATLAB assignment Help, MySQL assignment help, management assignment help, etc. are a few to name. The assignment help packages that they supply the students with ensure the students receive an HD or a full money back. With their assignment consultation services, the students can learn by exposing themselves to out-of-the-box learning when it comes to module related studies. For the quality of the in-depth research that is conducted before the experts at Sample Assignment lay their hands on a specific assignment, the prices are kept very close to the ground while the company has its head touching the sky. They offer services in Essays, CDRs, Resumes, Thesis, Research Proposals, Research Papers, Dissertations, etc. Be it any of the above, they provide ready to study from assignment solutions to the students who work-save in order to pay for the service and the online assignment services provider works on the motive of giving out value for every coin a particular student pays for the online assignment help Australia. With their Partial Payment and the optional feature of Countless Revisions, they have earned themselves two consecutive years of recognition.

cdrengineeraustralia said...

A wonderful post and a great opinion! If anyone depressed about the problems of CDR Australia writing, please visit MyCDRAustralia.Com for better solutions.
More Information Links-
CDR Australia
CDR Australia Services
CDR Australia Help
CDR Australia Writers
CDR Australia Samples
CDR for Migrants
CDR Help for Electrical Engineers
CDR Australia Blog
CDR Australia Reviews

Bernard Cypher said...

COPE TECHS is an organization of Technology experts🖥️💻 with the aim to help individuals with solving Technology difficulties. We offer the best hacking services as well as our aim is not for Theft purpose but to help individuals overcoming Technology issues with our skills.

✴️For example-: There are so many individuals out there who owe a lot of debts💶💷 to Banks and other Loan Firms and are working hard 🛠️⚒️to pay back but really can't pay. That's were our services can help you, we have a way of generating Bitcoin and funding it into a PayPal account and by this you can pay your debts.

✴️Another Example of our service-: A Man or Woman who suspects his/her Spouse of Cheating but have no prove, we could help by HACKING the Spouse Cell phone📱 so he/she could get access to Chats, Emails📩, Location📍, Phone calls 📞and text message✉️ of the Spouse anywhere they are.

✴️We also Help student in Universities/College/High Institute📚 in changing their Grades/results saving them from repeating exams and giving them a better Degree.
Other services we offer are-:
✴️Clearing of Bad Records from Courts and Police facilities.
✴️ Detection of weakness in Computer system security⚛️
✴️Funding a PayPal account💷💵
✴️Cyber Attacks☣️ and lots more
Put this on your mind, "AS LONG AS IT'S TECHNOLOGY, IT CAN BE HACKED"
We belong to the HACKERS forum HackerOne and we have the Top hackers in the forum always ready to take the risk and do a job. If you need hacking Services, contact-: COPETECHS@GMAIL.COM
We look forward to hacking for you.

cdraustraliahelps said...

Thank you for sharing such good and useful Information with us and the article was too good. We provide assignment writing help for all academic subjects with 100% plagiarism free and good quality work.
Quick Links-
Assignment Help Malaysia
Assignment Help Canada
Assignment Help Australia
Assignment Help UK
Assignment Help UAE
Assignment Help Ireland
Assignment Help Singapore
Assignment Help USA
Assignment Help NZ

iphongthuynet said...

datxoichecom

iphongthuy.net said...

iphongthuynet
iphongthuynet
iphongthuynet
iphongthuynet
iphongthuynet
iphongthuynet
iphongthuynet
iphongthuynet
iphongthuynet

Scarlet Klark said...

Academic writing is clear, concise, focussed, structured and backed up by evidence. Its purpose is to aid the reader’s understanding.
It has a formal tone and style, but it is not complex and does not require the use of long sentences and complicated vocabulary.
Each subject discipline will have certain writing conventions, vocabulary and types of discourse that you will become familiar with over the course of your degree. However, there are some general characteristics of academic writing that are relevant across all disciplines.
Read more about academic writing at Personal Statement Example

Exclusive Limousines said...

Thanks for sharing great info … Hiring a limousine are excellent option to make your special occasion more delightful. Limo Hire MelbourneHummer Hire Melbourne.

Assignment Help said...

This is really a good source of information, I will follow it to know more information and expand my knowledge, I think everyone should know it.
Assignment help

Hary Robert said...

Wonderful article… Thanks for sharing such useful article... melbourne limo hire | black limousine hire

Emma18 said...

That is why if you are a student and you need to write a term paper, we are here for you. you may be sure that this writing service will render you the necessary help at any time.

Andrew Robert said...

You are sharing a fantastic blog. It is straightforward to understand for anyone. Thank you so much for sharing the post. Moreover, I am a writer at No1AssignmentHelp.com where our team provides No 1 Assignment Help for all Australian universities. If you need any writing services, then you can connect with us.

lindanorwood said...

Thanks for sharing this. I think I would be able to write a course paper concerning this topic. However, I am so busy that I might not have enough time for this, so maybe I will buy course work and ease the process.

Andrew Robert said...

You are sharing a fantastic blog. It is straightforward to understand for anyone. Thank you so much for sharing the post. Moreover, I am a writer at No1AssignmentHelp.com where our team provides No 1 Assignment Help for all Australian universities. If you need any writing services, then you can connect with us.

Shainesh said...

Informative post. Thanks for sharing a wonderful post. car hire melbourne airport | car rentals melbourne 

Nino Nurmadi said...

Indonesia
lampungservice.com
lampung
lampung
info lampung
lampung
Indonesian
lampung

meldaresearch said...

You need not to worry any more, we are here to offer you the best academic writing
Solutions; order quality best writing service from us and learn how to purchase term paper today!

meldaresearch said...

Nursing Students always find out the best research paper writing services in usa since its very difficult because they require extensive research and most students lack the appropriate skills of researching. Students also seek help of top custom essay services.

cdrengineeraustralia said...

Great post! Thanks for sharing such a great article. If anyone needs CDR writing services to migrate to Australia, please visit our website or click this link- My CDR Australia

meldaresearchusa said...

Our best original essay writing service are focused on making your life in school smooth and enjoyable in comparison to what you might be going through at the moment. Seek services of cheap term papers today!

meldaresearch said...

One should know which company has the best writers whose essay is free from grammatical errors. Grammatical errors reduce the quality of a custom paper especially those who want to buy nursing papers online and those seeking for custom assignment services.

cdraustraliahelp said...

You have shared delicate information through your post. It is effortless and easy to understand for everyone. I appreciate your hard work. By the way, I am a writer. Our team provides immediate and quality writing services for CDR Engineers Australia. If anybody wants to get assistance, then they can connect with our team. Also, for more information, you can visit our website.

meldaresearch said...

In order to support the sections in the purchase term paper process, the student should only choose recent sources. The sources used should not be more than ten years old as they might be invalid. We have the best research papers help services since writers are available 24/7 to complete your custom research paper services.

Andrew Robert said...

Excellent post! You are sharing appropriate information with us. I am a big fan of your writing skills and appreciate your work. Also, I am an assignment writer at No1AssignmentHelp.com. Here, we offer No 1 Assignment Help for all academic courses. If you need any help, then you can contact our experts and get instant Assignment Writing Services.

Uylis Mecihok said...

The subject of Philosophy and its subcategories have been widely discussed in both the Western and non-Western world albeit with different focuses. Philosophy includes many different subfields involving investigation into our existence. These subfields include epistemology, ethics, logic, metaphysics, philosophy of science, social and political philosophy, and Metaphilosophy. Epistemology focuses on the study of Knowledge, also known as “Theory of Knowledge”. Ethics involves the study of moral values and rules, Logic; the study of reasoning. Metaphysics is the study of being and knowing also known as the principles of reality. Read more at http://writeacoverletters.com
One of the first points to be clear about is that a philosophical essay is quite different from an essay in most other subjects. That is because it is neither a research paper nor an exercise in literary self-expression. It is not a report of what various scholars have had to say on a particular topic. It does not present the latest findings of tests or experiments. And it does not present your personal feelings or impressions. Instead, it is a reasoned defense of a thesis.

Joson Froster said...

If you feel that you need help when it comes to writing sociology papers then we could help you. Here at http://term-paper-writing-service.com/ we have some of the best professional writers that are ready and waiting to make your academic writing very much easier. In fact, we can take all the stress and hard work out of writing, so that you are free to get on with whatever else you choose to do

You may decide to try and buy a sociology research paper online somewhere but you need to be aware of some things. Those sites will offer sociology papers for sale but they have been sold to hundreds of other people. You have no idea where those papers came from and who wrote them. You do not know the academic level of the writer and chances are you will have to spend time tweeking the paper to your professor’s specifications. For that kind of hassle you might as well just write the paper yourself.

Sophia Thomas said...

This is really a great stuff for sharing. I appreciate your efforts, keep it up. Thanks for sharing...
My Assignment Help

Andrew Robert said...

Informative Stuff! I truly value the sort of points you post here. Your post is straightforward and pleasant to read, made without complicated terms and phrases. Also, I am a writer at No1AssignmentHelp.com. Here, we offer Assignment Help UK at lowest rates. If you are looking assignment writing help, then you can connect with us.

MyAssignmentHelp said...

Do you desperately need Amway Case Study? Does writing a remarkable McDonalds Cases Study seem too daunting for you? Opt for the Amway Case Study Help from MyAssignmenthelp.co.uk, and witness a huge difference in your grades. MyAssignmenthelp.co.uk is your one-stop destination if you want to avail brilliant McDonald’s Case Study Solution.

cdraustraliahelp said...

You have shared delicate information through your post. It is effortless and easy to understand for everyone. I appreciate your hard work. By the way, I am a writer. Our team provides immediate and quality writing services for CDR Engineers Australia. If anybody wants to get assistance, then they can connect with our team. Also, for more information, you can visit our website.

AssignmentWritings.Com said...

Thanks for sharing this knowledgeable blog with us, truly a great informative site. It is very helpful for us. Also, we are providing online assignment help. If you need instant Assignment Writing help, then contact our team of writers. Also, for more information, you can visit our website.

Snega Bondato said...

Our accounting homework help is the best homework providing company. We believe that our homework plays an important role in the final grades of students. Due to several reasons, students are unable to write accounting homework. Accounting homework requires http://dohomeworkfor.me/ remarkable knowledge as well as in-depth understanding of the accounting concepts. Students should get our accounting homework help at our company’s website.

Biology, the study of life, can be fascinating and wondrous. However, certain biology topics can sometimes seem incomprehensible. The best way to get a clear understanding of difficult biology concepts is to study them at home, as well as at school. Students should use quality biology homework help resources when studying. Below are some good resources and information to help you answer some of your obilogy homework questions.

Adam Thomas said...

Thanks for sharing this wonderful post which is very informative.
Assignment Help
Java assignment help

assignmenthelpaus said...

Thanks for sharing this information! It was nice. Many of the people are depressed about the problems of Assignment writing. Well, don’t worry about that because we are providing Assignment Help Australia for students. For more information, visit our website- Assignmenthelpaus.com
Read Our Blog Here- Assignmenthelpaus.com Blog