<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><title>DevHawkDevHawk</title><link>http://devhawk.net</link><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/Devhawk" /><description>Passion * Technology * Ruthless Competence</description><language>en-US</language><lastBuildDate>Mon, 25 Jun 2012 08:06:23 PDT</lastBuildDate><sy:updatePeriod xmlns:sy="http://purl.org/rss/1.0/modules/syndication/">hourly</sy:updatePeriod><sy:updateFrequency xmlns:sy="http://purl.org/rss/1.0/modules/syndication/">1</sy:updateFrequency><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/Devhawk" /><feedburner:info uri="devhawk" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><geo:lat>47.640972</geo:lat><geo:long>-122.033189</geo:long><feedburner:browserFriendly>(Enter a personal message you would like to have appear at the top of your feed.)</feedburner:browserFriendly><item><title>Windows Camp Demo, Part Two</title><link>http://devhawk.net/2012/06/24/windows-camp-demo-part-two/</link><category>Development</category><category>Windows</category><category>Windows Runtime</category><category>C++</category><category>C++/cx</category><category>Channel 9</category><category>Metro style apps</category><category>Windows 8</category><category>Windows Camp</category><category>WinRT Components</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">DevHawk</dc:creator><pubDate>Sun, 24 Jun 2012 20:15:24 PDT</pubDate><guid isPermaLink="false">http://devhawk.net/?p=2012</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>In my <a href="http://devhawk.net/2012/06/19/windows-camp-demo-part-one/">previous post</a>, we set up a C++ WinRT component project and a C# Metro style XAML app to use the component. The code was dinky Hello, world type stuff. Now, let’s do something a little more interesting.</p>
<p>In preparing for this demo, I found a <a href="http://bitmap.codeplex.com/">C++ bitmap library</a> on CodePlex that includes a plasma texture generation function. This sounded like a good demo for both language interop and using existing code. It builds on the code from <a href="http://devhawk.net/2012/06/19/windows-camp-demo-part-one/">my previous post</a>, so either start there or <a href="https://github.com/devhawk/WindowsCampDemo">clone from GitHub</a> and checkout the part1 tag.</p>
<p>First step is to add the bitmap_image.hpp file from <a href="http://www.partow.net/index.html">Arash Partow’s</a> <a href="http://bitmap.codeplex.com/">C++ Bitmap Library</a> to the C++ component project. Download the <a href="http://bitmap.codeplex.com/SourceControl/list/changesets">latest commit</a> from CodePlex as a zip and extract the bitmap_image.hpp file into your C++ component project directory. Switch over to VS, right click on the component project node, select Add -&gt; Existing Item… and select the bitmap_image.hpp file.</p>
<p>Now that we have included the library code, we need to write the wrapper code to expose that library functionality to other languages via WinRT. We’ll start by adding the following namespace declarations to the top of the Class1.h header file:</p>
<pre class="brush:cpp">using namespace Windows::Foundation;
using namespace Windows::Storage::Streams;</pre>
<p>And then we’ll add the declaration for our GetPlasmaImageAsync method to Class1’s header file underneath the SayHello method. Note, in my original presentation I called this method GetPlasmaImage, neglecting to follow the naming convention of appending “Async” to name of all asynchronous methods.</p>
<pre class="brush:cpp">IAsyncOperation&lt;IRandomAccessStream^&gt;^ GetPlasmaImageAsync(
    unsigned int width, unsigned int height);</pre>
<p>We’re using two WinRT types in this method declaration.</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.streams.irandomaccessstream.aspx">IRandomAccessStream</a> represents a stream of binary data that supports random access. We’re going to return our plasma image as an IRandomAccessStream and then wrap it in a XAML bitmap image for use in our UI.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/br206598.aspx">IAsyncOperation&lt;T&gt;</a> represents an asynchronous operation that returns a value. Generating the image takes a significant amount of time (especially given the shortcut I used as you’ll see in a bit) so we need to make it async. Async is a <em>big</em> topic and we’re just touching on it in this walkthrough. For more on async in WinRT, check out my teammate <a href="http://blogs.msdn.com/b/windowsappdev/archive/2012/03/20/keeping-apps-fast-and-fluid-with-asynchrony-in-the-windows-runtime.aspx">Jason Olson’s post</a> on the <a href="http://blogs.msdn.com/b/windowsappdev/">Win8 app developer blog</a>.</li>
</ul>
<p>Now that we have the declaration, let’s switch over to the Class1.cpp file to add the method implementation. This isn’t a one line method like SayHello, so I decided to separate declaration from implementation as is traditional C++ best practice.</p>
<p>Before we do anything else, we need to #include the bitmap_image.hpp file. However, this bitmap library uses an unchecked destination STL copy function that <a href="http://msdn.microsoft.com/en-us/library/aa985872(v=vs.110).aspx">Microsoft considers unsafe</a>. I <em>really </em>should be updating the code to used <a href="http://msdn.microsoft.com/en-us/library/aa985965(v=vs.110)">checked iterators</a>, but since this is demo code, we’re going to turn off the warning instead. We do that by #defining _SCL_SECURE_NO_WARNINGS. While we’re doing that, let’s add the additional #includes and using namespace statements we’re going to need.</p>
<pre class="brush:cpp">#include "pch.h"
#include "Class1.h"

#define _SCL_SECURE_NO_WARNINGS
#include "bitmap_image.hpp"
#include &lt;string&gt;
#include &lt;ppltasks.h&gt;

using namespace WindowsCampComponent;
using namespace std;
using namespace concurrency;
using namespace Windows::Storage;</pre>
<p>In addition to the bitmap image library, we’re going to need the STL string library and the Parallel Patterns Library, so I’ve gone ahead and #included those header files and used those namespaces. We’re also going to use some types from the Windows::Storage namespace, so I’ve used that namespace as well.</p>
<p>The implementation of the GetPlasmaImageAsync method is going to happen in several steps:</p>
<ol>
<li>Generate the plasma image using the C++ Bitmap library</li>
<li>Save the plasma image to a temporary file</li>
<li>Reopen the temporary file as an IRandomAcessStream with WinRT’s file system APIs</li>
</ol>
<p>Saving and reopening the file is the shortcut I alluded to earlier. The image library includes a save_image method that uses STL streams to write the image out to a file. A better solution would be to factor the save_image method to support saving a bitmap to a stream and then implementing an STL -&gt; WinRT stream adapter, but this is a simple demo so I’ll leave that as an exercise to the reader. (Please send me a pull request if you do this!)</p>
<p>First, we’re going to generate the file path we’ll be saving the image to. Turns out this somewhat difficult because WinRT uses wide character strings while the bitmap library expects ASCII STL strings.</p>
<pre class="brush:cpp">//get the temp filename
auto tempFolder = ApplicationData::Current-&gt;TemporaryFolder;

wstring tempFolderPath(tempFolder-&gt;Path-&gt;Data());
string folderPath(begin(tempFolderPath), end(tempFolderPath));

auto filePath = folderPath.append("\\plasma.bmp");</pre>
<p>I’m not proud of this code. It’s the kind of code you write when you’re rushing to get a demo for your talk done. But lets look at it anyway.</p>
<p>First, I get the path to the temporary folder via the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.applicationdata.current.aspx">current</a> <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.applicationdata.aspx">ApplicationData</a> object. Then I converted it first to a std::wstring and then to a std::string. I probably could have created the std::string directly from the tempFolder variable, but using the begin and end iterators of the wstring is a clever hack I read somewhere online. Finally, I append the file name to the folder path to get the final file path name.</p>
<p>Next, we generate and save the plasma image. This code is lifted almost verbatim from the bitmap_test.cpp file that comes with the C++ image library. The only difference is that we’re using the width and height arguments as parameters to the bitmap_image constructor rather than hardcoded values.</p>
<pre class="brush:cpp">//create the image object
bitmap_image image(width, height);
image.clear();

double c1 = 0.9;
double c2 = 0.5;
double c3 = 0.3;
double c4 = 0.7;

::srand(0xA5AA5AA5);

//generate plasma image
plasma(image, 0, 0, image.width(), image.height(),
    c1, c2, c3, c4, 3.0, jet_colormap);

