Category Archives: C++ /CX

Using resumable functions in the CxxReadFileComponent sample

Hello,

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

    progress.report(25.0);

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

    progress.report(50.0);

    auto reader = ref new DataReader(istream);

    progress.report(75.0);

    progress.report(100.0);

    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!!

-Sridhar

How To: Use XAML and DirectX with C++ and create a compelling Windows Store app

One of the great benefits of using C++ to write Windows Store apps is the ability to mix and match various components and create compelling user experiences. There are a variety of apps that use XAML and DirectX together and have built delightful user experiences. For example, there is the FreshPaint app in the Windows Store that allows free form panting using touch or the OneNote app which allows for, as you know, note taking using a stylus (along with keyboard support).

However, if you want to take a look at code and learn from the experts and masters who have built such apps, there are very few options. One such code base is Project Austin which is a sample built by the C++ team to demonstrate using C++ (and CX) along with XAML and DirectX to build a great note taking app. Today’s post, however, is not about Project Austin. It is about a cool sample built by a colleague and C++ enthusiast, Thomas Petchel. Tom built a cool app named Weathr, which he describes as “3D weather app for Windows 8.1 using C++, DirectX, and XAML“. I cannot agree more. This is the best weather app I have seen in a long time and it shows in the user experience. Tom has also made the sources available for anyone to check out and play with. If you are serious about learning how to build such great experiences in your Windows Store apps, please check out the code. And if you make changes to the code, please ensure you contribute back the changes. This ensures that all the folks get the new stuff!!

I can talk about code and design, but I would leave that out for fellow programmers. The app is not on the Store though. So if you want to get the app, you have to build the sources J

Cheers and Happy Holidays!

-Sridhar

Coming Soon: Updated Code Samples with resumable support

Hello,

I will be posting a revised set of samples from my book, “Modern C++ and Windows Store apps” using the resumable function support available from the C++ November CTP. The impacted samples are the ones which use the WinRT Async APIs in conjunction with PPL tasks.

For more information on resumable functions, see this post on vcblog.

Stay tuned for the sample set.

-Sridhar

Learning C++ /CX with a console app on Windows 8.1

I have previously published a template on the VS Gallery that allows you to build console apps by writing C++ /CX code and not starting with XAML and code generation project default templates that VS ships. The previous blog entry is here and the link to the gallery item is here.

The good news is I have published a new template that allows you to use the Windows 8.1 SDK and winmd files to build command line apps while learning C++ /CX. You can get the template here.

Enjoy coding in C++ /CX!

-Sridhar

 

 

 

Targeting Modern C++ and Windows Store apps samples for Windows 8.1 – Part 1 of n

I have previously mentioned that I will not be updating “Modern C++ and Windows Store apps” to have an edition exclusively for Windows 8.1. My reason behind the decision is simple: The concepts and technologies I have introduced in the book continue to be relevant in Windows 8.1 and all of the samples will work on Windows 8.1. Having said that, during Windows 8.1 some WinRT APIs were deprecated and you will see warnings when you compile the samples for Windows 8.1. In this series of blog posts, I will show you how, with little effort and small changes, you can recompile the samples for Windows 8.1.

Note: This is just the first post in a series.

Let us begin with the very first example from the book, the DXBouncingBall sample. 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 as shown below.

Once you ask Visual Studio to retarget the solution to Windows 8.1, Visual Studio makes the necessary changes and opens the project. Once the project is fully loaded, try building the solution. You should see a series of warning messages indicating the usage of deprecated APIs. The warnings are all listed below.

1>e:\projects\old\dxbouncingball\dxbouncingball\directxpage.xaml.cpp(35): warning C4973: ‘Windows::Graphics::Display::DisplayPropertiesEventHandler’ : marked as deprecated

1> Message: ‘The DisplayProperties type and related event handlers may be altered and or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1> This diagnostic occurred while importing type ‘Windows::Graphics::Display::DisplayPropertiesEventHandler ‘ from assembly ‘Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null’.

