Tag Archives: Metro

101 Questions and Answers About Windows 8

1. What tools and information do I need to develop Windows 8 Store applications?

a. Windows 8 – Download free version here

b. Visual Studio 2012 Express – Download free version here

c. Windows Phone – Download free version here

d. Windows Server 2012 – Download free version here (Optional)

e. Microsoft Virtual Academy – Register here

2. How to develop a Windows Phone 8 app in 30 days?

Register at http://www.microsoft.com/click/services/Redirect2.ashx?CR_CC=200134727

3. For a Mac user, where can I get the free tools to build Windows Store apps for Windows 8?

Install Windows 8 and the dev tools on your Mac.

4. How to start planning now for a cloud-based backend service—user authentication, push notifications, and structured data?

Sign up for the Windows Azure 90-day Free Trial and receive 10 free Mobile Services running on shared instances.

5. Get the samples and get started!? Download the design assets—PSD assets include templates, common controls, and common components—and the sample apps pack.

6. Where to find Windows 8 Sessions and Keynotes — //BUILD Conference Site

7. Download the Bits — Windows Dev Center

8. PDF Manual — Windows Developer Preview Guide

9. Code Examples — MSDN “Metro Style” app examples (or get them all together in a Single ZIP)

10. What Devices will Run It? — List of Devices in Microsoft’s Test Lab

11. How to Install on My Machine without Losing Everything even if I don’t have Dual-Format DVDs or 8 GB Memory Sticks Handy — Installing Windows 8 Developer Preview as a Bootable VHD

12. What About Silver light? — It’s still here, with a diagram from Microsoft to prove it

13. Chat about Windows 8 or Cry for Help — MSDN Forums for Windows 8

14. What is WinRT? — Introduction to WinRT and WinRT demystified

15. Touch Input — Quickstart: Touch Input

16. Comfort Guide to Controls for Silverlight and WPF Developers — Controls List (for Xaml)

17. How do I Convert Silverlight to WinRT/Metro? — Blog Series on WinRT vs. Silverlight

18. But is Xaml REALLY There? — Yes, It Is

19. The New Architecture — Windows 8 WinRT Capabilities (Tip: Lean forward to make it look flat)

20. Platform and Tools Architecture — Windows 8 Platform and Tools (Tip: this time lean sideways)

21. Can I Borrow Someone’s Opinion? — Sure thing: Yours Truly, Michael Crump, Engadget, Wired

22. Create a bootable USB? jerrynixon.com

23. Setup boot to VHD? jerrynixon.com

24. Get an Azure account? http://aka.ms/w8cloud

25. Get Windows 8? http://aka.ms/w8download

26. Get Visual Studio 2012? http://aka.ms/w8tools

27. Get Windows Live SDK? http://aka.ms/w8live

28. Get Windows 8 Samples? http://aka.ms/w8samples

29. Get Multilingual Toolkit? http://aka.ms/w8language

30. Get Advertising SDK? http://aka.ms/w8ads

31. Get Design Assets? http://aka.ms/w8design

32. Register your App? http://aka.ms/w8reg

33. Join 30 to Launch? http://aka.ms/w8launch

34. View the online labs? http://aka.ms/w8vlabs

35. Does Windows 8 run Windows 7 software? Yes

36. Does Windows 8 support .Net 4.0? Yes

37. Does WinRT replace the .Net framework? No

38. Can users re-enable the start button in Windows 8? No

39. Can enterprises disable Microsoft Design Style on their Windows 8 desktops? No

40. Will Microsoft Design Style be part of the server version of Windows? Yes

41. Do developers need two apps in the Windows 8 store to support ARM? No

42. Can apps have a hidden URL in the Windows 8 store? No

43. What is the revenue split with Microsoft for the Store? 80/20

44. Do developers need a developer account in order publish an app? Yes

45. Can developers use payment systems other than Microsoft? Yes

46. Is HTML5 and JavaScript (JS) supported in Microsoft Design Style development? Yes

47. What is the HTML rendering engine in HTML-based Microsoft Design Style apps? IE10

48. Is IE10 Microsoft Design Style the same engine as IE10 desktop? Yes

49. Can desktop applications create live tiles? No

50. Can desktop applications use WinRT? Yes

51. Can desktop HTTP end point be accessed by Microsoft Design Style apps? No

52. Can Microsoft Design Style applications access a local SQL server? No

53. Do Microsoft Design Style applications have a local database solution? Yes, Sqlite

54. Can Microsoft Design Style applications access the internet while the pc is in standby? Yes

55. Can Microsoft Design Style applications access SkyDrive? Yes

56. Can Microsoft Design Style applications iterate through the user’s hard drive? No

57. Is there a Microsoft Design Style version of windows file explorer? No, see above

58. Can Microsoft Design Style applications detect other Microsoft Design Style apps? No

59. Can more than one Microsoft Design Style application run at one time? Yes, two

60. Can push notifications execute client code? No

61. Are there background tasks in Microsoft Design Style? Yes

62. Is the performance of HTML5 Microsoft Design Style applications comparable to XAML? Yes

63. Is native code (C++) supported in Microsoft Design Style development? Yes

64. Is Microsoft Design Style C different than traditional CPP? Yes

65. Should all desktop apps be migrate to Microsoft Design Style? No

66. Will the Windows 8 store support trials? Yes

67. Will the Windows 8 store support subscriptions? No

68. Will enterprise apps deliver through the Windows 8 store? No

69. Can enterprises disable the Windows 8 store? Yes

70. Can enterprises disable side-loading of apps? Yes

71. Can apps in the Windows 8 store access desktop apps & services? No

72. Can side-loaded apps access desktop apps & services? Yes

73. Can parents disable the Windows 8 store for kids? Yes

74. Can parents limit the hours in the day their kids can log in? Yes

75. Can parents limit the cumulative time in a day kids can use the PC? Yes

76. Can parents filter available web sites? Yes

77. Can parents disable games based on their rating? Yes

78. Can Visual Studio 2010 be used to build Microsoft Design Style apps? No

79. Can Visual Studio 2012 be used to build Windows 7 apps? Yes

80. Can Visual Studio 2010 access Team Foundation Server 2012? Yes

81. Can Visual Studio 2012 open 2010 projects without altering them? Yes

82. Can Visual Studio 2010 open 2012 projects? No

83. Does the .Net 4 async keyword work in WinRT? Yes

84. Does Windows 8 WinRT code run on Windows Phone 7? No

85. Does Windows Phone 7 code run on Windows 8? Yes, some

86. Does Windows Phone 8 code run on Windows 8? Yes, more

87. Does Windows 8 code run on Windows Phone 7? Yes, some

88. Does Windows 8 code run on Windows Phone 8? Yes, more

89. Can Microsoft Design Style applications roam settings/files across desktops? Yes

90. Can desktop applications roam settings, too? No

91. Can Microsoft Design Style applications roam settings/files to Windows Phone? No

92. Can Windows Phone roam settings to Windows 8? No

93. Does Windows 8 Microsoft Design Style support XNA game development? No

94. When was Windows 8 released? Friday, October 26, 2012.

95. Win+E – Explorer

96. Win+R – Run

97. Win+D – Desktop

98. Win+Plus or Win+Minus (no shift) – Magnifier/Zoom In and Out

99. Win+F – Find Files

100. Alt-Tab – Switch between Apps

