Application insights for Windows Phone and Store apps

Azure Application Insights lets you monitor your published Mobile apps


  • 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.


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)


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.


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.


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


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.


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.


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.


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


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();
  3.             telemetry.TrackPageView("HubPage");

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


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.


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();
  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


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.


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.


Set an alert to detect crashes


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


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:


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:


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


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


Using Diagnostic Search in Application Insights

When do you see Diagnostic Search?

You can open diagnostic search explicitly:


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 “…”.


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.)


Filter on property values

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


Steps to implement TelemetryApp in Windows Store apps using API:


1. Create Telemetry account (
There are two types of telemetry accounts
Telemetry Enterprise Edition – It is a premium account offering by telemetry. For more information Enterprise Edition account page.
Telemetry Community Edition – It is a free account which has very limited features to provide a preview of telemetry for new organizations. For more information please see our Community Edition account page.
telemetry comunity Account

2. After Successful login in to the, initially you will be prompted to add a Board.

create board
A Board (dashboard) is a collection of widgets linked to metrics organized across a user determined layout. Below is an example screenshot how a board looks after adding widgets.

view board


After successful creation of board now we need an agent to communicate with the board.

– Go to Agents tab and select Add agent

Add Agent

– Give a name and click on create

Agent Name

– Copy the Agent token to secure place, you will not be able to see it again.

Agent API tocken


Boards contain widgets. A widget may be a chart, a number or simply a box to contain other widgets

Adding a widget to the board:

a. Select Add Widget option right above board properties

Add properties

b. Now select a widget which is suitable for your application.

sample widgets

c. After adding widget the board looks like below

view widget


Flows are objects that represent the flow of metrics within Telemetry.

widget properties

Adjusting Board Properties:

Here you can title your Board and adjust the settings, or properties, of your Board.

board properties

Widget Properties:

After adding Flows to your Board, you can select a Flow and edit the properties of the selected Flow.

view widget properties


  • All your widgets on a board can be found as a list of layers under the Layers tab.


  • Each widget box can be moved around, resized, and even layered.
  • Select a widget you want to adjust, and on hover you can see options to drag out and resize your box or to move it.
  • You can even have just one or two very large widgets on a board.

Adding a Logo:

  • The best way to personalize and brand your board, is to add a custom logo to your board.
  • From our Image widget, upload an image of your logo directly to your board if you have a paid plan with us.
  • You can then change the background color of the Image widget so your logo looks its best.

Board Backgrounds:

  • Add an image or color background to give your board(s) a custom theme.
  • Adjust your widget background color and opacity so your widgets and background are visible.

Widget Background:

  • Adjust your widget background color and opacity so your widgets and background are visible.

Board Layout:

  • Do you want to create 5 tidy columns on your board but notice you have extra space or one column is smaller or larger than the others? You can adjust the number of rows and columns your widgets snap to under Board Properties.

3. API
a. Accounts:

The account object represents your account. Typically you’ll see this referenced by other objects. This is a read only object.

Account Object




A globally unique static string identifying the object.


The name of your account.


The contact email address.


The contact phone number.


API soft limit.


API hard limit.


API usage of the last 24 hours.


API usage of the last hour.


Users limit.


Boards limit.


Agents limit.


Viewers limit.


API version.


The plan of your account.


The plan expiry date (if any).

To read Account Details


This method will return your current account.

For Account Update


This method will update your current account.

b. Boards

The boards object represent the boards (dashboards) within your account.

Boards are collections of widgets and their flows contained together for display.

Board Object




A globally unique static string identifying the object.


The name of the board.


The theme for the board.


The number of columns in the board grid.


The number of rows in the board grid.


An array representing the native size of the board.


A string with the aspect ratio of the board.


Whether to show the board name at the top of the board or not.


The tag for the default channel for the board.


The external margin of a widget, defaults to 3.


The internal padding of a widget, defaults to 8.


The size of the font to use, can be ‘small’, ‘normal’ or ‘large’.


The font family to use, defaults to ‘normal’ which uses the theme default.


The background color of the board.


The background image URL of the board.


The background color of the widgets.


The color of the widgets’ titles.


The size of the widgets’ titles.

Boards Listing


This method will return a list of all boards on your account.

Board Details


This method will return a specific board on your account by id.

Export Board


This method will return a specific board on your account by id and also its widgets details.

Create a Board


This method will create a new board.

Import a Board


This method will create a new board and widgets based on the json input.

Update a Board


This method will update a board object.

Delete a Board


This method will delete a board object.

c. Widgets

Widgets are mostly hidden from the Telemetry web interface however they’re

Critical elements to position flows within a board.

Widget Object




A globally unique static string identifying the object.


A globally unique static string identifying the board that the widget belongs to.


The variant of the widget: barchart, box, bulletchart, clock, compass, countdown, funnelchart, gauge, graph, grid, icon, iframe, image, log, map, multigauge, multivalue, piechart, scatterplot, servers, status, table, text, tickertape, timeline, timeseries, upstatus, value, video, waterfall, weather.


The column of the top left of the widget on a board.


The row of the top left of the widget on a board.


The width of a widget in columns.


The height of a widget in rows.


The layer sorting order of the widget within the board.


The background color of the widget. Possible values are:
“default” => The background will be dark/light depends on the selected theme of the board
“none” => Transparent background
Hex code (e.g. #09ab3f) => Hex code of a color.


An optional parameter that specifies a specific renderer to use. Things like changing a line chart from a spline to an area. See the renderer options below.

List all Widgets


This method will return a list of all widgets on your account.

Display a Widget


This method will return a specific widget on your account by id. It also return an array of flows for the default channel of the board. There’s an optional channel_id parameter to return the flows for that channel instead of the default.

Create a Widget


This method will create a new widget.

Update a Widget


This method will update a widget object.

Delete a Widget


This method will delete a widget object.

Renderer Options

Different Widgets support different renderer options. You can select the renderer using the Telemetry Manager when designing a board. When embedding a specific widget however in order to use something other than the default renderer you must specify it in the embed tag.

The following renderer options are supported for the following flow variants:




gauge, heading


circle, combined, vertical, horizontal


line, spline, area, bar, scatter


equal, number, label, icon


spline, line, bar, area


line, spline, area, bar, scatter

4. Implement telemetry in Windows store or Phone app using API

In this article I am using bar chart to explain how to implement in windows store apps. The procedure is same for all widgets.
Bar Chart:

A bar chart is a stack of horizontal bars, each with a label, value and colour. The value determines the length of the bar. The bars will be sorted from top to bottom in terms of length by default. You can choose to turn off sorting. Send data with a hash of bars containing an array with each bar as a hash. Bar charts can display a maximum of 20 bars. There may be less than 20 shown if your widget box is too small. Resize your widget box if all your data is not being displayed.








array of objects

The bars



CSS color

The color of the bar.




The text to overlay on top of the bar.




A number representing the value of the barchart. This will determine the length of the bar.




The min possible value of the bar.




The max possible value of the bar.




Whether to sort the bars by value or not. The default is true.

– Adding a Bar Chart into board.
Log in into, go to boards and select edit board.

edit board

– Now click on add widget, under charts select Bar Chart.

add widget bar chart

select bar chart

After adding Bar chart into board, select the bar chart on board, now go to widget tab in properties window and expand general tab.

bar chart properties

Copy the Flow Tag to a note pad.

bar chart flow tag name

Now we have a widget to display the flow data on board.

5. Create a Windows store or Phone app (Phone 8.1 or Windows 8.1) project in visual studio to send flows to bar chart from windows app, in my example I created a Universal Hub App project.

create windows store app

Open HubPage.xaml.cs, under load state method write the following code to send the flow data to recently created Bar Chart.

To use API we need the following information

  • URI
  • API Token (refer step 2 under Agents)
  • Flow Tag (In earlier step we copied flow tag for bar chart)

URI = “ Tag/”;

For Authentication/Authorization we need to pass Agent Token as user name and password as blank in POST method.

Prepare list of bars information:

In this example I am using bar chart 

public class Bar
            public string color { get; set; }
            public string label { get; set; }
            public int value { get; set; }

        public class BarRootObject
            public List<Bar> bars { get; set; }


BarRootObject barRootObject = new BarRootObject();
            barRootObject.bars = new List<Bar>();
            var bar = new Bar();
            bar.color = "#66CC00";
            bar.label = "Users";
            bar.value = 4;

            bar = new Bar();
            bar.color = "#FF8900";
            bar.label = "Sessions";
            bar.value = 30;

            bar = new Bar();
            bar.color = "#FFFF33";
            bar.label = "Crashes";
            bar.value = 26;

            bar = new Bar();
            bar.color = "#FF0000";
            bar.label = "Exceptions";
            bar.value = 75;

In above code I am passing four bars information which include colour, label and value (If you want to know/pass more properties info please refer Bar charts Flow Object table above).

POST Method:

string URI = ";;
            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Authorization = CreateBasicHeader("**Replce with Agent Token**", "");
            metrics metric= new metrics();
            metric.values =new int[]{10,70,25,5};
            metric.labels = new string[] { "A", "B", "C", "D" };
            metric.colors = new string[] { "#1F1F33", "#669900", "#7A0000", "#334C4C" };
            string postData = JsonConvert.SerializeObject(metric);
            StringContent c = new StringContent(postData, Encoding.UTF8, "application/json");
            httpClient.MaxResponseContentBufferSize = 100000;
            var result = await httpClient.PostAsync(URI, c);
            var content = await result.Content.ReadAsStringAsync();


Method for creating Authentication Header Value:

public static AuthenticationHeaderValue CreateBasicHeader(string username, string password)
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(username + ":" + password);
            return new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

6. Run the App

Now go to telemetry dashboard and check the bar chart has added four new bars with values.

bar chart with bars info

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

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.


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.         }
  11.         public PersonViewModel PersonViewModelProp
  12.         {
  13.             get
  14.             {
  15.                 return ServiceLocator.Current.GetInstance<PersonViewModel>();
  16.             }
  17.         }
  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.         }
  9.         public Person personObject
  10.         {
  11.             get;
  12.             set;
  13.         }
  16.         private ICommand _savePersonCommand;
  17.         public ICommand SavePersonCommand
  18.         {
  19.             get
  20.             {
  21.                 return _savePersonCommand;
  22.             }
  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.         }
  42.         private bool CanSavePerson()
  43.         {
  44.             if (string.IsNullOrEmpty(personObject.FirstName) || string.IsNullOrEmpty(personObject.LastName))
  45.                 return false;
  46.             else
  47.                 return true;
  48.         }
  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();
  56.         }
  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=";
  4.     xmlns:x=";
  5.     xmlns:local="using:UniBlank_MVVMBasics"
  6.      xmlns:d=";
  7.     xmlns:mc=";
  8.     mc:Ignorable="d"
  9.     xmlns:vm="using:UniBlank_MVVMBasics.ViewModel">
  11.     <Application.Resources>
  12.         <vm:ViewModelLocator x:Key="Locator"
  13.                              d:IsDataSource="True"/>
  14.     </Application.Resources>
  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!!!!


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=";
  4.     xmlns:x=";
  5.     xmlns:d=";
  6.     xmlns:mc=";
  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.