1> This diagnostic occurred while importing type ‘Windows::Graphics::Display::DisplayProperties ‘ from assembly ‘Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null’.

1>e:\projects\old\dxbouncingball\dxbouncingball\directxpage.xaml.cpp(35): warning C4973: ‘Windows::Graphics::Display::DisplayProperties::LogicalDpi::get’ : marked as deprecated

1> Message: ‘DisplayProperties may be altered or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxpage.xaml.cpp(41): warning C4973: ‘Windows::Graphics::Display::DisplayPropertiesEventHandler’ : marked as deprecated

1> Message: ‘The DisplayProperties type and related event handlers may be altered and or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxpage.xaml.cpp(41): warning C4973: ‘Windows::Graphics::Display::DisplayProperties::LogicalDpiChanged::add’ : marked as deprecated

1> Message: ‘DisplayProperties may be altered or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxpage.xaml.cpp(44): warning C4973: ‘Windows::Graphics::Display::DisplayPropertiesEventHandler’ : marked as deprecated

1> Message: ‘The DisplayProperties type and related event handlers may be altered and or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxpage.xaml.cpp(44): warning C4973: ‘Windows::Graphics::Display::DisplayProperties::OrientationChanged::add’ : marked as deprecated

1> Message: ‘DisplayProperties may be altered or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxpage.xaml.cpp(47): warning C4973: ‘Windows::Graphics::Display::DisplayPropertiesEventHandler’ : marked as deprecated

1> Message: ‘The DisplayProperties type and related event handlers may be altered and or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxpage.xaml.cpp(47): warning C4973: ‘Windows::Graphics::Display::DisplayProperties::DisplayContentsInvalidated::add’ : marked as deprecated

1> Message: ‘DisplayProperties may be altered or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxpage.xaml.cpp(61): warning C4973: ‘Windows::Graphics::Display::DisplayProperties::LogicalDpi::get’ : marked as deprecated

1> Message: ‘DisplayProperties may be altered or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxbase.cpp(177): warning C4973: ‘Windows::Graphics::Display::DisplayPropertiesEventHandler’ : marked as deprecated

1> Message: ‘The DisplayProperties type and related event handlers may be altered and or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1> This diagnostic occurred while importing type ‘Windows::Graphics::Display::DisplayPropertiesEventHandler ‘ from assembly ‘Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null’.

1> This diagnostic occurred while importing type ‘Windows::Graphics::Display::DisplayProperties ‘ from assembly ‘Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null’.

1>e:\projects\old\dxbouncingball\dxbouncingball\directxbase.cpp(177): warning C4973: ‘Windows::Graphics::Display::DisplayProperties::LogicalDpi::get’ : marked as deprecated

1> Message: ‘DisplayProperties may be altered or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxbase.cpp(184): warning C4973: ‘Windows::Graphics::Display::DisplayProperties::CurrentOrientation::get’ : marked as deprecated

1> Message: ‘DisplayProperties may be altered or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxbase.cpp(214): warning C4973: ‘Windows::Graphics::Display::DisplayProperties::CurrentOrientation::get’ : marked as deprecated

1> Message: ‘DisplayProperties may be altered or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

Time for action! If you were to closely observe the warning messages, it should be pretty clear that there is one runtimeclass and some methods/properties/events associated with that particular class that are generating the warnings. That class happens to be the Windows::Graphics::Display::DisplayProperties. I will not go into the finer details of why this class has been deprecated in Windows 8.1 but for a teaser, it has to do with better multi-mon support J. Anyways back to our exercise.

The warning also informs us to use the newer class, DisplayInformation. This is one of the benefits of the great Intellisense support for WinRT apps in Visual Studio. All we need to do now, is replace the usage of DisplayProperties with DisplayInformation. Let’s begin the steps. I am showing you a table of the Windows 8 code and the new Windows 8.1 code to make the illustration easier. Each item in the table corresponds to the warnings in the order they appear.

 

File Name

Line Number in Windows 8 Code

Windows 8 Code

Windows 8.1 Code

DirectXPage.xaml.cpp

35

