Category: Programming

How to expose C# async methods in WinRT components

When authoring Windows Runtime (WinRT) components with C# you cannot use the standard C# async Task pattern. Say for example you have code like:

Visual Studio will give you a lengthy error similar to this:

'Demo.MyComponent.SaveToFilel(Windows.Storage.StorageFolder, System.String)' has a parameter of type 'System.Threading.Tasks.Task' in its signature. Although this generic type is not a valid Windows Runtime type, the type or its generic parameters implement interfaces that are valid Windows Runtime types.
Consider changing the type 'Task' in the method signature to one of the following types instead:
Windows.Foundation.IAsyncAction, Windows.Foundation.IAsyncOperation, or one of the other Windows Runtime async interfaces. The standard .NET awaiter pattern also applies when consuming Windows Runtime async interfaces.

The problem is Windows Runtime does not support Task for asynchronous operations. Developers must instead use IAsyncAction or IAsyncOperation. That creates a new problem though; if the function uses await it must be declared with the async keyword, and that requires the function to be return Task!

Thankfully there is a way out of this standoff. Keep the original function but mark it as private. Create a new public method that calls the private implementation and returns the result as an IAsyncAction or IAsyncOperation type with the AsAsyncOperation() method. It’s a bit messy but it works perfectly.

Here’s how it would look for the example above:

Embedding user defined resources in Visual C++ binaries

For my current project I wanted the ability to package my entire C++ project (dependent DLLs and data files) as a single Windows executable. To do this I had to find a way to embed the data files into the executable at build time. There’s multiple ways to do this. I settled on using the Windows resource system, since the project is (currently) Windows only.

Add external files

  1. Add text files named “Sample.txt” and “Sample2.txt” to the project with some random text.

Add a new resource file and header

  1. Add a new resource file (.rc) to your project. This example will use ExternalResources.rc.

  2. Add a new header file (.h) to your project with the same name but a .h extension.

  3. Open up the header file and create one entry for each external file you want. Each ID must be unique – it’s a good idea to start around 1000 and go up from there. I use C_ for the definition, but it’s totally optionally. Name your resource however you want!

  1. Open up the resource file (Right click -> View code), and delete everything in the file. Copy the following code, and modify it to fit your needs. The #include <windows.h> statement allows you to declare a language for a resource, which I can cover in a later tutorial.

Accessing resource data

Loading resources

You’re all done, congrats!


Redirecting standard output to console in Windows

When I first started making Windows programs in the early 2000s I needed a way to display logging information visually to the user. With some internet sleuthing I discovered how to create a windows console and using black magic, how to redirect the standard input/output streams to print to this window. With that problem solved I happily used that code unchanged for many years.

At some point it stopped working – I suspect when Microsoft updated their standard library implementation in a newer version of Visual Studio it caused the solution to stop working. Curious, I looked at the code for the first time in nearly a decade and recoiled in horror. The old code redirected output by mucking around with handles and copying the contents of internal FILE structs!

While researching a better solution to the problem of input redirection, I came across an answer on Stack Exchange. It turns out someone else was having the same problem I did, and one of the answers had the same story I did about using the code above and discovering how hacky it was years later! He gives a pretty detailed explanation for what the old code was doing, and how to use freopen to accomplish this behavior correctly.

And now for the solution! Here’s the new code I use to create a Windows console, and redirect standard input/error/output to the console:

That should do it! Remember to properly close the file pointers before the program closes. (It’s not the end of the world if you don’t – Windows will clean it up when the program exits).

GUID Generator

I love it when I need to whip up a quick application that solve a problem, and I have the time to play with something new. Or in this case, something very old. Recently I needed a tool that can generate GUIDs on the fly for me. Sure, there’s a bunch of online websites filled with ads that can do this, but it sounds like the perfect excuse to write an application to do that for me!

Enter GUID Generator! I wanted to see how minimalistic I could get when creating an application. Turns out, you can get pretty tiny. I wrote the application in C++, using only the Windows API and statically linked the C++ Runtime Library. Final result? No dependencies, and the release executable is less than 100k.

It's shocking how ugly a simple win32 app can look!

Anywhoo, I threw the code up into Github under an Apache 2.0 license. Feel free to download the project and use it yourself! If you like it, let me know! 🙂

PS: Using the raw Windows API is painful.

Getting rid of C#’s obj folders

A small tip for developers who are irritated with Visual Studio doing this to your pristine source tree:

Why Visual Studio, WHY?!
obj folders mucking up your day

To get the obj directories out of your source tree, and somewhere nicer (your project’s build output directory for example) open up your project’s .csproj file in an external editor. Locate any line that has the <OutputPath> tag on it. On the line below, insert the following:

For example, in my Dungeon Crawler project I have the following in Dungeon Crawler Shared.csproj

Hope that helped!

Hailstorm: First Version Tagged

Well, I know its not much… but I figured I should start writing about all my programming (and non-programming) exploits more regularly. A lot of these are going to be shorter status updates, since I may not always have that much to write about. At least I’m going to get back in to the habit. 🙂

Here’s a screenshot from my the new improved Hailstorm engine! A big thanks to Christine who got me a DirectX programming book for Christmas. Right now the program only starts up a window and DirectX, but more is coming.

[Scott: Replace the missing image]

Check out for the code and wiki!




Printing Generic C++ Containers

Always wanted a simple utility function to print our an arbitrary STL container? Well, so long as your container type support directional iterators… this method I wrote will work perfectly! Its a great example for why templates are awesome

And now how to use the function:

Compiling Qt with Visual Studio

So your awesome project that you’re developing with Visual Studio, and you want to use Trolltech’s Qt library? Luckily Trolltech provides an awesome Visual Studio plugin that does almost everything Qt creator does (minus Intellisense support for slots). The bad news is that Trolltech doesn’t directly tell you how to go about doing this:

  1. Download and install the Qt for Visual Studio plugin.
  2. Download the source code for Qt 4.7
  3. Start the Visual Studio 2010 Command Prompt ( Microsoft Visual Studio 2010 -> Visual Studio Tools -> Visual Studio Command Prompt)
  4. Navigate to the directory with your downloaded Qt SDK
  5. Run the configure program like so: “configure -platform win32-msvc2010 -debug-and-release -static -no-gif -no-qt3support -no-dbus -no-phonon-backend”
  6. Wait ten or so minutes for configure to finish
  7. Now run nmake. And make dinner, because this will take a very long time
  8. You have Qt ready to go! Yay!

The configure parameters I provide will configure Visual Studio to build the vast majority of Qt. There’s a lot of extra options you can explore if you desire more control – for instance, you can enable exception support.

Have fun!

C++ Template Name Madness

STL vectors can act as typical c-style arrays. To cast from vector<T> to T*, simply take the address of the first element.