Tag Archives: Windows Runtime

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

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
    {
    public:
        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.

image

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).

image

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.

image

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.

image

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.

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

In order to better understand  the concepts of WinRT, C#.NET, C++, etc. in the new Windows 8 environment, let us write some code. Then we will explore what happens under the hood when we compile code and run the applications. This will be explained in many parts as we progress.

First let us understand what WinRT is and what makes a WinRT DLL or WinRT component. There is no better place to start other than creating a WinRT component ourselves and examining it. So lets get started.

Creating a WinRT Component DLL:

Step 1:

Open VS 2011 Developer preview. Click on New Project. In the New Project Dialog, from Installed section, select Visual C++ in the left hand side navigation tree. Select WinRT Component DLL from the project templates and name the component as CppWinRTComponentDll. Click OK as shown in Fig 1.image

Fig 1: Selecting Visual C++ template for WinRT Component DLL project.

Note: As a test, I tried to create a component with name C++WinRTComponentDll and VS 2011 C++ compiler shows many errors in the class files created by the wizard. So try to avoid ++ in the names.

Glimpse of new Visual Studio 2011 Developer preview edition:

In the new Solution Explorer, hover over the files and for each file you will find that there is an icon on the far right edge; View additional information (Ctrl+Right) icon.
When you select an item in Solution Explorer, whether it be a file or class or method, etc., the icon appears on the right edge of the selection. The tooltip says "View additional information (Ctrl+Right)". Clicking on the icon will invoke the "View Additional Information" menu which, for class files and members will provide relationships that you can view in Solution Explorer. Examples include "Base/Derived Types", "Find References", "Call Hierarchy", Calls, Is Called By, Is Used By etc. as shown in the following Fig 2.

image

Fig 2: Figure showing the View additional information (Ctrl+Right)icon.

Step 2:

Goto WinRTComponent.cpp file and delete the WinRTComponent definitions. Goto WinRTComponent.h and delete some of the default code. The code of the .h & .cpp files will look as shown in the following code snippets.

Code Snippet
// WinRTComponent.cpp

#include "pch.h"
#include "WinRTComponent.h"

using namespace CppWinRTComponentDll;

 

Code Snippet
#pragma once

using namespace Windows::Foundation;

namespace CppWinRTComponentDll
{

}
// WinRTComponent.h

 

We need the namespace CppWinRTComponentDll. Everything in WinRT has to be part of a namespace because the resolution of the DLL is based on a namespace that the class is in and that’s how other programming languages will find the class based on namespaces and DLL name.

Let us declare a sealed class called CalculatorSample in  WinRTComponent.h as shown in the following code snippet. The class is sealed as we don’t want others to derive from it. Sealed means no Inheritance.

Code Snippet
public ref class CalculatorSample sealed
{
public:
    int Add(int x, int y);
    int Sub(int x, int y);
    int Mul(int x, int y);

};

 

Why use Ref in front of the class:

Previously some of us worked on COM and created COM components. For that we have to create an interface, we have to specify that we are deriving from IUnknown (or derived) , put this in an MIDL file, use the MIDL Compiler to generate files, then go to C++ component, implement this interface, then create a class factory for it to create an instance and register this component. and the list goes on.. Well, all of this is done by using the keyword Ref in front of the class. So here we are creating WinRT Component that is accessible by dynamic languages as well. Here we are saying that CalculatorSample is a ref class, a class for WinRT. In other words, a ref class is a user-defined class that can be passed across the ABI boundary.

Step 3:

In the WinRTComponent.cpp, define the CalculatorSample  class member functions as shown in the following code snippet.

Code Snippet
int CalculatorSample::Add(int x, int y)
{
    return x+y;
}

int CalculatorSample::Sub(int x, int y)
{
    return x-y;
}

int CalculatorSample::Mul(int x, int y)
{
    return x*y;
}

 

So by now we have declared and defined the methods for the WinRT class called CalculatorSample. This class can be used by C++,C#.NET, VB.NET, JavaScript apps.

To sum it up, the WinRTComponent.h file should have the following code.

Code Snippet
#pragma once

using namespace Windows::Foundation;

namespace CppWinRTComponentDll
{

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

    };
}
// WinRTComponent.h

WinRTComponent.cpp file contains the following code.

Code Snippet
// WinRTComponent.cpp

#include "pch.h"
#include "WinRTComponent.h"

using namespace CppWinRTComponentDll;

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

int CalculatorSample::Sub(int x, int y)
{
    return x-y;
}

int CalculatorSample::Mul(int x, int y)
{
    return x*y;
}

Step 4:

Do not Compile the project. pch.h and pch.cpp are like stdafx.h and stdafx.cpp in VC++ MFC.

This completes the creation of a WinRT Component DLL.

Let us create a new application and try to access the WinRT Component DLL that we just created. For that, I will use C#.NET, so that we can know how to call a WinRT Component DLL from C#.NET application.

Right Click on the Solution CppWinRTComponentDll, Click on Add and select the New Project menu item as shown in Fig 3.

image

Fig 3: Adding  a New project to the CppWinRTComponentDll solution.

Select Visual C# –> Application template and name the project as CSharpApplication as shown in Fig 4.

 

image

Fig 4: Creating a Visual C# Application project in VS 2011 Developer Preview.

Step 5:

Add a reference to the WinRT C++ calculator class we created to the C#.NET application as shown in the following figures.

image

Fig 5: Right click on References folder and Select Add Reference…

image

Fig 6: Select Solution tab in the left hand side navigation panel and select Projects. You should be able to see the CppWinRTComponentDll that we just created. Select CppWinRTComponentDll and click on Add button. click Close and go to step 6 if you have not encountered any error.

If you have compiled the C++ DLL by mistake before adding the reference, you will get a Failed to add reference dialog as shown below.

image

Fig 7: Failed to add reference dialog.

To fix the Failed to add reference dialog issue, clean up the CppWinRTComponentDll project as shown in the following figure 8.

image

Fig 8: Right Click on CppWinRTComponentDll  project, select Project Only, then select Clean Only CppWinRTComponentDll

Now repeat step 5 again to add a reference to the CppWinRTComponentDll and you should see the green circle icon with tick inside it as shown in Fig 9. This means the component is successfully referenced in the project.

image

Fig 9: Component successfully referenced in the project.

Click close.

Step 6:

Open MainPage.xaml file and add three text boxes to show the result of addition, subtraction and multiplication values returned from the C++ WinRT Component DLL.

Add the following XAML code.

Code Snippet
       <TextBox x:Name="txtAdd" HorizontalAlignment="Left" Text="TextBox" VerticalAlignment="Top" Margin="582,97,0,0" Height="36" Width="246" FontSize="20"/>
        <TextBox HorizontalAlignment="Left" Text="Calling Add method of C++ WinRT Component DLL" VerticalAlignment="Top" Margin="114,97,0,0"/>
       
        <TextBox x:Name="txtSub" HorizontalAlignment="Left" Text="TextBox" VerticalAlignment="Top" Margin="582,180,0,0" Height="36" Width="246" FontSize="20"/>
        <TextBox HorizontalAlignment="Left" Text="Calling Sub method of C++ WinRT Component DLL" VerticalAlignment="Top" Margin="114,180,0,0"/>
        
        <TextBox x:Name="txtMul" HorizontalAlignment="Left" Text="TextBox" VerticalAlignment="Top" Margin="582,260,0,0" Height="36" Width="246" FontSize="20">
        </TextBox>
        <TextBox HorizontalAlignment="Left" Text="Calling Mul method of C++ WinRT Component DLL" VerticalAlignment="Top" Margin="114,260,0,0"/>

 

