How to use Progress Indicator in Windows Phone

Progress bar is the very nice and interactive control which tells the user that currently the app is busy doing some task and hence he should wait to get the response from the app, the task may be fetching data, uploading data or something else. Progress Indicator is in the system tray. System Tray is the top section which contains the time, network and battery indicator.

System Tray WP8

System Tray WP8

I had an application which takes the user Geo-location and maps it on the map control on app load event and hence sometimes it took a huge time and user sometimes feel the app is not responsive and hence I realized the use of progress indicator in my application. Here are the steps which will hell you add a progress indicator to your application.

Step 1 – Create a new progress Indicator object and add it to system tray
[code lang="csharp"]
SystemTray.ProgressIndicator = new ProgressIndicator();
SystemTray.ProgressIndicator.Text = "Acquiring";
First line creates a new progress indicator object and the next line sets the progress indicator text, it is the text shown when some progress is going on in our app, I have set it to “acquiring” as it is acquiring location of my user.

Step 2 – Create a Function which will toggle the visibility of progress indicator
[code lang="csharp"]private void SetProgressIndicator(bool value)
SystemTray.ProgressIndicator.IsIndeterminate = value;
SystemTray.ProgressIndicator.IsVisible = value
this will set the visibility of the progress indicator when required and hide it when not. The first line says “IsIndeterminate” it means it will show the progress regardless of the progress value and the progress bar will keep moving (usually we use IsIndeterminate = true) , the next line sets the visibility.

Step 3 – Identify the time consuming process of your app

You need to identify the code snippets which might take some time or are network dependent process and you need to set the visibility of the progress indicator to be true before then and when the process is completed the progress indicator is hidden.

[code lang="csharp"]
In this example I have set the visibility of the progress indicator to be true before implementing my MapLocation method which takes some time and hence after mapping the location the progress indicator’s visibility is set to false. This is as simple as it seems but very helpful and makes the app more user friendly. Lets see the output screen of above code.

Progress Indicator WP8

Progress Indicator WP8

Hope this helps you in your application. Use progress indicators to make your app more attractive. Cheers.

Windows Phone Background Agents


Background agents are the scheduled tasks which run in background and add value to your application which the other application might not have. Here we will cover all about background agents, including their types and how and when to use them. I believe whatever app you have can be made better with the implementation of the background agents, background agents keep the user in touch with the application when the application is not actually working(i.e. not working in foreground). We will look at the different ways in which we can use the background agents. Windows Phone has a philosophy - “users first”, and hence all the basic architecture depends on the best possible performance and battery life.

Foreground Tasks

  • Normally a Windows Phone application runs in ‘foreground’.
    • Has access to the screen and interacts directly with the user of the phone.
  • At any given time only one application is running in the foreground.
    • Although others may be in the memory of the phone and can be selected as required.

As mentioned above Windows Phone follows a philosophy – “users first”, so the application running in the foreground is the only application, there might be other applications which have lots of memory but none of CPU, that is the reason Windows Phone has the most fluid interface. Now here comes in role the background agents, as we mentioned the app in foreground is the only app running but we also need some background processing for other apps like fetching emails etc. So instead of running the complete application in background we have background agents which run on behalf of the application and performs some specific tasks.

Background Agents

It is a totally different project in Visual Studio and is linked to the main application, it can interact with the background storage of the Windows Phone and can share data, but actually it is totally different piece of code. On the basis of consuming processor resources we have two types of background agents -

  • PeriodicTask
  • ResourceIntensiveTask

There is only one agent allowed per application, and agent can never be compared with the foreground application running in background as it has certain limitations. A background agents is limited in what it can do and access it has to the processor and other phone facilities.

Background Agent Health Warning

Operating System manages all the background agents, you can go to settings and manage all your running background agents,

  • The number of background agents is limited per application (i.e. 1 per app)
  • If the right conditions do not arise the agent will not be started.
    • Background agents run only in the situation whenever the operating system feels able to give them the processor to access.
  • If the phone gets into ‘Power Saver’ mode it may stop running background agents completely
  • User may not use agents to provide fundamental behaviors
    • A background agents is the cherry on top not the ice-cream.

