Convert StorageFile to a BitmapImage in Universal Windows Apps

We have already seen how to convert a WritableBitmap to a StorageFile in Universal Windows apps.

A StorageFile can be converted to a BitmapImage using the following function.

public class ImageUtils
    public static async Task<BitmapImage> StorageFileToBitmapImage(StorageFile savedStorageFile)
        using (IRandomAccessStream fileStream = await savedStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read))
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.DecodePixelHeight = 100;
            bitmapImage.DecodePixelWidth = 100;
            await bitmapImage.SetSourceAsync(fileStream);
            return bitmapImage;

To use the function call it as follows.

BitmapImage imageSource= await ImageUtils.StorageFileToBitmapImage(savedStorageFile);

convert a WritableBitmap to a StorageFile in Universal Windows apps

Convert Storage File to Byte Array in Universal Windows apps

This async function converts a storage file to a byte array.

public static async Task<byte[]> GetBytesAsync(StorageFile file)
    byte[] fileBytes = null;
    if (file == null) return null;
    using (var stream = await file.OpenReadAsync())
        fileBytes = new byte[stream.Size];
        using (var reader = new DataReader(stream))
            await reader.LoadAsync((uint)stream.Size);
    return fileBytes;

It accepts a StorageFile as argument and returns a byte array for it.

Universal Windows App Project File Structure

All Universal Windows apps following MVVM pattern should have a similar directory structure. The following snapshot shows a possible project file structure of a Universal Windows app.

Let us see briefly what all things go into each folders.

  • App.xaml
  • Controls: Reusable UI controls (application independent views) without view models. Platform specific Controls are added directly to the specific project and Shared controls are added in the Shared Project.
  • Strings: Classes and resources for application localization
    • en-US: Separate directory for every supported language.
      • Resources.resw
  • Models: Model and domain classes
  • ViewModels: View models classes
    • MainWindowModel.cs
    • MyViewModel.cs
    • Dialogs
      • SelectItemDialogModel.cs
  • Converters: This folder includes the Value Converters. Follow this article to see how Converters can be used in Windows apps.
  • Themes: It contains Theme Resources that is Resource Dictionary. Platform specific resources are added directly to the specific project and Shared resources are added in the Shared Project.
  • Services: This could include classes for web service calls, navigation service etc.
  • Utils: It includes all utility functions that would be used across the app. This may include AppCache, FileUtils, Constants, NetworkAvailability, GeoLocation, DataTemplateSelector etc.
  • Views: Contains the views. Platform specific Views are added directly to the specific project and Shared Views are added in the Shared Project.
    • MainWindow.xaml
    • MyView.xaml
    • Dialogs
      • SelectItemDialog.xaml

As shown in the list, the name of a view should end with its type:

  • Window: A non-modal window
  • Dialog: A (modal) dialog window
  • Page: A page view (mostly used in Windows Phone and Windows Store apps)
  • View: A view which is used as subview in another view, page, window or dialog

The name of a view model should be composed of the corresponding view’s name and the word “Model”. The view models are stored in the same location in the ViewModels directory as their corresponding views in the Views directory.

Universal Windows App Project Setup

This tutorial is a part of the series on Building a Universal Windows app using MVVM pattern. In this tutorial we will setup a new project for building a Universal Windows app.

Setting up the Project

In Visual Studio click on New Project and choose Blank App (Universal Windows 8.1) from the existing Templates. If you are unable to find this template in your Installed templates list then head over to the following link to download the latest SDK for Windows Phone.

Structure of Universal Windows app

When you first open up the Solution, the project structure looks something like this.

Each of the platform specific projects contain an Assets folder and a MainPage.xaml file. The shared project contains the App.xaml file which is shared by both the Windows 8.1 and Windows Phone 8.1 apps. The Windows and Windows Phone projects are platform projects and are responsible for creating the application packages (.appx), targeting the respective platforms. The shared project is a container for code that runs on both platforms. They don’t have a binary output, but their contents are imported by the platform projects and used as part of the build process to generate the app packages (.appx).

Switching between Startup projects

To set the startup project, right-click on the project node in the Solution Explorer and choose the option Set as Startup Project. You can quickly switch the startup project from the Debug target drop-down that now enumerates all the possible projects in the solution. The project that you choose is shown in bold in the Solution Explorer. The available debug targets change when switching startup projects.

  • When the Windows project is the startup project, the Debug target drop-down displays options for the Windows Simulator or Local Machine.
  • When the Windows Phone project is the startup project, the drop-down displays options for Device as well as various emulators.

Switch context in Code Editor

When writing code in a shared project, you can use the project context switcher in the navigation bar to select the platform you are actively targeting, which in turn customizes the IntelliSense experience in the code editor.

Cross-Platform Code in Shared Project

In the shared project, you typically write code that is common to both platforms. To isolate sections of code that are platform-specific, use the #ifdef directive. The constants WINDOWS_APP and WINDOWS_PHONE_APP are predefined for you.

We are done setting up our project and getting familiar with a few handy features of Visual Studio while building a Universal app. You could reference the following article to create your first universal Windows app.

Creating Your First Universal Windows App

Series Introduction: Building a Universal Windows app using MVVM pattern

I am starting a new series to help you get started with Universal Windows app development. If you take care of a few things then you could save a lot of time while building a Universal app. Almost all the code can be shared and only the UI needs to be built separately. Even the UI can be shared. In this series I will touching upon a lot of small things that can be used while building the app.