Getting Started with Visual Studio 2013, Windows Phone 8.1, Window Store 8.1, MVVM –Part 2 of N


In Part 1, we have seen how to write code in Model, view and viewmodel to wire up data and show it in the UI. There is a clear separation among the three layers. Now let us extend the sample and see how we can implement commanding. We will just add a Save button and when the user clicks Save, add a record to ObservableCollection and the UI automatically shows the data.

Step 1: Add a new class called DelegateCommand.cs and inherit from ICommand

  1. public class DelegateCommand : ICommand
  2.     {
  3.         private readonly Action<object> _executeMethod = null;
  4.         private readonly Predicate<object> _canExecuteMethod = null;
  5.         private bool _isAutomaticRequeryDisabled = false;
  7.         public DelegateCommand(Action<Object> executeMethod, Predicate<object> canExecuteMethod, bool isAutomaticRequeryDisabled)
  8.         {
  9.             if (executeMethod == null)
  10.             {
  11.                 throw new ArgumentNullException("executeMethod is null. Please set executeMethod.");
  12.             }
  13.             _executeMethod = executeMethod;
  14.             _canExecuteMethod = canExecuteMethod;
  15.             _isAutomaticRequeryDisabled = isAutomaticRequeryDisabled;
  16.         }
  18.         public bool CanExecute(object parameter)
  19.         {
  20.             return _canExecuteMethod == null ? true : _canExecuteMethod(parameter);
  21.         }
  23.         public event EventHandler CanExecuteChanged;
  25.         public void Execute(object parameter)
  26.         {
  27.             if (_executeMethod != null)
  28.                 _executeMethod(parameter);
  29.         }
  31.         //In WinRT, there is no CommandManager to raise events globally. you must update/raise CanExecuteChanged manually
  32.         public void RaiseCanExecuteChanged()
  33.         {
  34.             if (CanExecuteChanged != null)
  35.                 CanExecuteChanged(this, EventArgs.Empty);
  36.         }
  38.     }