Focus on the last point, background agents are the cherry on top and not the ice-cream means that it can just add the value to your application and not provide the basic features, they are kept as light as possible. Operating System manages all the background agents so as to ensure the behavior of  each agent and hence no agents can behave abnormal to utilize more CPU or memory to disturb smooth execution of the applications.

Agents and Tasks

Basically Task is the scheduling type you request when you schedule a background agent to run, and it is managed by the operating system which background agent runs in the appointed time. As discussed there are two kinds of Tasks -

  • Periodic tasks that run every now and then.
  • Resource Intensive tasks that run when the phone is in the position to let them.

PeriodicTask Agents

A periodic task runs every now and then, typically every 30 minutes or so, depending on loading on the phone. It is intended to perform a task regularly and complete quickly. It is good for location tracking, polling background services, tiles update.

  • Runs every 30 mins.
  • Runs for 25 seconds or so.
  • Memory Usage allowed < 11 MB.
  • Agent is unscheduled after two consecutive crashes.
  • The phone sets a limit the maximum number of active agents at any time.
  • An agent is active after 2 weeks of starting (if the application is not used for two weeks, operating system believes that you are not using this app and hence running its background is waste or processing resources.)

ResourceIntensive Agents

These are the agents which require high resources to perform the task, usually involves updating of phone, downloading large files etc. Whenever processor feels it is able to give access to the application the agents start running. Few features of ResourceIntensive Agents are -

  • It can run for up to 10 mins.
  • The phone must be on power source and the battery > 90% charged.
  • The phone must be connected to WiFi.
  • The phone should not be in use(Lock screen displayed).

Dual purpose Agents

There are some dual purpose agents also, as the name signifies they have the properties of both Periodic and Resource Intensive agents. Whenever the agent starts it determines in what context it is running and then behave accordingly. The agent will run periodically and when the phone is in position to allow resource intensive work it will switch it’s mode.

Background Agent Functionality

As discussed above some of the functionality is limited for the use of background agents and here is a list which shows all.




Display UI


Microphone and Camera




Play Audio (may only use background audio APIs)

R/W Isolated Storage


Most Framework APIs

This was all about Background agents in Windows Phone, in the coming posts we will learn how to implement toast notifications in your application.

Windows Phone Runtime Storage

Windows Storage is an older technique which was also used in tradition windows application development, it uses a namespace Windows.Storage. Similar to Isolated Storage there is also a terminology used in Windows Storage:

  • StorageFolder – It represents the storage area containing files and folder.
  • StorageFile – Represents a file and provides method for manipulating them.

Now here you need to keep a note of one thing that traditional name value pair i.e. ApplicationData.LocalSettings is not supported in Windows Phone 8, for this you can either create a custom file or use IsolatedStorageSettings.

Saving Data

[code lang="csharp"]
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile storageFile = await localFolder.CreateFileAsync("");
Stream writeStream = await storageFile.OpenStreamForWriteAsync();
using (StreamWriter writer = new StreamWriter(writeStream))
await writer.WriteAsync(databox.Text);

Loading Data

[code lang="csharp"]
private async string loadData()
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile storageFile = await storageFolder.GetFileAsync("");
Stream readStream = await storageFile.OpenStreamForReadAsync();
using (StreamReader reader = new StreamReader(readStream))
return await reader.ReadToEndAsync();
The code is as simple as it seems, lets have a quick demo on how it works.

Application Settings in Windows Phone

Application Settings is the most useful and easiest way to store and access data in Windows Phone, it is a wonderful name value pair dictionary. If we want to store setting we use the ApplicationSettings object in Isolated Storage. Basically it is used for properties, settings and other commonly used data in your application.

Saving Data

[code lang="csharp"]
private void saveData(string message)
IsolatedStorageSettings.ApplicationSettings["score"] = message;

Load Data

[code lang="csharp"]
private string loadData()
if (IsolatedStorageSettings.ApplicationSettings.Contains("score"))
return (string)IsolatedStorageSettings.ApplicationSettings["score"];
return null;
It is as simple as the code seems above, lets see a quick demo on how it works.

Storing Data Using WP7.1 Isolated Storage APIs