101. Win-Tab – Switch between Full Screen Apps

    Advertisements

    My First Windows Store App : Emergency – Help Me

    You can download from Windows Store at http://apps.microsoft.com/webpdp/en-US/app/emergency-help-me/477b898a-6781-4b75-a439-44dee5904f14

    Have you ever thought what you would do, if an unforeseen events happens and you need to alert/contact someone immediately, but for whatever reason you can’t? An emergency might impose itself in various ways, someone is stalking/following you, traffic accidents, car trouble, walking at night, lost during hiking/camping trip, threat during a foreign visit, and many more. Odds are that you might have your mobile device with you but given the nature of the situation you might not have time or the means to communicate conventionally via a text message/call for help and to let someone know of your situation. Unlikely? Maybe. But what if…?

    Emergency – Help Me is the first go-to app in case of an emergency. The App generates a SOS distress signal to attract attention of others, simulates a police siren and lights, displays emergency phone numbers for all countries, displays your current location, stores ‘In Case of Emergency’ information, Flash Light and has Request and Respond to alpine emergency (mountain help) light signal. Additionally, this provides you a feature to communicate with a click of a button. You can tell your current location, contact details when in emergency, your medical conditions, blood group, allergies and other information useful during an emergency situation. With just a click of a button, you can send the information to a variety of apps like Facebook, Twitter, Email and any app on Windows Store that accepts text to share.

    You can take advantage of 8 sensational features as shown in Fig 0.1:

    • SOS Emergency Flasher
    • Police Emergency
    • International Emergency Phone Numbers
    • GPS Location Data
    • In Case of Emergency (ICE)
    • Flash Light
    • Alpine Distress Signal
    • Respond to Alpine Distress Signal

    image 

    Fig 0.1: Figure showing the main launch page of the application

    Windows features supported in the app:
    • Color Preference and ICE Data Roaming – Roaming personalization settings is key to feeling connected to your preferences and data. You don’t want to configure or choose preferences every time you use a new device. The ‘Help Me’ app creates a connected experience by allowing the user to configure ICE (In Case of Emergency) data and color preference once and use it everywhere, so you don’t have to re-configure the app each time you access it from a different system. When you change the color of the screen by using app bar, it is automatically saves to your preferences. So the next time you open the app and use any feature from any PC or device, it knows the color of your choice and your configured data. The app helps you connect to your data from anywhere by having a continuous experience as you transition from one device to another. image

    Fig 1: Choose color preference from App Bar. The choice of color is automatically remembered by the application. image 

    Fig 2: Enter information of the person to be contacted during emergency and your medical data. The data is automatically saved and synced to your personal account you used to login.

    • Semantic Zoom – Users can now easily navigate countries list within a single view. Semantic Zoom organizes countries alphabetically in a single view and presents the data using the letters of the alphabet. The user could then zoom in on a letter to see the countries associated with that letter as shown in figure 3. image image

    Fig 3: Semantic Zoom of International Emergency Numbers.

    • Share charm – You often come across a situation where you want to share your emergency situation, current location and ICE information with someone or use it in another app. The “Help Me” app exchanges data with other apps without having to navigate away to share data. The app helps you to share content with another app or service quickly and easily by using Windows Share charm. So you can continue using the Help Me app and still share your information.

             image

    Fig 4: Sharing data with other apps using Share charm.

    • Search charm – Lets users search the app from anywhere in the system, including the app itself. Users will be able to use the Search charm to open a search pane where they can enter search queries and the app displays the search results with the following. 

    Suggestions: Start typing country name in the search pane, and you will get a list of suggestions as well. This displays a maximum of 5 countries in the suggestions list as shown in figure 5. image    Fig 5: Search pane automatically showing the Search suggestions as the user types in.

    Filter List: Country names and emergency numbers can be searched. Simply start typing in the search charm and you’ll see your list of countries or emergency numbers filter down to the one you are looking for as shown in figure 6. image image

    Fig 6: Search results displaying the countries that contain the string user searched for.

    • Secondary Tile – Help Me app enables you to pin a specific content or experience from an app to the start screen. Secondary tiles provide a direct link to the feature within the app. Pin any country or main features tile to the main screen and the app takes you directly to that feature shown in figure 7.

    image    

    Fig 7: Large Secondary Tiles (Shortcuts) to the app features.

    image

    Fig 7.1: Small Secondary Tiles (Shortcuts) to the app features.

    • Help Page: Help information is included to explain the features of the app. Every feature (tile) has a help page include with it to explain the functionality in detail as shown in figure 8.

    image image

    Fig 8: Help information displayed on Help screen.

    • Settings – Help me app implements Settings contract so that you can access its settings like switching location access on or off from the Settings charm.

    image

    Fig 9: Application Settings.

    • App Bars: The app bar contains contextual actions or commands for each screen in the app. Frequently used commands are kept near the right and the left edges so that they are easy to reach by hand as shown in figure 10.

    image

    Fig 10: One of the features showing App Bar.

    All tiles (screens) in the app support Share and Search contracts of Windows Store apps. The app adjusts the screen display perfectly in landscape, portrait, filled and snapped view as shown in the following figures A-K.

    image

    Fig A: Main Screen shown in portrait view.

    image

    Fig B: Main Screen shown in snapped view.

    image

    Fig C: Main Screen shown in filled view.

    image

    Fig D: SOS Emergency Signal Screen shown in snapped view.

    image

    Fig E: SOS Emergency Signal Screen shown in filled view.

    image

    Fig F: Police Emergency Signal Screen shown in portrait view.

    image

    Fig G: Police Emergency Signal Screen shown in snapped view.

    image

    Fig H: Police Emergency Signal Screen shown in filled view.

    image

    Fig I: International Emergency Numbers Screen shown in snapped view.

    image

    Fig J: International Emergency Numbers Screen shown in portrait view.

    image

    Fig K: International Emergency Numbers Screen shown in filled view.

    A distress signal is an internationally recognized means for obtaining help. Distress signals are commonly made by displaying a visually detected item or illumination, or making an audible sound, from a distance. In order for distress signaling to be the most effective, two parameters must be communicated:

    1. Alert or notification of a distress in progress
    2. Position or location of the party in distress.
    SOS Emergency Flasher:

    This is super easy to use. Just run it! A flashing emergency light with high distress signal sound for alerting people that you are in an emergency situation as shown in figure 11. A realistic light, in a variety of colors, that blinks and has attention grabbing pattern to make yourself visible in the dark, attract attention or warn others about an emergency or safety hazard.

    Simply run it to continuously display a flashing light and distress sound – perfect for use in traffic accidents, car trouble, running or walking at night, and more. Emergency Flasher is a feature dedicated to everyone who want to feel more secure any place, any time.

    Features:
    * Intuitive and elegant UI design
    * Realistic screen display with flashing.
    * Distress sound to alert or attract attention of others.
    * Variety of color options to choose from App bar. Your choice of color is remembered by the device automatically. If you open the app on a new device, it displays the light with your preferred color automatically.
    * App bar to play or stop the sound.
    * Use Windows Share charm to share your location and ICE details with other people or apps.

    image 

    Fig 11: SOS Emergency Signal screen.

    Police Emergency:

    Is someone stalking you? Use this feature to alert others. Real high quality police beacon and blue/red strobe light blow up to full screen that will turn any vehicle (such as your own personal vehicle) into your very own emergency vehicle! This is a cool feature that continuously simulates a police siren and lights. The app bar displays the controls to play, pause or stop the sound

    Features:
    * Realistic screen display with flashing.
    * Police Beacon sound to alert or attract attention of others.
    * App bar to play, pause or stop the sound.
    * Use Windows Share charm to share your location and ICE details with other people or apps.

    image

    Fig 12: Police Beacon screen.

    International Emergency Phone Numbers:

    Travel the world with peace of mind. Ever been on vacation abroad or on a business trip and an emergency occurs, and you wonder what number to call? Ever wondered how to call the police? The firefighter? Or an ambulance? To be perfectly honest, most people are not aware of these and added to that not every country in the world has the same emergency numbers. The problem arises when you need something fast and in case of emergency.. Don’t forget, roaming internet can be very expensive in other countries. With this app, simply select the country you are in and with just one tap the app displays the emergency numbers for the country you are in. It is possible to call an emergency number right away, without going to menus using snapped view. It doesn’t use internet, so no roam costs! Hopefully this app makes your holiday a lot safer. Have fun!

    Features:
    * Zooming functionality to easily navigate to the country that you are searching for.
    * Share emergency details with your friends and family members with just a button click.
    * No GPS or cell data network required.
    * Fast selection of which country you are in. Search by index or free search to quickly select the country. Each country is listed by its name and national flag.
    * No cell coverage? You can still call! It displays the emergency phone numbers from the country you select. Just read the emergency numbers from the app and make the call from a landline based phone.
    * Supports 237 countries (covers most of the world that support emergency telephone numbers).
    * Using Windows start screen, you can search for police, fire or medical emergency number of any country in this world and the app shows you the information directly with just a click.
    * Directly search for a country by typing in the Windows Search charm.

    image

    Fig 13: International Emergency Numbers screen.

    GPS Location Data:

    Never get lost. Using this feature, you can let others know your current location with just a click. GPS Location uses the device GPS to show your position coordinates and current address in case of emergency. With just a press of a button, you can send your position details to any of your contacts using any Windows Store app that can share information. Your GPS location will be displayed on the screen in any view so that you can quickly provide you exact location.

    Features:
    * Get GPS coordinates
    * See how accurate the GPS coordinates are
    * Send your position to a family member or friend through any Windows store app that shares information.
    * You can activate the Track Me feature and the app displays your current location coordinates, in real-time. You can stop the tracking feature when you want!
    * The application automatically detects your GPS coordinates [location]. These coordinates along with the information you entered into the In Case of Emergency tile of the application can be send with any Windows Store app that accepts text like Twitter, Facebook, Email and other social media services.

    image

    Fig 14: GPS Location Data screen.

    In Case of Emergency (ICE):

    This screen provides all the information needed in case of emergency. You can add your own emergency contacts. This fantastic tile rolls so many features into one screen:

    Features:
    * Store your Emergency contact Details like the person name to be contacted during emergency, phone number, Twitter ID, Facebook ID and email address of the person.
    * Store your allergies information
    * Store you prescriptions & important medical conditions
    * Record your insurance details (travel, car, home etc.) – making sure you have these details to hand at the right time.
    * Store your doctors contact details
    * Store your address in case someone needs it during emergency.
    * Use Windows Share charm to share your location and ICE details with other people or apps.

    image

    Fig 15: ICE Information screen.

    Flash Light:

    Bright. Fast. Simple. The most elegant and functional flashlight tile. Flashlight fills the device screen with bright white light to illuminate your world when you find yourself in a dark spot or concert.

    Features:
    * Full white screen.
    * Brightest Flashlight instantly ON.
    * Change flashlight color with just a click.
    * Choose from a variety of widely useful colors from App bar. Your choice of color is remembered by the device automatically.
    * Use Windows Share charm to share your location and ICE details with other people or apps.

    image

    Fig 16: Flash Light screen.

    Alpine Distress Signal (Mountain Emergency Help):

    Alpine Request is a feature that uses the device screen to transmit alpine distress help light indicating mountain emergency. The entire process is controlled automatically. The only thing you need to do is to trigger the process.

    Features:
    * Choose from a variety of commonly used colors to transmit light signal during daytime or night. Your choice of color is remembered by the device automatically.
    * Easy to use interface.
    * Share your location and ICE details with others.

    image

    Fig 17: Alpine Distress Signal screen.

    Respond to Alpine Distress Signal:

    Alpine Response is a feature that uses the device screen to transmit response to an alpine distress signal indicating that you have received the Alpine Emergency Signal. The entire process is controlled automatically. The only thing you need to do is to trigger the process.

    Features:
    * Choose from a variety of commonly used colors to transmit light signal during daytime or night. Your choice of color is remembered by the device automatically.
    * Easy to use interface
    * Share your location and ICE details with others
    * If the device has a light sensor, the app displays light in Red color if it is daytime and in bright white color if it is night.

    image

    Fig 18: Respond to Alpine Distress Signal screen.

    While we hope that you never need this app, we would like to give you peace of mind. Our goal is that in case of an emergency or an unforeseen event, you are prepared and you can easily communicate your situation and current location to others.

    The creator of this application is under no circumstances liable for any direct, indirect, incidental, consequential or exemplary injury or damages resulting from the use of this application. Calling an emergency number without reason is forbidden in most countries.

    There will be a continued commitment from the developer to implement new features or solve problems you encounter! Just drop a comment on this blog.

    Privacy Policy

    Your privacy is very important to us. Accordingly, we have developed this Policy in order for you to understand how we collect, use, communicate and disclose and make use of personal information. The following outlines our privacy policy.

    • The application uses internet connection only to retrieve your location information upon request. Other than that, we do not use internet connection at all.
    • Before or at the time of collecting personal information, we will identify the purposes for which information is being collected.
    • We do not collect any personal information. Personal information is used solely with the objective of fulfilling those purposes specified by us like In Case of Emergency information, unless we obtain the consent of the individual concerned or as required by law.
    • The application only retain ICE information as long as necessary for the fulfillment of those purposes. ICE information is saved onto your device and is stored with your device Windows account. Other than displaying the ICE information in the app, we do not use your ICE data at all for any other purposes.
    • ICE Personal data should be relevant to the purposes for which it is to be used, and, to the extent necessary for those purposes, should be accurate, complete, and up-to-date.
    • We will protect personal information by reasonable security safeguards against loss or theft, as well as unauthorized access, disclosure, copying, use or modification.
    • We will make readily available to customers information about our policies and practices relating to the management of personal information.

    We are committed to conducting our business in accordance with these principles in order to ensure that the confidentiality of ICE information is protected and maintained.

    Internals (Deep dive) of Metro Application calling WinRT Component DLL

    We have created a C++ XAML application that consumes the WinRT C++ DLL in part 1

    we have seen the compiler generated components when we compile a WinRT Component DLL.  Part2  discusses how the C# application interacts with the C++ WinRT component.

    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

    Part5 discusses developing JavaScript application that consumes WinRT Component DLL

    Lets dig deeper into how the C++ Application makes  a call across the WinRT Application Binary Interface to access the class methods inside the WinRT DLL. The slide in fig 1 is taken from the build conference which shows the internals of the method calls. We will examine the ABI and how C++ compiler extensions help reference that ABI without exposing the internal details of dealing with COM interfaces and COM activation.

    Download the source code from here.

    image

    Fig 1: Slide showing the flow of the method calls across the boundaries.

    A WinRT component implements the IInspectable interface, which is derived from IUnknown. 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.

    When WinRT components are accessed from C++ or from .NET languages, there is no need for the IInspectable interface – IUnknown::QueryInterface suffices for all intents and purposes. In fact, .NET “interop” with WinRT relies on simple COM interop – an RCW created by the CLR manages the lifetime of the underlying WinRT component. For C++ language bindings, the story is somewhat more complicated, and the language extensions come into play.

    The left side in Fig 1 is the C++ client application code which calls the method in right side WinRT DLL. So here if the method in C++ DLL throws an exception, it should be caught by the C++ application. But it’s not a good practice throw exceptions directly across boundaries.

    The left side call (C++ Client App: Consumer) to Add() method causes the compiler to create an inline native to COM wrapper method. Also, on the left hand side, COM HRESULTs are converted to exceptions and COM “retval” arguments are converted to return values. The Add() method makes a call to this wrapper method. This inline methods generated will be something like a COM method that we write in COM components. We can see the source code generated by the compiler using some compiler switch options. 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.

    From the WinMD file, the C++ application knows the WinRT API signature(shown at the top of the slide) and makes the appropriate call across the WinRT ABI.

    HRESULT __stdcall Add(Calculator* this, int i, int j, int * result)

    //On the LHS Application, the native to COM Wrapper is as follows (Consumer-side stub pseudo-code) . See the last section of this post to see the compiler generated code. 
    inline int Add(int i, int j) {
    int res;
    HRESULT hr = __cli_Add(this, i, j, &res);
    if (hr != 0) {

    __throw_hr_as_exception(hr); }
    return res;
    }

    On the right hand side too (C++ Component DLL), C++ compiler generates inline functions. Also, WinRT and C++ exceptions are converted to HRESULTs and return values are converted to “retval” arguments. Note that the only HRESULT, which does not represent an exceptional condition, is S_OK (numeric value 0). No more positive HRESULTs (such as S_FALSE) that need to be checked explicitly by the caller.

    //On the RHS C++ Component, COM to Native Wrapper stub pseudo-code is as follows:
    HRESULT __stdcall ___cli_Add(Calculator* calc,
    int i, int j, int* result) {
    try { *result = calc->Add(i, j); }
    catch(Platform::Exception^ e) { return e->HResult; }
    return S_OK;
    }

    See the last section of this post to see the compiler generated code.

    By the way, the inline wrappers can be called directly, bypassing the C++ language extensions.

    image

    The C++ language extensions (enabled by the /ZW switch) map WinRT to standard C++ patterns like constructors, destructors, class methods, and exceptions. For example, the language extensions hide the COM-style activation (RoActivateInstance) behind a constructor call (albeit with the ref new keyword), and hide reference counting (IUnknown::AddRef and Release) by automatically managing references. The syntax of these extensions is very similar to C++/CLI

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

    In the above code snippet, you can see we created the object of CalculatorSample class which is present in WinRT C++ Component using ref new. If you know COM, this is something like cocreateinstance() but its more than that. For now, use ref new to create objects of WinRT classes.

    Let us see how to skip to exception wrapper and directly calling the Add() method present in WinRT Component. Every function in the class has a low level equivalent inside the class and currently it is prefixed with __cli_ and it takes the output as last parameter. So using ToString() on an integer. So this is another way of calling the methods inside the WinRT components. If we need HResult, we need reference to windows.h. For that include Windows.h in pch.h file as shown below.

    Code Snippet
    //
    // pch.h
    // Header for standard system include files.
    //

    #pragma once

    #include <Windows.h>
    #include "App.xaml.h"

    The complete code to call the WinRT component method is as follows.

    Code Snippet
    MainPage::MainPage()
    {
        InitializeComponent();

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

        // declare a stack variable to hold the value of the result
        int result;
        //call into  calc object low level __cli_Add() but no intellisense in this preview
        HRESULT hr = calcobj->__cli_Add(10,20,&result);

        //typedef HRESULT (__std

        txtAddResult->Text = result.ToString();
    }

     

    Another (3rd) way is to use function pointers and call the methods using pointers. Basically, we we can take the calculator^ object, which is a pointer to a pointer to a vtable and reinterpret cast it so that it has a pointer to virtual function, which are vtables. Then we can find out the location of the method we need to call using some compiler switches which I will show below. For the Add function, we are going to specifically pick the sixth function of that and call into it. In the class layout mentioned below, I highlighted the member at 6th location. reinterpret_cast takes the calcobj ^ and cast it to a pointer to a pointer, that’s it. This is how the functions inside the components are called internally at a low level.

    Code Snippet
    MainPage::MainPage()
    {
        InitializeComponent();

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

        // declare a stack variable to hold the value of the result
        int result;
        //call into  calc object low level __cli_Add() but no intellisense in this preview
        //HRESULT hr = calcobj->__cli_Add(10,20,&result);

        //create a c function that actually represent an ABI call we will be making
        //to add function which takes this pointer, 2 input parameters and an out parameter.
        typedef HRESULT (__stdcall* AddFunc_t) (CalculatorSample^ calc, int i, int j, int * result);
        //now we can take the calculator^ object, which is a pointer to a pointer to a vtable
        //and reinterpret cast it so that it can say ok now i have a pointer of  virtual function
        //which are vtables and i am going to specifically pick the sixth function of that and call into it.
        //reinterpret_cast takes the calcobj ^ and cast it to a pointer to a pointer
        AddFunc_t* addFunc = *reinterpret_cast<AddFunc_t**>(calcobj);
        addFunc[6](calcobj,10,20, &result);

        txtAddResult->Text = result.ToString();
    }

    Basically a hat is a pointer to a pointer to an array of function pointers, which is Pointer to vptr to vtable. Hat (^) provides automatic reference counting.

    To find out the class layout, use the /d1reportSingleClassLayout<class name> compiler switch option. Right click on the WinRTComponent.cpp file in C++ WinRT Component DLL project and select Command Line which is under C/C++. In the Additional Options, mention /d1reportSingleClassLayoutCalculatorSample, click ok and compile the project. See the output window for the magic. There is also another option to see all classes layout by using the option /d1reportAllClassLayout.

    image

     

    1>—— Rebuild All started: Project: CppWinRTComponentDll, Configuration: Debug Win32 ——
    pch.cpp
    WinRTComponent.cpp
    class __ICalculatorSamplePublicNonVirtuals    size(4):
        +—
        | +— (base class Object)
    0    | | {vfptr}
        | +—
        +—

    __ICalculatorSamplePublicNonVirtuals::$vftable@:
        | &__ICalculatorSamplePublicNonVirtuals_meta
        |  0
    0    | &Object::__cli_QueryInterface
    1    | &Object::__cli_AddRef
    2    | &Object::__cli_Release
    3    | &Object::__cli_GetIids
    4    | &Object::__cli_GetRuntimeClassName
    5    | &Object::__cli_GetTrustLevel
    6    | &__ICalculatorSamplePublicNonVirtuals::__cli_Add
    7    | &__ICalculatorSamplePublicNonVirtuals::Add

    __ICalculatorSamplePublicNonVirtuals::Add this adjustor: 0
    __ICalculatorSamplePublicNonVirtuals::__cli_Add this adjustor: 0

    class __CalculatorSampleActivationFactory    size(12):
        +—
        | +— (base class IActivationFactory)
        | | +— (base class Object)
    0    | | | {vfptr}
        | | +—
        | +—
        | +— (base class Object)
    4    | | {vfptr}
        | +—
    8    | __cli_MultiThreadedRefCount __cli_refcount
        +—

    __CalculatorSampleActivationFactory::$vftable@Object@:
        | -4
    0    | &thunk: this-=4; goto __CalculatorSampleActivationFactory::__cli_QueryInterface
    1    | &thunk: this-=4; goto __CalculatorSampleActivationFactory::__cli_AddRef
    2    | &thunk: this-=4; goto __CalculatorSampleActivationFactory::__cli_Release
    3    | &thunk: this-=4; goto __CalculatorSampleActivationFactory::__cli_GetIids
    4    | &thunk: this-=4; goto __CalculatorSampleActivationFactory::__cli_GetRuntimeClassName
    5    | &thunk: this-=4; goto __CalculatorSampleActivationFactory::__cli_GetTrustLevel

    __CalculatorSampleActivationFactory::$vftable@IActivationFactory@:
        | &__CalculatorSampleActivationFactory_meta
        |  0
    0    | &__CalculatorSampleActivationFactory::__cli_QueryInterface
    1    | &__CalculatorSampleActivationFactory::__cli_AddRef
    2    | &__CalculatorSampleActivationFactory::__cli_Release
    3    | &__CalculatorSampleActivationFactory::__cli_GetIids
    4    | &__CalculatorSampleActivationFactory::__cli_GetRuntimeClassName
    5    | &__CalculatorSampleActivationFactory::__cli_GetTrustLevel
    6    | &__CalculatorSampleActivationFactory::__cli_Platform_IActivationFactory____cli_ActivateInstance
    7    | &__CalculatorSampleActivationFactory::ActivateInstance

    __CalculatorSampleActivationFactory::ActivateInstance this adjustor: 0
    __CalculatorSampleActivationFactory::__cli_QueryInterface this adjustor: 0
    __CalculatorSampleActivationFactory::__cli_AddRef this adjustor: 0
    __CalculatorSampleActivationFactory::__cli_Release this adjustor: 0
    __CalculatorSampleActivationFactory::__cli_GetIids this adjustor: 0
    __CalculatorSampleActivationFactory::__cli_GetRuntimeClassName this adjustor: 0
    __CalculatorSampleActivationFactory::__cli_GetTrustLevel this adjustor: 0
    __CalculatorSampleActivationFactory::__cli_Platform_IActivationFactory____cli_ActivateInstance this adjustor: 0

    class CalculatorSample    size(12):
        +—
        | +— (base class __ICalculatorSamplePublicNonVirtuals)
        | | +— (base class Object)
    0    | | | {vfptr}
        | | +—
        | +—
        | +— (base class Object)
    4    | | {vfptr}
        | +—
    8    | __cli_MultiThreadedRefCount __cli_refcount
        +—

    CalculatorSample::$vftable@__ICalculatorSamplePublicNonVirtuals@:
        | &CalculatorSample_meta
        |  0
    0    | &CalculatorSample::__cli_QueryInterface
    1    | &CalculatorSample::__cli_AddRef
    2    | &CalculatorSample::__cli_Release
    3    | &CalculatorSample::__cli_GetIids
    4    | &CalculatorSample::__cli_GetRuntimeClassName
    5    | &CalculatorSample::__cli_GetTrustLevel
    6    | &CalculatorSample::

    __cli_CppWinRTComponentDll___ICalculatorSamplePublicNonVirtuals____cli_Add
    7    | &CalculatorSample::Add

    CalculatorSample::$vftable@Object@:
        | -4
    0    | &thunk: this-=4; goto CalculatorSample::__cli_QueryInterface
    1    | &thunk: this-=4; goto CalculatorSample::__cli_AddRef
    2    | &thunk: this-=4; goto CalculatorSample::__cli_Release
    3    | &thunk: this-=4; goto CalculatorSample::__cli_GetIids
    4    | &thunk: this-=4; goto CalculatorSample::__cli_GetRuntimeClassName
    5    | &thunk: this-=4; goto CalculatorSample::__cli_GetTrustLevel

    CalculatorSample::Add this adjustor: 0
    CalculatorSample::__cli_QueryInterface this adjustor: 0
    CalculatorSample::__cli_AddRef this adjustor: 0
    CalculatorSample::__cli_Release this adjustor: 0
    CalculatorSample::__cli_GetIids this adjustor: 0
    CalculatorSample::__cli_GetRuntimeClassName this adjustor: 0
    CalculatorSample::__cli_GetTrustLevel this adjustor: 0
    CalculatorSample::__cli_CppWinRTComponentDll___ICalculatorSamplePublicNonVirtuals____cli_Add this adjustor: 0

    Analyzing the layout:

    Every WinRT object is laid out in the following way. The first 3 methods in the Vtable are from IUnknown and the next 3 interfaces methods are there for dynamic languages. The important one is GetRuntimeClassName and it allows JavaScript to call into .net  obtain the fully-qualified class name of the WinRT component. When JavaScript calls GetRuntimeClassName, it returns  CppWinRTComponentDll. CalculatorSample. JavaScript then goes and finds out which WinMD file in the system has the classname CppWinRTComponentDll.CalculatorSample. so Windows 8 will inform that it is inside CppWinRTComponentDll.DLL. It then loads the WinMD file of CppWinRTComponentDll.DLL and calls the Add function inside it. In C++, we don’t use these methods as we can directly interact with the class. It doesn’t do dynamic dispatch.

    0 | &CalculatorSample::__cli_QueryInterface
    1 | &CalculatorSample::__cli_AddRef
    2 | &CalculatorSample::__cli_Release

    3 | &CalculatorSample::__cli_GetIids
    4 | &CalculatorSample::__cli_GetRuntimeClassName
    5 | &CalculatorSample::__cli_GetTrustLevel

    6 | &CalculatorSample::

    __cli_CppWinRTComponentDll___ICalculatorSamplePublicNonVirtuals____cli_Add

     

    Coming to the calculator class, you notice CalculatorSample is of size 12. The first vprt we have is ICalculatorSamplePublicNonVirtuals and then we have vprt to Object and then the ref count.

    class CalculatorSample size(12):
    +—
    | +— (base class __ICalculatorSamplePublicNonVirtuals)
    | | +— (base class Object)
    0 | | | {vfptr}
    | | +—
    | +—
    | +— (base class Object)
    4 | | {vfptr}
    | +—
    8 | __cli_MultiThreadedRefCount __cli_refcount
    +—

    If we analyze the first vptr, it points to ICalculatorSamplePublicNonVirtuals. The layout of the interface is as follows. The first 3 methods are for IUnknown and the other 3 are IInspectable. Notice 6 and 7 are referencing the Add method we wrote in the DLL. There are here for a reason. No 7 is to support compile time inheritance. The C++ can directly call into C++.

    CalculatorSample::$vftable@__ICalculatorSamplePublicNonVirtuals@:
    | &CalculatorSample_meta
    | 0
    0 | &CalculatorSample::__cli_QueryInterface
    1 | &CalculatorSample::__cli_AddRef
    2 | &CalculatorSample::__cli_Release
    3 | &CalculatorSample::__cli_GetIids
    4 | &CalculatorSample::__cli_GetRuntimeClassName
    5 | &CalculatorSample::__cli_GetTrustLevel
    6 | &CalculatorSample::__cli_CppWinRTComponentDll___ICalculatorSamplePublicNonVirtuals____cli_Add
    7 | &CalculatorSample::Add

    To understand more, let us use the compiler option. right click on WinRTComponent.cpp and add /d1ZWtokens as shown below and compile the WinRTComponent.cpp class.

    image

    In the output window, search for __cli_CppWinRTComponentDll___ICalculatorSamplePublicNonVirtuals____cli_Add and see the inline code generated by the compiler. This gives us a better understanding of the inner workings of calling the WinRT components.

     

    1>—— Build started: Project: CppWinRTComponentDll, Configuration: Debug Win32 ——
    1>  WinRTComponent.cpp
    1>  Declaring Member 2: __ICalculatorSamplePublicNonVirtuals::Add (int __cdecl CppWinRTComponentDll::__ICalculatorSamplePublicNonVirtuals::Add(int,int)). [isVirtual=1 isPure=0 isStatic=0]
    1> 
    1>  Declaring Member 2: __ICalculatorSamplePublicNonVirtuals::__cli_Add (long __stdcall CppWinRTComponentDll::__ICalculatorSamplePublicNonVirtuals::__cli_Add(int,int,int *)). [isVirtual=1 isPure=1 isStatic=0]
    1> 
    1>  Declaring Member 4a: CalculatorSample::__cli_refcount
    1> 
    1>  Declaring Member 2: CalculatorSample::__cli_QueryInterface (long __stdcall CppWinRTComponentDll::CalculatorSample::__cli_QueryInterface(class Platform::Guid %,void **)). [isVirtual=0 isPure=0 isStatic=0]
    1> 
    1>  Declaring Member 2: CalculatorSample::__cli_AddRef (unsigned long __stdcall CppWinRTComponentDll::CalculatorSample::__cli_AddRef(void)). [isVirtual=0 isPure=0 isStatic=0]
    1> 
    1>  Declaring Member 2: CalculatorSample::__cli_Release (unsigned long __stdcall CppWinRTComponentDll::CalculatorSample::__cli_Release(void)). [isVirtual=0 isPure=0 isStatic=0]
    1> 
    1>  Declaring Member 2: CalculatorSample::__cli_GetIids (long __stdcall CppWinRTComponentDll::CalculatorSample::__cli_GetIids(unsigned long *,class Platform::Guid **)). [isVirtual=0 isPure=0 isStatic=0]
    1> 
    1>  Declaring Member 2: CalculatorSample::__cli_GetRuntimeClassName (long __stdcall CppWinRTComponentDll::CalculatorSample::__cli_GetRuntimeClassName(struct __cli_HSTRING__ **)). [isVirtual=0 isPure=0 isStatic=0]
    1> 
    1>  Declaring Member 2: CalculatorSample::__cli_GetTrustLevel (long __stdcall CppWinRTComponentDll::CalculatorSample::__cli_GetTrustLevel(enum __cli_TrustLevel *)). [isVirtual=0 isPure=0 isStatic=0]
    1> 
    1>  Declaring Member 2: CalculatorSample::__cli_CppWinRTComponentDll___ICalculatorSamplePublicNonVirtuals____cli_Add (long __stdcall CppWinRTComponentDll::CalculatorSample::__cli_CppWinRTComponentDll___ICalculatorSamplePublicNonVirtuals____cli_Add(int,int,int *)=long __stdcall CppWinRTComponentDll::__ICalculatorSamplePublicNonVirtuals::__cli_Add(int,int,int *)). [isVirtual=1 isPure=0 isStatic=0]
    1> 
    1>  Declaring Member 2: IActivationFactory::__cli_ActivateInstance (long __stdcall Platform::IActivationFactory::__cli_ActivateInstance(class Platform::Object ^*)). [isVirtual=1 isPure=1 isStatic=0]
    1> 
    1>  Declaring Member 2: __CalculatorSampleActivationFactory::ActivateInstance (class Platform::Object ^__thiscall CppWinRTComponentDll::__CalculatorSampleActivationFactory::ActivateInstance(void)). [isVirtual=1 isPure=0 isStatic=0]
    1> 
    1>  Declaring Member 2: __CalculatorSampleActivationFactory::CreateFactory (long __stdcall CppWinRTComponentDll::__CalculatorSampleActivationFactory::CreateFactory(unsigned int *,struct __cli___classObjectEntry *,class Platform::Guid %,struct __cli_IUnknown **)). [isVirtual=0 isPure=0 isStatic=1]
    1> 
    1>  Declaring Member 2: __CalculatorSampleActivationFactory::GetTargetClassName (const wchar_t *__stdcall CppWinRTComponentDll::__CalculatorSampleActivationFactory::GetTargetClassName(void)). [isVirtual=0 isPure=0 isStatic=1]
    1> 
    1>  Declaring Member 4a: __CalculatorSampleActivationFactory::__cli_refcount
    1> 
    1>  Declaring Member 2: __CalculatorSampleActivationFactory::__cli_QueryInterface (long __stdcall CppWinRTComponentDll::__CalculatorSampleActivationFactory::__cli_QueryInterface(class Platform::Guid %,void **)). [isVirtual=0 isPure=0 isStatic=0]
    1> 
    1>  Declaring Member 2: __CalculatorSampleActivationFactory::__cli_AddRef (unsigned long __stdcall CppWinRTComponentDll::__CalculatorSampleActivationFactory::__cli_AddRef(void)). [isVirtual=0 isPure=0 isStatic=0]
    1> 
    1>  Declaring Member 2: __CalculatorSampleActivationFactory::__cli_Release (unsigned long __stdcall CppWinRTComponentDll::__CalculatorSampleActivationFactory::__cli_Release(void)). [isVirtual=0 isPure=0 isStatic=0]
    1> 
    1>  Declaring Member 2: __CalculatorSampleActivationFactory::__cli_GetIids (long __stdcall CppWinRTComponentDll::__CalculatorSampleActivationFactory::__cli_GetIids(unsigned long *,class Platform::Guid **)). [isVirtual=0 isPure=0 isStatic=0]
    1> 
    1>  Declaring Member 2: __CalculatorSampleActivationFactory::__cli_GetRuntimeClassName (long __stdcall CppWinRTComponentDll::__CalculatorSampleActivationFactory::__cli_GetRuntimeClassName(struct __cli_HSTRING__ **)). [isVirtual=0 isPure=0 isStatic=0]
    1> 
    1>  Declaring Member 2: __CalculatorSampleActivationFactory::__cli_GetTrustLevel (long __stdcall CppWinRTComponentDll::__CalculatorSampleActivationFactory::__cli_GetTrustLevel(enum __cli_TrustLevel *)). [isVirtual=0 isPure=0 isStatic=0]
    1> 
    1>  Declaring Member 2: __CalculatorSampleActivationFactory::__cli_Platform_IActivationFactory____cli_ActivateInstance (long __stdcall CppWinRTComponentDll::__CalculatorSampleActivationFactory::__cli_Platform_IActivationFactory____cli_ActivateInstance(class Platform::Object ^*)=long __stdcall Platform::IActivationFactory::__cli_ActivateInstance(class Platform::Object ^*)). [isVirtual=1 isPure=0 isStatic=0]
    1> 
    1>  inline function header symbol: {ctor}
    1> 
    1>  {
    1> 
    1>   
    1> 
    1>  }
    1> 
    1>  inline function header symbol: {ctor}
    1> 
    1>  {
    1> 
    1>   
    1> 
    1>  }
    1>  <TokenStream>
    1> 
    1>  namespace CppWinRTComponentDll
    1> 
    1>  {
    1> 
    1>   inline int :: CppWinRTComponentDll :: __ICalculatorSamplePublicNonVirtuals :: Add ( int x , int y )
    1> 
    1>    {
    1> 
    1>      int __cli_returnValue ;
    1> 
    1>      long __hr = __cli_Add ( x , y , & __cli_returnValue ) ;
    1> 
    1>      __cli_WinRTThrowError ( __hr ) ;
    1> 
    1>      return __cli_returnValue ;
    1> 
    1>     
    1> 
    1>    }
    1> 
    1>   
    1> 
    1>  }
    1>  </TokenStream>
    1> 
    1>  <TokenStream>
    1> 
    1>  namespace CppWinRTComponentDll
    1> 
    1>  {
    1> 
    1>    inline long __stdcall :: CppWinRTComponentDll :: CalculatorSample :: __cli_CppWinRTComponentDll___ICalculatorSamplePublicNonVirtuals____cli_Add ( int x , int y , int * __cli_returnValue )
    1> 
    1>    {
    1> 
    1>      long __hr = 0 ;
    1> 
    1>      * __cli_returnValue = 0 ;
    1> 
    1>      try
    1> 
    1>      {
    1> 
    1>        auto __tempValue = Add ( x , y ) ;
    1> 
    1>        * __cli_returnValue = __tempValue ;
    1> 
    1>       
    1> 
    1>      }
    1> 
    1>      catch ( :: Platform :: Exception ^ __param0 )
    1> 
    1>      {
    1> 
    1>        __hr = __param0 -> HResult ;
    1> 
    1>       
    1> 
    1>      }
    1> 
    1>      catch ( … )
    1> 
    1>      {
    1> 
    1>        __hr = -2147467259 ;
    1> 
    1>       
    1> 
    1>      }
    1> 
    1>      return __hr ;
    1> 
    1>     
    1> 
    1>    }
    1>
     
    1>   
    1> 
    1>  }
    1>  </TokenStream>
    1> 
    1>  <TokenStream>
    1> 
    1>  namespace CppWinRTComponentDll
    1> 
    1>  {
    1> 
    1>    long :: CppWinRTComponentDll :: CalculatorSample :: __cli_QueryInterface ( class Platform::Guid % __param0 , void ** __param1 )
    1> 
    1>    {
    1> 
    1>      if ( __param0 . Equals ( __uuidof ( __cli_IUnknown ) ) || __param0 . Equals ( __uuidof ( __cli_IInspectable ) ) || __param0 . Equals ( __uuidof ( struct CppWinRTComponentDll::__ICalculatorSamplePublicNonVirtuals ^ ) ) )
    1> 
    1>      {
    1> 
    1>        * __param1 = reinterpret_cast < void * > ( static_cast < struct CppWinRTComponentDll::__ICalculatorSamplePublicNonVirtuals ^ > ( this ) ) ;
    1> 
    1>        __cli_refcount . Increment ( ) ;
    1> 
    1>        return 0 ;
    1> 
    1>       
    1> 
    1>      }
    1> 
    1>      return -2147467262 ;
    1> 
    1>     
    1> 
    1>    }
    1> 
    1>    unsigned long :: CppWinRTComponentDll :: CalculatorSample :: __cli_AddRef ( )
    1> 
    1>    {
    1> 
    1>      long __cli_returnValue = __cli_refcount . Increment ( ) ;
    1> 
    1>      return ( unsigned long ) __cli_returnValue ;
    1> 
    1>     
    1> 
    1>    }
    1> 
    1>    unsigned long :: CppWinRTComponentDll :: CalculatorSample :: __cli_Release ( )
    1> 
    1>    {
    1> 
    1>      long __cli_returnValue = __cli_refcount . Decrement ( ) ;
    1> 
    1>      if ( ! __cli_returnValue )
    1> 
    1>      {
    1> 
    1>        delete this ;
    1> 
    1>        :: Platform :: Heap :: Free ( reinterpret_cast < void * > ( this ) ) ;
    1> 
    1>       
    1> 
    1>      }
    1> 
    1>      return ( unsigned long ) __cli_returnValue ;
    1> 
    1>     
    1> 
    1>    }
    1> 
    1>    long :: CppWinRTComponentDll :: CalculatorSample :: __cli_GetIids ( unsigned long * __param0 , class Platform::Guid ** __param1 )
    1> 
    1>    {
    1> 
    1>      struct __s_GUID __interfaceList [ ] =
    1> 
    1>      {
    1> 
    1>       
    1> 
    1>        {
    1> 
    1>          -1302793136 , 5274 , 13110 , 160 , 43 , 249 , 241 , 108 , 73 , 159 , 212
    1> 
    1>        }
    1> 
    1>       
    1> 
    1>      } ;
    1> 
    1>     
    1> 
    1>      return __winRT :: __winRTRuntime . __getIids ( 1 , __param0 , __interfaceList , __param1 ) ;
    1> 
    1>     
    1> 
    1>    }
    1> 
    1>    long :: CppWinRTComponentDll :: CalculatorSample :: __cli_GetRuntimeClassName ( struct __cli_HSTRING__ ** __param0 )
    1> 
    1>    {
    1> 
    1>      return __winRT :: __winRTRuntime . __windowsCreateString ( ( const wchar_t * ) L"CppWinRTComponentDll.CalculatorSample" , 37 , __param0 ) ;
    1> 
    1>     
    1> 
    1>    }
    1> 
    1>    long :: CppWinRTComponentDll :: CalculatorSample :: __cli_GetTrustLevel ( enum __cli_TrustLevel * __param0 )
    1> 
    1>    {
    1> 
    1>      * __param0 = __cli_FullTrust ;
    1> 
    1>      return 0 ;
    1> 
    1>     
    1> 
    1>    }
    1> 
    1>   
    1> 
    1>  }
    1>  </TokenStream>
    1> 
    1>  <TokenStream>
    1> 
    1>  namespace Platform
    1> 
    1>  {
    1> 
    1>    inline class Platform::Object ^ :: Platform :: IActivationFactory :: ActivateInstance ( )
    1> 
    1>    {
    1> 
    1>      class Platform::Object ^ __cli_returnValue ;
    1> 
    1>      long __hr = __cli_ActivateInstance ( & __cli_returnValue ) ;
    1> 
    1>      __cli_WinRTThrowError ( __hr ) ;
    1> 
    1>      return __cli_returnValue ;
    1> 
    1>     
    1> 
    1>    }
    1> 
    1>   
    1> 
    1>  }
    1>  </TokenStream>
    1> 
    1>  <TokenStream>
    1> 
    1>  namespace CppWinRTComponentDll
    1> 
    1>  {
    1> 
    1>    inline long __stdcall :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: __cli_Platform_IActivationFactory____cli_ActivateInstance ( class Platform::Object ^* __cli_returnValue )
    1> 
    1>    {
    1> 
    1>      long __hr = 0 ;
    1> 
    1>      * __cli_returnValue = nullptr ;
    1> 
    1>      try
    1> 
    1>      {
    1> 
    1>        auto __tempValue = ActivateInstance ( ) ;
    1> 
    1>        * __cli_returnValue = __tempValue ;
    1> 
    1>       
    1> 
    1>      }
    1> 
    1>      catch ( :: Platform :: Exception ^ __param0 )
    1> 
    1>      {
    1> 
    1>        __hr = __param0 -> HResult ;
    1> 
    1>       
    1> 
    1>      }
    1> 
    1>      catch ( … )
    1> 
    1>      {
    1> 
    1>        __hr = -2147467259 ;
    1> 
    1>       
    1> 
    1>      }
    1> 
    1>      return __hr ;
    1> 
    1>     
    1> 
    1>    }
    1> 
    1>   
    1> 
    1>  }
    1>  </TokenStream>
    1> 
    1>  <TokenStream>
    1> 
    1>  namespace CppWinRTComponentDll
    1> 
    1>  {
    1> 
    1>    long :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: __cli_QueryInterface ( class Platform::Guid % __param0 , void ** __param1 )
    1> 
    1>    {
    1> 
    1>      if ( __param0 . Equals ( __uuidof ( __cli_IUnknown ) ) || __param0 . Equals ( __uuidof ( __cli_IInspectable ) ) || __param0 . Equals ( __uuidof ( struct Platform::IActivationFactory ^ ) ) )
    1> 
    1>      {
    1> 
    1>        * __param1 = reinterpret_cast < void * > ( static_cast < struct Platform::IActivationFactory ^ > ( this ) ) ;
    1> 
    1>        __cli_refcount . Increment ( ) ;
    1> 
    1>        return 0 ;
    1> 
    1>       
    1> 
    1>      }
    1> 
    1>      return -2147467262 ;
    1> 
    1>     
    1> 
    1>    }
    1> 
    1>    unsigned long :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: __cli_AddRef ( )
    1> 
    1>    {
    1> 
    1>      long __cli_returnValue = __cli_refcount . Increment ( ) ;
    1> 
    1>      return ( unsigned long ) __cli_returnValue ;
    1> 
    1>     
    1> 
    1>    }
    1> 
    1>    unsigned long :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: __cli_Release ( )
    1> 
    1>    {
    1> 
    1>      long __cli_returnValue = __cli_refcount . Decrement ( ) ;
    1> 
    1>      if ( ! __cli_returnValue )
    1> 
    1>      {
    1> 
    1>        delete this ;
    1> 
    1>        :: Platform :: Heap :: Free ( reinterpret_cast < void * > ( this ) ) ;
    1> 
    1>       
    1> 
    1>      }
    1> 
    1>      return ( unsigned long ) __cli_returnValue ;
    1> 
    1>     
    1> 
    1>    }
    1> 
    1>    long :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: __cli_GetIids ( unsigned long * __param0 , class Platform::Guid ** __param1 )
    1> 
    1>    {
    1> 
    1>      struct __s_GUID __interfaceList [ ] =
    1> 
    1>      {
    1> 
    1>       
    1> 
    1>        {
    1> 
    1>          53 , 0 , 0 , 192 , 0 , 0 , 0 , 0 , 0 , 0 , 70
    1> 
    1>        }
    1> 
    1>       
    1> 
    1>      } ;
    1> 
    1>     
    1> 
    1>      return __winRT :: __winRTRuntime . __getIids ( 1 , __param0 , __interfaceList , __param1 ) ;
    1> 
    1>     
    1> 
    1>    }
    1> 
    1>    long :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: __cli_GetRuntimeClassName ( struct __cli_HSTRING__ ** __param0 )
    1> 
    1>    {
    1> 
    1>      return __winRT :: __winRTRuntime . __windowsCreateString ( ( const wchar_t * ) L"CppWinRTComponentDll.__CalculatorSampleActivationFactory" , 56 , __param0 ) ;
    1> 
    1>     
    1> 
    1>    }
    1> 
    1>    long :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: __cli_GetTrustLevel ( enum __cli_TrustLevel * __param0 )
    1> 
    1>    {
    1> 
    1>      * __param0 = __cli_FullTrust ;
    1> 
    1>      return 0 ;
    1> 
    1>     
    1> 
    1>    }
    1> 
    1>   
    1> 
    1>  }
    1>  </TokenStream>
    1> 
    1>  <TokenStream>
    1> 
    1>  namespace CppWinRTComponentDll
    1> 
    1>  {
    1> 
    1>    class Platform::Object ^ :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: ActivateInstance ( )
    1> 
    1>    {
    1> 
    1>      return gcnew class CppWinRTComponentDll::CalculatorSample ( ) ;
    1> 
    1>     
    1> 
    1>    }
    1> 
    1>   
    1> 
    1>  }
    1>  </TokenStream>
    1> 
    1>  <TokenStream>
    1> 
    1>  namespace CppWinRTComponentDll
    1> 
    1>  {
    1> 
    1>    long __stdcall :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: CreateFactory ( unsigned int * , struct __cli___classObjectEntry * , class Platform::Guid % __param2 , struct __cli_IUnknown ** __param3 )
    1> 
    1>    {
    1> 
    1>      class CppWinRTComponentDll::__CalculatorSampleActivationFactory ^ __pActivationFactory = gcnew :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory ( ) ;
    1> 
    1>      return __pActivationFactory -> __cli_QueryInterface ( __param2 , reinterpret_cast < void ** > ( __param3 ) ) ;
    1> 
    1>     
    1> 
    1>    }
    1> 
    1>    const wchar_t * __stdcall :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: GetTargetClassName ( )
    1> 
    1>    {
    1> 
    1>      return L"CppWinRTComponentDll.CalculatorSample" ;
    1> 
    1>     
    1> 
    1>    }
    1> 
    1>   
    1> 
    1>  }
    1>  </TokenStream>
    1> 
    1>  <TokenStream>
    1> 
    1>  namespace CppWinRTComponentDll
    1> 
    1>  {
    1> 
    1>    const struct __cli___classObjectEntry __CalculatorSampleActivationFactory_Registration =
    1> 
    1>    {
    1> 
    1>      :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: CreateFactory , :: CppWinRTComponentDll :: __CalculatorSampleActivationFactory :: GetTargetClassName , nullptr , & __cli_no_factory_cache , nullptr
    1> 
    1>    } ;
    1> 
    1>   
    1> 
    1>    extern "C" __declspec ( allocate ( "minATL$__r" ) ) __declspec ( selectany ) const :: __cli___classObjectEntry * const CppWinRTComponentDll___CalculatorSampleActivationFactory__Entry = & __CalculatorSampleActivationFactory_Registration ;
    1> 
    1>   
    1> 
    1>  }
    1>  </TokenStream>
    1> 
    ========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

     

    The complete code of MainPage.xaml.cpp is as follows.

    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 new  CalculatorSample();
        //txtAddResult->Text = calcobj->Add(10,20).ToString();

        //// declare a stack variable to hold the value of the result
        int result;
        //call into  calc object low level __cli_Add() but no intellisense in this preview
        //HRESULT hr = calcobj->__cli_Add(10,20,&result);

        //create a c function that actually represent an ABI call we will be making
        //to add function which takes this pointer, 2 input parameters and an out parameter.
        typedef HRESULT (__stdcall* AddFunc_t) (CalculatorSample^ calc, int i, int j, int * result);
        //now we can take the calculator^ object, which is a pointer to a pointer to a vtable
        //and reinterpret cast it so that it can say ok now i have a pointer of  virtual function
        //which are vtables and i am going to specifically pick the sixth function of that and call into it.
        //reinterpret_cast takes the calcobj ^ and cast it to a pointer to a pointer
        AddFunc_t* addFunc = *reinterpret_cast<AddFunc_t**>(calcobj);
        addFunc[6](calcobj,10,20, &result);

        ////CalculatorSample^ calcobj = ref new CalculatorSample();
        ////int* vtable_array = (int*)calcobj;
        ////int* icalc_vtable = (int*)vtable_array[0];
        ////int* compute_will_be_fptr = (int*)icalc_vtable[6];
        ////typedef HRESULT (__stdcall *compute_fptr_t)(CalculatorSample^, int, int, int*);
        ////compute_fptr_t compute_fptr = (compute_fptr_t)compute_will_be_fptr;
        ////compute_fptr(calcobj,10,20, &result);

        txtAddResult->Text = result.ToString();
    }

    MainPage::~MainPage()
    {
    }

     

    Download the source code from here.

    "If you limit your choices only to what seems possible or reasonable, you disconnect yourself from what you truly want, and all that is left is a compromise."

    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