Step 7:

Open MainPage.xaml.cs file and add the following code.

To use the C++ WinRT Component DLL that we just created we need to specify it in the C#.NET project by mentioning using CppWinRTComponentDll;

In the MainPage(), add the following code.

Code Snippet
CalculatorSample calcobj = new CalculatorSample();
            txtAdd.Text = calcobj.Add(10,20).ToString();
            txtMul.Text = calcobj.Mul(10, 20).ToString();
            txtSub.Text = calcobj.Sub(20, 10).ToString();

 

The complete MainPage.xaml file XAML code is

Code Snippet
<UserControl x:Class="CSharpApplication.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="txtAdd" HorizontalAlignment="Left" Text="TextBox" VerticalAlignment="Top" Margin="582,97,0,0" Height="36" Width="246" FontSize="20"/>
        <TextBox HorizontalAlignment="Left" Text="Calling Add method of C++ WinRT Component DLL" VerticalAlignment="Top" Margin="114,97,0,0"/>
       
        <TextBox x:Name="txtSub" HorizontalAlignment="Left" Text="TextBox" VerticalAlignment="Top" Margin="582,180,0,0" Height="36" Width="246" FontSize="20"/>
        <TextBox HorizontalAlignment="Left" Text="Calling Sub method of C++ WinRT Component DLL" VerticalAlignment="Top" Margin="114,180,0,0"/>
        
        <TextBox x:Name="txtMul" HorizontalAlignment="Left" Text="TextBox" VerticalAlignment="Top" Margin="582,260,0,0" Height="36" Width="246" FontSize="20">
        </TextBox>
        <TextBox HorizontalAlignment="Left" Text="Calling Mul method of C++ WinRT Component DLL" VerticalAlignment="Top" Margin="114,260,0,0"/>

    </Grid>
    
</UserControl>

 

The complete MainPage.xaml.cs file C#.NET code is

Code Snippet
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using CppWinRTComponentDll;

namespace CSharpApplication
{
    partial class MainPage
    {
        public MainPage()
        {
            InitializeComponent();

            CalculatorSample calcobj = new CalculatorSample();
            txtAdd.Text = calcobj.Add(10,20).ToString();
            txtMul.Text = calcobj.Mul(10, 20).ToString();
            txtSub.Text = calcobj.Sub(20, 10).ToString();
            

        }
    }
}

 

Step 8: Build the solution.

The following information will be displayed in the output window. See the highlighted information. The Visual Studio 2011 is compiling the projects as well as deploying the projects. Later, we will see in detail what happens during deployment and how the applications is run by Windows 8.

1>—— Build started: Project: CSharpApplication, Configuration: Debug Any CPU ——
1>  CSharpApplication -> C:\Users\Prathima\Documents\Visual Studio 11\Projects\CppWinRTComponentDll With CSharp App\CSharpApplication\bin\Debug\csharpapplication.exe
1>  CSharpApplication -> C:\Users\Prathima\Documents\Visual Studio 11\Projects\CppWinRTComponentDll With CSharp App\CSharpApplication\bin\Debug\CSharpApplication.build.appxrecipe
2>—— Deploy started: Project: CSharpApplication, Configuration: Debug Any CPU ——
========== Build: 1 succeeded, 0 failed, 1 up-to-date, 0 skipped ==========
========== Deploy: 1 succeeded, 0 failed, 0 skipped ==========

 

The output of the programs is the application

image

Download the source code from here.

"The future belongs to those who see possibilities before they become obvious."  - John Scully

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

Part 3: Introduction to WinRT, the new ‘Windows Runtime’ in Windows 8

To install visual studio 2011 developer preview + Window 8 beta, refer to post here.

To get started working with Windows 8 operating system, see post here.

Fig 1: Windows 8 Platform and Tools slide shared at Build conference.

Windows Runtime, or shortly WinRT, is Microsoft’s new programming model that makes the backbone of the new Metro-style apps (also known as Immersive) in the new Windows 8 operating system. WinRT solves many of the problems of Win32, from an apps perspective. Apps created for WinRT are safe, secure, and sandboxed, can’t wreck other apps and all install in just 2-3 seconds. They feature isolated storage, single folder installs (as per the Mac), and require user consent to access the general file system. This is part of it, a modern, truly different app platform that is far more different, and far more capable, than many people understand right now.

WinRT isn’t another abstraction layer; it’s a new runtime sitting directly on top of the Windows Kernel Services just like the good old Win32 API as shown in the above figure that allows developers to write Metro style applications for Windows 8, using a variety of languages including C++ (with WRL or  with Component Extensions – C++/CX), the managed languages C# and VB.NET, as well as JavaScript. In the above figure, right on top of NT kernel (like Win32) is WinRT. This WinRT has an application model and three boxes of capabilities that are expressed by APIs (Communications & Data, Graphics & Media, and Devices & Printing). "Above" WinRT is the two sets of presentation layer/programming language couples: XAML and various high level programming languages (C#, VB, and so on) and HTML/CSS and JavaScript, respectively. (DirectX is left out, but sits on top of WinRT too.) WinRT is an unmanaged native layer and its API is object oriented that can be consumed both from native or managed languages, as well as JavaScript. In short, WinRT is the Object Oriented Programming replacement for Win32.

This marks the first major break in the core of Windows since Win32 was introduced in 1993 with Windows NT. WinRT represents a new application execution environment with semantics that are very different than Win32. Unlike Win32, which was designed with C in mind, the WinRT APIs are written in C++ and designed from the beginning to be object oriented. Consistency, ease of use, and performance are key aspects of the new runtime API. Every object in the WinRT API supports reflection so that even dynamic languages such as JavaScript can use them efficiently. Along with this comes a unified object model, a rarity for C++ based libraries. The new Windows SDK for Metro style apps also includes a subset of traditional Win32, Component Object Model (COM), and .NET Framework APIs, as well as HTML5 and CSS3 APIs that are accessible to Metro style app developers. I.e. Metro style apps can use a subset of the Win32 and COM API. This subset of APIs was chosen to support key scenarios for Metro style apps that were not already covered by the Windows Runtime, HTML/CSS, or other supported languages or standards. The Windows App Certification Kit ensures that your app uses only this subset of the Win32 and COM API. The subset of the Win32 and COM API that can be used in a Metro style app is indicated in the header files in the Windows Software Development Kit (SDK) for Metro style Apps. Look for the following statements in the header files:

#pragma region Application Family

#pragma region Desktop Family

The compiler and object browser in Microsoft Visual Studio 11 Express for Windows Developer Preview use these statements to determine whether to show or hide a Win32 or COM API element.

