Using WinRT from C# //build Demo

Yesterday at//build, Jesse Kaplan and I delivered the Using Windows Runtime from C# and Visual Basic talk. In the talk, I demonstrated how natural and familiar it is to use WinRT from C# by building a simple Metro style app. This app  takes a picture with a webcam and implements the share charm contract in less than 15 lines of C# code.

Instead of making you try and read code off the recorded video stream that should be published soon, I’ve written this walkthru to explain exactly what I did in that demo. In addition, I’ve started from scratch (i.e. File->New Project) so that you can follow along at home if you wish.

First, you need to install the Windows Developer Preview. I recommend the x64 version with tools. Scott Hanselman has a great write up on using boot to VHD to run the preview. (though I do disagree w/ his assessment of dual boot. I’ve been dual booting Win7 and Win8 on my laptop for months and it’s never ended in tears or blood). Also, you’re going to need a webcam in order to run the app yourself.

Once the Windows Developer Preview is up and running, run the Socialite app and login with your Facebook credentials. We’re going to use Socialite to share the picture we take with the webcam. Giving it your credentials up front makes the demo run smoother!

Next, fire up VS11 (aka Microsoft Visual Studio 11 Express for Windows Developer Preview). Create a new project and select the Visual C# -> Windows Metro Style -> Application template.

Once the new project has been created, you should be looking at the MainPage.xaml file. Update the Grid element to contain a button and an image.

<Grid x:Name="LayoutRoot" Background="#FF0C0C0C">
    <Button x:Name="ClickMe" Click="ClickMe_Click">Click Me</Button>
    <Image x:Name="Photo" Width="800" Height="600"
           HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>

Next, hover over the Click=”ClickMe_Click” attribute of the button, right click and select “Navigate to Event Handler”. VS11 will take you to MainPage.xaml.cs and automatically generate a skeleton event handler for you.

In my //build session, I demonstrated that VS11 can automatically resolve WinRT namespaces the same way that it resolves managed namespaces. But for the purposes of this blog post, it’s easier if you just add the additional using statements we’re going to need at the top of MainPage.xaml.cs now.

using Windows.Media.Capture;
using Windows.Storage;
using Windows.UI.Xaml.Media.Imaging;
using Windows.ApplicationModel.DataTransfer;
using Windows.Storage.Streams;

Now, we add the code for ClickMe_Click:

private async void ClickMe_Click(object sender, RoutedEventArgs e)
{
    var ui = new CameraCaptureUI();
    ui.PhotoSettings.CroppedAspectRatio = new Size(4, 3);

    var file = await ui.CaptureFileAsync(CameraCaptureUIMode.Photo);

    if (file != null)
    {
        var stream = await file.OpenAsync(FileAccessMode.Read);

        var bitmap = new BitmapImage();
        bitmap.SetSource(stream);
        Photo.Source = bitmap;
    }
}

A few things to note about this code:

  • Even though it’s using native WinRT libraries, the C# feels natural and familiar – as if you were calling into traditional managed libraries. We’re newing up classes, we’re passing in constructor parameters, we’re using primitive numbers and enums, we’re assigning properties, etc. That is very much by design.
  • We’re using a couple of async WinRT methods (CaptureFileAsync and OpenAsync). C# 5.0′s new await keyword to make it extremely easy to write linear looking code that doesn’t block on async operations.
  • No P/Invoke or COM Interop attributes anywhere to be seen!

Finally, before we can run this code we need to declare our intent to use the webcam. Double click on the Package.appxmanifest file, click on the “Capabilites” tab, and then check the Webcam checkbox.

With the capability declared, now we can run the app. Hit F5 and VS11 will compile and deploy the Metro style app you just built. Click the button, acknowledge that you want to let the program use the webcam, take a pic, crop it, and there it is in your UI!

For the second part of the demo, I added share contract support. Here’s how to do that.

First, we need to pull the stream variable into class instance scope so that we can access it in the share contract event handler. We do that by adding a private IRandomAccessStream variable named stream and removing the var declarations from the line where we call OpenAsync. The updated click event handler looks like this:

//here's the instance scope stream variable
IRandomAccessStream stream;

private async void ClickMe_Click(object sender, RoutedEventArgs e)
{
    var ui = new CameraCaptureUI();
    ui.PhotoSettings.CroppedAspectRatio = new Size(4, 3);

    var file = await ui.CaptureFileAsync(CameraCaptureUIMode.Photo);

    if (file != null)
    {
        //the only change from the code above was to remove
        //the var declaration from the following line
        stream = await file.OpenAsync(FileAccessMode.Read);

        var bitmap = new BitmapImage();
        bitmap.SetSource(stream);
        Photo.Source = bitmap;
    }
}

