Tag Archives: CodeProject

Application Insights User Guide

First step is Log-in to https://portal.azure.com/

In the left pane Click on Browse option, then select Application Insights then Application Insights sources will display and choose your Application Insights source

clip_image002

This is how your Application Insights Dashboard will look like

clip_image004

The Dashboard includes the following Items

1. Essentials

2. Application Overview

3. Metrics Explorer

4. Sessions

5. Crashes

6. Custom Events( If you create any)

7. Top Sessions by Country

8. Top Devices

9. Session Duration

10. Top Crashes

11. Diagnostic Search

12. Alert Rules( If you create any)

13. Events

Essentials

It contains the information about the Application Insights resource which includes Resource group, Application Type, Location, Subscription name, Instrumentation Key (Which is the Key for Telemetry data) and Subscription id.

clip_image005

Application Overview

It contains the Graphical Representation of USERS, SESSIONS, PAGE VIEWS, and CRASHES data

clip_image007

Users

Click on Users to view USERS data

clip_image009

It displays the Total no of Users and New Users and it also displays the users by Geographic location which is unique count of users by country or region.

If you click on USERS chart, you can customize the chart as per your needs. You can show it like Line, Area, Bar and Grid. You can add Chart Height, Add Grouping and do many more.

clip_image011

If you want to look at what are all the activities performed by United States region app users, then click on United States, it will display all the actions performed by the users which contains number of PAGE VIEW, CUSTOM EVENT, EXCEPTION, REQUEST AND DEPENDENCY.

clip_image013

If you click on any activity it gives more information regarding the user and much more information. Below picture includes all the information.

clip_image015

If you want to know more information just click on ‘…’ button it will give you more information.

clip_image017

clip_image019

You can add filters in the Chart to get the specific results as per your required criteria.

clip_image021

You can specify a Time range to see the results data in a particular time period.

clip_image023

Add Save Favorite

You can add favorites to your dashboard so that you can quickly view the favorite items.

clip_image025

You can view the favorite’s items in your dashboard.

clip_image027

Page Views

This segment contains the total number of page views of your app. If you want to see more about Page Views just click on PAGE VIEWS in the Application Overview.

clip_image029

In PAGE VIEWS section it also contains the information about all the pages in the app and the number of page views, number of users and the number of sessions for each page.

clip_image031

If you click on any Page name it will gives you more information about the specific page you selected.

clip_image033

If you click on any particular page view it will give you more information about the page from where it has been accessed and the client IP address.

test

If you click on ‘…’ then you will get more information

clip_image037

Here also you can Add chart, Time range, Filters, Alert Rules, Save favorites.

clip_image039

Sessions

A session is nothing but the amount of time used an app by the user.

It contains all the session information about the app that has been using by the users. Session includes the time

clip_image041

Custom Events

Custom events are created by developer. By inserting code to send custom events from your app, you can track your users’ behavior and the usage of specific features and scenarios.

clip_image043

If you select any Custom event it will give you more information about the specific Custom event metrics.

clip_image045

If you click on any custom event it will navigates to Custom Event properties windows and if you click on All telemetry for this user session under Related Items it will give you more results.

clip_image047

clip_image049

There is 1 Exception in the results, if you click on the it will give you the exception properties which contains more info about the exception which includes the information in the given picture.

clip_image051

Top Sessions by Count.

It will give the overall view of your app users in the different country across the world.

clip_image053

Top Devices

It will give you the top devices of customers which are using your app.

clip_image055

If you click on any device it gives more information about the operations performed by the device, which includes the number of users, number of sessions, session duration and the crashes count if there are any. It will locate the country or region of the device.

clip_image057

Diagnostic Search

It includes all the information of application at one place.

clip_image059

Alert Rules

Using Alert Rule you can track whenever there is any huge traffic or if any exception occurs in the app. There are certain types of metrics that you can create alerts for them. If there is smoothing happens as specified in the metrics for that alert it will notify to the email id which was given during the creation of alert.

