Monthly Archives: March 2012

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

JavaScript application calling WinRT Component DLL

In this part, we will create a C++ WinRT Component DLL and access it from a JavaScript 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

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

We have seen the C++ XAML application calling the C++ WinRT Component DLL here Under the hood Part 4 : C++ WinRT Component DLL & C++ XAML application – WinRT, Windows 8, C++, Metro

Generally, in a LOB application, we might have to build a C++ Component DLL to take advantage of the performance of C++ in complex or computationally-intensive operations. The C++ component can access Windows operating system services that are not accessible through the Windows Runtime in the current version. Mostly, to reuse existing code that is already written and tested.

Download the source code here.

Step 1:

Create a Windows Runtime C++ Component DLL:

Open Visual Studio 2011 –> File –> New Project –> Go to Installed Templates section –> Visual C++ –>Select WinRT Component DLL and name it as CPPWinRTComponentDll as shown in the following figure.

image

Fig 1: CPPWinRTComponentDll project

Open WinRTComponent.h file and create an Employee class as shown in the following code snippet. The Platform namespace is where C++ defines its classes that are specific Windows Runtime types.

Create a private variables address_ and employeeid_. These are used as backing store to hold the values. We will use get() & set() properties to set or get these values.

    private:
            // Backing store for property address_ & employeeid_.
            Platform::String^ address_;
            int employeeid_;

 

In the public section, add the following code which are properties for the above backing store.

        property Platform::String^ Address
        {
            Platform::String^ get()
            {
                return  (address_);
            }
        }

        // Property with custom setter/getter
        property int EmployeeId
        {
            int get()
            {
                return employeeid_;
            }

            //    ‘set’ accessor is missing its value parameter
            void set(int value)
            {
                if(value <= 0)
                {
                    throw ref new Platform::InvalidArgumentException();
                    employeeid_ = value;
                }
            }
        }

 

We can also add some trivial get/set property with the compiler generating the backing store.

    public:
        // Trivial get/set property with compiler-generated backing store.
        property Platform::String^ Name;

 

Following is the complete code of the Employee class.

Code Snippet
public ref class Employee sealed
    {
    private:
            Platform::String^ address_;
            int employeeid_;
           
            //If i use a stack syntax, i get compilation error
            //Platform::String address2_;
            //Error    1    error C3149: ‘Platform::String’ : cannot use this type here without a top-level ‘^’   
            //c:\projects\cppwinrtcomponentdll with cpp app string\cppwinrtcomponentdll\winrtcomponent.h   

    public:

        property Platform::String^ Name;
        property Platform::String^ Address
        {
            Platform::String^ get()
            {
                return  (address_);
            }
        }

        property int EmployeeId
        {
            int get()
            {
                return employeeid_;
            }

            //    ‘set’ accessor is missing its value parameter
            void set(int value)
            {
                if(value <= 0)
                {
                    throw ref new Platform::InvalidArgumentException();
                    employeeid_ = value;
                }
            }
        }

    public:
        Platform::String^ SayHello()
        {
            return "Hello World";
        }

    public:
        int Add(int x, int y)
        {
            return x+y;
        }

    };

 

When you code your C++ component, if needed, you can use the regular C++ library and built-in types inside the class code except at the abstract binary interface (ABI) boundary where you are passing data to and from JavaScript. There, use Windows Runtime types and the special syntax that Visual C++ supports for creating and manipulating those types.

You have to make the Employee class as activatable class so that it can instantiated from another language such as JavaScript. To be consumable from another language such as JavaScript, a component must contain at least one activatable class. If needed, a Windows Runtime component can contain multiple activatable classes as well as additional classes known only internally to the component. Client code creates an instance of the component by using the new keyword just as for any class.

The Employee class must be declared as public ref class sealed. The ref class keywords tell the compiler to create the class as a Windows Runtime compatible type, and the sealed keyword specifies that the class cannot be inherited. A class must be sealed to be consumed by JavaScript.

In the Platform::String^ address_, the ^ operator signifies a handle to a Windows Runtime string type that under the covers is reference-counted and deleted when the count reaches zero. Instances of these types are created by using the ref new keywords. Do not explicitly call delete on these instances.

Types must be passed to and from the public methods as Windows Runtime types. If you use the C++ built-in types such as int, double and so on, the compiler will automatically convert them to the appropriate Windows Runtime type. No such conversion occurs unless you are passing the type across the ABI. Complex types such as Platform::String^ must be specified explicitly.

Step 2:

Creating a JavaScript Windows Metro style Application project:

To create a project in this solution, right-click the solution node in Solution Explorer. and select Add Project > Blank Application. Name it as WinWebApp1.

image

Fig 2: creating the JavaScript project
Add a reference to the component project

After you have compiled the C++ project for the first time, you can add it as a project reference in the JavaScript project. Right-click the References node in the JavaScript project, and select Add. When the Add References Manager dialog box appears, click “Solution” to display the available references in the solution. Select  “CPPWinRTComponentDll ” in this solution and click on Add button as shown in figure 3; The namespace and all public types and methods are now available to your JavaScript code. You can verify this by experimenting with the Member List or Statement Completion feature in the JavaScript file.

image

Fig 3: Adding reference to the C++ WinRT Component DLL.
Add the HTML markup that invokes JavaScript.

Add the following HTML into the <body> node of the default.html page

<body>
    <button id="callwinrt" onclick="CallWinRT()">Call WinRT</button>
<p></p>
    <label id ="Label1" style="background-color: grey;">Activation Object Result ->  </label><label id ="loaded" style="background-color: #51B65A;"></label>
    <p></p>
     <label id ="Label2" style="background-color: grey;">Calling Employee::SayHello() method     </label><label id ="callmethod" style="background-color: #51B65A;"></label>
    <p></p>
     <label id ="Label3" style="background-color: grey;" >Getting  Employee.Name Property value    </label><label id ="retrievedproperty" style="background-color: #51B65A;"></label>
    <p></p>