m_renderer->Initialize(

Window::Current->CoreWindow,

SwapChainPanel,

DisplayProperties::LogicalDpi

);

auto info = DisplayInformation::GetForCurrentView();

 

m_renderer->Initialize(


Window::Current->CoreWindow,

SwapChainPanel,

info->LogicalDpi

);

DirectXPage.xaml.cpp

41

DisplayProperties::LogicalDpiChanged +=


ref
new DisplayPropertiesEventHandler(this, &DirectXPage::OnLogicalDpiChanged);

info->DpiChanged +=


ref
new
TypedEventHandler<DisplayInformation^, Object^>( this, &DirectXPage::OnLogicalDpiChanged );

DirectXPage.xaml.cpp

44

DisplayProperties::OrientationChanged +=


ref
new DisplayPropertiesEventHandler(this, &DirectXPage::OnOrientationChanged);

info->OrientationChanged +=


ref
new
TypedEventHandler<DisplayInformation^, Object^>( this, &DirectXPage::OnOrientationChanged );

DirectXPage.xaml.cpp

47

DisplayProperties::DisplayContentsInvalidated +=


ref
new DisplayPropertiesEventHandler(this, &DirectXPage::OnDisplayContentsInvalidated);

info->DisplayContentsInvalidated +=


ref
new
TypedEventHandler<DisplayInformation^, Object^>( this, &DirectXPage::OnDisplayContentsInvalidated );

DirectXPage.xaml.cpp

61

m_renderer->SetDpi(DisplayProperties::LogicalDpi);

m_renderer->SetDpi( DisplayInformation::GetForCurrentView()->LogicalDpi );

DirectXBase.cpp

177

if (m_dpi != DisplayProperties::LogicalDpi)

{


return;

}

if ( m_dpi != DisplayInformation::GetForCurrentView()->LogicalDpi )

{


return;

}

DirectXBase.cpp

184

m_orientation != DisplayProperties::CurrentOrientation

m_orientation != DisplayInformation::GetForCurrentView()->CurrentOrientation

DirectXBase.cpp

214

m_orientation = DisplayProperties::CurrentOrientation

m_orientation = DisplayInformation::GetForCurrentView()->CurrentOrientation

DirectXPage.xaml.h

41-43

void OnLogicalDpiChanged(Platform::Object^ sender);

void OnOrientationChanged(Platform::Object^ sender);

void OnDisplayContentsInvalidated(Platform::Object^ sender);

void OnLogicalDpiChanged( Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args );

 

void OnOrientationChanged( Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args );

 

void OnDisplayContentsInvalidated( Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args );

 

Change the method signatures appropriately in the DirectXPage.xaml.cpp too and rebuild the solution. It should build clean with no warnings and your app should work on Windows 8.1 without any issues.

Try to resize the application window to different sizes and see how resizing and redrawing are all handled smoothly without having to explicitly write code. Is it not cool to write future proof code? J

 

Have fun!

-Sridhar

Will there be an update for “Modern C++ and Windows Store apps” for Windows 8.1?

With Windows 8.1 now released as a Consumer Preview enabling developers to try out and begin building apps for the new Operating System, I wanted to let folks know if there is an updated version of my book, “Modern C++ and Windows Store apps” under development.

When I began contemplating writing a book about Windows 8, I did not want to just show how to build Windows Store apps using C++ /CX and XAML. That would probably have been a great disservice to C++ developers since it would have restricted the scope of the book to just XAML. Don’t get me wrong. XAML is a great UX framework but I wanted to show how the power and flexibility of C++ and C++ /CX can be used to build a vide variety of apps that could be run both on the Desktop and Modern.