clip_image061

Application insights for Windows Phone and Store apps

Azure Application Insights lets you monitor your published Mobile apps

Requirements:

  • A subscription to Microsoft Azure
  • Visual studio 2013 or later

Create an Application Insights resource

Log in to your azure portal.

In the azure portal, create a new Application Insights resource.

clip_image002

Select Application Type as Windows Phone Application (here you can choose in whichever the application you want to implement Application Insights, In my case it is Windows Phone Application)

clip_image004

Click on Create Button, It will create the Application Insights resource. A resource in Azure is an instance of a service. This resource is where telemetry from your app will be analyzed and presented to you.

Copy the Instrumentation Key

The key identifies the resource. You’ll need it soon, to configure the SDK to send the data to the resource.

clip_image005

Add the Application Insights SDK to your apps

In Visual Studio, add the appropriate SDK to your project.

If it’s a Windows Universal app, repeat the steps for both the Windows Phone project and the Windows project.

Right-click the project in Solution Explorer and choose Manage NuGet Packages.

clip_image006

1. Select Online, Include prerelease, and search for “Application Insights”.

clip_image008

2. Pick the latest version of the appropriate package – one of:

  • Application Insights for Windows applications – for Windows Phone and Store apps
  • Application Insights for Web Apps
  • Application Insights API – for Windows desktop apps

3. Edit ApplicationInsights.config (which has been added by the NuGet install). Insert this just before the closing tag

Code Snippet
  1. <InstrumentationKey>the key you copied</InstrumentationKey>

Windows Universal apps: Repeat the steps for both the Phone and the Store project.

clip_image010

Enable network access for your app

If your app doesn’t already request outgoing network access, you’ll have to add that in the manifest as a required capability.

clip_image012

Run your Project

Run your application with F5 and use it, so as to generate some telemetry.

In Visual Studio, you’ll see a count of the events that have been received.

clip_image014

See Monitor data

Open Application Insights in your azure portal you just created you will be able to see some data in your Application Insights dashboard

clip_image015

Track Usage

From the Overview timeline, click through Users and Sessions charts to see more detailed analytics.

Users are tracked anonymously, so the same user on different devices would be counted twice.

A session is counted when the app is suspended (for more than a brief interval, to avoid counting accidental suspensions).

Page Views

To discover the paths that users follow through your app, insert page view telemetry into your code:

Code Snippet
  1. var telemetry = new TelemetryClient();
  2.  
  3.             telemetry.TrackPageView("HubPage");

See the results on the page views chart, and by opening its details:

clip_image017

Click through any page to see the details of specific occurrences.

Custom Events

By inserting code to send custom events from your app, you can track your users’ behavior and the usage of specific features and scenarios.

For example:

Code Snippet
  1. var telemetry = new TelemetryClient();
  2.             telemetry.TrackEvent("AppStarted");

The data will appear in the Custom Events grid. You can either see an aggregated view in Metrics Explorer, or click through any event to see specific occurrences.

clip_image019

If you want you can also set up some properties and metrics along with the TrackEvent(). Below code explains how to set up properties and metrics.

Code Snippet
  1. var properties = new Dictionary<string, string> { { "IsSuccess", result.IsSuccessStatusCode.ToString() }, { "StatusCode", result.StatusCode.ToString() },
  2.                                                                     { "PlanogramId", completeOrder.PlanogramId.ToString() } };
  3.                 var metrics = new Dictionary<string, double> { { "RestockOrderAPI Process Time", stopwatch.Elapsed.TotalMilliseconds },
  4.                                                                 { "Products Count", completeOrder.linesList.Count() }};
  5.                 App.telemetry.TrackEvent("RestockOrderAPI", properties, metrics);

So, when you go to the dashboard in the Custom Events  you will ale to see the track event you created by the code and you will able to see the properties and metrics attached with the track event api.

Screenshot (218)

 

