Category Archives: WinRT

Using resumable functions in the CxxReadFileComponent sample


Welcome back from holidays. A few weeks ago, I posted a note about updating the samples of my book to the November CTP of Visual C++. The main goal behind the update is to move away from using PPL tasks for WinRT asynchronous programming and instead use the new resumable functions available in the CTP.

Today is the beginning! The first sample I will talk about updating is the CxxReadFileComponent sample that discusses about building a C++ WinRT Component that can be consumed from other WinRT supported languages.

Before we begin:

  1. Get the updated sample here. We will use this sample as a starting point for our migration. Before we write actual code, it is important to note that the CTP is only supported along with Microsoft Visual Studio 2013.
  2. The CTP works with VS 2013. In case you do not have VS 2013, you can get either an express (free) edition or a trial edition here.
  3. In case you have not already downloaded the Visual C++ November CTP, please do so. You can download and install the CTP from this location.
  4. Install VS 2013 first and then the CTP.
  5. Time for action!!!

The first step is to migrate the solution from Microsoft Visual Studio 2012 to the 2013 version.

When you attempt to open the solution file in Visual Studio 2013, Visual Studio prompts you to retarget the solution for Windows 8.1 as shown in the dialog below. If you choose not to retarget, then you will have to install the Windows 8 development tools in order to build the solution.

For the purpose of this exercise, go ahead and retarget the solution to Windows 8.1 by first clicking on OK in the above dialog and then right click on the project in Solution Explorer and choose Retarget to Windows 8.1

Once you ask Visual Studio to retarget the solution to Windows 8.1, Visual Studio makes the necessary changes and opens the solution. Once the solution is fully loaded, right click on the CxxReadFileComponent project in Solution Explorer and choose Properties. In the Properties Dialog, under the Platform Toolset, choose Visual C++ Compiler Nov 2013 CTP (CTP_Nov2013) and click on OK.

The CxxReadFileComponent has one class named ReadFile. You can find the relevant code in the wrongly named files, Class1.h and Class1.cpp. The ReadFile class defines public methods that returns one of the IAsync* interfaces that all WinRT asynchronous methods are expected to return. This allows for consumption of such async operations from other languages. Before we go ahead with changing code, let’s open pch.h and add a new reference for a header. Add a new include reference for pplawait.h in pch.h which pulls in all the required declarations necessary for the new resumable functions.

Things to remember when using resumable functions in C++ for WinRT

  1. You cannot have resumable support for any WinRT method that returns one of the IAsync* interfaces.
  2. Only methods that return either a Task<T> or void can be resumable.

Making code changes

Now, it is time to make changes to code. Open Class1.cpp and navigate to the ReadBytes function. The original function is listed below:

Original ReadBytes function using PPL tasks:

You can see from the code above, using tasks and chaining them can become quite “messy”. With the new resumable functions, each task can be replaced with a single call to the underlying async API along with the __await keyword prepended to the API call. That’s it. No lambdas, no chaining etc.

Updated ReadBytes function using resumable functions:

task<UINT> ReadFile::ReadBytes(String^ fileName) __resumable


    StorageFolder^ item = KnownFolders::DocumentsLibrary;

    auto storageFile = __await item->GetFileAsync(fileName);

    auto istream = __await storageFile->OpenAsync(FileAccessMode::Read);

    auto reader = ref new DataReader(istream);

    return __await reader->LoadAsync(static_cast<UINT>(istream->Size));


Disclaimer: I have not added error handling. You can add proper if- checks and handle errors. The intention here is to show the ease of use of the resumable functions.

Changes made:

  1. All resumable methods have a __resumable identifier added at the end of the function declaration in both the header and the source files.
  2. Use the __await keyword when making calls to the WinRT Async APIs.
  3. That’s it!!

Similarly I made changes to the ReadBytesWithProgress function. The original function is listed below:

Original ReadBytesWithProgress function using PPL tasks:

Updated ReadBytesWithProgress function using resumable functions:

