Author: Scott

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!

References

http://stackoverflow.com/questions/7288279/how-to-embed-a-file-into-an-executable
https://msdn.microsoft.com/en-us/library/6e7446zd.aspx
https://msdn.microsoft.com/en-us/library/aa381054%28v=vs.85%29.aspx
https://msdn.microsoft.com/en-us/library/ms648046%28v=VS.85%29.aspx

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

Hello World Redux

I swear that's not why I joined Microsoft. Well, maybe a little... :)

Well, it’s been awhile. I took a long hiatus from the online world over the last nine months or so. In that time, I took a big interest in online services (aka the CLOUD), married the most wonderful women in the world, left the game development world and joined the borg Microsoft, moved three thousand miles away to Seattle, and then moved again when our temporary housing was up.

So yup, the last few months have been a bit busy. But I’m settling down again, and would like to restart my previous attempts at blogging.

Read More Hello World Redux

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

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 https://github.com/smacdo/Hailstorm 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!

On Randomness

So, here’s an interesting problem that I’ve been thinking about. Most (if not all) games make very heavy use of random values to determine outcomes and results.

The interesting thing about this though is the idea of luck, or more specifically runs of bad luck (aka incurring the wrath RNG God) where you consistently do not realize the outcome you wish. Ask your average RPG player – what’s more frustrating then attacking a low level spider and missing the next five attacks only to have the spider slay you? Impossible? Not at all. Improbable? Of course. Another infuriating example of this comes in with loot drops. Many bosses drop unique or rare types of loot that people want to collect, and expecting to collect these items can be an exercise in frustration. A 25% drop in no way means that you will have the item within four kills, rather you will need to kill the boss 14 times before you have a 98% chance of collecting said item.

So basically, pure random rolls stink. Over time, the bad runs average out with the good runs, so its not like these situations happen all the time. However it’s human nature to remember the bad runs, and sometimes enough improbable bad strings of luck is enough to make the player quit your game entirely. Sure, it might be _fair_… but who plays a game to die to a lowly spider just because of bad luck? People play games because they want GOOD luck.

So how do we fix this? Well this is what I’ve been thinking about for the past few days. Instead of a pure random number generator, I want a “nice” random number generator that somehow ensures you will get a desired outcome sooner rather than later. Essentially, we want to break up runs of “bad results” with good results in between. The best answer I’ve found so far is the concept of a “grab bag”, which is array of pick results that is shuffled.

I’ll go over this concept more in my next post at some point in the future, and some of interesting properties it brings up. The results are more “balanced”, but does it ruin the concept of a game? Stick around!

(I’m going to try writing more entries to practice my writing abilities, and also to share my thoughts with everyone else on game programming and design. Please share criticism or suggestions with me!)