Tag Archives: development

WinRT from the eyes of a .NET developer

Following is the compilation of information related to what the .NET developer need to know about WinRT.

This biggest confusion, has been around the use of the .NET Framework across the blue side and green side. The reason for the, as I call it, .NET Metro Profile is because the Metro style apps run in an app container that limits what the application can have access to in order to protect the end user from potentially malicious apps. As such, the Metro Profile is a subset of the .NET Client Profile and simply takes away some of the capabilities that aren’t allowed by the app container for Metro style apps. Developers used to .NET will find accessing the WinRT APIs very intuitive – it works similarly to having an assembly reference and accessing the members of said referenced assembly.

At the lowest level, WinRT is an object model defined on ABI level. It uses COM as a base (so every WinRT object implements IUnknown and does refcounting), and builds from there. It does add quite a lot of new concepts in comparison to COM of old, most of which come directly from .NET – for example, WinRT object model has delegates, and events are done .NET-style (with delegates and add/remove subscriber methods, one per event) rather than the old COM model of event sources and sinks. Of other notable things, WinRT also has parametrized (“generic”) interfaces.

One other big change is that all WinRT components have metadata available for them, just like .NET assemblies. In COM you kinda sorta had that with typelibs, but not every COM component had them. For WinRT, the metadata is contained in .winmd files – look inside “C:\Program Files (x86)\Windows Kits\8.0\Windows Metadata\” in Developer Preview. If you poke around, you’ll see that they are actually CLI assemblies with no code, just metadata tables. You can open them with ILDASM, in fact. Note, this doesn’t mean that WinRT itself is managed – it simply reuses the file format.

Then there are a number of libraries implemented in terms of that object model – defining WinRT interfaces and classes. Again, look at “Windows Metadata” folder mentioned above to see what’s there; or just fire up Object Browser in VS and select “Windows 8.0” in the framework selector, to see what’s covered. There’s a lot there, and it doesn’t deal with UI alone – you also get namespaces such as Windows.Data.Json, or Windows.Graphics.Printing, or Windows.Networking.Sockets.

Then you get several libraries, which are specifically dealing with UI – mostly these would be various namespaces under Windows.UI or Windows.UI.Xaml. A lot of them are very similar to WPF/Silverlight namespaces – e.g. Windows.UI.Xaml.Controls is closely matching System.Windows.Controls; ditto for Windows.UI.Xaml.Documents etc.

Now, .NET has the ability to directly reference WinRT components as if they were .NET assemblies. This works differently from COM Interop – you don’t need any intermediate artifacts such as interop assemblies, you just /r a .winmd file, and all types and their members in its metadata become visible to you as if they were .NET objects. Note that WinRT libraries themselves are fully native (and so native C++ programs that use WinRT do not require CLR at all) – the magic to expose all that stuff as managed is inside the CLR itself, and is fairly low level. If you ildasm a .NET program that references a .winmd, you’ll see that it actually looks like an extern assembly reference – there’s no sleight of hand trickery such as type embedding there.

It’s not a blunt mapping, either – CLR tries to adapt WinRT types to their equivalents, where possible. So e.g. GUIDs, dates and URIs become System.Guid, System.DateTime and System.Uri, respectively; WinRT collection interfaces such as IIterable<T> and IVector<T> become IEnumerable<T> and IList<T>; and so on. This goes both ways – if you have a .NET object that implements IEnumerable<T>, and pass it back to WinRT, it’ll see it as IIterable<T>.

Ultimately, what this means is that your .NET Metro apps get access to a subset of the existing standard .NET libraries, and also to (native) WinRT libraries, some of which – particularly Windows.UI – look very similar to Silverlight, API-wise. You still have XAML to define your UI, and you still deal with the same basic concepts as in Silverlight – data bindings, resources, styles, templates etc. In many cases, it is possible to port a Silverlight app simply by using the new namespaces, and tweaking a few places in code where the API was adjusted.

WinRT itself doesn’t have anything to do with HTML and CSS, and it bears relation to JavaScript only in a sense that it is also exposed there, similar to how it is done for .NET. You don’t need to deal with HTML/CSS/JS when you use WinRT UI libraries in your .NET Metro app (well, I guess, if you really want to, you can host a WebView control…). All your .NET and Silverlight skills remain very much relevant in this programming model.

