Inside the Windows Runtime #1 – Camera API and Share Contract

I didn’t write anything about BUILD this week, I guess you had a blast reading many other news sites and watching some of the keynotes and sessions. Let’s jump right to the chase, some sweet Windows 8 programming using VS11 on the Windows DevPreview.
For Windows 8, Microsoft has implemented a great new framework, called the Windows Runtime. This framework has been made very easy to use for existing .NET developers and is built to support Metro apps from the ground up. Most of the framework code is built asynchronously so your UI stays responsive. It also contains a great set of APIs, an animations library, great security features and much more. You can target this framework from VB, C#, C++ and Javascript.
In this post we’ll use the good old C# and XAML to talk to the webcam, take a picture and share this picture with Socialite by using the Share Charm. Let’s get BUILDing!

Create and new blank project and let’s get started. First, our interface XAML code, we use the Grid and * systems to provide a UI that sizes accordingly independent of the screen resolution.

<Grid x:Name="LayoutRoot" Background="#FF0C0C0C">
<RowDefinition Height="4*" />
<RowDefinition Height="1*" />
<Image x:Name="img" Margin="50" Stretch="Uniform" />
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Center">
<Button Content="Take Picture" x:Name="btnTake" Click="btnTake_Click" />
<Button Content="Save Picture" x:Name="btnSave" Click="btnSave_Click" />

4* and 1* rows mean that the screen will be divided in 5 parts. 4 parts will take up the first row (the image), 1 part will take up the second row (the controls)

Now we’ll add the sourcecode. First let’s add the functionality to use our camera. Wiring up the camera only takes 2 lines of code. Then we convert the image to a stream, and use that stream to create a BitmapImage. That BitmapImage is used as the source of the image control.

 IRandomAccessStream stream;
        async private void btnTake_Click(object sender, RoutedEventArgs e)
            var camera = new CameraCaptureUI();
            var file = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo);

            var image = new BitmapImage();

            stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
            img.Source = image;

Note the use of the new async keyword in the signature? That’s a new C# language feature saying this method will be doing actions asynchronously. These actions should be preceded with the await keyword. Internally the code after the await keyword is handled as a callback when that line finishes. Until that happens, the other code outside this function executes and the UI stays responsible. When the callback finally executes it is executed on the UI thread, eliminating the need for a Dispatcher to update the UI from another thread.

We use the await keyword when waiting for the camera to take a picture and the stream to be generated. My explanation might be a bit rough, but you’ll find yourself using async and await keywords a lot when wanting to keep the UI responsive. Many of the WinRT stuff is built to support them too (e.g: methods ending in async).

The code won’t work yet, as we haven’t declared the App’s capabilities to use the Webcam and Microphone. This could lead to a security breach and so WinRT automatically denies access to these components unless you explicitly declare them. Go to your Package.appxmanifest and go to the Capabilities tab. Add Webcam and Microphone as seen below.

Test it, and you’ll be able to take pictures! Now let’s add the functionality to share the picture by using something called Contracts. One of the key features of Windows 8 is that applications can interact with each other without really knowing each other. These functionalities are called Charms. Windows 8 has several of them, accessible by hovering over the start orb (square actually) or swiping from the right.

  • Share: share content (pictures, text, links,…) with other applications that provide functionality to use them.
  • Search: search your PC or within installed applications enabling this functionality.
  • Devices: Connect and interact with hardware
  • Settings: provide application settings

The neat thing about these is that they all are encapsulated in the same UI, which will avoid lots of confusion and make applications more universally accessible.

To make use of the Search Charm, we’ll simply subscribe to the event that gets raised when you access the Search Charm, This event is encapsulated within the DataTransferManager, something each XAML window has. We’ll do it simply like this:

 public MainPage()

 var dataTransferMgr = DataTransferManager.GetForCurrentView();
 dataTransferMgr.DataRequested += new TypedEventHandler<DataTransferManager, DataRequestedEventArgs>(dataTransferMgr_DataRequested);

In the event handler we can set what data to share in the parameter, and even include an error message if there’s nothing to share. Using the Set* methods we can choose what kind of file we want to share. If installed applications can share that kind of data, it will appear in a list after pressing the Share charm.

        void dataTransferMgr_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
            if (stream == null)
                args.Request.FailWithDisplayText("No picture was taken");
                args.Request.Data.SetText("Shared via *name* using custom data contact on Windows 8");

When you run your application, take a picture and press the Share Charm you’ll see that you can pick Socialite and share the picture with your Facebook friends! Congats, we BUILD our first Metro application using the Windows Runtime and some cool Windows 8 features. There’s still this Save button waiting in XAML. Do you have the guts to get this working yourself? Maybe a sample on can get you started!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s