The more I thought about what to talk about in the book, the more my ideas began to crystallize around narrating the “C++ Renaissance” at Microsoft and in the industry. Discussing the “C++ Renaissance” is a vast topic in itself and I had to make a few hard decisions on the list of topics. After multiple deliberations, I ended up discussing the following topics:

  • Show the simplicity of developing Windows Store apps using C++ /CX
  • Important concepts of C++11
  • Introduction to C++ /CX
  • A High level tour of XAML
  • Using C++ /CX to combine XAML and DirectX
  • Advanced GPGPU Programming by using C++AMP in Desktop and Windows Store apps.
      • Under the covers of the Windows Runtime and the Windows Runtime Library (WRL)
      • Introducing the new native unit test support in VS2012.
      • Debugging tips for Windows Store apps
      • Performance tips for using XAML
      • Introduction to Windows Azure Mobile Services
      • A sneak preview of Windows Phone 8 “shared code”.

One of the ideas that I steadfastly took while developing samples and the narration was to focus explaining how C++ developers should be using XAML/DirectX interop techniques to make their apps stand apart from pure XAML or WWA counterparts. XAML/DirectX interop is really the “super pill” that can help C++ developers take full advantage of both the retained mode benefits of XAML and the immediate mode rendering provided by DirectX. When coupled with C++AMP, this has the added advantage of eking out maximum performance from the available hardware for all of your workloads.

With Windows 8.1, while XAML got a host of new controls, using those controls by itself is not an impossible task if you have already worked your way through my book. There simply is no point creating a new version of the book, when the fundamentals have already been discussed. All of the new updates are important but they are not breaking changes or stuff that is hard to incorporate. What is really interesting is the changes to the XAML/DirectX interop types. Does it warrant the creation of a new version of the book to explain 4 new interop types? I don’t think so. It, however, does merit explanation. So, going forward, I will begin posting content about the updated XAML/DirectX interop types. I will also update the samples from my book to show how to move code from Windows 8 to Windows 8.1. I hope that is of more value to readers instead of coming up with a new version of the book. What do you think? Please do let me know.

If you have noticed the topics I discussed in my book, attentive readers must have noticed that I did not discuss any communications or network API in the book. Is it a harbinger for things to come in future? Stay tuned for updates Smile

-Sridhar

What’s new in XAML for Windows 8.1?

//BUILD 2013 concluded last week and there was a ton of stuff to assimilate. I will attempt to summarize a few important changes for C++/XAML/DirectX developers in this blog post., focusing exclusively on the XAML/DirectX Interop scenarios.

If you are interested in knowing what is new with just the XAML framework (new controls, binding features etc), check out this great video from Tim Heuer.

New Stuff for XAML/DirectX interop scenarios using SwapChainPanel

1. A new SwapChainPanel control present in the Windows::UI::Xaml::Controls class.

2. In Windows 8, you were restricted to creating a full screen SwapChainBackgroundPanel and the swap chain had to be present at the root of your control hierarchy. The new SwapChainPanel controls removes these restrictions.

3. This does not mean you can have hundreds of SwapChainPanel controls in your app (Well, not even in the low double digits). Turns out using too many SwapChainPanel controls incurs a heavy cost. So restrict them to at the most 3 or 4. Do not go beyond that.

4. It is composable like any normal XAML element. You can have text layered below or above the control and have the XAML framework render content.

5. A Size Changed notification event provides for crisp re-drawing of content.

New Stuff for XAML/DirectX interop scenarios using the new SiS/VSiS

1. Has updated methods for faster D2D drawing by using drawing with a Direct2D DeviceContext.

2. Using the D2D DeviceContext allows the framework to batch the drawing requests.

3. Supports multi-threaded drawing.

4. Has new methods, SuspendDraw and ResumeDraw to enable you to suspend drawing operations and resume them later.

5. No longer needed to call BeginDraw on the XAML UI thread. In fact, BeginDraw, SuspendDraw and ResumeDraw can be called from any thread.

6. EndDraw should still be called on the UI thread. This allows the XAML framework to update the scene.

SwapChainPanel with Independent Input

1. The new SwapChainPanel now has support for processing touch, pen and mouse input on a background thread. This provides a path for low latency interactivity and high performance.

These are some of the high level changes. I encourage all of you to check out the excellent //BUILD 2013 talk by Bede Jordan,  a Senior Development Lead on the XAML team.

Enjoy the new C++/XAML/DirectX interop stuff in Windows 8.1

-Sridhar