And if you want to see the attached properties of that particular event just click on it view more information.

Screenshot (219)

 

Track Trace

Use this to help diagnose problems by sending a ‘breadcrumb trail’ to Application Insights. You can send chunks of diagnostic data, and inspect them in Diagnostic search.

 

Code Snippet
  1. var properties1 = new Dictionary<string, string> { { "message", result.RequestMessage.ToString() } };
  2.                 App.telemetry.TrackTrace("RestockOrderAPI Track Trace", properties1);

If you want to see the trace results, just open your AI resource and click on Diagnostic Search there you can see the number of traces has occurred.

Screenshot (220)

Screenshot (222)

Detecting Exceptions

Exceptions are reported to Application Insights by calling TrackException()

Code Snippet
  1. var telemetry = new TelemetryClient();
  2.  
  3.             try
  4.             {
  5.                 //put your logic here
  6.             }
  7.             catch (Exception ex)
  8.             {
  9.                 // Send the exception telemetry:
  10.                 telemetry.TrackException(ex);
  11.             }

 

 

Debug vs Release mode

Debug

If you build in debug mode, events are sent as soon as they are generated. If you lose internet connectivity and then exit the app before regaining connectivity, offline telemetry is discarded.

Release

If you build in release configuration, events are stored in the device and sent when the application resumes. Data is also sent on the application’s first use. If there is no internet connectivity upon startup, previous telemetry as well as telemetry for the current lifecycle is stored and sent on the next resume.

Monitor Crash Frequency

If your users experience crashes in your app, you’d like to know about it quickly, and you’d like details about what happened. With Application Insights, you can monitor how frequently crashes occur, get alerts when they occur, and investigate reports of individual incidents.

“Crash” means that the application terminates because of an uncaught exception. If your app catches an exception you can report it with the TrackException() API but continue running. In that case, it will not be logged as a crash.

clip_image020

Set an alert to detect crashes

clip_image022

Click on Alert Rules and then Alert Rules menu will open, in that select Add Alert

clip_image024

Diagnose crashes

To find out if some versions of your app crash more than others, click through the crashes chart and then segment by Application Version:

clip_image026

To discover the exceptions that are causing crashes, open Diagnostic Search. You might want to remove other types of telemetry, to focus on the exceptions:

clip_image028

Click any exception to see its details, including associated properties and stack trace.

clip_image030

See the other exceptions and events that occurred close to that exception:

clip_image032

Using Diagnostic Search in Application Insights

When do you see Diagnostic Search?

You can open diagnostic search explicitly:

clip_image034

Inspect individual items

Select any telemetry item to see key fields and related items. If you want to see the full set of fields, click “…”.

clip_image036

Filter event types

Open the Filter blade and choose the event types you want to see. (If, later, you want to restore the filters with which you opened the blade, click Reset.)

clip_image038

Filter on property values

You can filter events on the values of their properties. The available properties depend on the event types you selected.

clip_image040

MVVM Light–Visual Studio 2013, Universal Apps, Windows Phone 8.1, Windows Store 8.1 Apps–Part 3 of N

In this part 3, let us see how to build a Universal Application for Windows Phone 8.1 and Windows 8.1 with MVVM Light support. We will also learn how to create a shared viewmodel layer, how to detect design mode and what the result is in Blend and at runtime.

In Part 2, we created a Universal Phone 8.1 app that still uses all the components present inside the project. We will use MVVM Light toolkit and remove some of the classes we created as well as code written in code behind files. Then we will make this a truly Universal App, which can be created for Windows Phone 8.1 and Windows 8.1.  This offers a nice way to structure your app in order to share as much code and other files (Views, View Models, etc) as possible. It makes it easier than ever to create apps which target both the Windows Phone 8.1 and the Windows RT devices like Surface, XBox.

MVVM is the design pattern used to develop apps in Windows Store apps as well as Windows Phone apps. Lets use MVVM Light framework to develop a windows store app. You can get the latest MVVM Light toolkit from http://mvvmlight.codeplex.com/