One other big change is that all WinRT components have metadata available for them, just like .NET assemblies. Well, the Windows Runtime is exposed using API metadata stored in .winmd files as shown in the following figure 2. In COM you were able to achieve that with type libraries(Type libraries contain metadata that represent COM types), but not every COM component had them.  The metadata (API definitions) of WinRT contained in .winmd files are encoded in ECMA 335 metadata format, the same format that .NET uses but with a few modifications. The underlying binary contract makes it easy for you to access the Windows Runtime APIs directly in the development language of your choice. The shape and structure of the Windows Runtime 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++. This common metadata format allows for significantly less overhead when invoking WinRT from .NET applications compared to a P/Invoke, and much simpler syntax. Regular C++ (with COM-specific discipline) can also be used to program with WinRT components, with the help of new template library called Windows Runtime C++ Template Library (WRL), which is similar in purpose to what Active Template Library provides for COM. The MSDN documentation, however, recommends using C++/CX instead of WRL.

Fig showing the “C:\Program Files (x86)\Windows Kits\8.0\Windows Metadata\” folder in Windows 8 Developer Preview. You can observe that they are actually CLI assemblies with no code, just metadata tables. image

Fig 2: Windows RunTime Metadata files

As shown in the following Fig 3, you can open the .winmd file with ILDASM. Note, this doesn’t mean that WinRT itself is managed – it simply reuses the file format.image

Fig 3: Opening an C:\Program Files (x86)\Windows Kits\8.0\Windows Metadata\Windows.Applicationmodel.Activation.winmd file using ILDASM

For the structure of the Windows Runtime, see the Microsoft site.

There are a number of libraries implemented in terms of the new object model, i.e. defining WinRT interfaces and classes. 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; also for Windows.UI.Xaml.Documents etc.

The WinRT type system relies strongly on WinRT components, which are COM objects implementing a specific set of interfaces and adhering to a certain ABI (Application Binary Interface). WinRT is essentially a COM-based API, relying on an enhanced COM that implements the IInspectable interface. The IInspectable interface enables projecting Win32 and COM features into JavaScript and other languages, such as C# and Visual Basic. Implement the IInspectable interface when you want your class to be available in other programming environments. The IInspectable interface is the base interface for all Windows Runtime classes. All Windows Runtime classes must implement the IInspectable interface. The IInspectable interface inherits from the IUnknown interface. so every WinRT object implements IUnknown and does refcounting (WinRT objects are reference counted like COM for memory management, with weak references to avoid circularity), 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 parameterized (“generic”) interfaces. 

In short, Windows Runtime is a new set of libraries exposing Windows functionality and available to JavaScript/C#/VB/C++ as shown in figure 4. Each language has been made to understand and be able to call them directly rather than having to go through some thunking layer. Silverlight and WPF are flavors of XAML that run on the CLR. Among other functionality, Windows Runtime exposes a version of XAML very similar to Silverlight, but does so in a native way, not via the CLR. It can be accessed from the CLR, but also from C++.

Fig 4 : Microsoft Windows 8 Platform and Development Tools

Relation between .NET & WinRT