task<UINT> ReadFile::ReadBytesWithProgress(Platform::String^ fileName, Concurrency::progress_reporter<double> progress) __resumable


    StorageFolder^ item = KnownFolders::DocumentsLibrary;

    auto storageFile = __await item->GetFileAsync(fileName);;

    auto istream = __await storageFile->OpenAsync(FileAccessMode::Read);;

    auto reader = ref new DataReader(istream);;;

    return __await reader->LoadAsync(static_cast<UINT>(istream->Size));


With these changes made, build the solution and run the C# client test app. Make sure you have a text file named 127.txt in your Documents folder before you run the test app. Once you run the app, you can see that the app makes calls into your component and reads the number of bytes in the file using the updated methods, which really simplify writing asynchronous code using C++.

That’s it for today. See you soon for a next sample update. Stay tuned as this is getting very exciting!!


Tip of the day: Using Constants in WinRT

This tip comes courtesy of a question asked on an internal discussion list. Deon from the C++ team provided the answer.

WinRT does not support constants. This means you cannot have code such as the following in C++ /CX:

public ref class FooClass sealed



const int FooValue = 42;


How does one mimic constants with C++ /CX? Turns out using a static property is the solution.

namespace Foo


    public ref class FooClass sealed



        static property int Value


            int get()


                return x;


            void set(int _value)


                x = _value;




        static int x;



Having static properties allows you to write code as follows:

Foo::FooClass::Value = 42;

int i = Foo::FooClass::Value; 

Better, this code now works if you want to access such properties from other WinRT supported languages such as JS, C# etc.



Purchase Modern C++ and Windows Store apps in India


Wanted to provide a quick update on the availability of my book, “Modern C++ and Windows Store apps”, in India.

Get the eBook in Adobe PDF:

Get the paperback edition:



[Updated with purchase and discount links] Modern C++ and Windows Store Apps – A book about Modern C++ and native technologies

Over the past few months, I have been writing a book on developing apps using C++ and the various native technologies shipping as part of the Windows 8 wave. Some of these technologies include: C++11, C++ /CX, native XAML, the Windows Runtime, C++AMP, Windows Azure Mobile Services etc. I am happy to announce that the Kindle version of “Modern C++ and Windows Store apps” will be available shortly for purchase via the Amazon website. A paperback edition will also be available soon.

For purchasing the paperback edition of the book, please visit this link. You can use the discount code 5C56GCKN to get 20% discount off MRP.

For folks interested in an electronic edition, you can purchase a Kindle edition on Amazon

A quick update: This is just me self-publishing the book thereby bringing the work to its logical conclusion.

For the benefit of everyone, I am listing some of the topics that await anyone who picks up a copy of this book. For the more adventurous amongst us who would rather prefer to play with code, the book samples can be downloaded from the Downloads section of this blog.

The new native API
What is a Windows 8 App?
Quick walkthrough of a Windows 8 App

Hello Modern C++
Move semantics
Welcome to the Component Extensions
The C++ /CX Type System
Asynchronous Programming in C++ /CX
Building a WinRT component using C++ /CX and ISO-C++
Guidance on the use of C++ /CX

Introduction to XAML
Hello World with XAML and C++ /CX
Basic XAML Syntax
Using Panels to Layout UX
Basic XAML Controls
Windows 8 Signature XAML Controls
Handling Events
Markup Extensions
Data Binding
Binding to a Data Model
Building a XAML custom control
Using Animations in XAML Controls

Introduction to XAML + DirectX
Design considerations when using SiS and VSiS
The DrawIt Application – C++, XAML and DirectX

The C++ AMP Library
The ImageEffects application

Playing by the rules of the Windows Runtime
Introduction to the Windows Runtime Library
Hello World XAML App using Windows Runtime Library

Getting Started with Windows Store apps and Windows Azure Mobile Services
Creating a simple Windows Store app with Windows Azure Mobile Services
Supporting Push Notifications using Windows Azure Mobile Services

And more….

I had a lot of fun writing this stuff and learning along the way. I hope there are concepts that you can apply to your work as you build apps for the Windows 8 Store using C++.

Please send feedback on the book contents directly to win8book at sridharpoduri dot com

The power and flexibility of C++ or why you should write C++ apps for Windows 8 and beyond :-)