</body>

 

The default.html page appears as following.

Code Snippet
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>WinWebApp1</title>
    <!– WinJS references –>
    <link rel="stylesheet" href="/winjs/css/ui-dark.css" />
    <script src="/winjs/js/base.js"></script>
    <script src="/winjs/js/wwaapp.js"></script>
    <!– WinWebApp1 references –>
    <link rel="stylesheet" href="/css/default.css" />
    <script src="/js/default.js"></script>
</head>
<body>
    <button id="callwinrt" onclick="CallWinRT()">Call WinRT</button>
<p></p>
    <label id ="Label1" style="background-color: grey;">Activation Object Result ->  </label><label id ="loaded" style="background-color: #51B65A;"></label>
    <p></p>
     <label id ="Label2" style="background-color: grey;">Calling Employee::SayHello() method     </label><label id ="callmethod" style="background-color: #51B65A;"></label>
    <p></p>
     <label id ="Label3" style="background-color: grey;" >Getting  Employee.Name Property value    </label><label id ="retrievedproperty" style="background-color: #51B65A;"></label>
    <p></p>

</body>
</html>

 

Add the JavaScript event handlers that call into the component DLL

Add the following function CallWinRT() at the end of the default.js file. This function is called when you click the button “Call WinRT” on the main page. Notice how JavaScript activates the C++ class, and then calls its methods and populates the HTML labels with the return values.

function CallWinRT() {
    // activate the native Windows Runtime component
    var nativeObject = new CppWinRTComponentDll.Employee();
    document.getElementById(‘loaded’).innerHTML = nativeObject;

    //call a method
    var num = nativeObject.sayHello();
    document.getElementById(‘callmethod’).innerHTML = num;

    nativeObject.name = "Kishore Babu";

    // get the value of the string property
    var propValue = nativeObject.name;
    document.getElementById(‘retrievedproperty’).innerHTML = propValue;
}

 

The complete code of default.js file is as follows.

Code Snippet
(function () {
    ‘use strict’;
    // Uncomment the following line to enable first chance exceptions.
    // Debug.enableFirstChanceException(true);

    WinJS.Application.onmainwindowactivated = function (e) {
        if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
            // TODO: startup code here
        }
    }

    WinJS.Application.start();
})();

function CallWinRT() {
    // activate the native Windows Runtime component
    var nativeObject = new CppWinRTComponentDll.Employee();
    document.getElementById(‘loaded’).innerHTML = nativeObject;

    //call a method
    var num = nativeObject.sayHello();
    document.getElementById(‘callmethod’).innerHTML = num;

    nativeObject.name = "Kishore Babu";

    // get the value of the string property
    var propValue = nativeObject.name;
    document.getElementById(‘retrievedproperty’).innerHTML = propValue;
}

 

Build the solution & deploy the application. If you go to start window, you will find an application WinWebApp1. Click on it.

image

Click on call WinRT button. The values from the C++ DLL are returned and set in the JavaScript application as shown in the following figure.

image

When you build a solution that contains a JavaScript project and a Windows Runtime Component DLL project, the JavaScript project files and the compiled DLL are merged into one package, which you can then deploy locally or remotely for testing or submit to the Windows Store. You can also distribute just the component project as an Extension SDK.

Debugging: When you debug a JavaScript solution that has a component DLL, you can set the debugger to enable either stepping through script, or stepping through native code in the component, but not both at the same time. To change the setting, right-click the JavaScript project node in Solution Explorer, then select Properties > Debugging > Debugger Type.

Be sure to select appropriate capabilities in the package designer. For example, if you are attempting to open a file using the Windows Runtime APIs, be sure to select the Document Library Access checkbox in the Capabilities pane of the package designer.

Download the source code here.

As a C++ developer, I find this useful. If you are a C++ developer and new to JavaScript, you sometimes make the mistake of not using the camel-casing in JS. If your JavaScript code does not seem to be recognizing the public properties or methods in the component, make sure that in JavaScript you are using camel-casing. For example, the Platform::String^ SayHello() C++ method must be referenced as sayHello() in JavaScript.

"The task of the leader is to get his people from where they are to where they have not been." — Henry Kissinger

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.

image

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.

image

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.

image

Fig 3: Selecting WinRT CppWinRTComponentDLL.

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

image

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;

MainPage::MainPage()
{
    InitializeComponent();

      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();
}

MainPage::~MainPage()
{
}

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"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008&quot;
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
    mc:Ignorable="d"
    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"/>

    </Grid>
    
</UserControl>

 

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

interior_ptr:
/clr: Supported
/ZW: Not supported

pin_ptr:
/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^&

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

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

Generics:
/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*

friends:
/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

Finalizer:
/clr: Supported
/ZW: Not supported

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

T::typeid:
/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.

image

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:

image

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.

image

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.

image

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="1.0.0.0" />
  <Properties>
    <DisplayName>CSharpApplication</DisplayName>
    <PublisherDisplayName>Kishore</PublisherDisplayName>
    <Logo>Images\StoreLogo.png</Logo>
    <Description>CSharpApplication</Description>
  </Properties>
  <Prerequisites>
    <OSMinVersion>6.2</OSMinVersion>
    <OSMaxVersionTested>6.2</OSMaxVersionTested>
  </Prerequisites>
  <Resources>
    <Resource Language="en-us" />
  </Resources>
  <Applications>
    <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" />
      </VisualElements>
    </Application>
  </Applications>
  <Capabilities>
    <Capability Name="internetClient" />
  </Capabilities>
</Package>

 

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.

image

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.

image

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.

image

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