Under the hood Part 4 : C++ WinRT Component DLL & C++ XAML application – WinRT, Windows 8, C++, Metro

Calling WinRT Component from C++

We have developed a C++ WinRT Component DLL & C#.NET application in the post here Under the hood Part 1 : C++ WinRT Component DLL & C#.NET Metro application

we have seen the compiler generated components for making the C# application access the C++ WinRT component here Under the hood Part 2 : C++ WinRT Component DLL & C#.NET Metro application

We have seen the packaging and installation process that happens in the background during building and deploying of the applications here Under the hood Part 3 : WinRT, Windows 8, C++, C#.NET, Metro, WinRT Component DLL

Going further, I created a C++ Metro application and accessed the C++ WinRT Component DLL from this application. The interesting part here is that C++ applications is XAML based. No more .RC and resource.h files in C++ (for metro). In the previous post, we created a WinRT C++ DLL that contains a class calculatorSample. Now let us create  a C++ application to consume the C++ WinRT DLL.

To get started with creating a C++ XAML application, go to Visual Studio 2011 –> Solution Explorer–> New Project –> Go to Installed Templates section –> Visual C++ –>Select Application and name it as CPPApplication1 as shown in the following fig 1.


Fig 1: Creating a C++ XAML application.

Right click on the project, click on Add References and the following dialog shown in figure 2 comes up.


Fig 2: Reference manager dialog to add references to another components.

Click on Solution section –> Projects and Select  CppWinRTComponentDLL –> click on Add button and click on Close as shown in figure 3.


Fig 3: Selecting WinRT CppWinRTComponentDLL.

The CppWinRTComponentDLL reference appears in the References section as shown in the following figure 4.


Fig 4: CppWinRTComponentDLL dll appears in the References section.

Goto MainPage.xaml.cpp and include the namespace for CppWinRTComponentDLL

Code Snippet
using namespace CppWinRTComponentDll;


Then create an object of calculatorSample on the heap using ref new. In this scenario, ref new  is like cocreateinstance of COM. It’s a smart allocator. we also use ref class to indicate the authoring of a Windows Runtime class . using ^ to represent a “refcounted” pointer in ZW fits quite well

The following code shows how to use the ref new expression to create a new reference-counted Windows Runtime object. Note that you use the ^ (“hat”) symbol instead of the pointer dereference operator (*) when declaring the variable, but that you use the familiar -> operator to access the objects instance members. Note also that you do not call delete explicitly on the object. The object will be destroyed deterministically when the last remaining copy of it goes out of scope. At the lowest level, the object is basically a COM object owned by a smart pointer.

Code Snippet
CalculatorSample^ calcobj = ref new  CalculatorSample();
txtAddResult->Text = calcobj->Add(10,20).ToString();


So from the C++ application, we are calling the C++ Windows Runtime Component DLL. This is all native code. C++ calling C++ and everything is ref counted.

Compiler options: /ZW enable WinRT language extensions /AI<dir> add to assembly search path <dir> is the folder where the compiler searches the winmd files /FU<file> forced using assembly/module force the inclusion of the specified winmd file /D "WINAPI_FAMILY=2" set this define to compile against the ModernSDK subset of Win32

Linker options: /APPCONTAINER[:NO] marks the executable as runnable in the appcontainer (only) /WINMD[:{NO|ONLY}] emits a winmd; if “ONLY” is specified, does not emit the executable, but just the winmd /WINMDFILE:filename name of the winmd file to emit /WINMDDELAYSIGN[:NO] /WINMDKEYCONTAINER:name /WINMDKEYFILE:filename used to sign the winmd file

However, in a Metro style app or Windows Runtime component, all the C++ code is native. The /ZW compiler option causes the Component Extensions to be compiled for Windows Runtime. The /cli compiler option causes them to be compiled for C++/CLI. Currently, C++/CLI is not supported for Metro style apps

Code snippet of the complete MainPage class.

