Você está na página 1de 6

AzureCon Challenge

Integrating App Insights into your apps


Overview
Many times as developers, we launch applications into production and wash our hands clean of the project. The operations team is stuck with a web
solution and few ways to monitor it. Web analytics promises to open up deep insights into the way your application works, to accomplish many goals
such as; driving business and marketing decisions, alerting operations to abnormal behavior, tracking down edge-case bugs and even providing a
quantifiable base for scaling decisions
Application Insights is an extensible analytics service that helps you understand the performance and usage of your live application. It's designed for
developers, to help you continuously improve the performance and usability of your app. It works with both web and stand-alone apps on a wide variety
of platforms: .NET or J2EE, hosted on-premises or in the cloud; device apps on Windows, iOS, Android, OSX and other platforms.
For this challenge, you will use Application Insights to collect client-side (JavaScript) telemetry for your HTML5 web application. You will collect general
HTTP request metadata and user-specified custom events.

1. Login to Azure
For this challenge, you have either elected to use your own subscription or have created a new Azure
subscription using the provided Azure Pass (or Free Trial). If you want to switch to use the provided Azure
Pass the promotion code is displayed on the My Account page on the http://challenge.azurecon.com
web site. If there is no promo code displayed, you will need to use the free trial http://azure.microsoft.com/pricing/free-trial.
Azure has TWO management portals - the classic portal (http://manage.windowsazure.com) and a new
portal that is in Preview at http://portal.azure.com. You will use the Preview portal in this challenge.
1.

Open a browser and go to http://portal.azure.com

2.

Enter your Microsoft Account email address and password for the Microsoft Account you
associated with your Azure Pass or your own subscription.

3.

You will now be in your Azure subscription (see opposite) and from here you can create and
manage Azure services.

2. Create Azure Web App and Application Insights Resources


You will now create a Resource Group with a Web App resource and an Application Insights resource.
1.

Create your Web App, click + NEW -> Web + Mobile -> Web App

2.

For the name field, use a globally unique name. Suggest you use your email alias prefix plus webappinsight so if your email was bsmith@contoso.com you would use bsmith-webappinsight

3.

For the resource group field, create a new resource group with the name AppInsight.

4.

Click on App Service Plan and select Create New

5.

Use AppInsightASP as the plan name. Select ANY location and leave the S1 pricing tier the default. Click
OK

6.

For the App Service Plan field, create a new App Service Plan using the Free pricing tier, the name and
location do not need to be any specific value.

7.

Ensure that the Pin to Startboard checkbox remains selected (It is selected by default).

8.

Click the CREATE button.


The blade for your Web App will open automatically after 30-60 seconds.

9.

Click the Tools button at the top of the Web App blade.

10. On the Tools blade, select the Extensions option (at the bottom).
11. On the Extensions blade, click ADD (on the blade header at the top).

Page | 1

12. You need to choose an extension first SELECT Visual Studio Online and then click the OK button to Accept Legal Terms and then OK again
on the Add web app extension blade. After a few seconds, you will see the extension appear in your list of installed extensions.

13. Click the Visual Studio Online extension and then click the BROWSE button. A new browser
opens and after 10-20 seconds you will see the Visual Studio Online Monaco code editor we
will refer to this as Monaco. This is a lightweight, simple code editor integrated right into the
Portal. At the top left, you will see the only file on your web server hostingstart.html this is
the default page for your web server.

3. Deploy the Demonstration Application to the Web App using Visual Studio Monaco
You will now deploy the demonstration web application to your Web App instance using the Visual Studio
Monaco extension. This simple HTML5 application demonstrates features of Bootstrap
(http://getbootstrap.com/), Font Awesome (http://fontawesome.io/) and Chart.js (http://www.chartjs.org/).
This sample application is an incident management system used to view metrics about customers and to see
their latest tickets. Fortunately for you, this site is already implemented.
1.

In the Monaco editor, right-click the hostingstart.html file, select DELETE and then click OK.

2.

Hover your cursor on the WWWROOT line and click the New Document icon.

3.

In the name text box, enter index.html (it is important that you name the file exactly this!)

4.

Now you need to write the HTML and JavaScript to implement this web page. Heres the code to copy/paste right into your editor in Monaco.
The code is minified to a single line to make it easier for you to copy the code. You can always use a Unminifier website if you wish to learn
how the web page works. Copy and Paste this code into the editor for the index.html file.
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible"
content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Admin Home</title> <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/bootswatch/3.3.5/united/bootstrap.min.css" rel="stylesheet"> <link
href="//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"> <style
type="text/css"> canvas.chartjs{width: 100% !important;}</style> </head> <body> <ul class="breadcrumb"> <li
class="active" href="#">Home</li></ul> <div class="container-fluid"> <div class="row"> <div class="col-sm-3 colmd-2"> <ul class="nav nav-pills nav-stacked"> <li class="active"> <a href="/index.html"> <i class="fa fahome"></i>&nbsp;Home </a> </li><li> <a href="/tickets.html"> <i class="fa fa-tachometer"></i>&nbsp;Tickets<span
class="pull-right badge">~&nbsp;5</span> </a> </li></ul> </div><div class="col-sm-9 col-md-10"> <h1>Fabrikam
Video Service</h1> <div class="alert alert-dismissible alert-warning"> <button class="close" type="button" datadismiss="alert"></button> <h4>Warning!</h4> <p> A larger than average number of customers have reported issues
within the last 24 hours. Please view issues on the <a class="alert-link" href="/tickets.html">Ticket
Portal</a>. </p></div><h3>Analytics Highlights</h3> <div class="row"> <div class="col-sm-6 col-md-4"> <div
class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title"><i class="fa fausers"></i>&nbsp;&nbsp;Online Users by Browser</h3> </div><div class="panel-body"> <canvas id="piechart"
class="chartjs"></canvas> </div></div></div><div class="col-sm-6 col-md-4"> <div class="panel panel-primary">
<div class="panel-heading"> <h3 class="panel-title"><i class="fa fa-graduation-cap"></i>&nbsp;&nbsp;Popular
Courses (<span id="monthEntry"></span>)</h3> </div><div class="panel-body"> <canvas id="barchart"
class="chartjs" ></canvas> </div></div></div><div class="col-sm-6 col-md-4"> <div class="panel panel-primary">
<div class="panel-heading"> <h3 class="panel-title"><i class="fa fa-tablet"></i>&nbsp;&nbsp;Consecutive Viewers
by Hour</h3> </div><div class="panel-body"> <canvas id="linechart" class="chartjs" ></canvas>

Page | 2

</div></div></div></div></div></div></div><script
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script
src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <script
src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script> <script
src="/aiconfig.js"></script> <script type="text/javascript">Chart.defaults.global.responsive =
true;Chart.defaults.global.animation = false;Chart.defaults.global.maintainAspectRatio =
true;$(document).ready(function
(){$("span#monthEntry").html(["January","February","March","April","May","June","July","August","September","Oct
ober","November","December"][new Date().getMonth()]); var date=new
Date,hourLabels=[];hourLabels.push(date.getHours()+":00"),date.setHours(date.getHours()3),hourLabels.push(date.getHours()+":00"),date.setHours(date.getHours()3),hourLabels.push(date.getHours()+":00"),date.setHours(date.getHours()3),hourLabels.push(date.getHours()+":00"),date.setHours(date.getHours()3),hourLabels.push(date.getHours()+":00"),date.setHours(date.getHours()3),hourLabels.push(date.getHours()+":00"),date.setHours(date.getHours()3),hourLabels.push(date.getHours()+":00"),hourLabels.reverse(); new
Chart($("canvas.chartjs#piechart").get(0).getContext("2d")).Doughnut([{value:0.52,color:"#F7464A",highlight:"#FF
5A5E",label:"Internet Explorer"},{value:0.29,color:"#46BFBD",highlight:"#5AD3D1",label:"Google
Chrome"},{value:0.19,color:"#FDB45C",highlight:"#FFC870",label:"Mozilla Firefox"}],{}); new
Chart($("canvas.chartjs#barchart").get(0).getContext("2d")).Bar({labels:["C#","Ruby","F#","JS"],datasets:[{fillC
olor:"rgba(220,220,220,0.5)",strokeColor:"rgba(220,220,220,0.8)",highlightFill:"rgba(220,220,220,0.75)",highligh
tStroke:"rgba(220,220,220,1)",data:[48000,26000,80500,65000]}]},{}); new
Chart($("canvas.chartjs#linechart").get(0).getContext("2d")).Line({labels:hourLabels,datasets:[{fillColor:"rgba(
151,187,205,0.2)",strokeColor:"rgba(151,187,205,1)",pointColor:"rgba(151,187,205,1)",pointStrokeColor:"#fff",poi
ntHighlightFill:"#fff",pointHighlightStroke:"rgba(151,187,205,1)",data:[280,380,600,1900,1586,1227,905]}]},{});}
); </script> </body></html>
5.

No need to Save your changes, Monaco automatically detects when the file is dirty (has changes) and saves it for you.
Now we need to create a second file. We will follow the same steps to create a tickets.html file to represent the Tickets page on our web
application.

6.

In the Monaco editor, click the New Document icon again.

7.

In the name text box, this time enter tickets.html (it is important that you name the file exactly this!)

8.

Now you need to write the HTML and JavaScript to implement this web page. Heres the cope to copy/paste right into your editor in Monaco.
The code is minified to a single line to make it easier for you to copy the code. You can always use a Unminifier website if you wish to learn
how the web page works. Copy and Paste this code into the editor for the tickets.html file.
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible"
content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Admin Dashboard</title> <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/bootswatch/3.3.5/united/bootstrap.min.css" rel="stylesheet"> <link
href="//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"> <style
type="text/css"> canvas.chartjs{width: 100% !important;}</style> </head> <body> <ul class="breadcrumb"> <li><a
href="/index.html">Home</a></li><li class="active" href="#">Tickets</li></ul> <div class="container-fluid"> <div
class="row"> <div class="col-sm-3 col-md-2"> <ul class="nav nav-pills nav-stacked"> <li> <a href="/index.html">
<i class="fa fa-home"></i>&nbsp;Home </a> </li><li class="active"> <a href="/tickets.html"> <i class="fa fatachometer"></i>&nbsp;Tickets<span class="pull-right badge">~&nbsp;5</span> </a> </li></ul> </div><div
class="col-sm-9 col-md-10"> <h1>Tickets Dashboard</h1> <a id="refreshButton" class="btn btn-primary btn-sm pullright" href="#"> <i class="fa fa-refresh"></i>&nbsp;Refresh </a> <i id="loadingIndicator" style="display: none;
position: absolute;" class="fa fa-refresh fa-spin fa-5x"></></i> <table id="customersTable" class="table tablestriped table-condensed"> <thead> <tr> <th>Customer #</th> <th>Name</th> <th>Issue</th> <th>E-mail Address</th>
<th>Subscription Type</th> </tr></thead> <tbody> </tbody></table> </div></div></div><script
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script
src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <script
src="/aiconfig.js"></script> <script src="/aievent.js"></script> <script
type="text/javascript">$(document).ready(function (){var customers=[{"Id":1,"Name":"Orlando
Gee","EmailAddress":"orlando0@adventure-works.com","SubscriptionType":"Enterprise"},{"Id":2,"Name":"Keith
Harris","EmailAddress":"keith0@adventure-works.com","SubscriptionType":"Complimentary"},{"Id":3,"Name":"Donna
Carreras","EmailAddress":"donna0@adventure-works.com","SubscriptionType":"Retail"},{"Id":4,"Name":"Janet
Gates","EmailAddress":"janet1@adventure-works.com","SubscriptionType":"Enterprise"},{"Id":5,"Name":"Lucy
Harrington","EmailAddress":"lucy0@adventureworks.com","SubscriptionType":"Complimentary"},{"Id":6,"Name":"Rosmarie
Carroll","EmailAddress":"rosmarie0@adventure-works.com","SubscriptionType":"Retail"},{"Id":7,"Name":"Dominic
Gash","EmailAddress":"dominic0@adventure-works.com","SubscriptionType":"Enterprise"},{"Id":10,"Name":"Kathleen
Garza","EmailAddress":"kathleen0@adventureworks.com","SubscriptionType":"Enterprise"},{"Id":11,"Name":"Katherine
Harding","EmailAddress":"katherine0@adventure-works.com","SubscriptionType":"Complimentary"}]; function
addRandomCustomer(isNew){var customer=customers[Math.floor(Math.random()*customers.length)];var issue="Your site
is broken!";var
row=$("<tr>");if(isNew){row.addClass("success");}row.append($("<td>").text(customer.Id)).append($("<td>").text(c
ustomer.Name)).append($("<td>").text(issue)).append($("<td>").text(customer.EmailAddress)).append($("<td>").text

Page | 3

(customer.SubscriptionType));$("table#customersTable tbody").append(row);}for (i=1; i <=6;


i++){addRandomCustomer(false);}$("a#refreshButton").click(function(){$("table#customersTable > tbody >
tr").removeClass("success"),$("i#loadingIndicator").fadeIn(),$("table#customersTable").fadeTo(500,.25,function()
{setTimeout(function(){"function"==typeof
createCustomEvent&&createCustomEvent();addRandomCustomer(!0);$("i#loadingIndicator").fadeOut(),$("table#customer
sTable").fadeTo(500,1)},1e3)})});}); </script> </body></html>
Now we can test our application. We will browse to the application directly from Visual Studio
Monaco.
9.

Click the Run button on the left navigation bar. This button will have an arrow icon.
You should now see the sample application, feel free to interact with the charts, close the
warning banner on the home page, view the tickets and even click a button to refresh the tickets
list.

4. Implement Application Insights Simple Page


Tracking
Now that you have a running sample application with multiple pages lets add basic page tracking to the
application. You could add JavaScript to each page individually, but we will use a separate JavaScript file
that is shared between the pages.
1.

Go back to the Azure Portal tab in your browser and the currently open Web App blade. You
can close the blades related to Tools and the Visual Studio extension.

2.

In the Web App blade click the link to the appinsight resource group.

3.

In the Resource Group Summary panel, click the App Insights resource (light blub/globe icon)
it will have the same name as your webapp.
At this point you have not configured client-side instrumentation yet and will not see any metrics in Application Insights.

4.

Expand the Essentials panel on this blade and copy your Instrumentation Key to the clipboard.
This key will be used in your JavaScript code to send your metrics to the correct Application Insights instance.

5.

Go back to the Visual Studio Monaco tab in your browser.

6.

Click the New Document icon again.

7.

In the name text box, this time enter aiconfig.js (it is important that you name the file exactly this!)

8.

Start by creating your first line of JavaScript in the file. Type this JavaScript into your file:
var instrumentationKeyValue = "XXX";

9.

Replace XXX with your key you recorded in the previous steps.

10. You are now going to copy and paste the code necessary to connect to Application Insights. The code is minified to a single line to make it
easier for you to copy the code. You can always use a Unminifier website if you wish to learn how the script works. In the next line in the
editor, Copy and Paste the following script:
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.m
secnd.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

Page | 4

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:instrumentationKeyValue});window.appInsights=appInsi
ghts;
11. Now that you have configured Application Insights, you will add one more line of code to actually track that you have viewed the current page.
On a new line, Copy and Paste this JavaScript code into your file:
appInsights.trackPageView();
12. Once you are done, your code should look similar to this (the application has been magnified to make it easier to see):

13. Switch back to your browser showing the sample app (or click RUN button in Monaco on the left if you closed the browser).
14. Make sure to refresh your pages, visit both pages multiple times (we recommend 10+) and click on as many links as possible in the application
to send as much client-side telemetry to Application Insights as possible.
15. Go back to the Azure Portal tab in your browser.
16. You should see the Application Insights blade that you previously visited showing
metadata about your Browser Page Load times (you may have to open and close this
blade to refresh it quickly).
If you do not see this immediately, you can either click the Refresh button, modify the
Time Range or wait 2-3 minutes to see your information. Metrics are typically shown
within 2-5 minutes.
17. Click on the Browser Page Load chart to see more detail.
18. Back on the Application Insights blade, click on the Sessions tile to learn about the
Operating Systems viewing your web application.

19. Back on the Application Insights blade, click on the Page views tile to view the Activity by Page Name.

The metrics shown here are client-side telemetry that is captured from the browser and sent to Application Insights. Application Insights can also
capture server-side telemetry such as your applications performance, exceptions and custom counters. To learn more about this functionality, you can
view this web page: https://azure.microsoft.com/en-us/documentation/articles/app-insights-overview/

Page | 5

5. Implement Application Insights Custom Event Tracking


Your first task is to login to Azure. From your Session, open a browser the Azure web site will open.
1.

Go back to the Visual Studio Monaco tab in your browser.

2.

Click the New Document icon again.

3.

In the name text box, this time enter aievent.js (it is important that you name the file exactly this!)

4.

You will now create a function for the other pages to call if they want to track a custom event. On the tickets.html page, the JavaScript code
looks for this function and calls it every time you refresh your tickets. In Application Insights we can see (using a custom metric) how many
times people are refreshing the tickets and make decisions based on this data. Copy and Paste this JavaScript into your file:
function createCustomEvent() {
appInsights.trackEvent("User List Refreshed");
}

5.

Once you are done, your code should look similar to this (the application has been magnified to make it easier to see):

6.

Switch back to your web app and start testing.

7.

Go to the Tickets page and refresh the table by clicking the Refresh
button multiple times, you will see a spinning indicator when the
application looks for new tickets and refreshes the table. New tickets
will appear.

8.

Go back to the Azure Portal tab in your browser.

9.

You should see the Application Insights blade that you previously
visited (you may have to open and close this blade to refresh it quickly).

10.

Scroll-down and click on the Custom Events tile. If you see this is NOT
CONFIGURED just wait a few minutes for the events to come in.

11.

You should now see a new blade showing telemetry for your custom-created event.

Using custom events, you can track any information you want from any language you want to enable
deeper insight into the behavior and operations of your web applications.

--- END OF LAB --Go back to the AzureCon Challenge web site (http://challenge.azurecon.com) and complete the challenge question to get your points.
REMEMBER: You only have one chance at the question, make sure you really know the answer!

Page | 6

Você também pode gostar