We will be following MVVM design pattern as much as possible. I will strive to have zero code behind and all the code in ViewModel itself. Getting started with MVVM has a bit of learning curve involved but I think it’s best to follow MVVM while building a universal Windows app. I will keep updating this article with link to other parts of the series as I cover them.

Universal Windows App Project Setup

Universal Windows App Project File Structure

How to Check for Network Availability in Universal Windows apps

Application Data in Universal Windows Apps

How to Display Local Toast in Universal Windows Apps

Using Shared Theme Resources in Universal Windows Apps

How to Build a Gauge Control for Universal Windows App

How to Check for Network Availability in Universal Windows apps

If you are building a universal Windows app or an app for Windows Phone 8.1/Windows 8.1 then the following class can help you check for network availability.

Network Availability class

This is a singleton class, which means only a single instance of it will exist during the lifecycle of the app.

The method NetworkInformationOnNetworkStatusChanged gets called whenever the network status changes. This method in turn updates the IsNetworkAvailable property with the current network profile information.


Whenever you need to check if the network is available, simply use:

How to use Converters in Windows phone app (Silverlight/WinRT)

ValueConverters can be used whenever we need to present data in an easy and controllable way such that it doesn’t interfere with other layers of the application.

Converters are called by the Data Binding mechanism whenever binding actually occurs (for example, when a control is notified about the change in the underlying property).


ValueConverters need to implement IValueConverter, a simple two-method interface. The two methods are

1) Convert – Modifies the source data before passing it to the target for display in the UI.

2) ConvertBack – Modifies the target data before passing it to the source object. This method is called only in TwoWay bindings.

For more reference you can see this link.

In this following blog post I shall be demonstrating you how to create an indexvalue
converter for your Windows phone app. The different steps you need to follow are


Step 1:

First create a class having the name IndexToColorConverter in your Project.



And add the following code to it as shown below.




Note: The only difference between Silverlight and WinRT is that the data type of parameter culture has been changed to string in WinRT.


Step 2:

Open the XAML page where you need to use this converter and add the following code in the namespace of the XAML page.

Note: Here Tips8 is the name of the Project. You need to replace it with your own project name.


Step 3:

Add the following code into PhoneApplicationPage page resources section in the XAML. It will create a Static resource within the XAML page with a specific key which will be used by the UI elements further.


  Note: The name of the key can be same as the Class name of color converter or something else. In order to avoid confusion we have kept both names as same.   Step 4: Now in the UI element just bind the property you wish to do so. For example in our project we have binded the Background Property and have assigned the IndexToColorConverter to it. The code for the following is

Note: Here index is the object property to which button is binded.


If you have any doubts regarding data binding you can refer to the following blog post.

Reading and Writing in an Existing text file in Windows phone app (Silverlight / WinRT)

This is a small blog post in which I shall be explaining you how to read and write to an existing text file which is present locally in your project.

Let us suppose the text file is having the name myfile.text and is present under main root directory.



Step 1:

Now first thing you need to do is to set Build Action to Content. And, change Copy to Output Directory to Copy Always. This will ensure the file itself ships with your application. If it doesn’t, you won’t have a file to read.



Step 2:

Now you can read and write your text files easily as shown in the code below


Windows Phone Silverlight








In WinRT you can access files in the local app data store using the “ms-appdata:///local/” protocol. To access files in the app package, use Windows. ApplicationModel. Package. Current. InstalledLocation.







Note: Suppose your file is not located in main directory and is located under the root folder Files as shown below.



Then file name would be

Note: You can use the same technique for an xml or json file.

Adding app review reminder in Windows phone app without using rate my app toolkit

Reviews are key to your app achieving success.
High ratings in the Windows Phone Store encourage new users to download your app.
So there’s no harm in reminding your users to review your app.


I have just prepared a following code which can be useful to you and doesn’t require any toolkit or third party SDK.

So as to use it follow the certain steps given below


1. Add the following namespace given below in the MainPage.xaml.cs of the application or the Start page of the application.

  2. Add the following function in the MainPage.xaml.cs of your application.   For Windows 8/Windows 8.1 Silverlight  
For Windows 8.1(WinRT)/Universal app

The code is self-understandable. The only thing you need to do is to set the variable Appname in the code.

For Windows 8.1(WinRT) you need to add the App id also.


If you have any doubts you can refer to the following blog post.


3. Now call the following function in the constructor of the MainPage.xaml.cs.



When the user will open the app 4 time the following message will be shown to user.



If the user click on OK button the Review Page of Application will be shown to user.

If the user rejects the message and clicks on cancel button the same message will be shown to user 7 time. If then also he rejects the option the same process will be repeated in an interval of number 10 as written in the code. Once the user has rated the application the following message will not been shown to user.


Important Note:
When you are testing the application in debug state an error message will be shown to you when you click on ok button as shown below.



Until your application has passed the submission to be included in the store this error message will be shown to you.


Note: You can configure the interval according to your need. You can change if condition given in the review function code and set the interval according to your need.



For example I want to display this message in the interval of 5. I can change the If condition to as shown below.



I hope this post will be helpful to you. You can download the full project file from the link given below.

Download project file

You can also use ratemyapp toolkit for getting feedbacks from the user. The link of the blogpost is given below.

Adding app review and feedback reminder in Windows Phone 8 app using ratemyapp toolkit