Async/await is arguably one of the most important language improvement to ever come to C#. But there are a few notable gaps that can leave developers scratching their heads. Chiefly among these is the inability to support async events and properties. Fortunately, there are some patterns that developers can employ to solve these problems. In this article I will demonstrate one such way to support async events.

The following pattern is actually based on Microsoft’s own WinRT deferrable APIs so if you’ve ever built a Windows Phone or Windows Store app, chances are you are already familiar with the consumer side of the pattern.

How it works at a high level

Event handlers merely need to request a deferral from the event argument, run async code, then tell the deferral when they are done (either by calling a .Complete() on the deferral or disposing it). Easy breezy.

Event raisers need to instantiate a DeferrableEventArgs object, raise the event passing along this object to the event handler and then wait until all deferrals requested by the event handlers complete.

How to build and consume

Let’s take a look how to accomplish this in our own custom events.

Event handlers: We will start by examining what the event handler will look like. As mentioned, this should already be familiar to Windows developers if you’ve ever handled a deferrable event such as the Windows.UI.Xaml.Application.Suspending event.

MyClass myClass = new MyClass();
myClass.DoingSomething += MyClass_DoingSomething;
async void MyClass_DoingSomething(object sender, DeferrableEventArgs e)
    using (var deferral = e.GetDeferral())
        await Task.Delay(200); // run an async operation

Note: we could also call deferral.Complete() instead of .Dispose (by way of the using statement). Both have the same effect of signaling when the deferral has completed.

Event raisers: Next, let’s look at the code responsible for raising the event and awaiting all event handlers to complete work.

class MyClass
 public event EventHandler<DeferrableEventArgs> DoingSomething;

 public async Task DoSomethingAsync()
 if (DoingSomething != null)
 var args = new DeferrableEventArgs();
 DoingSomething(this, args);
 await args.DeferAsync(); // completes once all deferrals are completed.

The real magic: The real work happens in the DeferrableEventArgs object (which we need to create). I had hoped to find an existing .NET or WinRT base class already available but sadly, one does not exist. That said, Windows.Foundation.Deferral is available to reuse as the actual deferral object.

public sealed class DeferrableEventArgs
 readonly List<TaskCompletionSource<object>> taskCompletionSources;

 public DeferrableEventArgs()
 taskCompletionSources = new List<TaskCompletionSource<object>>();

 public Deferral GetDeferral()
 var tcs = new TaskCompletionSource<object>();
 var deferral = new Deferral(() => tcs.SetResult(null));
 return deferral;

 public IAsyncAction DeferAsync()
 return Task.WhenAll(taskCompletionSources.Select(tcs => tcs.Task)).AsAsyncAction();

Let’s dissect… Here we create and maintains a collection of TaskCompletionSource objects. Each time an event handler requests a deferral (by calling .GetDeferral), we create one TaskCompletionSource and mark it as complete (by calling .SetResult) when its associated deferral is signaled as completed by the event handler. The code responsible for raising the event calls DeferAsync to get a task that it can await. Here we use the Task.WhenAll method to combine all TaskCompletionSource tasks (ultimately converted to IAsyncAction to make WinRT compatible before returning it).

Hopefully this pattern will help you fully take advantage of the async await features in your app without compromising the architecture. There are other improvements that could be made here such as allowing event handlers to signal failures and cancellation, supporting deadlines, and sheltering event handlers from the DeferAsync method but hopefully this is ample to get you started with a nice reusable and robust pattern for supporting async events.

If you are a Windows 8 or Windows Phone developer you probably already know the importance of the Segoe UI Symbol font and how it provides a wealth of great “metro” icons that can be used in appbar buttons. If so, then you are also probably aware that finding the right character/glyph can be a laborious task.

There are a number of helpful, but incomplete lists on the web, and of course there is the dated ancient character map tool that comes installed with Windows but all have serious shortcomings.

After wasting a fair number of hours myself trying to hunt for glyphs, we at Vertigo set out to build the ultimate character map tool with developers in mind.