Code Snippet
// MainPage.xaml.cpp
// Implementation of the MainPage.xaml class.

#include "pch.h"
#include "MainPage.xaml.h"

using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Data;
using namespace CPPApplication1;

using namespace CppWinRTComponentDll;


      CalculatorSample^ calcobj = ref newCalculatorSample();
    txtAddResult->Text = calcobj->Add(10,20).ToString();

    int result;
    HRESULT hr = calcobj->__cli_Add(20,30,&result);
    txtAddResult->Text = result.ToString();


All Windows Runtime types derive from the universal base class Platform::Object. There is therefore an implicit conversion from any Windows Runtime object to Platform::Object.

Code snippet of the XAML page.

Code Snippet
<UserControl x:Class="CPPApplication1.MainPage"
    d:DesignHeight="768" d:DesignWidth="1366">
    <Grid x:Name="LayoutRoot" Background="#FF0C0C0C">
        <TextBox x:Name="txtAddResult" HorizontalAlignment="Left" Text="TextBox" VerticalAlignment="Top" Margin="343,90,0,0" Width="212"/>
        <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="Calling C++ component Add method from C++ XAML Application" VerticalAlignment="Top" Margin="81,90,0,0" Height="45" Width="258" FontSize="14" FontWeight="Bold"/>



Build the solution and deploy the application. The application output is as follows.image

Configuration settings:

Enable Windows Runtime Extensions enables the runtime extensions throughout the type system which includes the ability to do Boxing. I.e. Boxing to WinRT type system. Every fundamental types and WinRT types are derived from Platform.Object.image

heap-allocated objects with heap semantics:

Calculator^ calc = ref new Calculator(); // Calculator is a ref class from a custom WinRT component

txtResult->Text = calc->Add(10, 20).ToString();

The ^syntax will fire a destructor when the refcount on the object drops to 0, or if you explicitly call delete. (So if you handed the object out it’s not necessarily at the end of your scope)

heap-allocated objects with Stack semantics:

Calculator calc;

txtResult->Text = calc.Add(10, 20).ToString();

Both of those create heap-allocated objects behind the scenes, but the difference is whether you logically have heap semantics vs. stack semantics.

The stack syntax will fire a destructor when the object goes out of scope (or on an exception etc.). This is important when you e.g. handed of the object to another thread or async callback, so there may still be a refcount on it, but you need to get rid of it right away. (E.g. a file handle that needs to be closed otherwise the file is locked). The main advantage is exception-safe deterministic destruction.

PS: Because of the nature of refcounting, it’s a little bit less important with WinRT to have deterministic destruction than with e.g. the /clr and a garbage collected heap (where the point of destruction is virtually random). However, you will find that with async patterns it is common to get into a situation where you’re transfer the ownership of an object from one thread to another (e.g. via a lambda). There is then a race condition between the two threads for releasing the object. This is generally still ok, but if the object represents a file or other exclusive resource it might be critical to perform the destruction at a specific time, rather than relying on the timing between the two threads.

value classes & Ref classes

Int32 x(15); // Compiles and x is initialized and works as expected.

String str("test1"); // Doesn’t compile and compiler complains C3149: ‘Platform::String’ : cannot use this type here without a top-level ‘^’

Int32 is a value class, and String or the custom winRT component are all ref class. They are different.

Differences between C++/CLI and WinRT C++

In terms of the differences like flags are as follows.

Basic types:
/clr: From mscorlib.dll (System::* types)
/ZW: From vccorlib.dll (Platform::* types)

Lifetime management:
/clr: Garbage collected
/ZW: Refcounted

Cycles Broken:
/clr: By garbage collector
/ZW: Broken by user (weak references or explicit delete)

Code generation:
/clr: MSIL + native code. Can create a cross-platform binary if MSIL-only.
/ZW: Native code only. Binaries target a specific platform.

Object Creation:
/clr: gcnew
/ZW: ref new

/clr: Supported
/ZW: Not supported

/clr: Supported
/ZW: Not supported

V% (% when it refers to a byref (kind’a like an "interior_ref") ):
/clr: Supported
/ZW: Not supported