Last Friday, the C++ team in Redmond released source code for “Project Austin” a skunk works project that is essentially a note taking app. Check out the team’s announcement blog here.

This app is one great example of the power of C++ allowing you to code in a largely ISO-C++ code base and then interface with the Windows Runtime API. The app uses the XAML-DX SwapChainBackgroundPanel type and uses XAML to layer UI elements over the “main Window”. It also uses C++AMP and extensively uses DirectX and all of the native goodness that is present in C++ and Windows 8.

I could go on and on but I would defer you to the blog post above. And yes, all this goodness in graphics, performance, inking etc without the overhead of GC.


Programming Windows 8 Applications using C++ /CX–An update on the book

I have been thinking of providing an update on the status of my work on authoring “Programming Windows 8 Applications using Microsoft Visual C++”. Today marks a good time for a teaser Smile

As announced earlier, there are 6 chapters and I am almost done with 4 chapters along with samples that explain the finer concepts of the new platform. Here is a breakdown on the content in each of the chapters.

Chapter 1 – The Windows Runtime

  1. Introduction
  2. Traits of Windows 8 apps*
  3. What is the Windows Runtime?
  4. Playing by the rules of the Windows Runtime
  5. Mapping Windows 8 app* traits to the Windows Runtime
  6. A New UI Framework for C++ developers
  7. Introduction to the Windows Runtime Library
  8. Working with the Windows Runtime Library

Chapter 2 – Introduction to C++ /CX

  1. Introduction
  2. C++ /CX, Windows Runtime and ISO C++
  3. The C++ /CX Type System
  4. Asynchronous Programming in C++ /CX
  5. A peek inside the magic of C++ /CX
  6. Guidance on the use of C++ /CX

Chapter 3 – Programming XAML using C++ /CX

  1. Introduction
  2. Hello World with XAML and C++ /CX
  3. Basic XAML Syntax
  4. Using Panels to Layout UX
  5. Basic XAML Controls
  6. Windows 8 Signature XAML Controls
  7. Handling Events
  8. DataBinding
  9. Putting it all together: Developing a PhotoViewer App
  10. Introduction to XAML + DirectX
  11. Developing Apps using XAML + DirectX

Chapter 4 – C++ AMP and Windows 8* Apps

  1. Introduction
  2. The C++ AMP types
  3. Using Tiles in C++ AMP
  4. Debugging C++ AMP apps
  5. Developing Windows 8 Apps* using C++ AMP

The first three chapters are now with Microsoft Press and content being reviewed internally. I will post an update on this blog as the content moves through the various hoops and inches towards the end goal of getting into your hands.

It was fun writing all the stuff and I still have 2 more chapters to finish. Stay tuned and let me know your thoughts!!!


*Please note that all Windows 8 apps referred to here and in the book are based on the Windows Runtime and are not desktop apps.

Using JSON and C++ in Windows 8 Apps

The LiveSDK team has a bunch of exciting samples demonstrating using JavaScript along with HTML, C# with XAML to build apps that integrate Live services. Sadly however, a full blown C++ sample is missing from the lot as I write this today. Last week I built a proof of concept sample PhotoViewer app as part of writing samples for my upcoming book on building Windows 8 Apps using C++ and XAML. What follows below is a summary post on how to consume JSON APIs in C++.

Windows Runtime has built in APIs to support JSON APIs: both building objects based on responses from web services like the Live service in our case and then parse the object collection to build desired features. The namespace Windows::Data::Json namespace contains a list of APIs that make JSON consumption a breeze. The various classes and types that form part of this namespace are listed below:

  1. IJsonValue
  2. JsonArray
  3. JsonError
  4. JsonErrorStatus enumeration
  5. JsonObject
  6. JsonValue
  7. JsonValueType enumeration.

In order to make successful requests to Live services, it is recommended to have users sign in using “Microsoft Accounts”. Purchasing and downloading apps from the Windows Store needs users to sign in with Microsoft Account. Having such an account also enables single sign on for all Microsoft services. We will explore the process of triggering a sign in operation in a later blog post. For today, we focus on making requests to the skydrive APIs.