//Save the image to the file
image.save_image(filePath);</pre>
<p>Finally, we open the image file from the temporary folder using WinRT APIs. File access APIs in WinRT are exclusively async, so I’m using <a href="http://msdn.microsoft.com/en-us/library/hh750113(v=vs.110)">PPL tasks</a> to simplify the async code. Note, I’ve reworked this code from what I did in the video to make it easier to understand. I’ve also added explicit type declarations that I didn’t need to make it clear what each type is. If I replaced those all with the new auto keyword from C++11, the code would work the same.</p>
<pre class="brush:cpp">//reopen the image file using WinRT
IAsyncOperation&lt;StorageFile^&gt;^ getFileAsyncOp = 
    tempFolder-&gt;GetFileAsync(ref new String(L"plasma.bmp"));

task&lt;StorageFile^&gt; getFileTask(getFileAsyncOp);

task&lt;IRandomAccessStream^&gt; openFileTask = 
    getFileTask.then([](StorageFile^ storageFile) {
       return storageFile-&gt;OpenAsync(FileAccessMode::Read);
    });

return create_async(
    [openFileTask]() { return openFileTask; });</pre>
<p>First, we call GetFileAsync to get the file from the temp folder which returns an IAsyncOperation&lt;StorageFolder^&gt; object. We then convert the IAsyncOperation to a PPL task via the task constructor. Note, these two steps could be easily combined into a single step if you not being extra verbose for education purposes.</p>
<p>Once we have a PPL task to get the file, we specify the operation to do when the task completes by passing a lambda to the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh750044.aspx">task&#8217;s then method</a>. In this case, we’re going to open the file after we get it. The then method is nice because we can chain together as many async operations as we want in a nearly-synchronous coding style.</p>
<p>Finally, once we have built up the PPL task that represents the entire asynchronous operation, we use the <a href="http://msdn.microsoft.com/en-us/library/hh750102(v=vs.110).aspx">create_async</a> method to convert the PPL task back to an IAsyncOperation which we return from the function.</p>
<p>Now that we have written the component side, lets update the client side. Async operations are very succinct in CLR because of the <a href="http://msdn.microsoft.com/en-us/library/hh191443(v=VS.110).aspx">new await keywords</a>. Much nicer than the .then model used by PPL (which is probably why Herb Sutter <a href="http://herbsutter.com/2012/04/06/we-want-await-a-c-talk-thats-applicable-to-c/">wants to see await added to C++</a>).</p>
<pre class="brush:csharp">private async void Button_Click_1(object sender, RoutedEventArgs e)
{
    var wcc = new WindowsCampComponent.Class1();
    myText.Text = wcc.SayHello("Herb Sutter");

    var stm = await wcc.GetPlasmaImageAsync(800, 600);

    var bitmap = new BitmapImage();
    bitmap.SetSource(stm);
    myImage.Source = bitmap;
}</pre>
<p>And it works!</p>
<p><a href="http://devhawk.net/wp-content/uploads/2012/06/WCDemo2-RunningApp.png"><img class="alignnone size-medium wp-image-2015" title="WCDemo2-RunningApp" src="http://devhawk.net/wp-content/uploads/2012/06/WCDemo2-RunningApp-300x187.png" alt="" width="300" height="187" /></a></p>
<p>And that’s the entire demo. About 20 lines of code to wrap a  pre-existing library function and make it available to other languages via the Windows Runtime. I showed calling my WinRT component from C# here, but I could have called it from JavaScript just as easily.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Devhawk?a=6E4w_Vqd1UQ:HOIDpIteMM8:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=6E4w_Vqd1UQ:HOIDpIteMM8:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=6E4w_Vqd1UQ:HOIDpIteMM8:XQ266DUsA9M"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=XQ266DUsA9M" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=6E4w_Vqd1UQ:HOIDpIteMM8:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=6E4w_Vqd1UQ:HOIDpIteMM8:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Devhawk?i=6E4w_Vqd1UQ:HOIDpIteMM8:V_sGLiPBpWU" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Devhawk/~4/6E4w_Vqd1UQ" height="1" width="1"/>]]></content:encoded><description>In my previous post, we set up a C++ WinRT component project and a C# Metro style XAML app to use the component. The code was dinky Hello, world type stuff. Now, let’s do something a little more interesting. In preparing for this demo, I found a C++ bitmap library on CodePlex that includes a [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devhawk.net/2012/06/24/windows-camp-demo-part-two/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">0</slash:comments></item><item><title>Ambiguous ExtensionAttribute Errors</title><link>http://devhawk.net/2012/06/20/ambiguous-extensionattribute-errors/</link><category>Development</category><category>C#</category><category>CLR</category><category>Extension Methods</category><category>LINQ</category><category>Visual Basic</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">DevHawk</dc:creator><pubDate>Wed, 20 Jun 2012 20:46:59 PDT</pubDate><guid isPermaLink="false">http://devhawk.net/?p=2023</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>I was recently contacted by <a href="http://nathanaeljones.com/">Nathanael Jones</a> of the <a href="http://imageresizing.net/">ImageResizer project</a> about a <a href="http://stackoverflow.com/questions/11025100/escape-catch-22-with-extension-attributes-in-net-2-0">question</a> he had posted on Stack Overflow:</p>
<blockquote><p>How can a single .NET assembly, targeting 2.0, 3.0, 3.5, 4.0, and 4.5 concurrently, support extension methods for both C# and VB.NET consumers?</p>
</blockquote>
<p><strong>Short Answer</strong>: <u><em>You can’t.</em></u> You think you can, but if you’re serious about targeting .NET 2.0/3.0 and 3.5+ as well as that whole C# and VB support thing, you can’t. Not really. </p>
<p><strong>Long Answer</strong>: People <em>love</em> extension methods. Seriously, I think some people want to marry extension methods they love them so much. They just can’t stand to be without their extension methods, even when they’re using .NET 2.0. </p>
<p>Rather than go without, <a href="http://www.danielmoth.com/Blog/Using-Extension-Methods-In-Fx-20-Projects.aspx">some</a> <a href="http://msdn.microsoft.com/en-us/magazine/cc163317.aspx#S7">people</a> <a href="http://www.codethinked.com/using-extension-methods-in-net-20">figured</a> <a href="http://kohari.org/2008/04/04/extension-methods-in-net-20/">out</a> how to get extension methods support on older versions of the .NET Runtime. Extension methods are essentially a compile time technology – the IL that gets emitted for calling an extension method is identical to the IL for calling a normal static method. The only runtime dependency for extension methods is the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.extensionattribute.aspx">ExtensionAttribute</a> which is used to mark methods intended to be used as extension methods (as well as classes and assemblies that contain them). ExtensionAttribute is defined in System.Core from .NET 3.5, but it’s just a marker. If you define your own copy of ExtensionAttribute and use the VS 2008 or later version of the C# compiler, you can get extension methods to work on .NET 2.0.</p>
<p>Back when I was working on IronPython, we ran into this exact issue when we merged DLR expression trees with LINQ expression trees. LINQ trees used extension methods all over the place, but we still needed to support .NET 2.0 in IronPython. We were already using the VS08 compiler so all we had to do was add our own copy of ExtensionAttribute to the DLR and we were good to go…or so we thought. Instead, <a href="http://devhawk.net/2008/09/17/dlr-namespace-change-fire-drill/">we discovered</a> that this approach doesn’t work as advertised &#8211; at least not if you care about VB support. </p>
<p>The problem stems from having multiple copies of ExtensionAttribute. IronPython and DLR had no problem – they were compiled for .NET 2.0 and thus had only the one copy of ExtensionAttribute that we added to the DLR. But people who used IronPython or DLR in a .NET 3.5 project ended up two copies of ExtensionAttribute – the copy we added to DLR and the official System.Core version. Two copies of a system provided type == start of a big problem.</p>
<p>Actually, if you’re only using C#, having multiple copies of ExtensionAttribute isn’t that big a deal. The C# compiler raises a <a href="http://msdn.microsoft.com/en-us/library/8xys0hxk.aspx">warning</a> when it find multiple definitions of a type in the System namespace. Because ExtensionAttribute is in the System namespace, C# has to pick one of the colliding type definitions to use. However, since the copies of ExtensionAttribute are identical it doesn’t matter which version the C# compiler picks.</p>
<p>Unfortunately, Visual Basic is much less forgiving when it encounters multiple versions of the same type. Instead of a warning like C#, the VB compiler raises an <a href="http://msdn.microsoft.com/en-us/library/8f0k13d2.aspx">error</a> when it encounters multiple definitions of ExtensionAttribute. So the “define your own ExtensionAttribute” approach leaves you with a DLL that won’t work from VB on .NET 3.5 or later.</p>
<p>Excluding VB on what was the most recent version of .NET at the time was a non starter for us, so we investigated other options. We discovered that we could “solve” this issue (again “or so we thought”) by having an internal definition of ExtensionAttribute in every assembly that needed it. Since the types weren’t public, VB stopped complaining about type collisions. C# still had the compiler warning, but we had already decided not to care about that. </p>
<p>I <a href="http://devhawk.net/2008/09/17/dlr-namespace-change-fire-drill/">said at the time</a> “It seems counterintuitive, doesn’t it? To solve a multiple type definition problem, we defined even more copies of the type in question.” Yeah, turns out I was kinda way wrong about that. We <a href="http://devhawk.net/2008/10/21/the-fifth-assembly/">discovered later</a> that having an internal ExtensionAttribute per project solved the VB ambiguous type error but introduced a new “break all the other extension methods in the project error”. </p>
<p>Remember earlier when I wrote it didn’t matter which copy of ExtensionAttribute the C# compiler picks because they are “identical”? Remember when I wrote we could solve the VB ambiguous type error by changing the visibility of ExtensionAttribute? Woops. Changing the visibility of our ExtensionAttribute meant it was no longer identical which meant it kinda mattered which copy of ExtensionAttribute the C# compiler choose. If the C# compiler picked one of our internal ExtensionAttributes, it would break every use of extension methods in the project referencing IronPython or the DLR! </p>
<p>We investigated a bunch of ways to control which version of ExtensionAttribute was selected by the C# compiler, but we couldn’t find an easy, obvious way in MSBuild to control the order of references passed to the compiler. In the end, we moved the custom ExtensionAttribute into its own DLL. That way, we could reference it from our IronPython and DLR projects to get extension method support but .NET 3.5 projects referencing either IronPython or DLR could reference System.Core instead. We still got the C# warning, but since we were back to identical ExtensionAttribute&#160; definitions, the warning could be ignored. </p>
<p>Believe me, if there had been any way to remove the extension methods from the DLR and IronPython, we would have done it. Having a separate assembly with just a single custom attribute definition is an ugly hack, pure and simple. But the DLR was essentially the .NET 4.0 version System.Core – getting it to run along side the .NET 3.5 version of System.Core was bound to require hacks. </p>
<p>My <a href="http://stackoverflow.com/a/11113191">advice to Nathanial on SO</a> was the same as I gave at the top of this post: don’t use the “define your own ExtensionAttribute” hack to try and get extension method support on .NET 2.0. Extensions methods are nice, but they aren’t worth the headache of dealing with the errors that stem from multiple definitions of ExtensionAttribute when you try to use your library from .NET 3.5 or later.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Devhawk?a=W-1meielb1Q:F31qQSSQHs8:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=W-1meielb1Q:F31qQSSQHs8:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=W-1meielb1Q:F31qQSSQHs8:XQ266DUsA9M"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=XQ266DUsA9M" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=W-1meielb1Q:F31qQSSQHs8:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=W-1meielb1Q:F31qQSSQHs8:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Devhawk?i=W-1meielb1Q:F31qQSSQHs8:V_sGLiPBpWU" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Devhawk/~4/W-1meielb1Q" height="1" width="1"/>]]></content:encoded><description>I was recently contacted by Nathanael Jones of the ImageResizer project about a question he had posted on Stack Overflow: How can a single .NET assembly, targeting 2.0, 3.0, 3.5, 4.0, and 4.5 concurrently, support extension methods for both C# and VB.NET consumers? Short Answer: You can’t. You think you can, but if you’re serious [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devhawk.net/2012/06/20/ambiguous-extensionattribute-errors/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">1</slash:comments></item><item><title>Windows Camp Demo, Part One</title><link>http://devhawk.net/2012/06/19/windows-camp-demo-part-one/</link><category>Development</category><category>Windows</category><category>Windows Runtime</category><category>C++</category><category>C++/cx</category><category>Channel 9</category><category>Metro style apps</category><category>Windows 8</category><category>Windows Camp</category><category>WinRT Components</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">DevHawk</dc:creator><pubDate>Tue, 19 Jun 2012 20:13:34 PDT</pubDate><guid isPermaLink="false">http://devhawk.net/?p=2002</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Several weeks ago, I did a talk on <a href="http://devhawk.net/2012/06/08/building-winrt-components-with-cpp-cx/">building Windows Runtime components in C++</a>. As part of that talk, I did a demo that showed accessing a WinRT component written in C++ from a C# XAML application. Like I did for <a href="http://devhawk.net/2011/09/15/using-winrt-from-csharp-build-demo/">my //build talk</a>, I’ve written this walkthrough so you can follow along at home without having to read code off the recorded video stream. I’ve also published the source up on <a href="https://github.com/devhawk/WindowsCampDemo">GitHub</a>.</p>
<p>The demo had two parts – the first was a “Hello, world!” style demo, the second demonstrated wrapping an <a href="http://bitmap.codeplex.com/">existing C++ library</a> in a WinRT component to make it callable from other languages. This post covers the first part of the demo. I’ll post a walkthrough of the second part of the demo soon.</p>
<p>In order to follow along, you’ll need the <a href="http://windows.microsoft.com/en-US/windows-8/release-preview">Windows 8 Release Preview</a> as well as <a href="http://msdn.microsoft.com/en-us/windows/apps/hh852659">Visual Studio 2012 Express RC for Windows 8</a>. You should be able to use the RC version of VS 2012 <a href="http://www.microsoft.com/visualstudio/11/en-us/professional">Pro</a>, <a href="http://www.microsoft.com/visualstudio/11/en-us/premium">Premium</a> or <a href="http://www.microsoft.com/visualstudio/11/en-us/ultimate">Ultimate</a>, but I’ve only tested with Express. Note, the original presentation was done on Win8 Consumer Preview / VS 11 Beta, but I figured it made more sense to write up the walkthrough on the latest bits.</p>
<p>We’re going to start by creating the C# XAML app we’ll use as the component client. Fire up VS 2012 RC and select new project. Select Visual C# -&gt; Windows Metro Style -&gt; Blank App (XAML), name the project “WindowsCamp” and press OK. Once the project has been created, open up the MainPage.xaml file, replace the Grid element that’s there by default with the following XAML code:</p>
<pre class="brush:xml">&lt;StackPanel Background="{StaticResource ApplicationPageBackgroundThemeBrush}"&gt;
    &lt;Button Click="Button_Click_1"&gt;Click me&lt;/Button&gt;
    &lt;TextBlock x:Name="myText" FontSize="20"&gt;&lt;/TextBlock&gt;
    &lt;Image x:Name="myImage"&gt;&lt;/Image&gt;