As of now we have learned about various file storing technique and in this post we will start with the first one in detail i.e. Storing Data Using WP7.1 Isolated Storage APIs. First of all we need to have a namespace so for this we have a namespace System.IO.IsolatedStorage. Here is a quick terminology used in Isolated Storage :

  • IsolatedStorageFile – represents an isolated storage containing files and directories.
  • IsolatedFileStrem – exposes a file stream access to a file stored within Isolated Storage.
  • IsolatedStorageSettings – it is a very nice name value pair dictionary, which is basically used to store the settings of your application

Saving Data

Now we have understood the terminology then lets’s take a quick look on how data is stored. Below is the sample code -
[code lang="csharp"]
private void saveData(string message)
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
using (IsolatedStorageFileStream fstream = isf.CreateFile(""))
StreamWriter writer = new StreamWriter(fstream);
First we created the IsolatedStorageFile object and then a IsolatedStorageFileStream to create our file, and then the old stuff by creating the StreamWriter object and passing the IsolatedStorageFileStream to it and then writing the message and closing it.

Loading Data

[code lang="csharp"]
private string loadData()
string result = null;
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
if (isf.FileExists(""))
using (IsolatedStorageFileStream fstream = isf.OpenFile("", System.IO.FileMode.Open))
StreamReader reader = new StreamReader(fstream);
result = reader.ReadLine();
return result;

Files and Storage on Windows Phone 8

In this article we are going to learn about the storage in windows phone, it will be a local data storage and we will see different methods to use it. Let’s get a quick overview about how the data is stored locally in a windows phone.

storage overview

There are two different locations in which the data is stored:

  1. Installation Folder – This is the place from where the application gets all its item to the phone, it is also referred as App Data folder. This is ready only folder where we can just read the files which are required for installation and we cannot perform any writing operation.
  2. Local Folder – It is formerly known as Isolated Storage, here we can perform both read and write operations, this is the place we are going to spend our most of the time.

There are different methods for addressing storage location:

File Type / API

Installation Folder

Local Folder


Local Database Data Context appdata:/ isostore:/ MyDataContext db =

new MyDataContext(“isostore:/mydb.sdf”);

File access using WP7.1 Isolated Storage API Not supported StorageFile and StorageFolder APIs var isf =IsolatedStorageFile.


File access using Windows.Storage APIs via URIs ms-appx:/// ms-appdata:///local/ StorageFile storageFile = await Windows.Storage.StorageFile.