Step 2: Modify the person class created in Part 1 to includes command for Save.

  1. public class PersonViewModel
  2.     {
  3.         public ObservableCollection<Person> Persons
  4.         {
  5.             get;
  6.             set;
  7.         }
  9.         public Person personObject
  10.         {
  11.             get;
  12.             set;
  13.         }
  16.         private ICommand _savePersonCommand;
  17.         public ICommand SavePersonCommand
  18.         {
  19.             get
  20.             {
  21.                 return _savePersonCommand;
  22.             }
  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 = "Bill", LastName = "Gates" });
  33.             _persons.Add(new Person { FirstName = "Steve", LastName = "Ballmer" });
  34.             Persons = _persons;
  35.             personObject = new Person { FirstName = "Satya", LastName = "Nadella" };
  36.             _savePersonCommand = new DelegateCommand(SavePerson, CanSavePerson, false);
  37.         }
  39.         private bool CanSavePerson(object obj)
  40.         {
  41.             if (string.IsNullOrEmpty(personObject.FirstName) || string.IsNullOrEmpty(personObject.LastName))
  42.                 return false;
  43.             else
  44.                 return true;
  45.         }
  47.         private void SavePerson(object obj)
  48.         {
  49.             Persons.Add(new Person { FirstName = personObject.FirstName, LastName = personObject.LastName });
  50.             //MessageDialog dialog = new MessageDialog(string.Format("Saved: {0}  {0}", personObject.FirstName, personObject.LastName));
  51.             //await dialog.ShowAsync();
  53.         }
  56.     }