Download Character Map for free from the Windows Store


Easy to browse: scroll through the list of available glyphs in any font installed on your system. The icons are large enough to easily see so you won’t ruin your eye sight trying to find one ;)

All glyphs are accounted for: the app queries the OS (DirectWrite actually) to find the unabridged list of glyphs for the given font. You might be surprised to see what you’ve been missing.

Filter by Unicode range: Want to exclude certain Unicode ranges to reduce the number of glyphs for a given font? We’ve got that too.

Dark and light theme: You can tap on the large glyph on the right to toggle foreground and background colors – or – you can go to the settings charm to change the theme of the entire app from dark to light.

Get the enumerated named: Some of the Segoe UI Symbol fonts have names. This is the preferred way to reference the icon in code and also helps give you an indication of the intended meaning for that glyph.

Get the Unicode name: sometimes glyphs have a defined meaning and name in Unicode that can be useful to know.

Get hex, decimal, and markup. Markup is especially useful for referencing the glyph in code, Xaml, or HTML when an enumerated name does not exist.

Search: Type in what you’re after into any of the fields on the right to find the glyph you’re looking for. For example: search by enumerated name by just typing into the “Enum” text box.

Save as transparent image: Save the given glyph as a transparent png of any size. Remember, you can simply tap the icon to reverse the colors before saving if you needed.

Copy to clipboard: No character map tool would be complete without the ability to easily copy the selected character to the clipboard.


Complete source code is also available

Since both this post and the app were written with developers in mind and because we developers tend to be a curious bunch, I’m guessing a few of you might also be interested in how this app was built. Therefore, we decided to fully open source Character Map to offer a way to see what’s under the hood or even contribute if you come up with a must-have feature.


Happy icon hunting and I hope you enjoy! Please rate the app in the store if you like it and please post suggestions, bugs and requests in the discussion forum on CodePlex to make them easy to track.

Back at the dawn of .NET I wrote a useful little tool for myself called Seeker. Seeker is just a simple GUI Windows app that could search for text in your file system and optionally replace it with other text. To this day I still use this tool on a regular basis and have often thought about updating, open sourcing and sharing it with the world. Today’s the day!


Install Seeker now


What does it do?

  • Search files of any type for text.
  • Optionally replace text found with different text.
  • Optionally use regular expressions.
  • Search for multiple entries in a file.
  • Control the encoding used to search and replace files. By default, encoding is automatically detected and preserved.

Aren’t there already other tools out there that do the same thing? Certainly, there are a number of great options out there already. Windows Explorer itself allows you to search for text in files and the first grep tool was probably invented before my time.

So why did I write yet another search and replace tool for Windows? A few reasons: 1) Way back in the day, it served a fun little weekend project to help me learn .NET 2) I needed all the features listed above and was having trouble finding a free version that did everything I needed. Yes, I’m cheap ;) 3) I wanted to be able to easily modify it if special needs arose.

Warning: Seeker is a very powerful tool and can be configured to change text in any file that you have permission to modify. Therefore, Be VERY careful when doing replace operations to ensure you don’t accidentally modify files you don’t intend to. There’s no ability to undo so use at your own risk.

Seeker is also 100% open source and can be found at seeker.codeplex.com.

Please post feedback either here or on CodePlex and enjoy!

The Kinect sensor that comes with all Microsoft Xbox One units needs to be set up either just below or above your screen. The Kinect sensor has a nice flat base that makes it easy to set on a level surface.

However, depending on how your entertainment system is organized, it may be necessary to mount the Kinect sensor to your wall. For example, if your TV is hung on a wall (as opposed to in a cabinet or on a table) or if you use a projector instead of a TV.

It is worth noting that the Xbox 360 Kinect had a number of accessories to mount your Kinect to a wall, TV, or even use a floor stand. Additionally, you can buy an Xbox One Kinect sensor mounting kit for $20.00. but it sadly appears to be made for clipping the sensor to a TV, not attaching to a wall.