(new Uri(“ms-appdata:///local/”));

File access using Windows.Storage APIs via StorageFolder Refrence Windows.Application







var localFolder = Windows.Storage.ApplicationData.



storageFile = await localFolder.GetFileAsync


Windows Phone 8 File Access Alternatives

Let’s have a look at getting a reference of a file by three different ways.

  1. WP7.1 Isolated Storage APIs
    [code lang="csharp"]var isf = IsolatedStorageFile.GetUserStoreForApplication();
    IsolatedStorageFileStream fs = new IsolatedStorageFileStream("CaptainsLog.Store", FileMode.Open, isf);[/code]
  2. WP8 Storage APIs using URI
    [code lang="csharp"] StorageFile storageFile = await
    Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appdata:///local/"));[/code]
  3. WP8 Storage APIs
    [code lang="csharp"] Windows.Storage.StorageFolder localFolder =
    Windows.Storage.StorageFile storageFile =

So, now we are aware of different type of file handing techniques, in the coming posts we will learn how to use them individually.

Windows Phone : Application Bar

Application bar is one of the important thing required in Windows Phone applications, there might be many options which doesn’t fit well if we have a full screen app display and hence we need this application bar where we can actually have some buttons and menu items. Let’s take a quick look at the anatomy of a windows phone app page.

Page Layout

System Tray

It is the system owned indicator area that display system level status information, user can show/hide this in app.

Microsoft.Phone.Shell.SystemTray.IsVisible = false;

Application Bar

We are going to discuss about application bar in our app, it is a place in our app where we place the most common tasks and can also have popup menu for less common tasks.

  1. Use application bar don’t try to create your own menu tray.
  2. You can use up to 4 buttons but that doesn’t mean you have to use all four, fill the slots only if needed.
  3. You can also add up a number of menu items, you just need to swipe up the bar and bring up the menu.
  4. Use white foreground on transparent background for icons, system will colorize button according to user selected theme.
  5. If you want to do some common things you can find the icons located at C:Program Files (x86)Microsoft SDKsWindows Phonev8.0Icons, or you can create your own.

Sample PhoneApplicationBar XAML

<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
<shell:ApplicationBarIconButton IconUri="/refresh.png" Text="refresh"
<shell:ApplicationBarIconButton IconUri="/" Text="search"
<shell:ApplicationBarMenuItem Text="about" Click="ApplicationBarMenuItem_Click_1"/>

As you can see the above code has two buttons refresh and search and one menu item about, they have IconUri property which set the icon source for them and also a Text property which contains a small text which is displayed below the icon. Menu items do not have IconUri as they do not contain images. I have also added the click event on each button and menu item.

When you switch you app in the landscape mode the application bar paints itself in the side of the screen and has some built in animations to that. You can also set the opacity of the application bar less than 1 so that it gives a different look and the background text is visible.

<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True" Opacity=".5">

app bar

Windows Phone : Page Navigation

Page navigation is an important aspect which is required for developing quality app because you just can’t build a single page app, you just need to navigate and this post will help you in navigating to pages in different styles. First of all we should learn the hierarchy where the page resides.

Frame and Page Navigation

Frame and Page Navigation

Frame is the top most container, if you have ever noticed in the App.xaml.cs at the time of bootstrapping of your app the first object your application creates is the phone frame object, Frame contains all the pages and other controls of the application and we don’t program the frame its just present there by default. Then the page covers the whole frame which has the contents and other UI controls which are used in the application.

XAML apps on Windows Phone uses a page based navigation model which is similar to web page model and each page is identified by a URI. Since it is a web based model it has events like NagivatedTo, NavigateBack etc and hence work easily and each page is considered and rendered when NavigatedTo event is fired.

Simple Forward Page Navigation

NavigationService.Navigate(new Uri("/SecondPage.xaml", UriKind.Relative));

This will take you to the SecondPage.xaml, the navigate function takes two parameters first one is the URI and the next one is the UriKind, UriKind is of three types :

  1. Absolute : It means a absolute http url on internet.
  2. Relative : It means it is relative to the root of the application (preferably used within the app navigation) .
  3. AbsoluteOrRelative : It covers all the basis of both Absolute and Relative.

Simple Backward Page Navigation


It is as simple as it seems in the code, yeah it’s a built in behavior and no coding is required for it. WP app creates a history and navigates through those pages in backward fashion and when the above method is called on the MainPage of the app then the app exits.  The hardware back key present on the phone will also do the same work as the above code. But sometimes we need to override the hardware back key action and perform action as per our choice and we will see it in next section.

Overriding Back Key

Sometimes there is a scenario that we have a popup or other control overlaying the main screen and the user wants to close it and go back to main screen and presses the back button but the built in behavior only has navigation between pages and hence it will not close the popup rather will take you to the previous page and hence we need to override the way the back key behaves.




private void MyBackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
 e.Cancel = true; //tell system you have handled it
//you code here

The above code is very easy to understand, if we set the Cancel property of args to true it tells the system you need not to worry yes I have handled it, and below it you can start writing your code about what you want your back button to do.

Passing Data Between Pages

You can pass string data between pages using query string, query strings are passed in a similar fashion as in web based model.

NavigationService.Navigate(new Uri(string.Format("/Selection.xaml?id={0}", 1), UriKind.Relative));

on destination page

private void PhoneApplicationPage_Loaded_1(System.Windows.Navigation.NavigationEventArgs e)
string id;
 if(NavigationContext.QueryString.TryGetValue("id", out id))
 textBlock1.Text = id;

On destination page we can get the parameters passed by using the NavigationContext and TryGetValue function to check whether this navigation holds the value for a particular key or not.

Passing Objects Between Pages

Often you will realize the need of passing the object between pages as when a list item is selected and the page is navigated to it’s detail page then the object is need to be passed. One thing you can do is store your data in the App class and make it global to whole application or you can pass the ID of the selected item as the query string.

NavigationService.Navigate(new Uri("Selection.xaml?selectedItem=" +
 (MyList.SelectedItem as MyViewModel).ID,

And this can be handled at the destination page.

That’s all about page navigation, stay tuned for more on windows phone.

Windows Phone : Data Binding

Data Binding is the most important part of developing a good quality dynamic application. You can set data of TextBox or someother control by creating different pages and you need to write a lot of code for that and hence data binding helps you to easily bind some data to your controls in creating complex applications.

[code lang="xaml"]
Text="{Binding PostName}" />

Here we have a TextBlock for a post name, we can have the value of TextBlock each time but it will make the code more unhealthy and the practice is not recommended and hence you can notice a Binding statement which is pointing at something called PostName, PostName here is the property of some data source and next we have to define the data source by setting the DataContext either on the page or on a specific element (preferably on page). These act as objects which says that against any binding statements I will resolve the data associated with it. So the PostName here is the instance of the data source and once we have defined the data source it automatically pulls the post name and assigns it to the PostNameTextBox.

Data Binding Modes

There are different binding modes which can be used according to the requirement of the application :

OneTime :  It means when the page is rendered any binding statements are resolved against the DataContext, this is done one a single time i.e. if after resolving the data there is a change in data source it is not reflected back on the application page.

OneWay : It gets the data from the data source and there may be a web service or background code running which updates the data source so the UI control gets updates, so it is the synchronized method of data binding.

TwoWay : It is the next step from OneWay, it does everything the OneWay does and can also update the data source for example if a user has TextBox where a user can enter a data or radio button where a user can select a data, then the change goes the other way as well i.e. the data in the data source also gets updated. And the best part is that user don’t have to write any code to update the data source it does it automatically.
[code lang="xaml"]
Text="{Binding PostName, Mode=TwoWay}"  />

So now with data binding we have much more cleaner code much more maintained and a healthy programming practice.

Creating First Emgu CV Project

In the last post we read about Starting with Emgu CV, now here we will start our first Emgu CV project. Emgu CV is not so difficult all we have to do is to add certain references and make use of Emgu Controls. Lets get started.

Lets start creating a blank windows form application.

My First Emgu CV Project

You will get a new project created for you, before starting further enable “show all settings” under tools, this enables a lots of features like form designer layout, snap to grid and many.

tools visual studio

Options page visual studio









Now lets start, first thing we will do is Add References, browse for the Emgu bin folder (by default it is located at C:Emguemgucv-windows-x86 ), in the bin folder there must be some dlls add all those starting with “Emgu.CV” (choose only one among Emgu.CV.DebuggerVisualizers.VS2008.dll and Emgu.CV.DebuggerVisualizers.VS2010.dll depending on the visual studio you are using, in my case it is Emgu.CV.DebuggerVisualizers.VS2010.dll)

Add Reference

Emgu CV Reference DLL

 Now we need to add some existing items, Goto Project>Add Existing Items and now again browse for bin directory of Emgu CV and this time choose all the dll files starting with “opencv_“, these dll files are required for each time the output is generated via Emgu that is why we added them to our project directory, we will also change there property so that they get copied always to the output folder. So, select all the dll added and select properties and change the “Copy to Output Directory” to “Copy Always“.

Add existing items emgu cv












We already have added the Emgu custom controls to our toolbox, now lets design our form, we will be using two ImageBox (Emgu Control), one Button and a Textbox, design the form as below.

Emgu CV Form Design


Now come to the form1.cs code view, and add the following namespaces;

using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV.UI;

Next create some member variables :

Capture capturecam = null; //instance for capture using webcam
bool CapturingProcess = false; //boolean stating the capturing process status
Image<Bgr, Byte> imgOrg; //image type RGB (or Bgr as we say in Open CV)
Image<Gray, Byte> imgProc; //processed image will be grayscale so a gray image

Now its time to add a form load event, we will start capturing via webcam under it.

capturecam = new Capture();

this will associate the default webcam with capturecam object.

code snippet















We have added the associated to capture object in try catch block in order to avoid the error if the webcam is already in use.

We added a event handler to Application.Idle, so that it performs task when idle, and the task is to get the next frame. ProcessFunction is called at every idle state of application.

QueryFrame gets the next frame from the webcam, if it is null it means there is some problem and hence we stop our app there.

InRange function takes two parameter min range and max range of Bgr.

SmoothGaussian applies the Gaussian smoothing with the x,y length = 9, we can pass different parameters for x and y also.

Now lets come to the coding part of playorpause button:

playorpause code










this is the simplest part, it checks the boolean value of CapturingProcess and accordingly changes the button text and stops streaming from webcam.

Sample Output: 

emgu cv output