R% (% when it refers to an implicitly dereferenced ref type):
/clr: Supported
/ZW: Supported

Ref to ^:
/clr: R^%
/ZW: R^&

/clr: syntax V^
/ZW: IReference<V>^

Dereferenced box type:
/clr: V%
/ZW: const V

/clr: Generics classes, interfaces & delegates allowed.
/ZW: Generic interfaces & delegates only.

Static constructors:
/clr: Supported
/ZW: Not supported

Address of member of ref class:
/clr: Returns an interior_ptr
/ZW: Returns a type*

/clr: Not supported
/ZW: Supported

C++ class embedded in ref class:
/clr: Not supported
/ZW: Supported

ref class embedded in C++ class:
/clr: Not supported
/ZW: Supported (R-on-stack)

^ embedded in C++ class:
/clr: Not supported (Needs GCHandle)
/ZW: Supported

^ embedded in value class with value class on native heap:
/clr: Not supported
/ZW: Supported (for String^)

Global ^:
/clr: Not supported
/ZW: Supported

Global R-on-stack:
/clr: Not supported
/ZW: Supported

/clr: Supported
/ZW: Not supported

/ZW: Runs on IDisposable::Dispose (delete / stack unwind) only
/clr: Runs on IDisposable::Dispose (delete / stack unwind) -or- last release (never both)

/clr: Supported
/ZW: Not supported