Step 3: Add a button to UserControl in PersonView.xaml and add Command property from viewmodel.

  1. <UserControl
  2.     x:Class="UniBlank_MVVMBasics.PersonView"
  3.     xmlns=";
  4.     xmlns:x=";
  5.     xmlns:d=";
  6.     xmlns:mc=";
  7.     mc:Ignorable="d"
  8.     d:DesignHeight="300"
  9.     d:DesignWidth="400" Loaded="UserControl_Loaded"
  10.     xmlns:local="using:UniBlank_MVVMBasics">
  11.     <Grid>
  12.         <StackPanel HorizontalAlignment="Left">
  13.             <ListView ItemsSource="{Binding Path=Persons, Mode=TwoWay}">
  14.                 <ListView.ItemTemplate>
  15.                     <DataTemplate>
  16.                         <StackPanel Orientation="Horizontal" Margin="20,20,0,0">
  17.                             <TextBlock Margin="10,0,20,0" Text="{Binding Path=FirstName, Mode=TwoWay}" Style="{StaticResource HeaderTextBlockStyle}"></TextBlock>
  18.                             <TextBlock Text="{Binding Path=LastName, Mode=TwoWay}" Style="{StaticResource HeaderTextBlockStyle}"></TextBlock>
  19.                         </StackPanel>
  20.                     </DataTemplate>
  21.                 </ListView.ItemTemplate>
  22.             </ListView>
  23.         </StackPanel>
  25.         <StackPanel>
  26.              <Button Content="Save" HorizontalAlignment="Right" Width="80" Command="{Binding Path=SavePersonCommand}"/>
  27.         </StackPanel>
  29.     </Grid>
  30. </UserControl>

Note: In WinRT, you must update/raise CanExecuteChanged manually. There is no CommandManager to do this globally. You could look at this as a pain in the neck, or a serious performance boost now that CanExecute is not called constantly. It does mean you have to think about cascading property changes where before you did not have to. But this is how it is. Manual.

Download the source code from here.

Getting Started with Visual Studio 2013, Windows Phone 8.1, Window Store 8.1, MVVM –Part 1 of N

With the recent release of Universal Apps, Windows Phone 8.1, Visual Studio 2013 Ultimate Update 2 RC , Windows Store 8.1 Update & Windows 8.1 update from Microsoft, I thought to blog some articles on these new technologies and there is no better design pattern to use than MVVM. So I will walk through some of the latest programming updates from MS along with MVVM.

Required Software’s:

Benefits of MVVM:

1. Separation of Concerns (View, ViewModel, Model)
2. Clean testable and manageable code. Can include presentation tier logic in unit testing.
3. No code behind code, so the presentation layer and the logic is loosely coupled.
4. Better way of data binding.
5. With the new Window Runtime support for Windows Phone 8.1, we can now use the same Windows Store code for ICommand pattern implementation.

Overview MVVM Layers


Steps to Implement MVVM:

Lets get our hands dirty. Here we are going to develop a Windows Phone 8.1 application using Windows Runtime & XAML (Not Silverlight). Figure 1 shows the UI we are planning to develop.

Before writing code, analyze what we want to achieve and then come up with the class names, draw relation ships on paper and see how all the components fit together. Here I have two variables firstname and lastname and I wanted to show the data in the UI as shown in figure 1. So lets use MVVM to achieve this.


Figure 1: Views showing Model data using MVVM design pattern

Step 1: Fun with MVVM begins. Create a Universal Project by opening VS 2013 –> New –> Project –> Templates->Visual C#->Store Apps->Universal Apps and select Blank App (Universal Apps). Name it as UniBlank_MVVMBasics as shown in Figure 2.


Figure 2: New Universal Apps Project template in Visual Studio 2013