Kinect Sensor TV Mounting Clip view 1

Good news: upon further examination, I discovered that the Kinect has a standard camera tripod mount on the base (this is just a standard 1/4 inch screw hole). Yes, this does means that you could easily put your Kinect on any standard tripod, although for most I’m guessing this is probably not a very cost effective nor aesthetically pleasing option.


…just to prove it will attach to a standard tripod.

OK, so how do I mount it to a wall? The fact that the Kinect for Xbox One has a standard tripod mount opens the door to attaching your Kinect sensor to the myriad of 3rd party camera equipment readily available on the market. For example, just by searching the web you can easily find a number of affordable “camera wall mount” accessories available (I’m guessing these products may be sold primarily for security cameras).

For my living room I wanted something discrete, solid (metal not plastic), with an adjustable head, and be black to match the color of my Kinect. I chose the VideoSecu Camera Mounting Bracket on Amazon for only $6.99 with my Amazon Prime account.



Note: I also looked in my local Best Buy, Radio Shack for an option but came up empty handed. For me, the VideoSecu Camera Mounting Bracket was a great option and so far I have no complaints!

Know of a better option? Let me know!

Happy Xbox One-ing!

The other day I was looking at the Google Analytics data for my Windows 8 app and discovered that almost 5% of my users were running a resolution of 1371.42858886719 x 771.428588867188. Huh!?

The bad news is, this was due to a bug in the Google Analytics SDK for Windows 8 and Windows Phone — which I wrote! :)

The good news is, I have since fixed it, learned a lesson (that I should have already known), and can now share my findings with you.

The point of this post is to walk through the subject of detecting physical screen resolution from within your Windows 8 and Windows Phone apps. Although not terribly complicated, it is slightly more involved than you might expect. The cruxes are 1) there is no single API to query the size of the screen your app is running on and 2) you need to understand how a certain magical feature called scaling works.

First, what not to do:

You might be tempted to determine screen resolution via the following mechanisms…

For Windows Phone 8:

Size resolution = new Size(



For Windows 8:

Size resolution =

    new Size(Window.Current.Bounds.Width, Window.Current.Bounds.Height);

The problem with this code (there are actually 2 issues for Windows 8 but I’ll get to that next) is that it doesn’t account for scaling.

Scaling is an awesome feature built into the platform where the OS attempts to stretch everything on the screen so an app will display at an ideal and consistent DPI regardless of the physical screen size and resolution. It does this by fooling the app into thinking that it’s running at a lower resolution than it actually is, but internally scales everything up to the real resolution before showing it on the screen. Also important to know: assets will not lose quality when they have more pixels than the pre-scaled size (this will make sense after my example below).

An example of scaling:

Let’s take an example of a 10.6” 1080p monitor (note: this is one of the screen resolutions you can set the Windows 8 simulator to).

Because this resolution is fairly high but the physical screen size is fairly small, Windows will automatically enable scaling and fool your app into thinking it is running on a lower resolution monitor. To re-iterate, this is a good thing because it means you as a developer or designer don’t have to worry about your UI looking really tiny on this particular device. To your app, the dimensions of the app (as reported by the APIs above) will actually be 1371.42858886719 x 771.428588867188 and so fonts and icons and shapes, …etc in your app will conveniently layout nicely and end up appearing at a similar size and position as it would on a 10.6” 720p monitor. Scaling gives you this little gift for free without you as the developer writing special code to change font sizes, …etc depending on physical screen DPI.

Avoiding pixilation!

I won’t get too much into the weeds about pixilation or best practices but I feel obligated to discuss 2 important things:

1) If you build your UI using a vector language (Xaml & HTML are vector languages), Windows and Windows Phone will be able to scale your UI to get the most out of every pixel without pixilation. Your app doesn’t need to do anything extra; scaling will automatically occur when visual elements are rendered and every pixel will be used. Learn more about vector graphics if that doesn’t make sense.