Next, we need to wire up the share event handler in the XAML page’s constructor. That’s a single line of code and VS11 intellisense writes most of  it for you

public MainPage()
{
    InitializeComponent();
    DataTransferManager.GetForCurrentView().DataRequested +=
        new TypedEventHandler<DataTransferManager, DataRequestedEventArgs>(MainPage_DataRequested);
}

If you’ve ever wired up an event handler in C# before with VS, you’ll be familiar with the “Press TAB to insert” the correct event handler type followed by “TAB to generate handler”. Even though hthis is a WinRT event, VS11 helps you wire it up just the same as it does for managed events.

Now we implement the share contract event handler. That’s just a simple if statement – calling args.Request.Data.SetBitmap if the user has taken a picture and calling args.Request.FailWithDisplayText with an error message if they have not.

private void MainPage_DataRequested(DataTransferManager sender,
    DataRequestedEventArgs args)
{
    if (stream == null)
        args.Request.FailWithDisplayText("No picture taken!");
    else
        args.Request.Data.SetBitmap(stream);
}

This part of the demo shows off static methods and event handlers. Again, note how natural and familiar it feels to use WinRT from C#.

And we’re done, so hit F5 to build, deploy and run the app again.

I didn’t remember to do this in the //build talk, but first try selecting the share contract before taking a picture. Windows will display the “No picture taken” text in share contract window since the user taken a picture to share yet. That’s pretty boring so dismiss the share contract and take a picture like you did before. Then select the share contract, select Socalite, write a pithy message and press “Share in Facebook”.

That’s the entire demo! Taking a picture with the webcam, uploading to facebook, calling native WinRT APIs from C# in a natural and familiar way and all in just under 15 lines of code!

With our talk and demos, Jesse and I wanted to communicate just how important C# and VB are in the overall developer story for Windows 8. This demo shows off the hard work our two teams have done in order to make sure the managed developer’s experience with Windows 8 was the best that it could be. As I said in the talk – if you’re a managed developer, you already know how to build these Metro style apps.

I know I said it before, but I really can’t wait to see what you guys build with Windows 8!

The Windows Runtime

After nearly 2 years of not being able to tell anyone what I was working on – or even the name of the team I was on! – //build is finally here and the Windows 8 developer preview is finally out there in the open for everyone to start building applications for. You have NO idea how hard it’s been for me to keep my mouth shut and blog quiet about this!

I am a program manager on the Runtime Experience team, one of many teams in the Windows division building Windows 8. Our team is responsible for building the underlying infrastructure that powers the Windows Runtime (or WinRT for short). In particular, I work on the WinRT metadata infrastructure. I also work closely with our partners in Developer Division that use the metadata to project WinRT APIs into multiple languages.

In a nutshell, WinRT is the new API surface area for Metro style apps in Windows 8. WinRT APIs are available across multiple languages – C#, Visual Basic, C++ and JavaScript – enabling developers to build Metro style apps using the language and frameworks they are most familiar with. Much, much more info is available on the new Windows Dev Center.

In addition to the developer preview docs for WinRT, there are several sessions at //build focusing on WinRT – what it is, how it works under the covers, and how you use it from the various languages. Here’s a handy list of all the //build sessions you should check out if you want to know more about WinRT:

As I write this, not all the sessions have been delivered and none of them are available online yet. But they should all be online within a couple of days. Also, you can also get more information as well as ask questions over at the Windows Dev Center Forums. Our dev manager has already been very busy answering questions!

I am so excited that you can finally see what we’ve been working on and I can wait to see what you build with Windows 8!

Open Position On My Team

My team is hiring. I don’t have a link to the job description on the Microsoft Careers site yet, but the job description is below.

Interested? Send me mail.

IC PM2/Senior Program Manager Position in the Windows Developer Experience Team

Do you want to help ship the most ambitious release of Windows to date? Do you want to make your impact on millions of developers and hundreds of millions of users?

We are the Developer Experience Team. We are building the next generation of developer technologies for creating Windows applications. Our platform powers the new APIs that developers will use to create stunning new Windows applications. You will own the design and delivery of key platform features that will be used by developers in the Windows org, at Microsoft, and around the world to create the APIs that power the next generation of Windows applications.