Step 2: VS 2013 creates two projects. One for Windows Store and other for Windows Phone. Both use Windows Runtime API as the core targeting 8.1 platforms. Shared project is the shared component between the two projects and we will get to this when we learn more about Universal Apps Project template.


Figure 3: Universal Apps Projects in VS 2013.

Step 3: Adding a class. Right click on UniBlank_MVVMBasics.WindowsPhone –>Add->Class as shown in Figure 4.image

Figure 4: Adding a class in Visual Studio 2013.

Step 5: Name it as Person.cs as shown in Figure 5.image

Figure 5: Add New Item Dialog

Step 6: Create a Simple Model (Person.cs) with required properties and implement PropertyChanged property of INotifyPropertyChanged.

Person Class Code
  1. class Person : INotifyPropertyChanged
  2.     {
  3.         public event PropertyChangedEventHandler PropertyChanged;
  5.         private string _firstName;
  6.         public string FirstName
  7.         {
  8.             get
  9.             {
  10.                 return _firstName;
  11.             }
  13.             set
  14.             {
  15.                 if (_firstName != value)
  16.                 {
  17.                     _firstName = value;
  18.                     OnPropertyChanged("FirstName");
  19.                 }
  20.             }
  21.         }
  23.         private string _lastName;
  24.         public string LastName
  25.         {
  26.             get
  27.             {
  28.                 return _lastName;
  29.             }
  31.             set
  32.             {
  33.                 if (_lastName != value)
  34.                 {
  35.                     _lastName = value;
  36.                     OnPropertyChanged("LastName");
  37.                 }
  38.             }
  40.         }
  42.         public void OnPropertyChanged(string property)
  43.         {
  44.             if (PropertyChanged != null)
  45.             {
  46.                 PropertyChanged(this, new PropertyChangedEventArgs(property));
  47.             }
  48.         }
  49.     }