R-on-stack (ref class on stack) syntax is supported on C++/cli and C++/CX, but you’ll notice that unfortunately the /CX implementation in the developer preview release has a code generation bug that will make it impractical to test this right now. (R^ and R% should be fine though). The most important reason for R-on-stack is exception-safe destruction (Like ‘using’ gives you in C#) – other than that it is purely compiler syntactic sugar.

Download the source code here.

"If one advances confidently in the direction of his dreams, and endeavors to live the life which he has imagined, he will meet with success unexpected in common hours." — Henry David Thoreau

Design & Develop for the present and future – WinRT, .NET, C++, HTML5

A collection of useful information from the web.

With the new Windows 8, Metro , WinRT and other stuff coming out of Microsoft, the question is when should we care about Metro and WinRT from a development perspective? Here is the information from different sources like Gartner, Magenic, etc. that I found useful.

As per Research, Windows Phone will be No. 2 smartphone OS by 2015 according to Gartner, IDC.  The question to ask is how long it will take until Windows 8 is finally out and reached a critical mass. Coming to desktops, a lot of machines out there still run Windows XP. Windows 7 is way better and I guess the transition to Windows 8 will take even longer. Windows 8 will probably mainly pushed by non-PC multi-touch consumer devices in the near future. Win8 will probably RTM in time for hardware vendors to create, package, and deliver all sorts of machines for the 2012 holiday season. So probably somewhere between July and October 2012.

Understanding of some of the new common terms:

  • Windows 8 – the new operating system that runs in a “dual mode”: Desktop (Win32) and WinRT
  • Win32 – the OS API that supports today’s applications in Win8
  • WinRT – the new OS API that supports future applications
  • Metro – a user experience design language often used when building WinRT applications.
  • “WinRT apps” includes any/all apps written on the WinRT API.
  • “Metro apps” that are probably a WinRT app, that also follows the Metro user experience guidelines.

For consumer apps this means you might care about Win8 now, because you might want to make sure your cool app is in the Win8 online store for the 2012 launch. So you will start writing code using Windows 8 Runtime, Metro and bunch of other tools.

For business apps the timing is quite different. Corporations roll out a new OS much later than consumers get it through retailers. As an example, Windows 7 has now been out for about three years, but some corporations still use Windows XP!!! So for business apps, we can look at doing a reasonable amount of Win8 Metro development around 2014-2015.

Attached is the Technology Comparison Chart:image

* Note: combinations of factors not listed here may point to two or more UI technologies being needed.

  1. If touch is needed in the future, application can be designed to Metro style standards.
  2. Windows 8 phones are planned to be supported with Metro applications.
  3. HTML5/JS Metro applications could be selected if there is an internal skill set for that technology.
  4. WebForms are generally considered an older technology, in general use ASP MVC unless there is a compelling reason to use WebForms.
  5. For applications not in the app store, a deployment system will be needed.
  6. Mono may make app store approval more difficult.
  7. Windows Phone 7 leverages .NET skill sets.

Some of us will be lucky enough to work for "type A" companies that jump on new things as they come out, and we’ll get to build Metro apps starting in Q1- Q2 2012.

Most of us work for "type B" companies, and they’ll roll out a new OS after SP1 has been deployed by the "type A" companies – these are the companies that will deploy Win8 after has been out for 1-2 years.

Some unfortunate souls work for "type C" companies, and they’ll roll out Win8 when Win7 loses support (so around 2018?).  That’s a hard place to find yourself as a developer. Yet those companies do exist even today.

What does this all mean? It means that for a typical corporate or business developer, we have around 2-3 years from today before we’re building WinRT apps. The logical question to ask then (and you really should ask this question), is what do we do for the next 2-3 years? How do we build software between now and when we get to use Metro/WinRT? Obviously the concern is that if you build an app starting today, how do you protect that investment so you don’t have to completely rewrite the app in 3 years?

This flowchart by the Telerik guys sums it up pretty nicely.


Clearly any app that uses multiple windows or modal dialogs (or really any dialogs) will not migrate to Metro without some major rework. The one remaining concern is the new run/suspend/resume/terminate application model. Even Silverlight doesn’t use that model today – except on WP7. I think some thought needs to go into application design today to enable support for suspend in the future. I don’t have a great answer right at the moment, but I know that I’ll be thinking about it, because this is important to easing migrations in the future.

It is true that whatever XAML you use today won’t move to WinRT unchanged. Well, I can’t say that with certainty, but the reality is that WinRT exposes several powerful UI controls we don’t have today. And any Metro style app will need to use those WinRT controls to fit seamlessly into the Win8 world. For better compatibility with future versions of Windows, it seems sticking to the XAML path would be more beneficial. What does this mean for developers? Well, if you are on .NET today, you can simply start learning the new WinRT using the XAML/C#/VB route and start creating Metro apps. If you are a HTML/CSS/JS developer, ramp up on HTML5/CSS3 and the JavaScript extensions and frameworks available as well as the WinRT code. If you want to build an application that would run both on Windows 7 and Windows 8 you can create it with XAML and then for Windows 8 also provide a Metro XAML frontend. We will of course need to see how all of this comes together as we start getting more information out of Microsoft.

Conversion Strategies:


No existing technologies map directly to the WinRT platform. Figure 4 shows how existing technologies map to the Windows 8 development platform. As you can see, all existing technologies map directly to the Windows 8 desktop environment. This is illustrated by the green lines, indicating that these applications are expected to work in Windows 8 with no effort.

The yellow line for Silverlight indicates that many Silverlight applications can be migrated to WinRT with reasonable effort. We will discuss this in more detail later in the paper.

The red line for WPF indicates that migration to WinRT is possible, but will require more substantial effort.

The red dashed line for HTML indicates that development skills will transfer, and a limited amount of existing HTML, CSS, and code assets may apply to WinRT application development.

Applications written using existing technologies will require effort to migrate to WinRT. For applications written with technologies other than Silverlight and WPF, the term “rewrite” is probably more accurate than “migrate”.

In summary, Windows 8, WinRT, and Metro are a big deal. But not in the way most people seem to think. The .NET/C#/CLR/BCL story is evolutionary and just isn’t that big a deal. It is the user experience and application lifecycle story that will require the most thought and effort as we build software over the next several years. These are good challenges, and I very much look forward to building .NET applications that deeply integrate with Windows 8. People will ultimately be building business applications on WinRT. Those apps may or may not be strictly “Metro”, but by running on WinRT they’ll gain the benefits of the new runtime API, services, and application model.

Under the hood Part 3 : Internals of how the application is installed and run – WinRT, Windows 8, C++, C#.NET, Metro

Under the hood Part 3 : WinRT, Windows 8, C++, C#.NET, Metro, WinRT Component DLL

We have developed a C++ WinRT Component DLL & C#.NET application in the post here Under the hood Part 1 : C++ WinRT Component DLL & C#.NET Metro application

we have seen the compiler generated components for making the C# application access the C++ WinRT component here Under the hood Part 2 : C++ WinRT Component DLL & C#.NET Metro application

See the post on First Look at What’s New in Windows 8 here.

Going further, I created a C++ Metro application and accessed the C++ WinRT Component DLL from this application. The interesting part here is that C++ applications is XAML based. No more .RC and resource.h files in C++ (for metro). We will explore the C++ application in another post. In this post, let us walk through the packaging and installation process that happens in the background during building and deploying of the applications.

Basically, there are two registrations for our application.

  1. Extension registration
  2. Class registration.

The figure 1 (from Build con) shows the relation between the two.


Fig : Slide related to Extension Catalog and Class Catalog shown @ Build con.

Go to  Visual Studio 2011 –> Solution Explorer –> CSharpApplication project, here you can find a file named Package.appxmanifest as shown in figure 1 . This file has most of the information needed to deploy the application. This is the information that windows uses to identify the application. Package Name is the name used in most of the identification process.


Fig 1: Package.appxmanifest file in Visual Studio 2011 Solution Explorer.

Code snippet of Package.appxmanifest file.

Code Snippet
<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/2010/manifest">
  <Identity Name="CSharpApplicationCallingCPPComponent" Publisher="CN=Kishore" Version="" />
    <Resource Language="en-us" />
    <Application Id="App" Executable="csharpapplication.exe" EntryPoint="CSharpApplication.App">
      <VisualElements DisplayName="CSharpApplication" Logo="Images\Logo.png" SmallLogo="Images\SmallLogo.png" Description="CSharpApplication" ForegroundText="light" BackgroundColor="#222222" InitialRotationPreference="portrait">
        <SplashScreen Image="Images\SplashScreen.png" />
    <Capability Name="internetClient" />


The applications implement contract like search contract, share, play queue contract. Those contract registrations are the extensions registration for the operating system.  Tile that you see in the Windows start page is just another contract activation. I,e windows.launch contract. So if you go to HKEY_CURRENT_USER\Software\Classes\Extensions\ContractId\Windows.Launch, you can find your application package id that we saw in figure 1. Everything under Windows.Launch is organized by package ID as shown in the figure 2 below.


Fig 2: Registry settings showing the registered Extensions.

From figure 2, we can see our package HKEY_CURRENT_USER\Software\Classes\Extensions\ContractId\Windows.Launch\ PackageId\csharpapplicationcallingcppcomponent_1.0.0.0_x86_neutral_kb63pw67p0swp. This package has a  ActivatableClassId key . Under that we see App as shown in figure 3. This is the class registration for this extension. image

Fig 3: App registry settings for your application.

Let us see how the class registration for the applications looks like. First, We have extensions which say I implement this contract for ex I implement this launch and then we have classes. The extensions point to the classes. classes are actually the implementation. All applications are just Windows Runtime objects to the Windows OS, this is where all it starts. This is the windows runtime class that the OS knows about for your application.

The interesting part is in the class registration for the application. If we go up in the registry editor, we should see a registry key called ActivatableClasses at  HKEY_CURRENT_USER\Software\Classes\ActivatableClasses, this is where the class registrations are for all of our applications are. Here again we find package. All extensions, all classes are organized based on the package. That means our application or package has unique set of classes and they don’t share extension points or classes with other applications. They are all unique for our app. If we expand it, we see ActivatableClassId, the same name we saw in extensions. Here we should find the App classId. This is the WinRT class registration. This is the same for all types of applications, libraries etc.

Here we can see some registration attributes . The ActivationType is an important one. Windows Runtime supports two activation styles.

  1. InProcess activation
  2. Out of process activation

So Windows Runtime supports InProcess activation where we provide the DLL and windows load that into the process and it also supports out of process activation, where we will provide an exe and windows will launch the exe as your class implementation.

Registry key values:

ActivationType = 1 indicates its out of process activation class. out of process classes have a server. we have to know where the executable is, so there is a server registion here.

ActivationType = 0 indicates its in process activation

Out of process has a server and so there is a server registration here. Server with value App.AppXpdnr4x0evrk1yjmz5xfw2ksncfcjc5er.mca as shown in figure 4.image

Fig 4: Server registry values for your application.

In figure 3, below the ActivationType , we can find Server attribute and it contains the App.AppXpdnr4x0evrk1yjmz5xfw2ksncfcjc5er.mca we got from the above Server value.  The server registration, tells the windows runtime enough information about what code we actually need to get from the disk and start running to get the app up and running. The ExePath attribute gives the path to the exe.

Windows runtime supports two apartment models. MTA & STA. If you have worked in VC++ COM, COM+ earlier, then you might have programmed the components for Multi Threaded Apartment model & Single Threaded Apartment model.

Let us see some more ActivatableClassId entries for Windows Runtime present at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WindowsRuntime as shown in figure 5.


Fig 5: Windows Runtime classes information.

Finally, the slide that caught my attention was the deployment pipeline process shown in Fig 6 that shows the overall view of the above mentioned information.


Figure 6 showing the role of the deployment engine @ Build Con.

"Only those who risk going too far can possibly find out how far they can go." – T.S. Eliot

Under the hood Part 2 : C++ WinRT Component DLL & C#.NET Metro application

We have developed a C++ WinRT Component DLL & C#.NET application in the post here Under the hood Part 1 : C++ WinRT Component DLL & C#.NET Metro application

The important point here is that the  C# application is accessing the C++ WinRT component through RCW mechanism. The same application can be developed with JavaScript also that can use the C++ DLL that we developed. Wow, cool right? 

To understand the simplicity of the new programming model, we created a C++ WinRT Component DLL in part 1, which is all the code you need to author a Windows Runtime component.

Please download the code and extract the files.

Code Snippet
#pragma once

using namespace Windows::Foundation;

namespace CppWinRTComponentDll

    public ref class CalculatorSample sealed
        int Add(int x, int y);
        int Sub(int x, int y);
        int Mul(int x, int y);


In this example, you will immediately notice some keywords that are not part of standard C++. Visual C++ defines a few Component Extensions that, in a Metro style app, are essentially syntactic sugar over the underlying COM calls involved in creating and consuming Windows Runtime types. You typically use these extensions in the public interfaces where your code is passing Windows Runtime types back and forth across the ABI to JavaScript, C#, or Visual Basic (or even another C++ module). Visual C++ provides a variety of implicit conversions between Windows Runtime types and standard C++ types. The typical pattern is to use standard C++ types and libraries internally as usual, and convert to Windows Runtime types in the public interfaces.

So how did the C++ component get pulled into .net application? When we build the CppWinRTComponentDll project, we see the following in the output window. Notice the highlighted CppWinRTComponentDll.winmd text. This means the compiler is generating a file of type windmd.

1>—— Build started: Project: CppWinRTComponentDll, Configuration: Debug Win32 ——
1>  CppWinRTComponentDll.vcxproj -> C:\Users\Kishore\Documents\Visual Studio 11\Projects\CppWinRTComponentDll With CSharp App\Debug\CppWinRTComponentDll\CppWinRTComponentDll.winmd
1>  LINK : C:\Users\kishore\Documents\Visual Studio 11\Projects\CppWinRTComponentDll With CSharp App\Debug\CppWinRTComponentDll\CppWinRTComponentDll.dll not found or not built by the last incremental link; performing full link
1>     Creating library C:\Users\kishore\Documents\Visual Studio 11\Projects\CppWinRTComponentDll With CSharp App\Debug\CppWinRTComponentDll\CppWinRTComponentDll.lib and object C:\Users\kishore\Documents\Visual Studio 11\Projects\CppWinRTComponentDll With CSharp App\Debug\CppWinRTComponentDll\CppWinRTComponentDll.exp
1>  CppWinRTComponentDll.vcxproj -> C:\Users\kishore\Documents\Visual Studio 11\Projects\CppWinRTComponentDll With CSharp App\Debug\CppWinRTComponentDll\CppWinRTComponentDll.dll
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

You can notice the CppWinRTComponentDll.winmd file in the debug folder (CppWinRTComponentDll With CSharp App\Debug\CppWinRTComponentDll) as shown in Figure 1.


Fig 1: .WinMD File present in CppWinRTComponentDll folder inside the Debug folder.

This WinMD file is essentially a CLI meta data file and can be opened in ILDASM as shown in figure 2. CppWinRTComponentDll is exposed using API metadata present in CppWinRTComponentDll.winmd file. The format of WinMD file is Ecma-335 and this is the same format used by the .NET framework. It just used the ECMA-335 file format standard & the framework and nothing more than that. The underlying binary contract makes it easy for us to access the CppWinRTComponentDll APIs directly in the development language of our choice. The shape and structure of the CppWinRTComponentDll APIs can be understood by both static languages such as C# and dynamic languages such as JavaScript. IntelliSense is available in JavaScript, C#, Visual Basic, and C++ as you can see in the C# application (CSharpApplication project).


Fig 2: Opening CppWinRTComponentDll.winmd file using ILDASM.

This CppWinRTComponentDll.winmd file is created by c++ compiler and this can be seen as a cross language header file because c# cannot understand c++ header and neither JavaScript. so we need to have the file format that all languages understand and that is the .winmd file format. Although we authored a CalculatorSample class, what the compiler did for us is that, it also created a interface __ICalculatorSamplePublicNonVirtuals as shown in figure 3, which is the com interface used to talk to the calculator class. This adds it to the public surface.image

Fig 3: Interface ICalculatorSamplePublicNonVirtuals created by the compiler

Manifest of the CppWinRTComponentDll.winmd file can be seen in figure 4.image

Fig 4: Manifest of the CppWinRTComponentDll.WinMD File. Note the first entry, mscorlib.

we can see the Add method signature stored in the WinmD file in figure 5.image

Figure 5: Add method signature present in CppWinRTComponentDll.winmd file.

Code Snippet
.method public newslot abstract virtual instance int32
Add(int32 x,
int32 y) cil managed
} // end of method __ICalculatorSamplePublicNonVirtuals::Add