2) Assets like images and videos will automatically scale to fit the final resolution, not the fake application resolution. This one might be a little counter-intuitive. Imagine the following Xaml to display a 300×300 image:

<Image Source="/img300.png" Stretch="Uniform" Width="214" Height="214"/>

Because we set the width and height on the image control explicitly, your first impression might be that the image will always be stretched (Stretch = Uniform after all) to 214×214. The correct answer is: it depends.

If Windows has determined not to scale (because your monitor and resolution are close enough to the ideal DPI), then yes, the image above will be shrunk down to 214×214 when displayed on the screen.

However, if Windows scaling is occurring (lets assume at 1.4x), the image will actually be displayed on the screen in it’s full 300×300 glory. (214 * 1.4 = ~300)

To prove it, here are 2 images I created in Photoshop from the same vector source. One is saved at 214×214 pixels and the second is saved at 300×300 pixels. Using the following Xaml:

<StackPanel Orientation="Horizontal" Background="White">

 <Image Source="///img214.png" Stretch="Uniform" Width="214" Height="214"/>

 <Image Source="///img300.png" Stretch="Uniform" Width="214" Height="214"/>


When scaling is turned off (1x scaling):


Notice, the images look identical. This is because Windows will shrink the 2nd image (300×300) down to 214×214 before displaying it on the screen just like the Xaml says to do.

When Windows is scaling at 1.4x:


If you look closely, you can see that the second image is crisper. This is because the 300×300 pixel image is actually being displayed on the screen at 300×300 pixels despite what our Xaml’s height and width say will happen. The first image is actually being stretched to 300×300 when it is rendered to the screen.

Back to detecting resolution. And the correct answer is…

Easy, simply get the scaling factor (accessible via an API) and multiply it by the dimensions we gathered earlier.

For Windows Phone 8:

var content = Application.Current.Host.Content;

double scale = (double)content.ScaleFactor / 100;

int h = (int)Math.Ceiling(content.ActualHeight * scale);

int w = (int)Math.Ceiling(content.ActualWidth * scale);

Size resolution = new Size(w, h);

For Windows 8:

var bounds = Window.Current.Bounds;

double w = bounds.Width;

double h = bounds.Height;

switch (DisplayProperties.ResolutionScale)


    case ResolutionScale.Scale140Percent:

        w = Math.Ceiling(w * 1.4);

        h = Math.Ceiling(h * 1.4);


    case ResolutionScale.Scale180Percent:

        w = Math.Ceiling(w * 1.8);

        h = Math.Ceiling(h * 1.8);



Size resolution = new Size(w, h);

Almost there, don’t forget about snapped mode and orientation.

…I warned earlier that there was a 2nd problem with the Windows 8 code at the top.

For the Windows Phone, you actually don’t have to do anything. There is no such thing as snapped mode on the phone and Application.Current.Host.Content.ActualHeight and .ActualWidth always return values as if the app is running in portrait mode (even when it’s landscape).

For Windows 8, you do need to account for both snapped mode and orientation.

To help with this, you can compensate based on the ApplicationViewState. For example, here is the code I use to calculate the actual screen size, even when in portrait mode or filled mode (filled mode is when another app is in snapped mode next to your app).