Step 7: Create a ViewModel (PersonViewModel.cs) with required logic to bind Model to ViewModel. (Repeat step 3 t step 5 and name class as PersonViewModel.cs.

Code Snippet
  1. class PersonViewModel
  2.     {
  3.         public ObservableCollection<Person> Persons
  4.         {
  5.             get;
  6.             set;
  7.         }
  9.         public void LoadPersons()
  10.         {
  11.             ObservableCollection<Person> _persons = new ObservableCollection<Person>();
  12.             _persons.Add(new Person{ FirstName="Bill", LastName="Gates"});
  13.             _persons.Add(new Person{ FirstName="Satya", LastName="Nadella"});
  14.             Persons = _persons;
  15.         }
  16.     }

Step 8: Instead of using MainPage.XAML to show the data, let us create Views as we do typically in a software development. Create a View (PersonView.xaml) and bind the data with ViewModel. Add a User Control to the solution and name it as PersonView.xaml as shown in Figure 6.image

Figure 6: Adding View (User Control) to the project in VS 2013

Step 9: As we have to display firstname and lastname, lets use TextBlock’s. We will use  ItemsControl and Persons (observablecollection property) as DataContext and put them inside a DataTemplate to display the data from model in the view. In PersonView.XAML, write the following code inside Grid tag as shown below.

XAML code- Person User Control
  1. <Grid>
  2.         <StackPanel HorizontalAlignment="Left">
  3.             <ItemsControl ItemsSource="{Binding Path=Persons}">
  4.                 <ItemsControl.ItemTemplate>
  5.                     <DataTemplate>
  6.                         <StackPanel Orientation="Horizontal" Margin="20,20,0,0">
  7.                             <TextBlock Margin="10,0,20,0" Text="{Binding Path=FirstName, Mode=TwoWay}" Style="{StaticResource HeaderTextBlockStyle}"></TextBlock>
  8.                             <TextBlock Text="{Binding Path=LastName, Mode=TwoWay}" Style="{StaticResource HeaderTextBlockStyle}"></TextBlock>
  9.                         </StackPanel>
  10.                     </DataTemplate>
  11.                 </ItemsControl.ItemTemplate>
  12.             </ItemsControl>
  13.         </StackPanel>
  15.     </Grid>

Step 10: In PersonView.xaml.cs, let us create an object of PersonViewModel class and pass it as DataContext to the View we just created as shown below.

PersonView.xaml.cs code
  1. private void UserControl_Loaded(object sender, RoutedEventArgs e)
  2. {
  3.     PersonViewModel personViewModelObject = new PersonViewModel();
  4.     personViewModelObject.LoadPersons();
  5.     this.DataContext = personViewModelObject;
  6. }

Step 11: In MainPage.xaml, let us import the xmlns:views=”using:UniBlank_MVVMBasics” namespace and put the views inside the grid as shown below.

MainPage.xaml code
  1. <Page
  2.     x:Class="UniBlank_MVVMBasics.MainPage"
  3.     xmlns=";
  4.     xmlns:x=";
  5.     xmlns:local="using:UniBlank_MVVMBasics"
  6.     xmlns:d=";
  7.     xmlns:mc=";
  8.     mc:Ignorable="d"
  9.     Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
  10.     xmlns:views="using:UniBlank_MVVMBasics" >
  12.     <Grid>
  13.         <views:PersonView></views:PersonView>
  14.     </Grid>
  15. </Page>

That’s it. Download the source code here.

Below are some of the points to remember about MVVM layers.


1. Represents the Data.
2. The Entity.
3. Model classes are non-visual classes that encapsulate the application’s data and business logic.
4. They are responsible for managing the application’s data and for ensuring its consistency and validity by encapsulating the required business rules and data validation logic.
5. The model classes do not directly reference the view or view model classes and have no dependency on how they are implemented.
6 The model classes typically provide property and collection change notification events through the INotifyPropertyChanged and INotifyCollectionChanged interfaces.
7. This allows them to be easily data bound in the view.
8. Model classes that represent collections of objects typically derive from the ObservableCollection<T> class.
9. The model classes typically provide data validation and error reporting through either the IDataErrorInfo or INotifyDataErrorInfo interfaces.
10. The model classes are typically used in conjunction with a service or repository that encapsulates data access and caching.
11. Not required to know where it gets its data from i.e from a WCF service. WCF RIA Services, etc.
12. May contain validation.


1. The view is a visual element, such as a window, page, user control, or data template.
2. The view defines the controls contained in the view and their look and feel, visual layout and styling.
3. The view references the view model through its DataContext property.
4. The controls in the view are data bound to the properties and commands exposed by the ViewModel.
5. The view may customize the data binding behavior between the view and the view model.
For e.g, the view may use value converters to format the data to be displayed in the UI, or it may use validation rules to provide additional input data validation to the user.
6. The view defines and handles UI visual behavior, such as animations or transitions that may be triggered from a state change in the view model or via the user’s interaction with the UI.
7. The view’s code-behind may define UI logic to implement visual behavior that is difficult to express in XAML or that requires direct references to the specific UI controls defined in the view. 


1. The ViewModel is a non-visual class and does not derive from any WPF or Silverlight base class.
2. It encapsulates the presentation logic required to support a use case or user task in the application.
3. The ViewModel is testable independently of the view and the model.
4. The ViewModel typically does not directly reference the view. It will have UI Friendly Entities, UI State, Actions and Public properties that are bound to a View.
5. It implements properties and commands to which the view can data bind.
6. It notifies the view of any state changes via change notification events via the INotifyPropertyChanged and INotifyCollectionChanged interfaces.
7. Interacts with View with various Commands.
8. The view model coordinates the view’s interaction with the model.
9. It may convert or manipulate data so that it can be easily consumed by the view and may implement additional properties that may not be present on the model.
10. It may also implement data validation via the IDataErrorInfo or INotifyDataErrorInfo interfaces.
11. The view model may define logical states that the view can represent visually to the user.
12. Invokes services to communicate outside the MVVM triad.

Developing Apps for Microsoft Surface, Windows 8, Windows RT and Windows Phone 8

Recently, at one of the conference i presented at Microsoft Technology center, i was asked the following questions.

  • Is .NET dead? What is .NET Client profile?
  • Is Windows 8 compatible with my current Windows app?
  • Can I build Windows 8 Metro apps in .NET?
  • Can I build apps for both Windows 8 and Windows Phone?

The following table summarizes the latest devices and their operating systems as well as the development technologies along with other useful information (for developers)


Well, here are some of the answers and commonly used Windows 8 terminology.

  • Windows Phone 8 now shares a common core with Windows 8. This means you can expect to write apps for one and easily port it to the other, with UI retooling of course. Developers targeting both should use C#/VB + XAML for apps, and C++/D3D for games. Portable class library definitely helps when developing for both the platforms.
  • The term “Metro Apps” now called “Microsoft Design Language” denotes apps that can be purchased in the official Windows App Store and that are built on top of the WinRT runtime, using either C# + XAML, or WinJS + HTML5. Even though Windows Phone features a Metro user interface (and the original one at that), the term Metro Apps does NOT apply to Windows Phone 7.5 apps.
  • The term “Metro Games” denotes apps that can be purchased in the official Windows App Store and that are built on top of the WinRT runtime, using Direct3D (D3D) and C++. Windows RT & Windows 8 Metro games cannot be built in XNA.
  • XNA can still be used to create Windows Phone 7.5, 7.8 and 8.0 games, and sold in the marketplace. You will not need to keep Visual Studio 2010 since Visual Studio 2012 and the Windows Phone 8.0 SDK will still support new development in XNA.
  • WinRT is the new native Runtime for Windows RT and the Metro side of Windows 8. It completely replaces .NET and Win32. Let me make this clear: If you look under the covers of WinRT, there is no .NET and no Win32, all you’ll find is the Windows Kernel. Since the only dev platform supported by Windows RT is WinRT, that means you cannot use .NET to build apps for Windows RT (or for the Metro side of Windows 8). Read this post on Paul Thurrott’s Windows Supersite for a more in-depth explanation.
  • WinRT is not based on .NET but you can use a subset of .NET from WinRT. Microsoft provides a subset of managed types called the .NET APIs for Metro style apps which enables .NET Framework developers to create Metro style apps within a familiar programming framework. Note that porting some .NET apps to WinRT could be trivial while others could be hard, based on which namespaces & classes you use. Check this section of the Metro style development documentation for more details.
  • Side-loading implicates installing non-certified applications using external media, thus bypassing the official Microsoft Windows App Store, whether it originates from a CD/DVD, USB key or web download. Note that developers can always side-load their own apps in a developer-unlocked device.
  • Xbox LIVE games are always platform specific. Microsoft Surface and Windows Phone both feature Xbox LIVE enabled games but this does NOT mean it runs the same Xbox LIVE Arcade games as the Xbox 360.
  • 2D game development can also be done using the same platform as apps. For example, on Windows Phone, 2D games can be built in Silverlight and do not require XNA.
  • Confused about version numbers for Windows Phone? Read my blog post that demystifies it all here.
  • Windows 8 can also be installed on any PC running Windows 7 today, and will also come pre-loaded on future generations of OEM (Dell, HP, Lenovo, Toshiba, etc.) computers, laptops, notebooks, Ultrabooks, Netbooks and tablets. The first column applies to all these other Windows 8 computers as well.
  • Windows RT will also be available on third-party tablet devices offered by Microsoft’s OEM partners (Samsung, Toshiba, Lenovo, etc.) Windows RT cannot be installed manually by a consumer, it must be licensed and pre-loaded by the OEM manufacturing the tablet.

  • 101 Questions and Answers About Windows 8

    1. What tools and information do I need to develop Windows 8 Store applications?

    a. Windows 8 – Download free version here

    b. Visual Studio 2012 Express – Download free version here

    c. Windows Phone – Download free version here

    d. Windows Server 2012 – Download free version here (Optional)

    e. Microsoft Virtual Academy – Register here

    2. How to develop a Windows Phone 8 app in 30 days?

    Register at

    3. For a Mac user, where can I get the free tools to build Windows Store apps for Windows 8?

    Install Windows 8 and the dev tools on your Mac.

    4. How to start planning now for a cloud-based backend service—user authentication, push notifications, and structured data?

    Sign up for the Windows Azure 90-day Free Trial and receive 10 free Mobile Services running on shared instances.

    5. Get the samples and get started!? Download the design assets—PSD assets include templates, common controls, and common components—and the sample apps pack.

    6. Where to find Windows 8 Sessions and Keynotes — //BUILD Conference Site

    7. Download the Bits — Windows Dev Center

    8. PDF Manual — Windows Developer Preview Guide

    9. Code Examples — MSDN “Metro Style” app examples (or get them all together in a Single ZIP)

    10. What Devices will Run It? — List of Devices in Microsoft’s Test Lab

    11. How to Install on My Machine without Losing Everything even if I don’t have Dual-Format DVDs or 8 GB Memory Sticks Handy — Installing Windows 8 Developer Preview as a Bootable VHD

    12. What About Silver light? — It’s still here, with a diagram from Microsoft to prove it

    13. Chat about Windows 8 or Cry for Help — MSDN Forums for Windows 8

    14. What is WinRT? — Introduction to WinRT and WinRT demystified

    15. Touch Input — Quickstart: Touch Input

    16. Comfort Guide to Controls for Silverlight and WPF Developers — Controls List (for Xaml)

    17. How do I Convert Silverlight to WinRT/Metro? — Blog Series on WinRT vs. Silverlight

    18. But is Xaml REALLY There? — Yes, It Is

    19. The New Architecture — Windows 8 WinRT Capabilities (Tip: Lean forward to make it look flat)

    20. Platform and Tools Architecture — Windows 8 Platform and Tools (Tip: this time lean sideways)

    21. Can I Borrow Someone’s Opinion? — Sure thing: Yours Truly, Michael Crump, Engadget, Wired

    22. Create a bootable USB?

    23. Setup boot to VHD?

    24. Get an Azure account?

    25. Get Windows 8?

    26. Get Visual Studio 2012?

    27. Get Windows Live SDK?

    28. Get Windows 8 Samples?

    29. Get Multilingual Toolkit?

    30. Get Advertising SDK?

    31. Get Design Assets?

    32. Register your App?

    33. Join 30 to Launch?

    34. View the online labs?

    35. Does Windows 8 run Windows 7 software? Yes

    36. Does Windows 8 support .Net 4.0? Yes

    37. Does WinRT replace the .Net framework? No

    38. Can users re-enable the start button in Windows 8? No

    39. Can enterprises disable Microsoft Design Style on their Windows 8 desktops? No

    40. Will Microsoft Design Style be part of the server version of Windows? Yes

    41. Do developers need two apps in the Windows 8 store to support ARM? No

    42. Can apps have a hidden URL in the Windows 8 store? No

    43. What is the revenue split with Microsoft for the Store? 80/20

    44. Do developers need a developer account in order publish an app? Yes

    45. Can developers use payment systems other than Microsoft? Yes

    46. Is HTML5 and JavaScript (JS) supported in Microsoft Design Style development? Yes

    47. What is the HTML rendering engine in HTML-based Microsoft Design Style apps? IE10

    48. Is IE10 Microsoft Design Style the same engine as IE10 desktop? Yes

    49. Can desktop applications create live tiles? No

    50. Can desktop applications use WinRT? Yes

    51. Can desktop HTTP end point be accessed by Microsoft Design Style apps? No

    52. Can Microsoft Design Style applications access a local SQL server? No

    53. Do Microsoft Design Style applications have a local database solution? Yes, Sqlite

    54. Can Microsoft Design Style applications access the internet while the pc is in standby? Yes

    55. Can Microsoft Design Style applications access SkyDrive? Yes

    56. Can Microsoft Design Style applications iterate through the user’s hard drive? No

    57. Is there a Microsoft Design Style version of windows file explorer? No, see above

    58. Can Microsoft Design Style applications detect other Microsoft Design Style apps? No

    59. Can more than one Microsoft Design Style application run at one time? Yes, two

    60. Can push notifications execute client code? No

    61. Are there background tasks in Microsoft Design Style? Yes

    62. Is the performance of HTML5 Microsoft Design Style applications comparable to XAML? Yes

    63. Is native code (C++) supported in Microsoft Design Style development? Yes

    64. Is Microsoft Design Style C different than traditional CPP? Yes

    65. Should all desktop apps be migrate to Microsoft Design Style? No

    66. Will the Windows 8 store support trials? Yes

    67. Will the Windows 8 store support subscriptions? No

    68. Will enterprise apps deliver through the Windows 8 store? No

    69. Can enterprises disable the Windows 8 store? Yes

    70. Can enterprises disable side-loading of apps? Yes

    71. Can apps in the Windows 8 store access desktop apps & services? No

    72. Can side-loaded apps access desktop apps & services? Yes

    73. Can parents disable the Windows 8 store for kids? Yes

    74. Can parents limit the hours in the day their kids can log in? Yes

    75. Can parents limit the cumulative time in a day kids can use the PC? Yes

    76. Can parents filter available web sites? Yes

    77. Can parents disable games based on their rating? Yes

    78. Can Visual Studio 2010 be used to build Microsoft Design Style apps? No

    79. Can Visual Studio 2012 be used to build Windows 7 apps? Yes

    80. Can Visual Studio 2010 access Team Foundation Server 2012? Yes

    81. Can Visual Studio 2012 open 2010 projects without altering them? Yes

    82. Can Visual Studio 2010 open 2012 projects? No

    83. Does the .Net 4 async keyword work in WinRT? Yes

    84. Does Windows 8 WinRT code run on Windows Phone 7? No

    85. Does Windows Phone 7 code run on Windows 8? Yes, some

    86. Does Windows Phone 8 code run on Windows 8? Yes, more

    87. Does Windows 8 code run on Windows Phone 7? Yes, some

    88. Does Windows 8 code run on Windows Phone 8? Yes, more

    89. Can Microsoft Design Style applications roam settings/files across desktops? Yes

    90. Can desktop applications roam settings, too? No

    91. Can Microsoft Design Style applications roam settings/files to Windows Phone? No

    92. Can Windows Phone roam settings to Windows 8? No

    93. Does Windows 8 Microsoft Design Style support XNA game development? No

    94. When was Windows 8 released? Friday, October 26, 2012.

    95. Win+E – Explorer

    96. Win+R – Run

    97. Win+D – Desktop

    98. Win+Plus or Win+Minus (no shift) – Magnifier/Zoom In and Out

    99. Win+F – Find Files

    100. Alt-Tab – Switch between Apps

    101. Win-Tab – Switch between Full Screen Apps