What do we need from you? Awesomeness. What exactly does that mean? You can drive ambiguous goals independently to completion. You know what needs to get done and by when. You lead by example, cat-herd by necessity, and make a positive impact on your peers in PM, Dev and Test. Others in your org seek out your help because they know you will get it done, or that you will show them how to get it done better if they are coming to you for advice.

Requirements:

  • You have 5+ years of experience in Program Management.
  • You love software developers and can see the world from their perspective.
  • You have strong JavaScript/C#/C++ skills
  • You have completed multiple ship cycles on a large-scale product.
  • You have intellectual horsepower and creativity, and can quickly adapt to new technologies and go deep in new areas.
  • You have excellent communication and partnering skills. You can drive features
    across teams who have different needs and priorities.
  • Experience delivering developer platforms a significant plus.

Job Opening on my Team

I’m just starting the third week in my new job – though between Thanksgiving and an intestinal virus, I’ve only been in my office for five days total so far. That’s not enough time to establish enough groundwork to be comfortable talking about what my team is doing yet. However, I just found out we’re still hiring and better yet there’s a public description of the job opening. So if you’ve ever thought “I want to work for Microsoft/Windows Division/With Harry”, here’s your chance! And if you aren’t looking for a new job, at least you can get some small hints as to what I’m doing in my new gig – “building substantial improvements into the Windows development platform” sounds interesting, doesn’t it?

Senior Program Manager(708846 -External)

Job Category: Software Engineering: Program Management
Location: United States, WA, Redmond
Job ID: 708846 9986
Product: Windows 
Division: Windows Division

Developers! Developers! Developers!

Developers are the key to the success of Windows and at the center of a software ecosystem that represents hundreds of billions of dollars. Our team is chartered with reinvigorating the Windows developer ecosystem by building substantial improvements into the Windows development platform (APIs, tools and the underlying infrastructure) and making developing for Windows fun!

The team is currently seeking a Senior Program Manager to help us achieve our mission. The ideal candidate will have:

  • Strong core PM competencies with special emphasis on developer tools and collaboration skills.
  • Proven track-record of delivering results in a cross-team (ideally cross-division) environment.
  • Has been a Program Manager shipping key products for at least 6 years.
  • Deep empathy for the developer as a customer; ability to empathize through 1st hand experience of writing apps some of the issues developers are facing with respect to APIs, tooling such as Visual Studio and SDK.
  • A demonstrated track record of excellence and delivering in ambiguous V1 situations.
  • Has Bachelors in Computer Science or engineering.

Joining Windows

Big news in DevHawk land: I’ll be taking on a new role in the Windows division after I come back from TechEd Europe (plus a week vacation visiting my bro-in-law in Germany after TechEd).

You guys have heard of Windows, right? They just released a new version recently you might be aware of…Actually, I hear it was your idea!

Seriously, I am stoked to be joining the Windows team. I can’t say much about the new job beyond a) it’s in Windows Client (as opposed to Windows Server) and b) I’m working on a team that’s focused on the Windows developer experience. The Windows team is deep in what you might call “building on teh awesome that is Windows 7” but that they simply call “planning”, so sorry if specifics are kinda sparse. I’ll be back working for Mahesh Prakriya, who originally hired me into my current role on the IronPython team. Someday I might tell you the Mahesh PyCon Lego Story, but for now I’ll just say I was great working for Mahesh the first time and I think this time is going to be even better.

Working on Windows…focused on developer experience…for Mahesh – It’s like the perfect storm of work geekdom for me.

Of course, starting a new job means my time on the IronPython team is coming to an end. As excited as I am about this new opportunity in the Windows division, I’m a little sad to be leaving Developer Division and the IronPython team. I’ve joked with audiences that I care about Python because Microsoft pays me to care about Python, but that’s not completely true. Python is a fantastic language and IronPython’s combination of Python + .NET is hard to beat in my opinion. IronPython has made significant progress while I’ve been here the last eighteen months – two major releases (well, 2.6 is almost done), redisting the Python standard library, Visual Studio 2010 compat – but there’s still much for IronPython to accomplish. And of course, leaving behind such great teammates like Dino, Dave, Jim and Jimmy is ALWAYS hard.

The Windows team is somewhat tighter lipped than the totally transparent approach we use in IronPython. Not to worry, my evangelism skills were part of the reason I got the job so you’ll be hearing plenty from me soon enough. However, my posting here will be kinda sparse until I get my bearings over there. Until then, I’m sure that you will be absolutely fascinated by non-work-related-but-still-sometimes-geeky minutia I post on Twitter.