&lt;/StackPanel&gt;</pre>
<p>As you can see, my UX skills have not improved since //build.</p>
<p>Now, we need to add a project for the C++ WinRT component. Right click on solution in the Solution Explorer and select Add -&gt; New Project. In the New Project dialog, Select Visual C++ -&gt; Windows Metro Style -&gt; Windows Runtime Component, name the project “WindowsCampComponent” and press OK.</p>
<p>Once the component project has been created, we’re going to add some code to it. Open Class1.h if it’s not already open. Update the file to read as follows:</p>
<pre class="brush:cpp">#pragma once

using namespace Platform;

namespace WindowsCampComponent
{
    public ref class Class1 sealed
    {
    public:
        Class1();

        String^ SayHello(String^ name) {
            return String::Concat(
                ref new String(L"Hello there "),
                name);
        };
    };
}</pre>
<p>The code is a bit more complex than your typical Hello, world. The SayHello method takes a string parameter that represents someone’s name. The method concatenates the provided name with a hard coded greeting string and returns the resulting string. Doesn’t get much simpler. However, even though it’s just a single line of code there are several concepts that are important to point out:</p>
<ul>
<li>ref class – WinRT objects are projected in C++/CX as ref classes and vise-versa. Since we’re building a WinRT component to consume from C#, we define it as a ref class. Note, unless you’re writing a XAML control, all WinRT classes must be sealed.</li>
<li>Hats – The ‘^’ character after the String type declarations is the handle-to-object modifier. It’s basically the pointer-to-object modifier (aka ‘*’) but for ref classes. We’ll see in the second part of the demo that you invoke members on a ref class using the same ‘-&gt;’ syntax that you use in vanilla C++.</li>
<li>ref new – You create instances of ref clases using “ref new” instead of “new” as you do in vanilla C++. Ref new returns a handle to the newly created ref class – a String^ in this case.</li>
<li>Platform::String – C++/CX projects some non-class WinRT types as ref classes in the Platform namespace. In this case, C++/CX projects the new language interoperable string type <a href="http://msdn.microsoft.com/en-us/library/br205775(v=vs.85).aspx">HSTRING</a> as a Platform::String ref class. HSTRINGS are UTF-16, so Platform::String provides a constructor that takes a wide string literal. We imported the Platform namespace via the “using namespace” directive so we wouldn’t have to type “Platform::” multiple times.</li>
</ul>
<p>For more information about the design of the C++/CX language, check out <a href="http://blogs.msdn.com/b/vcblog/archive/2011/10/20/10228473.aspx">Jim Springfield’s post</a> on the <a href="http://blogs.msdn.com/b/vcblog/">Visual C++ team blog</a>.</p>
<p>Now that we’ve written our WinRT component, we’ll write the code to consume it in C#. First, we need to add a reference to the C++ WinRT component project in our C# Metro style XAML app. WinRT references are added just like traditional CLR references – via the Add Reference dialog. Right click on the WindowsCamp node of the Solution explorer, select “Add Reference…” from the menu, click the check box next to the WindowsCampComponent project from the solution and press OK.</p>
<p>Go back to MainPage.xaml and double click on the button labeled “Click Me” in the designer. This will add a click event handler named Button_Click_1 and take you to MainPage.xaml.cs so you can write the code for it. Type in “var wcc = new Windows” and look at the resulting intellisense list. Notice that WindowsCampComponent is missing.</p>
<p><img class="alignnone size-full wp-image-2004" title="WCDemo1-Intellisense1" src="http://devhawk.net/wp-content/uploads/2012/06/WCDemo1-Intellisense1.png" alt="" width="496" height="241" /></p>
<p>This is because the C++ component hasn’t been compiled yet. We need compile the C++ component project in order to generate the Windows metadata file (aka the file with the .winmd extension) that is used to drive intellisense. Delete the line of code you just added and compile the solution. Now type that line of code again, and you’ll notice that the WindowsCampComponent namespace is available.</p>
<p><img class="alignnone size-full wp-image-2005" title="WCDemo1-Intellisense2" src="http://devhawk.net/wp-content/uploads/2012/06/WCDemo1-Intellisense2.png" alt="" width="490" height="238" /></p>
<p>Now, update the button click event handler to read as follows:</p>
<pre class="brush:csharp">private void Button_Click_1(object sender, RoutedEventArgs e)
{
    var wcc = new WindowsCampComponent.Class1();
    myText.Text = wcc.SayHello("Herb Sutter");
}</pre>
<p><img class="size-thumbnail wp-image-2008 alignleft" title="WCDemo1-RunningApp" src="http://devhawk.net/wp-content/uploads/2012/06/WCDemo1-RunningApp-e1340161688130-150x74.png" alt="" width="150" height="74" />Now, run the app, click the “Click Me” button and marvel at the wonder of WinRT language interop to print a greeting to Herb Sutter. I used <a href="http://herbsutter.com/">Herb Sutter</a> from the C++ team since he was the keynote speaker at the Windows Camp event and was standing in the back of the room when I did the demo.</p>
<p>And that’s it for the Hello, world demo. Kind of a lot of steps for essentially 3 lines of code – 1 line of component code and 2 lines of client code. However, we did get the infrastructure set up so we add more substantial code in the next post.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Devhawk?a=-kcRIhBzB_c:7dB6_P3Dhqw:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=-kcRIhBzB_c:7dB6_P3Dhqw:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=-kcRIhBzB_c:7dB6_P3Dhqw:XQ266DUsA9M"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=XQ266DUsA9M" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=-kcRIhBzB_c:7dB6_P3Dhqw:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=-kcRIhBzB_c:7dB6_P3Dhqw:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Devhawk?i=-kcRIhBzB_c:7dB6_P3Dhqw:V_sGLiPBpWU" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Devhawk/~4/-kcRIhBzB_c" height="1" width="1"/>]]></content:encoded><description>Several weeks ago, I did a talk on building Windows Runtime components in C++. As part of that talk, I did a demo that showed accessing a WinRT component written in C++ from a C# XAML application. Like I did for my //build talk, I’ve written this walkthrough so you can follow along at home [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devhawk.net/2012/06/19/windows-camp-demo-part-one/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">2</slash:comments></item><item><title>Building WinRT Components with C++/CX</title><link>http://devhawk.net/2012/06/08/building-winrt-components-with-cpp-cx/</link><category>Development</category><category>Windows</category><category>Windows Runtime</category><category>C++</category><category>C++/cx</category><category>Channel 9</category><category>Windows 8</category><category>Windows Camp</category><category>WinRT Components</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">DevHawk</dc:creator><pubDate>Fri, 08 Jun 2012 14:25:55 PDT</pubDate><guid isPermaLink="false">http://devhawk.net/?p=1941</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>I don&#8217;t get out to talk to customers like I used to in previous jobs. &lt;sigh&gt; But a few weeks ago, I got a chance to do a session at Channel 9&#8242;s <a href="http://channel9.msdn.com/Events/Windows-Camp/Developing-Windows-8-Metro-style-apps-in-Cpp">Developing Windows 8 Metro style apps with C++</a> <a href="http://channel9.msdn.com/Events/Windows-Camp">Windows Camp</a>. There were some great talks at the event on <a href="http://channel9.msdn.com/Events/Windows-Camp/Developing-Windows-8-Metro-style-apps-in-Cpp/Building-Metro-style-apps-with-XAML-and-Cpp">XAML with C++</a>, <a href="http://channel9.msdn.com/Events/Windows-Camp/Developing-Windows-8-Metro-style-apps-in-Cpp/Cpp-and-DirectX-for-Metro-Style-Games">C++ for Metro Style Games</a> and  using <a href="http://channel9.msdn.com/Events/Windows-Camp/Developing-Windows-8-Metro-style-apps-in-Cpp/Building-Apps-with-Cpp-XAML-and-DirectX">DirectX and XAML together</a>. My talk was on building <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh441572(v=vs.110).aspx">Windows Runtime Components </a>in C++. Here&#8217;s the abstract:</p>
<blockquote><p>The Windows Runtime enables developers from a variety of languages – JavaScript, C#, Visual Basic and C++ &#8211; to use the Windows APIs in a natural and familiar way. But did you know that you can build your own components that project into those same languages for use in your Metro style apps? Watch this session to learn how to build your own Windows Runtime components with C++ that can be used across languages in Metro style applications.</p></blockquote>
<p>I haven&#8217;t had time, but I plan to blog the demo step-by-step like I did for my <a href="http://devhawk.net/2011/09/15/using-winrt-from-csharp-build-demo/">//build demo</a>. In the meantime, check out the talk:</p>
<p><iframe style="width: 620px; height: 351px;" src="http://channel9.msdn.com/Events/Windows-Camp/Developing-Windows-8-Metro-style-apps-in-Cpp/Building-Windows-Runtime-Components-with-Cpp/player?w=620&amp;h=351" frameborder="0" scrolling="no" width="320" height="240"></iframe></p>
<p>(Note, the static image below appears cut-off, but the video should scale to the width of my blog automatically. If not, head on over to the <a href="http://channel9.msdn.com/Events/Windows-Camp/Developing-Windows-8-Metro-style-apps-in-Cpp/Building-Windows-Runtime-Components-with-Cpp">official page</a> for the talk over on Channel 9)</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Devhawk?a=YV-o4D2uMRY:5hxwJjNvkJg:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=YV-o4D2uMRY:5hxwJjNvkJg:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=YV-o4D2uMRY:5hxwJjNvkJg:XQ266DUsA9M"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=XQ266DUsA9M" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=YV-o4D2uMRY:5hxwJjNvkJg:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=YV-o4D2uMRY:5hxwJjNvkJg:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Devhawk?i=YV-o4D2uMRY:5hxwJjNvkJg:V_sGLiPBpWU" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Devhawk/~4/YV-o4D2uMRY" height="1" width="1"/>]]></content:encoded><description>I don&amp;#8217;t get out to talk to customers like I used to in previous jobs. &amp;#60;sigh&amp;#62; But a few weeks ago, I got a chance to do a session at Channel 9&amp;#8242;s Developing Windows 8 Metro style apps with C++ Windows Camp. There were some great talks at the event on XAML with C++, C++ [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devhawk.net/2012/06/08/building-winrt-components-with-cpp-cx/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">2</slash:comments></item><item><title>My //build Talk</title><link>http://devhawk.net/2011/10/06/my-build-talk/</link><category>Development</category><category>Windows</category><category>Windows Runtime</category><category>//build</category><category>C#</category><category>Metro style apps</category><category>Windows 8</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">DevHawk</dc:creator><pubDate>Thu, 06 Oct 2011 08:17:52 PDT</pubDate><guid isPermaLink="false">http://devhawk.net/?p=1927</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>I just realized that while I posted the <a href="http://devhawk.net/2011/09/15/using-winrt-from-csharp-build-demo/">demo steps</a> from my //build talk, I never posted the talk itself here on DevHawk. Consider that oversight rectified with this post.</p>
<p>(Note, the static image below appears cut-off, but the video should scale to the width of my blog automatically. If not, head on over to the <a href="http://channel9.msdn.com/events/BUILD/BUILD2011/TOOL-531T">official page</a> for the talk over on Channel 9)</p>
<p><iframe style="width: 620px; height: 351px;" src="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-531T/player?w=620&amp;h=351" frameborder="0" scrolling="no" width="320" height="240"></iframe></p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Devhawk?a=RNZ03qrmiY4:KiYyQIFKQpc:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=RNZ03qrmiY4:KiYyQIFKQpc:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=RNZ03qrmiY4:KiYyQIFKQpc:XQ266DUsA9M"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=XQ266DUsA9M" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=RNZ03qrmiY4:KiYyQIFKQpc:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=RNZ03qrmiY4:KiYyQIFKQpc:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Devhawk?i=RNZ03qrmiY4:KiYyQIFKQpc:V_sGLiPBpWU" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Devhawk/~4/RNZ03qrmiY4" height="1" width="1"/>]]></content:encoded><description>I just realized that while I posted the demo steps from my //build talk, I never posted the talk itself here on DevHawk. Consider that oversight rectified with this post. (Note, the static image below appears cut-off, but the video should scale to the width of my blog automatically. If not, head on over to the [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devhawk.net/2011/10/06/my-build-talk/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">0</slash:comments></item><item><title>Using WinRT from C# //build Demo</title><link>http://devhawk.net/2011/09/15/using-winrt-from-csharp-build-demo/</link><category>Development</category><category>Windows</category><category>Windows Runtime</category><category>//build</category><category>C#</category><category>Metro style apps</category><category>Windows 8</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">DevHawk</dc:creator><pubDate>Thu, 15 Sep 2011 09:39:30 PDT</pubDate><guid isPermaLink="false">http://devhawk.net/?p=1924</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Yesterday at<a href="http://www.buildwindows.com/"> //build</a>, Jesse Kaplan and I delivered the <a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-531T">Using Windows Runtime from C# and Visual Basic</a> 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.</p>
<p>Instead of making you try and read code off the recorded video stream that should be published soon, I&#8217;ve written this walkthru to explain exactly what I did in that demo. In addition, I&#8217;ve started from scratch (i.e. File-&gt;New Project) so that you can follow along at home if you wish.</p>
<p>First, you need to install the <a href="http://msdn.microsoft.com/en-us/windows/apps/br229516">Windows Developer Preview</a>. I recommend the x64 version with tools. Scott Hanselman has a <a href="http://www.hanselman.com/blog/GuideToInstallingAndBootingWindows8DeveloperPreviewOffAVHDVirtualHardDisk.aspx">great write up</a> on using boot to VHD to run the preview. (though I do disagree w/ his assessment of dual boot. I&#8217;ve been dual booting Win7 and Win8 on my laptop for months and it&#8217;s never ended in tears or blood). Also, you&#8217;re going to need a webcam in order to run the app yourself.</p>
<p>Once the Windows Developer Preview is up and running, run the Socialite app and login with your Facebook credentials. We&#8217;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!</p>
<p>Next, fire up VS11 (aka Microsoft Visual Studio 11 Express for Windows Developer Preview). Create a new project and select the Visual C# -&gt; Windows Metro Style -&gt; Application template.</p>
<p>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.</p>
<pre class="brush:xml">&lt;Grid x:Name="LayoutRoot" Background="#FF0C0C0C"&gt;
    &lt;Button x:Name="ClickMe" Click="ClickMe_Click"&gt;Click Me&lt;/Button&gt;
    &lt;Image x:Name="Photo" Width="800" Height="600"
           HorizontalAlignment="Center" VerticalAlignment="Center"/&gt;
&lt;/Grid&gt;</pre>
<p>Next, hover over the Click=&#8221;ClickMe_Click&#8221; attribute of the button, right click and select &#8220;Navigate to Event Handler&#8221;. VS11 will take you to MainPage.xaml.cs and automatically generate a skeleton event handler for you.</p>
<p>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&#8217;s easier if you just add the additional using statements we&#8217;re going to need at the top of MainPage.xaml.cs now.</p>
<pre class="brush:csharp">using Windows.Media.Capture;
using Windows.Storage;
using Windows.UI.Xaml.Media.Imaging;
using Windows.ApplicationModel.DataTransfer;
using Windows.Storage.Streams;</pre>
<p>Now, we add the code for ClickMe_Click:</p>
<pre class="brush:csharp">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;
    }
}</pre>
<p>A few things to note about this code:</p>
<ul>
<li>Even though it&#8217;s using native WinRT libraries, the C# feels natural and familiar &#8211; as if you were calling into traditional managed libraries. We&#8217;re newing up classes, we&#8217;re passing in constructor parameters, we&#8217;re using primitive numbers and enums, we&#8217;re assigning properties, etc. That is very much by design.</li>
<li>We&#8217;re using a couple of async WinRT methods (CaptureFileAsync and OpenAsync). C# 5.0&#8242;s new await keyword to make it extremely easy to write linear looking code that doesn&#8217;t block on async operations.</li>
<li>No P/Invoke or COM Interop attributes anywhere to be seen!</li>
</ul>
<p>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 &#8220;Capabilites&#8221; tab, and then check the Webcam checkbox.</p>
<p>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!</p>
<p>For the second part of the demo, I added share contract support. Here&#8217;s how to do that.</p>
<p>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:</p>
<pre class="brush:csharp">//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;
    }
}</pre>
<p>Next, we need to wire up the share event handler in the XAML page&#8217;s constructor. That&#8217;s a single line of code and VS11 intellisense writes most of  it for you</p>
<pre class="brush:csharp">public MainPage()
{
    InitializeComponent();
    DataTransferManager.GetForCurrentView().DataRequested +=
        new TypedEventHandler&lt;DataTransferManager, DataRequestedEventArgs&gt;(MainPage_DataRequested);
}</pre>
<p>If you&#8217;ve ever wired up an event handler in C# before with VS, you&#8217;ll be familiar with the &#8220;Press TAB to insert&#8221; the correct event handler type followed by &#8220;TAB to generate handler&#8221;. Even though hthis is a WinRT event, VS11 helps you wire it up just the same as it does for managed events.</p>
<p>Now we implement the share contract event handler. That&#8217;s just a simple if statement &#8211; 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.</p>
<pre class="brush:csharp">private void MainPage_DataRequested(DataTransferManager sender,
    DataRequestedEventArgs args)
{
    if (stream == null)
        args.Request.FailWithDisplayText("No picture taken!");
    else
        args.Request.Data.SetBitmap(stream);
}</pre>
<p>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#.</p>
<p>And we&#8217;re done, so hit F5 to build, deploy and run the app again.</p>
<p>I didn&#8217;t remember to do this in the //build talk, but first try selecting the share contract <em>before </em>taking a picture. Windows will display the &#8220;No picture taken&#8221; text in share contract window since the user taken a picture to share yet. That&#8217;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 &#8220;Share in Facebook&#8221;.</p>
<p>That&#8217;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!</p>
<p>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&#8217;s experience with Windows 8 was the best that it could be. As I said in the talk &#8211; if you&#8217;re a managed developer, <span style="text-decoration: underline;">you already know how to build these Metro style apps</span>.</p>
<p>I know I <a href="http://devhawk.net/2011/09/15/the-windows-runtime/">said it before</a>, but I really can&#8217;t wait to see what you guys build with Windows 8!</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Devhawk?a=GaLuqADVRTo:i97L0YP2f8k:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=GaLuqADVRTo:i97L0YP2f8k:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=GaLuqADVRTo:i97L0YP2f8k:XQ266DUsA9M"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=XQ266DUsA9M" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=GaLuqADVRTo:i97L0YP2f8k:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=GaLuqADVRTo:i97L0YP2f8k:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Devhawk?i=GaLuqADVRTo:i97L0YP2f8k:V_sGLiPBpWU" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Devhawk/~4/GaLuqADVRTo" height="1" width="1"/>]]></content:encoded><description>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 [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devhawk.net/2011/09/15/using-winrt-from-csharp-build-demo/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">6</slash:comments></item><item><title>The Windows Runtime</title><link>http://devhawk.net/2011/09/15/the-windows-runtime/</link><category>Development</category><category>Windows</category><category>Windows Runtime</category><category>//build</category><category>Activation</category><category>C#</category><category>C++</category><category>JavaScript</category><category>Lanugages</category><category>Metadata</category><category>Metro style apps</category><category>Visual Basic</category><category>Windows 8</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">DevHawk</dc:creator><pubDate>Thu, 15 Sep 2011 07:40:31 PDT</pubDate><guid isPermaLink="false">http://devhawk.net/?p=1919</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>After nearly 2 years of not being able to tell anyone what I was working on &#8211; or even the name of the team I was on! &#8211; <a href="http://www.buildwindows.com/">//build</a> is finally here and the <a href="http://msdn.microsoft.com/en-us/windows/apps/br229516">Windows 8 developer preview</a> is finally out there in the open for everyone to start building applications for. You have NO idea how hard it&#8217;s been for me to keep my mouth shut and blog quiet about this!</p>
<p>I am a program manager on the Runtime Experience team, one of <a href="http://blogs.msdn.com/b/b8/archive/2011/08/17/introducing-the-team.aspx">many teams</a> in the Windows division building Windows 8. Our team is responsible for building the underlying infrastructure that powers the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh464942(v=VS.85).aspx">Windows Runtime</a> (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.</p>
<p>In a nutshell, WinRT is the new API surface area for <a href="http://msdn.microsoft.com/en-us/windows/apps/">Metro style apps</a> in Windows 8. WinRT APIs are available across multiple languages &#8211; C#, Visual Basic, C++ and JavaScript &#8211; 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 <a href="http://dev.windows.com">Windows Dev Center</a>.</p>
<p>In addition to the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh464942(v=VS.85).aspx">developer preview docs for WinRT</a>, there are several sessions at //build focusing on WinRT &#8211; what it is, how it works under the covers, and how you use it from the various languages. Here&#8217;s a handy list of all the //build sessions you should check out if you want to know more about WinRT:</p>
<ul>
<li><a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/PLAT-874T">Lap Around Windows Runtime</a><br />
Martyn Lovell &#8211; the dev manager for the Runtime Experience team &#8211; provides a overview of the Windows Runtime.</li>
<li><a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-531T">Using the Windows Runtime from C# and Visual Basic</a><br />
Jesse Kaplan from the CLR team and I cover how you can build managed Metro style apps and how you use WinRT from C# and VB. Obviously, I highly recommend this session because&#8230;Well, it&#8217;s my session isn&#8217;t it? What am I gonna say? Don&#8217;t watch my talk?</li>
<li><a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-533T">Using the Windows Runtime from JavaScript</a><br />
Luke Hoban from the JavaScript team talks about how WinRT is used when building the new Metro style apps in HTML5 and JavaScript.</li>
<li><a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-532T">Using the Windows Runtime from C++</a><br />
Herb Sutter from the C++ team as well as the C++ standards committee talks about how WinRT is used for C++ developers building native Metro style apps.</li>
<li><a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/PLAT-203T">Async Everywhere: creating responsive APIs and apps</a><br />
Ben Kuhn, a developer on the Runtime Experience team, dives deep on how async is exposed and implemented in WinRT</li>
<li><a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/PLAT-875T">Windows Runtime Internals: understanding &#8220;Hello World&#8221;</a><br />
Matt Merry, a teammate on the Runtime Experience PM team, goes under the hood and shows you how the internals of WinRT work.</li>
<li><a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/PLAT-877T">Being Pragmatic by leveraging existing code in Metro style apps</a><br />
<a href="http://twitter.com/#!/jolson88">Jason Olson</a>, a teammate on the Runtime Experience PM team and my next door office neighbor, talks about how you bring your existing code into the new world of Metro style apps. In particular, he&#8217;s got a <a href="http://code.msdn.microsoft.com/windowsapps/Groove-Drum-Sequencer-cc6028ec">wicked cool demo</a>.</li>
<li><a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/PLAT-657T">Windows Interns: our summer of apps</a><br />
John Lam, my immediate boss, is MCing this session with some of the Windows Interns who built the first Windows 8 Metro style apps over the summer.</li>
</ul>
<p>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 <a href="http://forums.dev.windows.com">Windows Dev Center Forums</a>. Our dev manager has already been <a href="http://social.msdn.microsoft.com/profile/martyn%20lovell%20%5Bmsft%5D/">very busy answering questions</a>!</p>
<p>I am so excited that you can finally see what we&#8217;ve been working on and I can wait to see what <span style="text-decoration: underline;">you</span> build with Windows 8!</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Devhawk?a=XCTI_RlWPq0:4bxIXNS-ST8:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=XCTI_RlWPq0:4bxIXNS-ST8:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=XCTI_RlWPq0:4bxIXNS-ST8:XQ266DUsA9M"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=XQ266DUsA9M" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=XCTI_RlWPq0:4bxIXNS-ST8:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=XCTI_RlWPq0:4bxIXNS-ST8:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Devhawk?i=XCTI_RlWPq0:4bxIXNS-ST8:V_sGLiPBpWU" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Devhawk/~4/XCTI_RlWPq0" height="1" width="1"/>]]></content:encoded><description>After nearly 2 years of not being able to tell anyone what I was working on &amp;#8211; or even the name of the team I was on! &amp;#8211; //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 [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devhawk.net/2011/09/15/the-windows-runtime/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">5</slash:comments></item><item><title>Open Position On My Team</title><link>http://devhawk.net/2011/06/15/open-position-on-my-team/</link><category>Windows</category><category>Working at MSFT</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">DevHawk</dc:creator><pubDate>Wed, 15 Jun 2011 10:58:45 PDT</pubDate><guid isPermaLink="false">http://devhawk.net/?p=1913</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>My team is hiring. I don&#8217;t have a link to the job description on the Microsoft Careers site yet, but the job description is below.</p>
<p>Interested? <a title="Job Opening on your team" href="mailto:harry.pierson@microsoft.com">Send me mail</a>.</p>
<blockquote><p><span style="text-decoration: underline;"><strong>IC PM2/Senior Program Manager Position in the Windows Developer Experience Team </strong></span></p>
<p>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?</p>
<p>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.</p>
<p>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.</p>
<p>Requirements:</p>
<ul>
<li>You have 5+ years of experience in Program Management.</li>
<li>You love software developers and can see the world from their perspective.</li>
<li>You have strong JavaScript/C#/C++ skills</li>
<li>You have completed multiple ship cycles on a large-scale product.</li>
<li>You have intellectual horsepower and creativity, and can quickly adapt to new technologies and go deep in new areas.</li>
<li>You have excellent communication and partnering skills. You can drive features<br />
across teams who have different needs and priorities.</li>
<li>Experience delivering developer platforms a significant plus.</li>
</ul>
</blockquote>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Devhawk?a=P-7MSkBWRlI:GaMwl9FMdmo:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=P-7MSkBWRlI:GaMwl9FMdmo:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=P-7MSkBWRlI:GaMwl9FMdmo:XQ266DUsA9M"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=XQ266DUsA9M" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=P-7MSkBWRlI:GaMwl9FMdmo:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=P-7MSkBWRlI:GaMwl9FMdmo:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Devhawk?i=P-7MSkBWRlI:GaMwl9FMdmo:V_sGLiPBpWU" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Devhawk/~4/P-7MSkBWRlI" height="1" width="1"/>]]></content:encoded><description>My team is hiring. I don&amp;#8217;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 [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devhawk.net/2011/06/15/open-position-on-my-team/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">0</slash:comments></item><item><title>Using Task in ASP.NET MVC Today</title><link>http://devhawk.net/2011/05/19/using-task-of-t-in-asp-net-mvc-today-2/</link><category>Development</category><category>ASP.NET</category><category>ASP.NET MVC</category><category>Async</category><category>C#</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">DevHawk</dc:creator><pubDate>Thu, 19 May 2011 18:44:07 PDT</pubDate><guid isPermaLink="false">http://devhawk.net/?p=1864</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>I&#8217;ve been experimenting with the <a href="http://msdn.microsoft.com/en-us/vstudio/async.aspx">new async support</a> coming in the next version of C# (and VB). I must say, I&#8217;m very impressed. Async is one of those things you know you&#8217;re supposed to be doing. However, traditionally it has taken a lot of code and been hard to get right. The new await keyword changes all that.</p>
<p>For example, here&#8217;s an async function to download the <a href="http://dev.twitter.com/doc/get/statuses/public_timeline">Twitter public timeline</a>:</p>
<pre class="brush:csharp">public async Task PublicTimelineAsync()
{
  var url = "http://api.twitter.com/1/statuses/public_timeline.xml";
  var xml = await new WebClient().DownloadStringTaskAsync(url);
  return XDocument.Parse(xml);
}</pre>
<p>That&#8217;s not much more difficult that writing the synchronous version. By using the new async and await keywords, all the ugly async <a href="http://en.wikipedia.org/wiki/Continuation-passing_style">CPS</a> code you&#8217;re supposed to write is generated for you automatically by the compiler. That&#8217;s a huge win.</p>
<p>The only downside to async is that support for it is spotty in the .NET Framework today. Each major release of .NET to date has introduced a new async API pattern. .NET 1.0 had the <a href="http://msdn.microsoft.com/en-us/library/ms228963.aspx">Async Programming Model (APM)</a>. .NET 2.0 introduced the <a href="http://msdn.microsoft.com/en-us/library/wewwczdw.aspx">Event-based Async Pattern (EAP)</a>. Finally .NET 4.0 gave us the <a href="http://msdn.microsoft.com/en-us/library/dd537609.aspx">Task Parallel Library (TPL)</a>. The await keyword only works with APIs writen using the TPL pattern. APIs using older async patterns have to be wrapped as TPL APIs to work with await. The <a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=4738205d-5682-47bf-b62e-641f6441735b&amp;displaylang=en">Async CTP</a> includes a bunch of extension methods that wrap common async APIs, such as DownloadStringTaskAsync from the code above.</p>
<p>The async wrappers are nice, but there are a few places where we really need the TPL pattern plumbed deeper. For example, ASP.NET MVC supports <a href="http://msdn.microsoft.com/en-us/library/ee728598.aspx">AsyncControllers</a>. AsyncControllers are used to avoid blocking IIS threads waiting on long running I/O operations &#8211; such as getting the public timeline from Twitter. Now that I&#8217;ve been bitten by the <a href="http://blogs.msdn.com/b/lucian/archive/2011/04/15/async-ctp-refresh-design-changes.aspx">async zombie virus</a>, I want to write my async controller methods using await:</p>
<pre class="brush:csharp">public async Task&lt;ActionResult&gt; Index()
{
    var t = new Twitter();
    var timeline = await t.PublicTimelineAsync();
    var data = timeline.Root.Elements("status")
        .Elements("text").Select(e =&gt; e.Value);
    return View(data);
}</pre>
<p>Unfortunately, neither the main trunk of MVC nor the MVC futures project has support for the TPL model [1]. Instead, I have to manually write some semblance of the async code that await would have emitted on my behalf. In particular, I have to manage the outstanding operations, implement a continuation method and map the parameters in my controller manually.</p>
<pre class="brush:csharp">public void IndexAsync()
{
    var twitter = new Twitter();

    AsyncManager.OutstandingOperations.Increment();
    twitter
        .PublicTimelineAsync()
        .ContinueWith(task =&gt;
        {
            AsyncManager.Parameters["timeline"] = task.Result;
            AsyncManager.OutstandingOperations.Decrement();
        });
}