if (ApplicationView.Value == ApplicationViewState.FullScreenLandscape){

    resolution = new Size(w, h);


else if (ApplicationView.Value == ApplicationViewState.FullScreenPortrait)


    resolution = new Size(h, w);


else if (ApplicationView.Value == ApplicationViewState.Filled){

    resolution = new Size(w + 320.0 + 22.0, h); // add the width of snapped mode & divider grip


The only thing lacking here is detecting the screen size when the app is snapped mode. While this bothers the purist in me, I find that most users don’t start apps in snapped mode so as long as you get the resolution at the beginning of your app’s lifetime and remember it, 99.9% of the time you will be able to accurately determine the actual screen resolution.

Worthy of mention…

Apparently it is possible using DirectX and C++/CX to determine the actual screen size. I haven’t tried this for myself but there is a blog post on how to detect screen resolution from a C++ WinRT component here.

Additional resources

Scaling to different screens

Guidelines for scaling to screens (Windows Store apps)

Multi-resolution apps for Windows Phone 8

The Windows 8 and Windows Phone developer dashboards offer some fantastic and useful metrics without developers having to lift a finger. This is great for tracking the basics such as purchases, downloads, & crashes but if you’re serious about understanding your users and improving your apps, you’ll quickly realize there are easily dozens of questions this data fails to answer. Or maybe you just want near real time information.

In a quest to improve my own apps: PuzzleTouch for Windows Phone and PuzzleTouch for Windows 8, I created the Google Analytics SDK for Windows 8 and Windows Phone and am excited to share my work with other developers. This SDK is a full featured Google Analytics client-side open source library to help your app report data to the new Google Analytics service just released last month. It supports both Windows 8 store apps and Windows Phone 7 & 8 apps and includes the same features offered in the Google Analytics SDKs for iOS and Android.


Aren’t there already some great open source Google Analytics libraries out there for Win8 and WP developers?

The short answer: Yes, but they don’t work with the latest version of Google Analytics. If you want all the great new features supported today by Google Analytics or if you are setting up Google Analytics for your app for the first time, you are are required to use an SDK that supports the new Google Analytics Measurement Protocol. This new protocol is completely different from the older UTM protocol and is not backward compatible. As far as I am aware, no others libraries exist at the time of this post.

Find out more on the Google Analytics for Windows 8 and Windows Phone SDK CodePlex page about how and if this affects your existing apps.

What additional features does the new Google Analytics service include?

The ability to track and filter by app name and version.

This is extremely powerful and allows you to:

  1. Create one property for all your apps (Windows 8, Windows Phone, Android, iOS, …etc) and use filters to view them separately.
  2. On the flip side, it also allows you to compare all apps against each other.
  3. Create arbitrary filters to allow you to group certain apps (for example, you could see data for both the WP7 and WP8 version of your app as well as see that data separately.
  4. Radically change what data you track from one version to the next and create a new filter to only view data from newer versions of your app without loosing old data or having it pollute new data.
  5. Track different editions of the same app. For example, you might have a free and a paid version that you want to track together yet be able to filter on.

Track exceptions and crashes

The Windows Phone and Windows Store dashboard both offer a way to see stack traces from crashes. However, the Windows store requires some effort to see your stack traces (for Xaml based apps) and both take at least two days before data data shows up (often much longer from my experience).

When you release a new version of your app, one of the most valuable things you could possibly know is “did I break something”? The new Google Analytics service offers a great way to capture errors (handled and unhandled) in near real-time so you can analyze what went wrong and try to ship a fix before more users are affected. Don’t think you’re immune to needing this! :)

Custom dimensions and metrics

Custom dimensions and custom metrics are like default dimensions and metrics (e.g. sessions and page views), except you create them yourself. You can use them to collect up to 200 data points that Google Analytics doesn’t automatically track. These offer numerous advantages to the old custom variable feature. Read more about custom dimensions and metrics.

Screen views and more

If you’re familiar with the classic version of Google Analytics, you may remember that screen views were displayed as page views. Google Analytics classic tried to treat your app like a website and with it came irrelevant information such as bounce rate and referrers. The new version of Google Analytics knows if you’re tracking an app and the reporting tools have been overhauled to easily help you find information relevant for apps, not websites.

Additionally, there are some additional improvements to allow you to tie custom events to specific screens in your app. No longer will you have to create 2 different events and prefix the name with the name of the page from whence it came.


Possibly the best new feature of all is E-Commerce tracking. Now you can treat transactions like transactions and not have to stuff them in custom events with overloaded point values. Google Analytics easily shows you how much money you’re making in your currency of choice and information about what lead up to a purchase.

Much More

Plus, there are many other new features in Google Analytics like app timings (e.g. how long did it take my game play screen to load?), social network tracking (e.g. do users like sharing on FaceBook or Twitter more?), and much more.

How do I get started?

If you have an iOS or Android app, Google has already built SDKs for you.

If you want to track a Windows Phone (7 or 8) or Windows 8 Store app (JavaScript, C++, or .NET), go to CodePlex to learn more about the Google Analytics SDK for Windows 8 and Windows Phone or download it from NuGet.

Google Analytics itself is free (at least until you reach its quota). It’s extremely easy to spin up a new account, property and profile and start testing immediately.

The Google Analytics SDK for Windows 8 and Windows Phone is free and open source under the Ms-PL license (basically don’t sue me and use it for whatever you want).

What about other 3rd party analytics services?

There are other 3rd party analytics services available today with their own SDK. Some of these might be better than Google Analytics but I haven’t had a chance to check them out personally. Feel free to post a comment from your own experience with another analytics services.

Azure Blobs is a great, inexpensive, and scalable cloud storage service that you can use to host any static file. In particular, I find it extremely useful for hosting progressive download videos (e.g. .mp4 files). Note: if you need the uber-solution (encoding, adaptive streaming, …etc) check out Windows Azure Media Services which offers a full range of services to deliver high quality video to a range of different platforms.

While Azure Blobs is very easy to setup and manage, there’s one essential configuration setting you will want to change before serving progressive download video that isn’t so obvious: byte-range support.

Let’s start with the problem. Out of the box, if you throw a .mp4 file on your Azure Blobs container and point your video player at the video, you’ll see the video play and buffer just fine. But, what happens, when you try to seek to an unbuffered portion of the content?


Result: Buffering, waiting, annoyance, time for a coffee break?


The reason is simple: by default, Azure Blobs does not enable support for byte range requests. Described with less jargon: in order to jump to a portion of the video that hasn’t downloaded yet you can either:

1) wait until the download (buffer) catches up to the new position of playback (results seen above) or

2) the solution: tell the server to skip all the data yet to be buffered prior to the new position (identified below in red) and instead start buffering from the new position.