The important concept to understand is that the .NET framework now has two profiles.

  1. .NET Metro profile (CLR that deal with Metro application)
  2. .NET Client profile (CLR runtime for C#,VB.NET applications)

The .NET APIs for Metro style apps provide a set of managed types that you can use to create Metro style apps for Windows using C# or Visual Basic. The .NET APIs for Metro style apps include a subset of types from the .NET Framework and enable .NET developers to create Metro style apps within a familiar programming framework. You use these types with types from the Windows Runtime API to create Metro style apps.

In some cases, a type that you used in a .NET Framework application does not exist within the .NET APIs for Metro style apps; instead, you must use a type from the Windows Runtime. For example, the System.IO.IsolatedStorage.IsolatedStorageSettings class is not included in the .NET APIs for Metro style apps; instead, you use the Windows.Storage.ApplicationDataContainer class for app settings. You retrieve an instance of the ApplicationDataContainer class through the Windows.Storage.ApplicationData.Current.LocalSettings property.

  • The .NET Framework 4.5 is used in both Desktop Mode apps and in Metro style apps. There is a difference though. Metro style apps use what is best described as a different .NET Profile (e.g. Desktop apps use the .NET Client Profile and Metro style apps use the .NET Metro Profile). There is NOT actually a different profile, but the implementation of .NET in Metro style apps is LIKE a different profile. Don’t go looking for this profile – its basically rules built into the .NET Framework and CLR that define what parts of the framework are available.
  • There is only one CLR. Each application or application pool (depending on the app type) spins up a process and the CLR is used within that process. Meaning, a Metro style app and a Desktop Mode app running at the same time are using the same CLR bits, but separate instances of the CLR.
  • Whether a Desktop Mode app or a Metro style app, if it is a .NET app, it is compiled to the same MSIL. There isn’t a special Windows 8 Metro IL – there is, like the CLR, only one MSIL.

In the above diagram (Fig 4) you can see that the CLR and the .NET Framework 4.5 are used for C# and Visual Basic apps in either Desktop Mode apps (blue side) or Metro style apps (green side). Silverlight is still only available in Desktop Mode as a plug-in to Internet Explorer (yes, out of browser is still supported in Desktop Mode). Another addition in this diagram is DirectX, which was strangely absent from the original diagram. DirectX is the defacto technology for high-polygon count applications, such as immersive games. DirectX leverages the power of C++.

This biggest confusion, has been around the use of the .NET Framework across the blue side and green side. The reason for the .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.

Additionally, some of the changes in the Metro Profile are to ensure Metro style apps are constructed in the preferred way for touch-first design and portable form factors. An example is File.Create(). Historically if you were using .NET to create a new file you would use File.Create(string fileLocation) to create the new file on the disk, then access a stream reader to create the contents of the file as a string. This is a synchronous operation – you make the call and the process stalls while you wait for the return. The idea of modern, Metro style apps is that asynchronous programming practices should be used to cut down on things like IO latency, such as that created by file system operations. What this means is that the .NET Metro Profile doesn’t provide access to File.Create() as a synchronous operation.

Ultimately all of this means that you have some choice, but you don’t have to sacrifice much if anything along the way. You can still build .NET and Silverlight apps the way you are used to, and they will run on Windows for years to come. If you want to build a new Metro style app, you have four options to choose from:

  1. XAML and .NET (C# or VB): You don’t have to giving up too much in the .NET Framework (remember, you only give up what is forbidden by the Application Container), and you get access to WinRT APIs for sensor input and other system resources.
  2. XAML and C++: You can use your skills in XAML and C++ in order to leverage (or even extend) WinRT. Of course you don’t get the benefit of the .NET Framework. You can use WRL or  with Component Extensions – C++/CX
  3. HTML and JavaScript: You can leverage the skills you have in UI layout, and make calls from JavaScript to WinRT for access to system resources, and sensor input.
  4. DirectX and C++: If you’re building an immersive game you can use DirectX and access the device sensors and system resources through C++ and WinRT.

image

Fig 5 : Deciphering the new WinRT – Metro style application API’s.

.NET with WinRT:

C#/VB: The end of P/Invoke : Calling native functions from .NET usually involves building up structures and manipulating pointers. Under WinRT all APIs are exposed as objects that C# and VB can consume directly. This puts .NET developers on level footing with C++ developers.

Application responsiveness is very important to Microsoft. In order to convey that to developers all OS-level API calls that take longer than 50 milliseconds will be exposed as an asynchronous operation.

image

Fig showing the overview of CLR components.

A managed Metro application (e.g. written in C#) will still load the CLR.  The CLR version bundled with the preview is 4.0.30319.17020, and that’s the version that gets loaded inside a Metro app.  Symmetrically, a “fully” .NET application (e.g. a WinForms app) can reference the WinRT metadata assemblies and use WinRT APIs. This will be a necessity in some cases, for example to tap into the WinRT sensor APIs.

.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 read a .winmd file, and all types and their members in its metadata become visible to you as if they were .NET objects. Note that native C++ programs that use WinRT do not require CLR at all (WinRT libraries themselves are fully native) – 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 and IVector become IEnumerable and IList; and so on. This goes both ways – if you have a .NET object that implements IEnumerable, and pass it back to WinRT, it’ll see it as IIterable.

Some developers are confused as to whether .NET is there or not in the first place, as not all of the .NET APIs are present (File I/O, Sockets), many were moved and others were introduced to integrate with WinRT. When you use C# and VB, you are using the full .NET framework. But they have chosen to expose a smaller subset of the API to developers to push the new vision for Windows 8. And this new vision includes safety/sandboxed systems and asynchronous programming. This is why you do not get direct file system access or socket access and why synchronous APIs that you were used to consuming are not exposed. What they did was that they only exposed to the compiler a set of APIs when you target the Metro profile. So your application will not accidentally call File.Create for example. At runtime though, the CLR will load the full class library, the very one that contains File.Create, so internally, the CLR could call something like File.Create, it is just you that will have no access to it. So for managed applications, the Metro projects in Visual Studio are targeting a special subset of the .NET framework, and will not have access to all the classes – not even all the classes of the .NET Client Profile. For example, the System.IO.FileStream class is not available.

Although these limitations may seem artificial, annoying, and counterproductive, there is probably a good reason for having them. The Metro UI and Metro apps are a fresh start for Windows applications and their developers. There is no trivial way to port an existing UI app to Metro without a considerable UI redesign. It’s also a great opportunity to enforce additional limitations that make sure Metro apps respect the user’s privacy, conserve battery power, integrate well with the UI guidelines, and live in harmony within the application sandbox.

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.

C++11 with WinRT: C++ Development

A good news for C++ developers is that User interfaces in C++ will be written primarily in XAML for immersive applications. However, this is not available for classical, Win32 applications. This libraries for working with XAML have all been ported to C++ and are compiled to native x86. Metro applications written with XAML and C++ do not run on top of .NET, they get compiled directly to x86 just like any other Visual C++ application. Calling methods on UI controls is just like calling methods on any other object in C++.

Microsoft has created a new language called C++ Component Extension, or simply C++/CX. While the syntax is very similar to C++/CLI, the language is not managed, it’s still native. WinRT components built in C++/CX do not compile to managed code, but to 100% native code.

App Container and Application Permissions : Metro applications run in what’s known as the “app container”. This appears to replace the windowing environment used by Win32 based applications.

Most API calls are sent directly to the underlying kernel. Some, however, some will be routed through the system broker. The system broker ensures that applications can only access features that the user has approved. For example, the first time an application tries to access the camera the service broker will prompt the user for their approval. Applications are required to include a manifest that indicates all of the restricted services the application may need. This model will be very familiar to mobile device developers.

All Metro applications run within WinRT’s app container and thus are monitored by the system broker, even those written in C++. The idea is to limit the ability of applications to damage the system. While probably not impossible, building malware with WinRT will be much harder than it is in Win32.

Overlapping Windows No Longer Exist : In Metro, there are no overlapping top-level windows. There’s still Popup (http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.primitives.popup). Dialog boxes, a core concept from previous versions of Windows, does not exist in WinRT. The performance cost and usability concerns are simply no longer justifiable to Microsoft. Applications that wish to use this pattern will have to develop other ways to express things such as message boxes. Another library that didn’t make it into WinRT is GDI. If an application is going to use the Metro interface it needs to do so from top to bottom, it appears that mixing Metro and classic user interfaces is not possible.

PlayTo Contract : Another contract that is being exposed is PlayTo. This allows applications to send media files such as audio and video to a charm. The charm will then allow the user to choose which application they want to use to view the file. Presumably these aren’t just physical files, but rather any form of media that can be expressed as a data stream.

All Metro Applications Must be Digitally Signed: Anonymous applications are not allowed. Applications can be self-signed for testing, but by the time they appear in the app store they will need to be signed using a real certificate.

JavaScript :

Another major language for Windows 8 is JavaScript. While it doesn’t use XAML, it does have direct access to the underlying WinRT API just like native and .NET applications. This isn’t just a container like PhoneGap, JavaScript developers get the same rich API that other developers use. Since this is JavaScript the UI toolkit of choice is HTML and CSS rather than XAML. The same rendering engine used by Internet Explorer 10 us used by Metro JavaScript applications, though they don’t actually run in a browser. A JavaScript application looks just like any other Metro application. Expression Blend 5 now supports editing HTML5, much like you use it for editing XAML.

User controls in JavaScript are nearly on par with those in C++ and .NET. Some controls are intrinsic to the HTML rendering engine, others are written in JavaScript. These JavaScript based ones are div based much like controls built using jQuery.

The IInspectable interface contains three methods: GetIids, which returns the interfaces implemented by the component; GetRuntimeClassName, which returns the fully-qualified name of the component; and GetTrustLevel, which returns the component’s trust level that can be used to control component activation.

IInspectable is used by the dynamic language bindings from JavaScript. Given a reference to a WinRT component, the JavaScript interpreter can call the IInspectable::GetRuntimeClassName method and obtain the fully-qualified class name of the WinRT component. Using the namespace name the interpreter can ask Windows to load the metadata file (.winmd) describing the component, and from the metadata determine how to use the interfaces implemented by the component.

WinRT Projections

What we call "bindings" Microsoft now calls "projections". Projections are the process of exposing APIs to three environments: Native (C and C++), HTML/JavaScript and .NET.  If you author a component in C++ or a .NET language, its API will be stored in a WinMD file and you will be able to consume it from all three environments (Native, JavaScript and .NET). Even in C++ you are not exposed to COM. The use of COM is hidden behind the C++ projection tools. You use what looks and feels like a C++ object oriented API. To support the various constructs of WinRT, the underlying platform defines a basic set of types and their mappings to various environment. In particular, collection objects in WinRT are mapped to constructs that are native to each environment.

Conclusion:

WinRT solves many of the problems of Win32, from an apps perspective. Apps created for WinRT are safe, secure, and sandboxed, can’t wreck other apps, can’t cause "Windows rot," and all install in just 2-3 seconds. They feature isolated storage, single folder installs (as per the Mac), and require user consent to access the general file system.

To summarize, WinRT does not replace .NET, nor does it compete with .NET – and the same applies to Win32. You can write server and client applications using .NET, including WPF and Silverlight. You can write server and client applications using C++, including Win32 and MFC. However, if you choose to believe in the Metro way, you can write Metro applications for Windows 8 using .NET languages or using C++ or using JavaScript, with a consistent set of APIs exposed through WinRT. At the same time the Win32 applications will continue to run just as before and you can still (and most certainly will) develop Win32 applications.

Finally, I am very impressed with the details of Windows 8! It’s fantastic. There are three ways to write WinRT applications. One is C++, in which case you write directly to the “projection” of WinRT into your language. The second is .NET, in which case your code goes via the CLR. The third is HTML and JavaScript, in which case your code goes via the “Chakra” JavaScript engine also used by Internet Explorer 9 and higher. There is no message loop in WinRT. There is no GDI in WinRT. All graphics are via DirectX. XNA, the .NET games framework, is not supported. The WinMD (Windows Metadata – which makes the whole Windows Metro API available to any language – hence the ability to use JavaScript, for example) is great. The new object-oriented API, with namespaces and interfaces etc., is great. The language projections are great. Oh and the native support in Microsoft C++!! for the Windows Runtime, and the fact that C++ is ideal for it (since it is, at the core, an extension of COM), is great. So much to learn!!

A great leader’s courage to fulfill his vision comes from passion, not position. - Paul John Maxwell

Part 2: Getting started with using new Windows 8 features

First Look at What’s New in Windows 8

Microsoft’s "re-imagining" of Windows 8 is focused very heavily on a new, Metro-style touch-based interface. And no matter what device you’re on, you can switch between the simple Metro interface and the traditional Windows desktop to fit whatever your needs are at that given moment. Instead of loading the traditional Windows desktop at startup, you’ll see the new, Windows Phone-like Metro UI. This is by far the biggest change in Windows 8, and can be the most confusing to use at first—especially for desktop users. Here’s how to get around the Metro UI.

The Lock Screen:

photo

The first thing you’ll see when you start up is the lock screen—a simple screen that shows the time, date, Wi-Fi connectivity, battery power (where applicable), and more. Just tap and drag it up to unlock it on a touch device. Desktop users can click and drag up, but that isn’t exactly "natural"—you can also double-click the mouse or tap any key on your keyboard to unlock it. From there, you’ll be taken to the login screen as shown below, where you can type in your password to gain access to your system.

photo (1)

By default, it’ll use your regular old Windows password, though you can change this to use a PIN number or a gesture-based password from the Control Panel. Note that when you first install Windows 8, you can opt to use your Windows Live ID and password to log in instead of a regular local username—this allows you to sync your preferences between Windows 8 machines, which is really nice. Windows 8 shows off some pretty neat touch-based features, particularly a "picture password" feature shown above. Instead of using a PIN or a lock pattern to get into your system, you swipe invisible gestures using a picture to orient yourself. In the above picture, I need to click on X in xaml, H in HTML and then C in css to login to my Windows 8 machine. That’s how I have setup the Windows 8 password.

The Home Screen (Start menu):

Next you’ll see the home screen (also known as the new Start menu), complete with tiles that take you to Internet Explorer, your news feeds, games and the new Microsoft App Store. If you’re on a touch device, you can swipe to the right or the left to move through the main menu; if you’re on a desktop machine, you can scroll up and down with the scroll wheel. If you prefer, you can also drag the auto-hiding scrollbar at the bottom of the screen, or use the Page Up and Page Down keys on your keyboard. Tablet users can pinch out to see a zoomed-out view of all the tiles on their home screen.

The home screen is very familiar to anyone who’s used Windows Phone 7. You’ve got a set of tiles, each of which represents an application, and many of which show information and notifications that correspond to the app. For example, your email tile will tell you how many unread emails you have (and who they’re from), your calendar tile will show upcoming events, your music tile will show you what’s playing, and so on. You can also create tiles for games, contacts, and even traditional Windows apps that will pull you into the Windows desktop. The tablet-optimized apps are all full screen and "immersive", though, and you can rearrange their icons on the home screen easily.

image

Any time you install a new app, whether its a Metro app or a desktop app, it’ll show up at the end of this Start menu. You can move apps by tapping, holding, and dragging them somewhere else on the screen. You can also right-click on an app’s tile to resize it, uninstall it, or unpin it from the Start menu as shown in the above Fig. Touch users should get this menu just by tapping and holding on a tile. Some apps will have other options, like running it as an administrator. Your user tile in the upper right-hand corner will let you lock and log off your machine, as well as customize your user profile (which we’ll talk about in a minute).

Running Apps:

image

To launch an app, just tap or click on it. I.e. you tap on the application home screen icon (tile) or click on it and it goes full screen. When you want to leave an app, just hit the Windows button—think of it as the "Home" button on an iPhone or Android device. Once you’ve left an app, it’ll be suspended, meaning it won’t be sucking up any CPU cycles or making your machine slower. Think of the Metro UI as you’d think of an iPhone, Android, or Windows Phone device and less like you would a desktop machine. The browser has lots of touch-based controls, like pinch to zoom and copy and paste, and apps can also share information one another easily. To do so, you just need to select text in the browser or choose a photo in their cloud-based photo app and hit the "Share" button—you’ll then be able to pick an app to which you want to send that text or picture, and work with it from there. For example, you can share photos to Facebook, send text from a web page in an email, and so on.

Within any app, you can right-click to bring up the "app bar", which is basically that app’s menu. For example, right-clicking in the Feeds app will let you add feeds, refresh, or remove all your feeds. In Internet Explorer, it brings up the navigation and tab bar. The above Fig shows the app bar for the build application.

You can quickly switch between apps by dragging your mouse to the left side of the screen. You’ll see a thumbnail of your most recently used app, and if you click, it’ll open it up. If you want to see other recently used apps, you can scroll up with your mouse’s scroll wheel to see thumbnails of other recent apps. You can also use Win+Tab and Alt+Tab to switch between open apps. None of this is brand new to touch-based platforms, but what is new is the ability to not only multitask, but run these apps side by side. Say you want to watch a video and keep an eye on your news feed at the same time. Just like in Windows 7 for the desktop, you can dock an app to one side of the screen while docking another app at the opposite side, which is a seriously cool feature. Imagine being able to IM and play a game at the same time, or browse the web while writing an email. It’s a fantastic way to fix one of the big shortcomings of mobile OSes, thus allowing you to ignore the full desktop interface more often and stay in the touch-friendly, tablet view.

The App Store:

image

The Windows App Store looks much like the home screen, with tiles that correspond to different categories and featured apps. From there, you can look at a more detailed list of the available apps in a given section. And, the store contains not only touch-based apps for the tablet interface, but some of the more traditional desktop Windows apps you’re used to, so you have one portal to discover all your Windows apps no matter what interface you’re using. I took the above picture from the build conference. As of today, there are no apps in the store as it is in beta. Am sure there will be millions of apps in the coming days.

Windows Live Cloud Syncing:

Windows Live is taking center stage as the backend for all of Windows 8′s cloud syncing abilities. Your address book, photos, SkyDrive data, and even data within third-party apps can sync up to the cloud with Windows Live. The address book also syncs with other services like Facebook and Twitter as well. You can even sync all of your settings from one Windows 8 PC to another. Just sign onto your Windows 8 with a Windows Live ID and you’ll get all your themes, languages, app settings, taskbar, and other preferences will show right up. It’s a pretty neat feature if you have multiple Windows 8 PCs and don’t want to set them all up separately—just a few taps and you’ve got all your preferences ready to go.

A New Task Manager:

Microsoft’s finally redesigned the task manager, and it looks pretty great. You have a very simple task manager for basic task killing, but if you’re a more advanced user, you can bring up the detailed task manager filled with information on CPU and RAM usage, Metro app history, and even startup tweaking—so you can get rid of apps that launch on startup without going all the way into msconfig.exe.  This makes it easier to monitor running apps, resource usage, and startup apps and quit them when necessary.

A New Default, Minimalist Interface:image

When you first start up Task Manager, you’ll see its much simpler than the Task Manager of yore. Instead of a bunch of tabs that, frankly, can be a little cryptic and confusing, you’ll see a simple window with a list of running apps on it. You can click on one and hit the "End Task" button to end it if it’s misbehaving. Metro apps will say "suspended" next to them if you’ve launched them, but aren’t actively using them. That’s because Metro apps don’t run in the background when you exit them—thus, there’s no need to "kill" Metro apps when you want to quit them, unless they’re having trouble. They won’t eat up CPU cycles when they aren’t directly in use.

However, this simple window is hardly enough for the power users out there. By hitting the "More Details" button, you can open up the Advanced Task Manager shown below, complete with many more options and a lot more data about how your apps are using your system’s resources.

The Advanced Task Manager:image

The Processes tab groups things by category, like "applications" and "background processes" to help differentiate between them. It also gives you information about more than just the CPU and RAM they use; instead you’ll also see whether they’re actively using your hard disk and network connection and at what speed. There’s even a restart button in the corner (right click on Windows Explorer row) if, say, you wanted to restart the Explorer process without the tedious task of manually killing it and then starting it back up.

image

The Performance tab has been completely redone, with large line graphs detailing your CPU, RAM, disk, and network usage over time. Click on one in the sidebar and you’ll get more details about each, through large, almost Metro-style oversized text, which is nice. For example, clicking on CPU will tell you the speed at which your CPU is running, how much of it is being used, and how many processes are using. it. The RAM pane will tell you how much RAM you have free, how much is active, and so on.

image

The App History tab is new. This shows how often you use each app on your system, as well as how much CPU and network they use over time. I can see this being more useful for tablets and laptops, since it helps you keep an eye on your battery life (by eying the CPU and network usage) and your data caps, if you have any (by eying the network usage).

The Startup tab is similar to Startup tab we’re all familiar with from msconfig. Here, you can change which applications start up with Windows. If you have a few processes that are slowing down your boot process (or slowing down your computer by being "always on"), you can just disable them from this list and they won’t start up as soon as you log in. It’s a good deal easier to use than the old Startup manager in msconfig, though, showing you icons, actual program names, the program’s publisher, and even how much of an impact it can have on your startup time.

The Users, Details, and Services are pretty much the same tabs you know from the old Task Manager—they haven’t been revamped much at all, but are still there if you need access to them.

Windows Explorer:image

Tablet users won’t be the only ones impressed by Windows 8—some big changes have come to the desktop too, especially the newest version of Windows Explorer. Here are some of the biggest changes in Windows’ default file manager. Office users will find Windows Explorer’s new interface very familiar, as it sports an Office-style ribbon across the top. Now, you have access to large buttons for any action you could want to perform, instead of having to root around a tiny context menu. By default, you have three tabs across the top: Home, Share, and View. The Home tab contains functions like Copy, Paste, Move to, Delete, Rename, New Folder, Properties, and more. Clicking on the Share tab will let you email a file or folder, put it into a zip file, or even burn it to disc. The View tab manages what Explorer looks like—this is where you can turn on the preview pane, choose your icon view, and set how Windows sorts your icons in the Explorer window.

What’s really cool is that many popular file types will add more tabs into Windows Explorer’s ribbon, with functions tied to that specific file type, For example, if you click on an image file, you’ll get a "Manage" tab under a "Picture Tools" heading that lets you rotate images right form Explorer, start a slideshow, or set that image as your desktop background. Clicking on a disk under My Computer will bring up a Disk Tools tab that lets you eject, format, or clean up a disk. Clicking on an EXE file will even let you pin it to the taskbar, run it as an administrator, or troubleshoot its compatibility, all with just one click.

Of course, if you aren’t a fan of the ribbon, you can easily hide it by hitting the little arrow in Explorer’s upper right-hand corner. You’ll still have access to those tabs if you want them, but it won’t stay visible all the time. This is especially nice if you’re, say, on a netbook and Explorer’s taking up a bit too much space.

image

The new File menu is pretty snazzy. None of the functions inside are all that new, but it does have a really nice "Open Command Prompt" option that’ll open up a Windows Command Prompt in your current folder—either as the current user or as an administrator.

Instead of using third party Virtual Clone Drive, We’ll have a native ISO mounting in Windows Explorer.

The Quick Access Toolbar:image

The quick access toolbar is a small set of buttons in the title bar of Windows Explorer, containing a few of the functions inside the ribbon. There, you can put some of your most-used functions for super-quick access. You can customize the toolbar with the small arrow button at the end of it, which will let you put any combination of the Undo, Redo, Delete, New Folder, Properties, and Rename buttons on the top left of the toolbar. If you know the keyboard shortcuts for these actions, you probably won’t use the quick access toolbar, but it’s nice to have there if you aren’t a keyboard junkie.

The Search Menu:

image

To search for apps, settings, or files from the Metro UI, just start typing on your keyboard. By default, this will search for apps, though if you want to search for files, you can hit Ctrl+F from the home screen instead. Once the search bar pops up on the right, you can choose what you want to search: apps, settings, files, or within one of your apps (like the App Store, Twitter, or just the internet). Clicking on Apps will also give you an alphabetical listing of your apps, which is a nice touch. From the search screen, you can once again right-click on an app to pin it to the start menu, or open up an advanced menu that will let you run it as an administrator, among other things.

The Share Menu

image

From any given app, you can share text, images, and other content through Windows 8′s universal Share menu. To bring it up, tap the right side of the screen and swipe to the left. If you’re using a mouse, either hit Win+C or mouse to the bottom-right side of the screen. Hit Share, and you’ll see a bar pop up on the right side, showing the apps you can send that information too—like Twitter, Email, and so on. Another bar will pop up on the right side from which you can tweet, email, or otherwise share that info without ever leaving the app you’re in.

The Control Panel:

image

Control Panel is where you can tweak all sorts of settings related to the Metro Interface. Hit the Control Panel button (home tile) on the home screen. Most of the stuff in here is self-explanatory, but here are the general categories you have to choose from and what’s inside:

  • Personalize: From here you can change the picture on your lock screen, add small notification tiles to your lock screen, and change your user picture.
  • Users: If you want to add a new account, or change your password (including adding a PIN or gesture-based "picture password"), this is where you’ll do it.
  • Wireless: If your device has wireless capabilities, you can turn them on and off here, as well as enable Airplane Mode with the flip of a switch.
  • Notifications: If you want to turn notifications on or off for different apps (or turn notifications off entirely), you can head to this pane. It lists all your notification-compatible apps with an on/off switch for each. You can also mute notification sounds from here.
  • Privacy: Here is where you tell Windows whether you want apps to be able to access your location, name and account picture, or other information about what you’re using. You can also edit the number of apps in your "App History", which are those thumbnails on the left side of the screen we talked about earlier.
  • General: On the General pane, you can change your time zone, touch keyboard preferences, and refresh or reset your PC, which either give it a one-click clean install of Windows (without losing your files) or wiping your PC entirely and starting from scratch.
  • Search: You can clear your search history and remove apps from the search menu here.
  • Share: This pane helps you make the Share bar easier to use, by adding and removing apps, as well as tweaking your "share history" which give you quick access to oft-used Share-enabled apps.
  • Send: This is where you can adjust the apps you use to send stuff to other devices, like attached TVs.
  • Ease of Access: This lets you edit settings for those that are hard of hearing, have poor vision, etc.
  • Devices: This is where you manage your other devices, like printers, webcams, mice, and other hardware.
  • Sync PC Settings: This is one of the cooler features of Windows 8, that lets you sync your settings to other Windows 8 devices through a Windows Live ID. Here, you can choose what to sync, like background and lock screen, themes, app settings, browser bookmarks and history, passwords, and more.
  • Homegroup: If you’re running your machine on a home group for sharing files, you can enter your password and connect it here.
  • Windows Update: This is where you’ll see if you have any pending updates for Windows, and when your last update was.
  • More Settings: This takes you to the desktop Control Panel we all know and love, for any settings not covered in the above categories.
Accessing the Desktop

While Windows 8 boots up into the Metro UI by default, you can get to the traditional desktop just by clicking on the desktop tile (see below the Windows Explorer and Control Panel in the above Fig). Alternatively, you can hit Win+M on your keyboard and it’ll take you straight there.

Windows 8 treats the desktop just like any other app, so if you’re Win+Tabbing or Alt+Tabbing through applications, your desktop will be one of them. Similarly, if you use the application history feature by dragging your mouse to the left side of the screen, the desktop will be one of the apps available in that history.

The Start Button, Settings, and Search

The desktop and Metro UI interact via the new Start button. The Start menu is gone in Windows 8 by default; instead, hitting the Start button takes you back to the Metro UI (as does hitting the Windows button on your keyboard). Of course, if you want the old-style Start menu back, there’s a way to do that, but you’ll lose access to the Metro UI entirely.

image

If you hover your mouse over the bottom left-hand corner of the Start button, you’ll see the new "Charms" menu pop up. From there you can access a Metro-based Settings bar, the Devices bar, the Share bar, and the Search bar. The Settings pane, which you can also access by hitting Win+I, will let you adjust the brightness, volume, language, notifications, and Wi-Fi settings.

image

The most important part of the Settings pane, however, is that this is where you shut down from the desktop—you have to hit Win+I to get to the settings bar and hit the shut down button from there. It’s annoying, but the only option if you want to keep Metro around.

To search your computer, you can hit Win+F or access Search from the Charms menu. It’ll open search up in the Metro UI, where you can search for apps, settings, files, and within Metro apps themselves. If you’d rather search for files from the desktop itself, you have to open up Windows Explorer and search from the search bar.

Multiple Monitors:

image

By default, when you boot up, it’ll show the Metro UI on one monitor, and the desktop on the other, which is pretty cool. If you want the desktop to show up on both monitors, just hit Win+M as you would on a single monitor. You’ll also see a new button in place of the Start button on the desktop monitor, which lets you swap the two screens with the click of a button—which is awesome if you’re working with Metro and the desktop at the same time and want to flip between them often.

The other cool thing you’ll notice is that Windows 8 now supports showing the taskbar on both monitors. This is enabled by default, but if you want to disable it and show the taskbar only on one monitor, just right click on the taskbar, go to Properties, and uncheck "Show Taskbar on All Displays". And, lastly, Windows 8 now also supports dual monitor wallpapers under Appearance and Personalization in the Control Panel.

 
The New Dialogs:

Deleting files:image

Copying Files:image

Fig showing the new choose files dialog. This dialog comes up if you select “choose the file to keep in the destination folder” option in “Replace or Skip Files” dialog.

Anyone who’s ever copied multiple and/or large files in Windows knows that their file moving dialog could use a bit of work. Well, they’ve revamped the entire process in Windows 8, making it much easier to move, copy, and replace duplicate files in Windows Explorer.

image

The biggest change you’ll notice is the dialog itself. If you hit the "Details" button, you now see a speed meter that lets you keep track of how fast your files are copying over time. If you have multiple copy operations running at the same time, you can view them all from one consolidated window, and even pause each of them one-by-one if you want to give certain operations priority.

The other big change in file copying is the file conflict dialog as shown above. If you’re copying a number of files to a folder that contains files of the same name, you no longer get a series of annoying windows that each asks you about a separate file. Now, the file collision dialog is consolidated into one window with two columns—new files on the left, old files on the right. All you do is check the boxes next to the files you want to keep, and Windows Explorer does the rest—much easier than the way it was in Windows 7.

Performance Increases:

Windows 8 actually has better performance than Windows 7, even with this metro interface running on top of a desktop. Tablet users and netbook users should notice a fairly significant performance increase with Windows 8. What it really "feels" like in real-world usage remains to be seen, but you can see a comparison between a task manager running on both operating systems above—which makes us pretty hopeful. Furthermore, any of your tablet-based apps will suspend themselves when you jump into the traditional desktop, so they don’t take up any of your resources.

Enabling Hibernate:

image

To enable hibernate functionality from the power option discussed earlier, you need to change the settings. As shown in the above picture, click on “change settings that are currently unavailable” and select “Show Hibernate” option. So from now on, you can see the Hibernate as an option in Power button menu.

Other cool features:

Along with these cool features, Windows 8 also comes with other features we’ve come to know and love in our mobile OS. It’s got system-wide spellchecking, so you don’t have to rely on a specific app to keep your writing top-notch, as well as a system-wide search feature shown above, that lets you search anything from your music library to your contacts to the web itself. It also has a really cool feature for desktop users that lets your run the Metro UI on one monitor while running the traditional desktop on the other.

It also has a really cool feature called "refresh your PC", where you can do a clean install with the tap of a button. This is present in General tab of control panel. Whether you’re selling your machine or just want a cleaner, faster installation of Windows, you can do it all in one click. You can even set refresh points, similar to restore points, so you can refresh your PC to the way it was at a certain point in time.

After trying Windows 8 I don’t see myself using Metro style Apps a lot on my PC when I work at the desk. However, I will love to use it when I’m hanging out on my couch with a tablet. The good news is, both models are supported by Windows 8 and therefore can run on one device, including ARM hardware. Awesome!

Those who try to lead the people can only do so by following the mob – Oscar Wilde

Part 1: My Experiments With Windows 8 – Getting started guide

Microsoft unveiled new Windows 8 operating system and new development improvements on September 13, 2011, day one of the BUILD developer conference. Microsoft released a developer preview of Windows 8 for the developer community to download and start working with. This developer preview includes tools for building "metro style apps", such as Microsoft Windows SDK, Microsoft Visual Studio 11 Express Developer Preview and Microsoft Expression Blend 5 developer preview. Microsoft has shown a development roadmap at the BUILD conference over the course of 3 days.

Downloading & Installing Windows 8:

Note: The size of the Windows 8 ISO file is 4.8 GB which requires a large DVD format. You cannot use the normal DVD format as it is around 4.3 to 4.4 GB size only. The best option is to use the USB flash drive which is of size 5 GB or higher. Information to install Windows 8 using USB drive can be found at http://liliputing.com/2011/09/how-to-install-windows-8-using-a-usb-flash-drive.html.

Fig 1 showing my old dell laptop re-imaged with windows 8 developer preview operating system and my Windows 7 laptop side by side.2012-02-04 18.02.55 

Fig 2 showing my new Windows 8 start screen connected to my Twitter, Facebook, weather updates, blog updates and much more.image

Windows 8 is the codename for the next version of the Microsoft Windows computer operating system following Windows 7. It adds support for ARM microprocessors in addition to the previously supported x86 microprocessors from Intel and AMD. A new Metro-style interface has been added that was designed for touchscreen input in addition to mouse, keyboard, and pen input. Its server version is codenamed Windows Server 8.

The cool feature is a new authentication method allows users to sketch in three different places over the picture to login, instead of typing a password. Currently, I am using this feature to login to my machine.

Windows 8 contains a new user interface based on Microsoft’s design language named Metro. With the new change, the Start Menu was replaced in favor of the new Start Screen, where there are tiles that contain shortcuts to applications grouped by type, Metro style applications, and updating tiles as shown in the above Fig 1. Windows Explorer now uses a ribbon interface, similar to those used in Microsoft Office applications.

Observations of a developer:

The languages that are directly supported by Microsoft for writing applications for Windows 8 are JavaScript and HTML, Visual Basic, C++, and C#, but there are many third party compilers which allow application development for the platform, for example, Free Pascal allows writing Object Pascal applications.

Fig 3 showing the screenshot of the Windows 8 Platform and tools snatched from the build conference.image

We all know about desktop apps. Coming to the new Metro style App model, Metro is a code name for a typography-based design language created by Microsoft. Microsoft’s "re-imagining" of Windows 8 is focused very heavily on a new, Metro-style touch-based interface. You can switch between the simple Metro interface and the traditional Windows desktop to fit whatever your needs are at that given moment.

Metro Style Application:

Windows 8 represents Microsoft’s first official entry into the tablet space, and the Metro UI is how developers deliver unique multi-touch experiences to this new platform. WinRT is the OOP replacement for Win32. A Metro Style Application is a full screen applications integrated according to user’s choice.

There are many features it integrates such as given below.

Immersive and Fluid : Your Metro style apps fill the entire screen for an engaging experience and saving you from any distraction. Apps can adapt to a variety of form factors and screen resolutions, and can work on x86, x64, and ARM platforms.

Engaging : Metro style apps engage users with the info they are interested in and the people they care about. Live tiles present activity updates to users at a glance and the Start screen shows off what apps are great at.

Everywhere : Your apps are ready for you on any Windows 8 PC you use. When   you sign in with your connected Microsoft account to a PC running Windows 8, your Metro style apps and settings go with you. You’ll also be signed in to all of the websites you were signed in to.

Work Together : Metro style apps can communicate with each other in Windows 8, making it easier to search, share, and send content between them. So, if you want to send pictures in email, and they’re in different places like Facebook or on your hard drive, you can easily pick and send the ones you want.

Always On : Metro style apps run and stay up to date even when the PC is on standby. When Windows comes out of standby, your apps don’t need time to catch up.

Multitasking : While apps immerse your users in a full screen environment, Windows also makes it possible for them to multitask. The Snapped view allows users to do more than one thing at once while the Filled view allows users to snap one app and keep another app in the fill space.

Windows 8 Platform and tools:

I think the below picture is a way more accurate picture of the Windows 8 platform architecture.image

Information for Windows 8 software Development:

  • Metro applications are now officially the first class applications that can fully leverages the touch features of Windows.
  • Expression Blend 5 now supports editing HTML5, much like you use it for editing XAML.
  • Support for Wide Variety of Hardware.
    • The hardware support for Windows 8 seems really awesome. The demos features Windows 8 running on a variety of hardware devices
    • New and improved features include
      • Multi monitor support with start button on all screens
      • Hyper V Support for client
      • USB 3 Support
      • Hardware acceleration for all applications
      • Malware detection in boot strap.
      • A boot mode called “Cold Boot“ which is super fast
  • Windows Live integration
    • The whole suite of Windows Live services are neatly integrated with Windows 8.
    • All the Windows Live applications (Mail, Calendar, Photos) are now developed in JavaScript/HTML5 and is native.
    • You can connect multiple devices via Windows Live
  • New APIs and Extension Points
    • Charms: Apps can share charms, to inter-operate. For example, an “Insert Picture” dialog box can show you results from other applications that can handle the image/picture data type.
    • Direct Compute API: Enables you to leverage the power of GPU in your applications
    • Sensor Fusion API : A Single API for all your sensors like Accelerometer, magnetometer and gyroscope
  • To a great extent, your XAML assets can be reused across multiple devices – desktops, slates and phone.
  • Windows 8 Store.
    • Transparent approval process
    • Developers can publish applications right from Visual Studio.
  • If you want to build a new Metro style app, you have four options to choose from:
      1. XAML and .NET (C# or VB). You don’t have to giving up too much in the .NET Framework (remember, you only give up what is forbidden by the Application Container), and you get access to WinRT APIs for sensor input and other system resources.
      2. XAML and C++. You can use your skills in XAML and C++ in order to leverage (or even extend) WinRT. Of course you don’t get the benefit of the .NET Framework, but hey….some people like managing their own garbage collection.
      3. HTML and JavaScript. You can leverage the skills you have in UI layout, and make calls from JavaScript to WinRT for access to system resources, and sensor input. Which means you can now develop native Windows applications using JavaScript and HTML by accessing native WinRT APIs straight from Java script. This is particularly interesting because JavaScript development model suits a lot of cloud based applications, and now JS developers can develop first class Windows 8 applications.
      4. DirectX and C++. If you’re building an immersive game you can use DirectX and access the device sensors and system resources through C++ and WinRT.

More on WinRT API’s, Metro, developer insights and sample code in the up coming blogs.

This and the following Windows 8 articles and its contents are based on the first public developer preview of Windows 8, Visual Studio 2011 developer preview and Expression Blend 5 developer preview.

The best teacher is the one who suggests rather than dogmatizes, and inspires his listener with the wish to teach himself.- Edward Bulwer-Lytton