public ActionResult IndexCompleted(XDocument timeline)
{
    var data = timeline.Root.Elements("status")
        .Elements("text").Select(e =&gt; e.Value);
    return View(data);
}</pre>
<p>I promise you, writing that boilerplate code over and over gets old pretty darn quick. So I wrote the following helper function to eliminate as much boilerplate code as I could.</p>
<pre class="brush:csharp">public static void RegisterTask&lt;T&gt;(
    this AsyncManager asyncManager,
    Task&lt;T&gt; task,
    Func&lt;T, object&gt; func)
{
    asyncManager.OutstandingOperations.Increment();
    task.ContinueWith(task2 =&gt;
    {
        //invoke the provided function with the
        //result of running the task
        var o = func(task2.Result);

        //use reflection to set asyncManager.Parameters
        //for the returned object's fields and properties
        var ty = o.GetType();
        foreach (var f in ty.GetFields())
        {
            asyncManager.Parameters[f.Name] = f.GetValue(o);
        }
        foreach (var p in ty.GetProperties())
        {
            var v = p.GetGetMethod().Invoke(o, null);
            asyncManager.Parameters[p.Name] = v;
        }

        asyncManager.OutstandingOperations.Decrement();
    });
}</pre>
<p>With this helper function, you pass in the Task&lt;T&gt; that you are waiting on as well as a delegate to invoke when the task completes. RegisterTask takes care of incrementing and decrementing the outstanding operations count as appropriate. It also registers a continuation that reflects over the object returned from the invoked delegate to populate the Parameters collection.</p>
<p>With this helper function, you can write the async controller method like this:</p>
<pre class="brush:csharp">public void IndexAsync()
{
    var twitter = new Twitter();

    AsyncManager.RegisterTask(
        twitter.PublicTimelineAsync(),
        data =&gt; new { timeline = data });
}