Under the hood, this is supported automatically by most modern video players AS LONG AS the server serving the video supports returning byte ranges and returns the response header: “Accept-Ranges: bytes”

The good news is, Azure Blobs does support this, you just need to enable it by setting the default version of the service to a newer one.

The bad new is, this setting is not exposed in the Azure Portal nor most tools I’ve used (e.g. CloudBerry).

So how do it change it? Send a Set Blob Service Properties REST API request.

Seriously? Isn’t there an easier way? Well, there are free tools out there to do this for you. For example: Plasma AzureBlobUtility.

BlobUtility.exe -k AccessKey -a AccountName -c ContainerName --setDefaultServiceVersion 2012-02-12

Or, if you’re paranoid like me and don’t like to give the key to your house to a stranger (no offense Plasma). Here are the steps and code to do it yourself in VS2012 in <1 minute:


Create a new C# project. (I chose a WPF application which is probably not the best choice but I’m just going to throw this away when I‘m done).


Add a NuGet package for Azure Storage by right clicking on your project and choosing Manage NuGet Packages.


Search for “azure storage” and install the “Windows Azure Storage” NuGet Package by Microsoft.

Finally, add the following code to your app, replace the account name and secret key for your Azure Blobs account and run it…

public MainWindow()

    var credentials = new StorageCredentials("myaccountname", "mysecretkey");
    var account = new CloudStorageAccount(credentials, true);
    var client = account.CreateCloudBlobClient();
    var properties = client.GetServiceProperties();
    properties.DefaultServiceVersion = "2012-02-12";

Notice that we didn’t need to specify the container. This change will apply to all containers for that account.

DONE! Now all videos served from your Azure Blobs account will support seeking into the unbuffered area of the video without significant delay.


Get every new post delivered to your Inbox.

Join 26 other followers