In the ILDASM, click on the .class interface private abstract auto ansi windowsruntime. The GUID attribute. this is like specifying the GUID of the interface as shown in figure 6. This is the GUID for the component.


Fig 6: GUID of the interface.

The WinMD file does not contain any IL. This is just like a header information so that other languages can understand. This makes the Projections to happen. The calculator is a ref class itself. The CppWinRTComponentDll.CalculatorSample class implements from .__ICalculatorSamplePublicNonVirtuals and it implements Add,Sub and Mul methods as shown in the following figure 7.


Fig 7: CppWinRTComponentDll.CalculatorSample class implements from __ICalculatorSamplePublicNonVirtuals Interface.

Note that every object inside WinRT is ref counted.

Details about the C++ WinRT Component DLL created in part 1 (MSDN): C++/CX (Component Extensions)

Visual C++ in Visual Studio 11 for has a new programming model for creating Metro style apps and components. One of the primary features of the new model is the abstract binary interface, or ABI, which defines an interface for inter-language communication. In Windows Developer Preview, native C++ can communicate across the ABI with JavaScript and with the managed .NET languages C# and Visual Basic. This means you can create high-performance components in native C++ and consume them directly from one of these other languages. It also means you can consume Windows Runtime types directly in native C++, without having to interop with a managed layer as when you consume .NET Framework types.

At a low level, the new programming model is based on an updated version of COM, but the way that you program against this new model is more simple and natural than old-style COM programming. When you create a consumable Windows Runtime components or Metro style apps in native C++ you work primarily with classes and members just as in standard C++. JavaScript or .NET code instantiates your object by using new (or New) and the object is destroyed according to the mechanisms of the client language. When native C++ consumes a Windows Runtime object, destruction is handled by means of reference counting.

Download the code and extract the files.

"Cultivate optimism by committing yourself to a cause, a plan or a value system. You’ll feel that you are growing in a meaningful direction which will help you rise above day-to-day setbacks." — Dr. Robert Conroy

Note: The code is developed using Windows 8 & Visual Studio 2011 developer preview, which might change when the actual versions are released.