Creating the Application

Step 1: Open the project created in Part 2 using Visual Studio 2013.
Step 2: Right click on the References folder in the Windows Phone 8.1 application, and select Manage Nuget Packages.
Step 3: Select the Online source for Nuget and search for MVVM Light.
Step 4: Select the package MVVM Light Libraries only. Alternatively you can select the package named MVVM Light Libraries Only (PCL). This will install the exact same binaries and eventually I will remove this package and keep only the main one.
Step 5: Repeat steps 2 to 5 for the Windows 8.1 application.
Step 6: At this point, you have added MVVM Light support to both your applications as shown in Figure 1. Now we can add the files that will bring the full support for the ViewModel layer and the design support.

image

Figure 1: MVVM Light libraries referenced in Universal Projects in VS 2013

Adding ViewModel Layer:

it’s time to instantiate and create the ViewModels. This is the ViewModelLocator class task. This class is quite important in the application structure enabled by MVVM Light. It’s created as a XAML resource in the file App.xaml. This creates the important link between XAML markup and source code, allowing the visual designers to create the ViewModels and to run the design-time code. Lets create two files ViewModelLocator and the MainViewModel.

Adding ViewModelLocator & PersonViewModel:

The main task of ViewLocator is to link up your views with the view models. It’s responsible for creating and disposing of all of your View-Models. In this ViewLocator, mostly we just add additional views. Let’s do that.

The main task of ViewLocator is to link up your views with the view models. It’s responsible for creating and disposing of all of your View-Models. In this ViewLocator, mostly we just add additional views. Let’s do that.

Step 7: Right click on the Shared node and select Add, New Folder. Name this folder ViewModel.
Step 8: Right click on the new ViewModel again and select Add, New Item. Select a Class, and name it ViewModelLocator.cs
Step 9: Modify the ViewModelLocator code to look like in the code segment 1 below.
Step 8: Move the class PersonViewModel.cs from Windows Phone 8.1 to ViewModel present in shared node.
Step 9: Modify the MainViewModel class to look like code snippet 2 below. Of course you can add a bunch of new methods, observable properties and commands to this ViewModel as usual in MVVM.

Here I created PersonViewModelProp property that returns an instance of PersonViewModel and we registered this PersonViewModel class in line 23 of code snippet 1.

Code Snippet 1
  1. public class ViewModelLocator
  2.     {
  3.         public MainViewModel Main
  4.         {
  5.             get
  6.             {
  7.                 return ServiceLocator.Current.GetInstance<MainViewModel>();
  8.             }
  9.         }
  10.  
  11.         public PersonViewModel PersonViewModelProp
  12.         {
  13.             get
  14.             {
  15.                 return ServiceLocator.Current.GetInstance<PersonViewModel>();
  16.             }
  17.         }
  18.  
  19.         static ViewModelLocator()
  20.         {
  21.             ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
  22.             SimpleIoc.Default.Register<MainViewModel>();
  23.             SimpleIoc.Default.Register<PersonViewModel>();
  24.         }
  25.     }

Code Snippet 1: ViewModelLocator