Fetching Album data from Skydrive

The Live Services team built a great “test” portal for testing various Live APIs here.  The first web request to fetch a list of album data is to make a GET request to the base API url at and append an authentication token. This token is initially obtained when the user signs in to the Live OAuth authentication API. For our C++ code to make a successful web request, we rely on XHR (Xml Http Request). The LiveSDK samples on GitHub have a helper class called XHREvent and we will rely on the same. Our code to make a web request looks like this:

 1: std::wstring url = PhotoSkyCpp::BaseApiUrl + L"/me/albums" + SampleDataSource::GetAccessTokenParameter();

 2: SendRequest(

 3:     ref new Uri(ref new String(url.c_str())),

 4:     "GET",

 5:     ref new XHRDataReceivedHandler(this, &SampleDataSource::OnDataAvailable),

 6:     ref new XHRCompletedHandler(this, &SampleDataSource::OnGetAlbumDataCompleted),

 7:     ref new XHRFailedHandler(this, &SampleDataSource::OnSendRequestFailed));

The SendRequest function accepts a URL, an action verb, which in our case is “GET” and three callback functions, one for notifying if data is available, one for the data fetch completion status and finally a callback to handle request send failures.

For the case of our discussion, we will ignore both the OnDataAvailable and OnSendRequestFailed functions. When the Live API sends a response to our “/me/albums” request, it does so in JSON format. This response is passed back to the OnGetAlbumDataCompleted handler and we will build our JSON objects here.

In order to build a Json Object successfully from a web response such as Live service, we first need to initialize the Json object as follows:


 1: JsonObject^ tokenResponse = ref new JsonObject();


The JsonObject class listed above has a static function named TryParse that accepts a string and a reference to a JsonObject type that can be initialized with the said response string.


 1: if (JsonObject::TryParse(responseString, &tokenResponse))

 2: {

 3:     ... use the JsonObject tokenResponse

 4: }


Once the JsonObject is initialized successfully, we obtain a read-only collection of the Json Objects. The next step is parsing this collection for the data key. For a valid Json object view, a data key must be present. The Lookup method on the IMapView collection returns a IJsonValue^ associated with the data key. The next step is to obtain a string representation of the series of Jsonvalues by calling the Stringify method on the IJsonValue^ obtained from the previous step.


 1: auto map = tokenResponse->GetView();

 2: IJsonValue^ value = map->Lookup("data");

 3: String^ s = value->Stringify();


The final step is to iterate over the collection of items present in this string and do whatever is needed for your app.


 1: JsonArray^ mapValue = ref new JsonArray();

 2: if (JsonArray::TryParse(s, &mapValue))

 3: {

 4:     auto vec = mapValue->GetView();

 5:     std::for_each(begin(vec), end(vec), [this](IJsonValue^ M)

 6:     {

 7:         Name = M->GetObject()->GetNamedString("name");

 8:         ID = M->GetObject()->GetNamedString("id");

 9:         //Do specific operations using the Name and ID properties

 10:     });

 11: }


This is a very simplified introduction to using the JSON APIs in Windows Runtime and consume the same from C++.



Announcement: Book on C++ /Cx and Metro style app development


I am happy to announce an upcoming book on C++ /Cx and Metro style app development. This book is currently in the works and will be published by Microsoft Press. I present a brief list of topics that are covered in the book.

1. Windows Runtime, WRL and writing apps using WRL.

2. C++ /Cx and C++ 11 features.

3. XAML and C++ /Cx (includes discussion on XAML plus DirectX)

4. Incorporating C++ AMP in Metro style apps.

5. Building WinRT components using C++ /Cx

6. Unit Testing support for C++ in VS 2011.

C++ 11 is new; C++ /Cx is new and so is WinRT. I am super excited to work on these technologies and author a book. Stay tuned for more!!


Reflection in the native Windows Runtime

If the Windows Runtime has all sorts of metadata information on classes, types, interfaces etc, could a developer implement Reflection for native types? James McNellis has done just that. He has coded up a reflection library for native types. Just shows how cool native really is!!

Head over to his blog for more details.