Tag Archives: WinRT

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.

Advertisements

Windows8 Desktop Keyboard Shortcuts

Keyboard Shortcut

Details

Windows + I

Window Restart, Shutdown, Sleep, Taskbar Notification Icons like Network, Sound Control, Brightness, Notifications, Keyboard.

 

 

Windows + X

Menu for frequent Administrator Tasks

Windows + 0

Opens 10th application on taskbar with  Normal Privileges. You can use the following values for applications on Taskbar.

  1. 1st Application on taskbar of Classic Desktop View
  2. 2nd Application on taskbar of Classic Desktop View
  3. 3rd  Application on taskbar of Classic Desktop View
  4. 4th  Application on taskbar of Classic Desktop View
  5. 5th  Application on taskbar of Classic Desktop View
  6. 6th  Application on taskbar of Classic Desktop View
  7. 7th  Application on taskbar of Classic Desktop View
  8. 8th Application on taskbar of Classic Desktop View
  9. 9th  Application on taskbar of Classic Desktop View

You can rearrange your applications on taskbar  according your choice and priority to take advantage of this shortcut.

Windows + Ctrl + Shift + 0

Opens 10th application on taskbar with  Elevated Privileges. You can use the following values for applications on Taskbar.

  1. 1st Application on taskbar of Classic Desktop View
  2. 2nd Application on taskbar of Classic Desktop View
  3. 3rd  Application on taskbar of Classic Desktop View
  4. 4th  Application on taskbar of Classic Desktop View
  5. 5th  Application on taskbar of Classic Desktop View
  6. 6th  Application on taskbar of Classic Desktop View
  7. 7th  Application on taskbar of Classic Desktop View
  8. 8th Application on taskbar of Classic Desktop View
  9. 9th  Application on taskbar of Classic Desktop View

You can rearrange your applications on taskbar  according your choice and priority to take advantage of this shortcut.

Windows + C

This shortcut gives you view the Settings, Devices, Start, Share & Search. This is the same option that comes when you move the mouse to the extreme bottom right corner.

Ctrl + Shift + Esc

Task Manager

Windows  

Toggle between Modern Desktop & Legacy Desktop

Windows + D

Takes you to Legacy Windows Desktop.

If you press this key from the Modern Desktop, this takes you to the currently active application on the Legacy Desktop.

If you press this key from the Legacy Desktop, this displays the Desktop.

Pressing the same key combination, will Toggle Between the Legacy Desktop and Active Application on the Legacy Desktop

Only Legacy Desktop shown when all applications are in a minimized state

Windows + B

From the Modern Desktop, this takes you to the currently active application on the Legacy Desktop.

If all application are in minimized state on Legacy Desktop, this command will take you to the Legacy Desktop.

No effect when used from a Legacy Desktop.

Windows + M

From the Modern Desktop, this takes you to the Legacy Desktop and minimizes all applications on the  Legacy Desktop

When used from a Legacy Desktop, minimizes all applications.

If all application are in minimized state on Legacy Desktop, this command will take you to the Legacy  Desktop.

 

Windows + Q

Displays Apps windows with all apps and Search Bar

Windows + W

Displays Search Settings.

Windows + E

Windows Explorer displaying Computer Folder. Same as clicking on My Computer.

Windows + R

Display Run window.

Windows + T

Displays the Window Group Thumbnails on your taskbar. This is equivalent of hovering the mouse over the Taskbar Icons.

Each time you press the Windows + T combination, the next application group is  displayed

Windows + U

Displays Ease of Access Center

Windows + P

Option to Extend the display.

Windows + +

Zoom Windows

Windows + F

Search Files

Windows + H

Display Share options

Windows + K

Display Devices to Share with.

Windows + <

Preview Legacy Desktop

Windows + L

Lock the Computer

Can you use Windows 8 WinRT API from .NET Desktop applications?

Over the course of time I received a number of comments on my blog in this area. Many questions were asked like “Can you use WinRT from Desktop applications?”, “Can you use WinRT from .NET applications?”, etc..

Well, the answer is YES. It is possible to use WinRT from Desktop applications. WinRT APIs may be tied to Metro style apps, Desktop apps or potentially available to both. The documentation will list which environments (Desktop, Metro style or both) a given API works in.

Note: Custom WinRT components are only supported in Metro style applications. They are not supported in Desktop applications.

For ex, WinRT has an API for Accelerometer. The Accelerometer class represents an accelerometer sensor which returns G-force values with respect to the x, y, and z axes.

Namespace: Windows.Devices.Sensors namespace
Class: Accelerometer

If we open the API documentation at http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.sensors.accelerometer.aspx, see the section Applies to: Metro style apps | desktop apps. Which means this class works in Metro Apps as well as desktop apps.

image

Figure 1: MSDN documentation showing WinRT API and it’s applies to section.

WinRT from the eyes of a .NET developer

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

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

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

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

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

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

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

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

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

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

Under the hood Part 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.