Code Snippet 2
  1. public class PersonViewModel : ViewModelBase
  2.     {
  3.         public ObservableCollection<Person> Persons
  4.         {
  5.             get;
  6.             set;
  7.         }
  8.  
  9.         public Person personObject
  10.         {
  11.             get;
  12.             set;
  13.         }
  14.  
  15.  
  16.         private ICommand _savePersonCommand;
  17.         public ICommand SavePersonCommand
  18.         {
  19.             get
  20.             {
  21.                 return _savePersonCommand;
  22.             }
  23.  
  24.             set
  25.             {
  26.                 _savePersonCommand = value;
  27.             }
  28.         }
  29.         public PersonViewModel()
  30.         {
  31.             ObservableCollection<Person> _persons = new ObservableCollection<Person>();
  32.             _persons.Add(new Person { FirstName = IsInDesignMode
  33.                                     ? "bill" : "Bill",
  34.                                       LastName = IsInDesignMode
  35.                                           ? "gates" : "Gates" });
  36.             _persons.Add(new Person { FirstName = "Steve", LastName = "Ballmer" });
  37.             Persons = _persons;
  38.             personObject = new Person { FirstName = "Satya", LastName = "Nadella" };
  39.             _savePersonCommand = new RelayCommand(SavePerson, CanSavePerson);
  40.         }
  41.  
  42.         private bool CanSavePerson()
  43.         {
  44.             if (string.IsNullOrEmpty(personObject.FirstName) || string.IsNullOrEmpty(personObject.LastName))
  45.                 return false;
  46.             else
  47.                 return true;
  48.         }
  49.  
  50.         private void SavePerson()
  51.         {
  52.             Persons.Add(new Person { FirstName = personObject.FirstName, LastName = personObject.LastName });
  53.             //MessageDialog dialog = new MessageDialog(string.Format("Saved: {0}  {0}", personObject.FirstName, personObject.LastName));
  54.             //await dialog.ShowAsync();
  55.  
  56.         }
  57.  
  58.  
  59.     }

Code Snippet 2: PersonViewModel

Adding Locator resource to App.XAML

Open the App.xaml file in Visual Studio 2013 and modify it to look like code snippet 3 below. This creates a new resource with the ViewModelLocator, which we will use in the designer. Notice the addition of the “d” and “mc” XML namespaces so that we can mark the ViewModelLocator as a DataSource, which will make it show up in the Data panel in Blend.

Code Snippet 3
  1. <Application
  2.     x:Class="UniBlank_MVVMBasics.App"
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
  5.     xmlns:local="using:UniBlank_MVVMBasics"
  6.      xmlns:d="http://schemas.microsoft.com/expression/blend/2008&quot;
  7.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
  8.     mc:Ignorable="d"
  9.     xmlns:vm="using:UniBlank_MVVMBasics.ViewModel">
  10.     
  11.     <Application.Resources>
  12.         <vm:ViewModelLocator x:Key="Locator"
  13.                              d:IsDataSource="True"/>
  14.     </Application.Resources>
  15.  
  16. </Application>

Making it a truly Universal App:

Since there is nothing great we are doing here, we can easily make it a universal app with all the code shared between both the projects.  Move all the files that we created from Windows Phone 8.1 to Shared node as shown in Figure 2. Delete the files from Windows Phone 8.1 project. In Windows 8.1 project too, delete MainPage.XAML and hurray, we have our first universal app with MVVM. Now, Windows 8.1 store app begins to show up the same UI we have created for Windows Phone 8.1. Amazing!!!!

image

Figure 2: Moving files to Shared node for making this a Universal app code.

Connecting View and ViewModel:

Step 10: Set the DataContext of the Page to the MainViewMode as shown in Code Snippet 4.

Code Snippet 4
DataContext="{Binding PersonViewModelProp, Source={StaticResource Locator}}"

This is the complete code of PersonView User control.

Code Snippet
  1. <UserControl
  2.     x:Class="UniBlank_MVVMBasics.PersonView"
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
  5.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008&quot;
  6.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
  7.     mc:Ignorable="d"
  8.     d:DesignHeight="300"
  9.     d:DesignWidth="400" Loaded="UserControl_Loaded"
  10.     xmlns:local="using:UniBlank_MVVMBasics"
  11.     DataContext="{Binding PersonViewModelProp, Source={StaticResource Locator}}" >

Comment the code we wrote in PersonView.xaml.cs

Code Snippet
  1. private void UserControl_Loaded(object sender, RoutedEventArgs e)
  2.       {
  3.           //PersonViewModel personViewModelObject = new PersonViewModel();
  4.           //this.DataContext = personViewModelObject;
  5.       }

 

Download the source code from here.