//IndexCompleted hasn't changed
public ActionResult IndexCompleted(XDocument timeline)
{
    var data = timeline.Root.Elements("status")
        .Elements("text").Select(e =&gt; e.Value);
    return View(data);
}</pre>
<p>It&#8217;s not as clean as the purely TPL based version. In particular, you still need to write separate Async and Completed methods for each controller method. You also need to build an object to map values from the completed tasks into parameters in the completed method. Mapping parameters is a pain, but the anonymous object syntax is terser than setting values in the AsyncManager Parameter collection.</p>
<p>It&#8217;s not full TPL support, but it&#8217;ll do for now. Here&#8217;s hoping that the MVC team has async controller methods with TPL on their backlog.</p>
<hr />
<p>[1] I&#8217;m familiar with Craig Cavalier&#8217;s <a href="http://craigcav.wordpress.com/2010/12/23/asynchronous-mvc-using-the-task-parallel-library/">Async MVC with TPL</a> post, but a fork of the MVC Futures project is a bit too bleeding edge for my needs at this point.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Devhawk?a=oIyOzVP0w8I:3QJOjncAruI:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=oIyOzVP0w8I:3QJOjncAruI:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=oIyOzVP0w8I:3QJOjncAruI:XQ266DUsA9M"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=XQ266DUsA9M" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=oIyOzVP0w8I:3QJOjncAruI:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=oIyOzVP0w8I:3QJOjncAruI:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Devhawk?i=oIyOzVP0w8I:3QJOjncAruI:V_sGLiPBpWU" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Devhawk/~4/oIyOzVP0w8I" height="1" width="1"/>]]></content:encoded><description>I&amp;#8217;ve been experimenting with the new async support coming in the next version of C# (and VB). I must say, I&amp;#8217;m very impressed. Async is one of those things you know you&amp;#8217;re supposed to be doing. However, traditionally it has taken a lot of code and been hard to get right. The new await keyword changes [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devhawk.net/2011/05/19/using-task-of-t-in-asp-net-mvc-today-2/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">7</slash:comments></item><item><title>Build Your Own WDS Discovery Image</title><link>http://devhawk.net/2011/05/19/build-your-own-wds-discovery-image/</link><category>General Geekery</category><category>Deployment</category><category>WDS</category><category>Windows</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">DevHawk</dc:creator><pubDate>Thu, 19 May 2011 06:19:23 PDT</pubDate><guid isPermaLink="false">http://devhawk.net/?p=1900</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Given that I <a href="http://devhawk.net/2009/10/26/joining-windows/">work on the Windows team</a>, it shouldn’t come as a surprise that we use <a href="http://technet.microsoft.com/en-us/library/cc772106(v=WS.10).aspx">Windows Deployment Services</a> to distribute Windows images internally. For most machines, it’s really convenient. You trigger a network boot (on my Lenovo, you press the “ThinkVantage” button during start up), select the image to install and what partition to install it to, wait a while, answer the installation finalization questions (machine name, user name, etc) and you’re done.</p>
<p>However, I have an <a href="http://www.dell.com/us/p/inspiron-duo/pd">Dell Inspiron Duo</a> (with the cool flip screen) netbook that lacks a built in network port. No network port, no network boot. I’ve got a USB network dongle, but it doesn’t support network boot either. No network boot, no ultra-convenient WDS installation, sad DevHawk.</p>
<p>I was able to work around this by building a custom <a href="http://technet.microsoft.com/en-us/library/cc730907(WS.10).aspx">WDS Discover image</a> that I loaded onto a USB flash drive. Now, I plug in the USB drive, select it as the boot device and I’m off and running…err, off and installing at any rate. Building the image was kind of tricky, so I figured it would be a good idea to write it down and share.</p>
<p><strong>Step One: Install the <a href="http://technet.microsoft.com/en-us/library/dd349343(v=WS.10).aspx">Windows Automated Installation Kit (AIK)<br />
</a></strong>The AIK is a set of tools for customizing Windows Images and deployment. In particular, it includes the <a href="http://technet.microsoft.com/en-us/library/dd744322(v=WS.10).aspx">Windows Preinstallation Environment</a> (aka WinPE) which is the minimal OS environment that Windows Setup runs in. We’ll be building a custom WinPE image to launch the WDS discovery and setup from.</p>
<p><strong>Step Two: Create a new PE image<br />
</strong>The AIK includes a command line tool for creating a blank PE image. Step 1 of this <a href="http://technet.microsoft.com/en-us/library/dd744530(v=WS.10).aspx">walkthru</a> shows you how to use it. It’s pretty easy. Open the Deployment Tools Command Prompt as an administrator and run the following commands:</p>
<pre class="brush:plain">copype.cmd x86 C:\winpe_x86
copy winpe.wim ISO\sources\boot.wim</pre>
<p>The copype.cmd batch file creates a new PE image of the specified architecture in the specified location. The Inspiron is an Atom processor so I chose an x86 PE image.</p>
<p>Note, in several steps below I assume you’ve created your  PE image in c:\winpe_x86. If you’ve created it somewhere else, make sure to swap in the correct path when executing the steps below.</p>
<p><strong>Step Three: Mount the PE Boot image with DISM<br />
</strong>Now that we have our basic PE boot image, we need to update it with custom drivers and the setup experience that can load WDS images across the network. Before we can update boot.wim, we need to mount it on the file system.</p>
<p>The AIK includes the <a href="http://technet.microsoft.com/en-us/library/dd744256(WS.10).aspx">Deployment Image Servicing and Management (DISM)</a> tool for working with WIM files. To mount the boot.wim file, execute the following command:</p>
<pre class="brush:plain">dism /Mount-WIM /WimFile:C:\winpe_x86\ISO\sources\boot.wim /index:1 /MountDir:c:\winpe_x86\mount</pre>
<p>Copype.cmd created an empty mount directory specifically for DISM to mount WIM images in.</p>
<p><strong>Step Four: Add Custom Device Driver<br />
</strong>The driver for my USB network dongle is not included in the standard Windows driver package, so it needs to be <a href="http://technet.microsoft.com/en-us/library/dd799289(WS.10).aspx">manually added to the PE image</a>. Again, we use DISM to do this.</p>
<pre class="brush:plain">dism /image:c:\winpe_x86\mount /add-driver /driver:"PATHTODRIVERDIRECTORY"</pre>
<p><strong>Step Five: Add Setup packages<br />
</strong>The PE image does not include the Windows Setup program by default. There are <a href="http://technet.microsoft.com/en-us/library/dd744533(WS.10).aspx">several optional packages</a> that you can add to your PE image. For WDS discovery, you need to add the setup and setup-client packages. Again, we use DISM to update the image.</p>
<pre class="brush:plain">dism /image:c:\winpe_x86\mount /add-package /packagepath:"c:\Program Files\Windows AIK\Tools\PETools\x86\WinPE_FPs\winpe-setup.cab"
dism /image:c:\winpe_x86\mount /add-package /packagepath:"c:\Program Files\Windows AIK\Tools\PETools\x86\WinPE_FPs\winpe-setup-client.cab"</pre>
<p><strong>Step Six: Add winpeshl.ini file<br />
</strong>Now that we’ve added the setup program to the image, we need to tell setup to <a href="http://technet.microsoft.com/en-us/library/cc730907(WS.10).aspx#BKMK_custom">run in WDS discovery mode on startup</a>. This is accomplished by adding a winpeshl.ini file to the WindowsSystem32 folder of the PE image.</p>
<p>Note, the <a href="http://technet.microsoft.com/en-us/library/cc730907(WS.10).aspx#BKMK_custom">official instructions</a> on TechNet have a bug. The path to setup.exe should be %<strong>SYSTEMDRIVE</strong>%sources, not %<strong>SYSTEMROOT</strong>%sources. Here’s the contents of my winpeshl.ini file:</p>
<pre class="brush:plain">[LaunchApps]
%SYSTEMDRIVE%\sources\setup.exe, "/wds /wdsdiscover"</pre>
<p>You can also add /wdsserver:&lt;server&gt; to the command line if you want to hard code the WDS Server to use in your image.</p>
<p><strong>Step Seven: Add Lang.ini file<br />
</strong>If you do all the above steps and try to boot the resulting image, you’ll get a nasty “Windows could not determine the language to use for Setup” error. Turns out there’s another bug in the official docs – <a href="http://www.msfn.org/board/topic/139298-winpe-30-wds-problems/">you need a lang.ini file in your sources directory</a> along side setup.exe in order to run. I just grabbed the lang.ini file off the normal Win7 boot image and copied it to the sources directory of my mounted boot image.</p>
<p><strong>Step Eight: Commit and Unmount the PE Boot image<br />
</strong>We’re now done updating the boot image, so it’s time to close and unmount it. This is accomplished with DISM:</p>
<pre class="brush:plain">dism /unmount-wim /mountdir:c:\winpe_x86\mount /commit</pre>
<p>At this point, the contents of the ISO folder are ready to be transferred to a USB stick for booting.</p>
<p><strong>Step Nine: Prepare the USB Flash Drive<br />
</strong>To enable your USB flash drive to be bootable, it needs to have a single FAT32 partition spanning the entire drive. Instructions in this <a href="http://technet.microsoft.com/en-us/library/dd744530(v=WS.10).aspx">walkthru</a> show you how to configure and format your USB drive.</p>
<p>Note, not all USB drives are created equal. I have one USB drive where the Duo just comes up with a blank screen when I try to use it for USB Boot. If you follow these steps and can’t boot, try a different USB drive.</p>
<p><strong>Step Ten: Copy the image contents to the Flash Drive<br />
</strong>I just did this with xcopy. In this case, my flash drive is E:, but obviously you should swap in the drive letter for your flash drive.</p>
<pre class="brush:plain">xcopy c:\winpe_x86\ISO\*.* /e e:</pre>
<p><strong>Step Eleven: Boot your Netbook from the USB drive<br />
</strong>With the USB drive containing the image + the network dongle both plugged in, boot the machine and trigger USB boot. For the Duo, you can hit F12 during boot to manually select your boot source. Your custom image will be booted, and it will then look out on the network to find the WDS server to load images from. Select the image you want and where you want to install it and away you go.</p>
<p>One thing to remember is that you&#8217;re adding the  USB network dongle driver to the WDS discovery boot image, but <em>not</em> to the image that gets installed via WDS. So chances are you&#8217;ll need the driver again once you get the image installed. I put that driver on the same USB key that holds the boot image. That way I can easily install the driver once Windows is installed.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Devhawk?a=W9S_jxlOh1U:VmaabQZdbCY:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=W9S_jxlOh1U:VmaabQZdbCY:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=W9S_jxlOh1U:VmaabQZdbCY:XQ266DUsA9M"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=XQ266DUsA9M" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=W9S_jxlOh1U:VmaabQZdbCY:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/Devhawk?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Devhawk?a=W9S_jxlOh1U:VmaabQZdbCY:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Devhawk?i=W9S_jxlOh1U:VmaabQZdbCY:V_sGLiPBpWU" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Devhawk/~4/W9S_jxlOh1U" height="1" width="1"/>]]></content:encoded><description>Given that I work on the Windows team, it shouldn’t come as a surprise that we use Windows Deployment Services to distribute Windows images internally. For most machines, it’s really convenient. You trigger a network boot (on my Lenovo, you press the “ThinkVantage” button during start up), select the image to install and what partition [...]</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://devhawk.net/2011/05/19/build-your-own-wds-discovery-image/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">2</slash:comments></item></channel></rss>
