New video episode on MSDN about activation pitfalls with WinRT

I have to apologize for the delay to publish the third and last part of my Interprocess Communication posts: it should be out next week.

However, I had valid reasons: I was preparing the new episode of the series that Robert Evans started two weeks ago. I’m detailing both in text and video how to avoid a few pitfalls related to multiple activations with WinRT.

I hope this helps.

Posted in .NET, C#, Store App, WinRT | Tagged , , , , | Leave a comment

Inter-Process communication with protocol association in WinRT – Part 3

The previous post presented how file association is used to exchange information between Windows Store Apps (WSAs) and Desktop Apps (DAs). The same kind of feature can be provided by the protocol association.

WARNING: all these techniques are violating the point 3.1 from the Windows Store Requirements that states: “Your app may only depend on software listed in the Windows Store“. Therefore, you should not use them for a WSA that you plan to publish into the Windows Store because it will be rejected.

How to activate another application?

From a WSA, the Launcher.LaunchUriAsync method activates another application that is associated to a given protocol.

The LauncherOptions is set to avoid unnecessary popup to the end user.

LauncherOptions options = new LauncherOptions();
options.DisplayApplicationPicker = false;
options.TreatAsUntrusted = false;
// See Mainform.cs for the details of the daipp protocol syntax
Uri uri = new Uri("daipp://...");
bool success = await Launcher.LaunchUriAsync(uri, options);

The uri format must follow the usual url rules or you’ll get a System.UriFormatException with “Invalid URI: The hostname could not be parsed” as a reason. For example
ProtocolInvalidFormat
will fail because there is no initial host name.

I’m using the command to be parsed by the activated application as the hostname:
ProtocolUriFormat
The parameters are then passed as value pairs with the same format as a query string. Spaces are supported but values and parameter names should not contain the ‘=’ character.

In the DA case, the Process.Start method activates the associated application:
Process p = Process.Start(string.Format("saipp://{0}", answer));

Unfortunately, the returned Process instance is always null… Does it means that it is impossible to figure out if something went wrong? Not always. You know when the WSA associated with the protocol does not start fast enough because a Win32Exception is thrown by Process.Start.
ExceptionWhenWSADoesNotStartQuicklyEnough

For other weird errors such as crashes in the activated WSA, another WinException will be thrown but this time with a remote procedure call failure.
ExceptionWhenWSACrashes

If you want to test a protocol, simply use the Run dialog box that pops up when you hit WIN+R.
RunWeatherProtocol

When you type the bingweather protocol, guess what? The Windows Weather WSA will be activated! This is the basics to build shortcuts to well-known installed Windows WSA and read this post for more détails.

How to associate an application to a custom protocol?

As with file extension, a WSA registers a protocol in its manifest via the Déclarations section
WSAProtocolDeclarationManifest

Without any surprise, a DA registers a custom protocol in the Registry under HKEY_CLASSES_ROOT and the protocol name
DAProtocolRegistryAssociation
The default value of the “command” subkey points to the command line to execute.

How to handle application activation?

When a WSA gets activated, the OnActivated override of its Application-derived class is called. The received IActivatedEventArgs parameter provides an ActivationKind information via the Kind property with Protocol as value. In that particular case, the argument should be cast into ProtocolActivatedEventArgs to access the expected Uri
ProtocolActivatedEventArgs
This Uri type comes from WinRT, not from the BCL.

The WIN+R Run dialog box helps you to test your uri values
ProtocolWithSPACE
In that case, the received Uri looks like the following under the debugger:
UriUnderDebugger

The Host and LocaPath properties are your friends because they have been url-decoded, unlike the AbsolutePath and AbsoluteUri properties. There is a gotcha if the uri is not well-formed: when you try to access the Uri property of the activation argument override, a System.UriFormatException is raised without any chance to get access to the original string uri. Even worse, as explained in MSDN, this exception is not available for WSA. As a consequence, you need to catch the base class FormatException to detect such a case.

For a DA, the uri is passed via the command line
DAProtocolActivationUri
without any need to uri-decode the string. The Environment.CommandLine property starts with the process pathname surrounded by quotes followed by a space and the protocol query string.

Use a query string Luke!

The two commands the DA provides via the custom protocol will start a DA like Notepad.exe or activate a WSA. As the previous examples have shown, the best way to define you’re a protocol is to use a query string-based syntax. Unlike Bing Map, it won’t be too complicated because only a few parameters are needed.

Activate a WSA from a DA

ActivateCommandDescription
This code is first checking if the given WSA identity is installed on the machine by leveraging the PackageManager type exposed by WinRT. This code has already been detailed in one of my posts where I described how to call WinRT API from a DA.

The WinRT API can’t help for the activation part but, hopefully, the Windows SDK exposes in ShObjIdl.h the signatures and GUID necessary to activate a WSA as described in http://msdn.microsoft.com/en-us/library/windows/desktop/hh706902(v=vs.85).aspx.

The complicated part is to build the first parameter of the ApplicationActivationManager.ActivateApplication method. We are lucky that the Package returned by the WinRT PackageManager provides exactly what we need as shown in the following code:
ActivateWSAwithWinRT

Start a DA from a DA

StartCommandDescription
This one is very easy to implement thanks to the Process.Start method method that accepts the executable as a parameter.

Download source code for WSA and DA

The next and last post of the series will discuss advanced communication scenario such as silent communication, without switching the user between the Modern UI world and the Desktop world.

Posted in .NET, C#, Metro, Store App, WinRT | Tagged , , , , , | 5 Comments

Inter-Process Communication with file association in WinRT – Part 2

The previous post presented the WinRT Contracts that are available to exchange information between WSAs and WSAs/DAs. It is time to dig into the details of leveraging the file association feature of Windows to let one application activate another application.

FileActivationHighLevel

WARNING: all these techniques are violating the point 3.1 from the Windows Store Requirements that states: “Your app may only depend on software listed in the Windows Store“. Therefore, you should not use them for a WSA that you plan to publish into the Windows Store because it will be rejected.

Using file association to communicate between applications

In Windows, the file association mechanism allows automatic creation of a process to open a file based on its extension.

How to activate another application?

The first step is to figure out how to trigger the file-based activation. For a WSA, you simply need to create a file with the expected extension and pass the corresponding StorageFile object to the Launcher.LaunchFileAsync method and Windows does the rest. The other LauncherOptions parameter lets you decide if you want the confirmation dialog to appear.

UPDATE – 2013/03/09: If there is no application (either DA or WSA) associated to the file extension, the dialog will always popup, even if you did not ask for it.

FindStoreAppAssociatedToFileExtension

As you can see from the flyout, the end user is able to “look for an app in the Store” that would support the file extension. If there is no such an application, the search page will be empty

WindowsStoreSearchPerFileExtension

It is good to see that the Windows Store is able to find a WSA based on a file extension but you won’t be able to find a DA that way into the Store.

Last point to take into account when you try to activate another application via Launcher.LaunchFileAsync: this method will always return true even if no application was found locally or into the Store!


In my sample WSA, the file is created inside its local folder given by ApplicationData.Current.LocalFolder. I’ve first tried to create it in the user Document library folder but a WSA is allowed to create a file in this folder only if the file has an extension supported by the WSA itself… this is definitively not compatible with what I’m trying to achieve since the DA already handles the files with this extension and I don’t want that a confirmation dialog pops up to let the user pick which application should open the file!

In the case of a DA, you call CreateProcess with the filename as parameter. In both cases, you write the parameters you want to pass to the other application into the file.

How to associate an application to a file extension?

Both a WSA and a DA can register its execution with a file extension. The former requires changes in the manifest:

WSAFileTypeDeclarationManifest

The latter requires more work in the Registry:

DAFileTypeRegistryAssociation

As you can see, the registration happens in two places under HKEY_CLASSES_ROOT. The default value associated to the extension name (without forgetting the “dot” character) gives the name of the next key where to look at for the shell/open/command default value. This is where the command line to execute is defined: note the %1 used as placeholder for the command line corresponding to the filename that triggers the launch.

The DAFileAssociation project calls the AssociationRegistrationHelper.RegisterFileAssociation method that takes care of all the Registry setup. The returned enumeration value lets you know what happened

public enum AssociationRegistrationStatus
{
Created,
AlreadyExist,
DoesNotExist,
WrongRegistration,
SecurityFailure
}

The calling process must run under an elevated administrator account to update the Registry or the SecurityFailure value will be returned because the updated failed.

Last but not least, if you need to check that the file associations are correct on a machine, Control Panel is your friend via the WIN+X|Control Panel shortcut.

ControlPanel4FileAssociation

How to handle application activation?

The activation process will work but the activated WSA will have to carefully access the file. As you may know, a WSA is very restricted in term of file access: it is allowed to access a file without going through the File Picker if the capability corresponding to the containing folder (from Documents, Music and Pictures libraries) has been added into its manifest. As I just mentioned, there is another condition to open or create a file there: its extension must also be added into the Declarations section of the manifest. This is perfect for the WSA that we want to activate but not possible for another WSA because we don’t want to have both activated for the same type of file.

Hopefully, the OnFileActivated override from the Application-derived class allows you to access files without going through the File Picker. The FileActivatedEventArgs event argument provides two important parameters. Its string Verb property has the “open“ value in this kind of activation but other are supported such as print. The IReadOnlyList<Windows.Storage.IStorageItem> Files property lets you get to the list of files that activate the WSA. However, there is a trick here: only the pathname of a file is accessible by the IStorageItem interface via its Name or Path string property as shown in the MSDN documentation.

MSDNOnFileActivatedHelp

If you try to access the file by calling the StorageFile.GetFileFromPathAsync method passing the pathname, an UnauthorizedAccessException is thrown with AccessDenied.

The solution is to cast the IStorageItem into a StorageFile and use a stream/data reader pair to read the file content:

StorageFile sf = file as StorageFile;

if (sf!= null)

{

IRandomAccessStream stream = await sf.OpenAsync(FileAccessMode.Read);

DataReader reader = new DataReader(stream.GetInputStreamAt(0));

UInt32 size = await reader.LoadAsync((UInt32)stream.Size);

string content = reader.ReadString(reader.UnconsumedBufferLength);

}

For DA, the filename is available from Environment.CommandLine with the following format:

“C:\…\DaFileAssociation.exe” C:\Users\<user>\ AppData\Local\Packages\8fe887ce-3234-45e3-9f00-71c02429fd5f_2g303v4t3xrhw\LocalState\2269fc55-6189-4d9a-b2d9-3d45a5a095ee.daparams

The sample application code looks for the last “ character to extract the filename. In a DA, the limits to read the file contents do not exist and StreamReader.ReadToEnd() is your friend:

using (StreamReader sr = new StreamReader(filename))
{

String line = sr.ReadToEnd();

tbWorkload.Text = line;

}

What data to exchange?

The simple examples shown since the beginning of the post are exchanging plain text. It would be better to be able to exchange more structured data. If you try to use basic .NET serialization, you will find out that the binary serializer is not available for a WSA written in .NET; use my BCLDiff tool to have the complete list of missing types:

MissingSerializableAttributeWithBCLDiff

Fortunately, the DataContract-based serialization is usable from both sides which makes it a good candidate to exchange strongly typed objects. Then, you need to decide which formatter to use; for example Json could be used to exchange smaller payload than with XML. Also note that WinRT JsonArray and JsonObject types make it easy to manipulate and parse Json structures for a WSA, while a DA could use a JsonDataContractSerializer.

As you may know, there is no API for a WSA to change the Windows desktop wallpaper. However, Microsoft provides C# code sample to do so in a DA. The WSA built for this post allows the end user to use the webcam to take a picture and send the fill option with the image filename as a workload serialized in Json

ComplexDataWorkloadExchange

to the DA that use it to change the Windows wallpaper

ChangingDesktopWallpaperFromWSA

Download source code for the sample WSA and DA

The next post will describe how to achieve the same kind of features but with custom protocols.

Posted in .NET, C#, Store App, WinRT | Tagged , , , , , | 2 Comments

Inter-Process Communication with WinRT – Part 1

Since the pre-release of Windows 8 at the Microsoft BUILD conference in 2011, I’ve been investigating the different ways for a Windows Store App (WSA in the rest of the post) to interact with either other WSAs or Desktop Apps (DA in the rest of the post). Unlike .NET that was built from the beginning with interoperability in mind, WinRT is another beast.

A Microsoft collegue has been working on a WSA that makes it simple to deploy and launch applications in an enterprise environment (visit http://companystore.codeplex.com/ for more details). However, some actions are not allowed from a WSA such as looking for installed WSAs and launch them. This was a great opportunity to turn my research into real code. I’m sharing the outcome in a few blog posts starting with this one.

The WinRT API comes with well-defined contracts that let WSAs interact both with the system and with other WSAs. Note that the data and the user interface are strictly controlled in each case and DA are not eligible to be part of the dance (except for Clipboard):

  • Share: sort of Clipboard on steroid, a source App lets the user select data to be shared with other target WSAs via well-known formats (text, image, uri) or even custom schemas.
  • Search: WSAs receive textual input from the user via the Charm UI and provides feedbacks and recommendations; not usable to exchange data between applications.
  • File Picker: a “providing” WSA is able to show custom UI to the user in a “get a file“ workflow retrieved by a “calling” WSA; a sample from the Windows SDK is available.
    With this contract, you could easily imagine implementing a WSA that would provide a non-file oriented UI and return information via a file; this file would contains a documented set of data that would be parsed by the calling WSA. This is circumvented but totally feasible: for example, a WSA could implement the File Picker contract and let the user scan a bar code via a nice UI that drives the camera. The returning file would contains the bar code description in XML for example. You can see this kind of interaction as the opposite as the Share Contracts: the user is in the WSA where the information is needed and she accesses the source WSA via the File Picker Contract. The big limitation is the lack of parameter the calling WSA could pass to the providing WSA…
    Let’s be clear, this is not the way this contract is supposed to be used because the UI provided by the system is very FILE oriented, but… it works. Last but not least, a private file extension should be chosen to limit the number of choices automatically offered by the picker.
  • The usual Windows Clipboard is accessible for WSAs via the same DataPackage and DataPackageView types used by the Share Contract. The corresponding guidelines are available on MSDN.

As you can see, all these solutions are limited compared to the other kinds of inter-process interaction available to Windows Desktop Applications such as COM interop, Dll-based API, sockets or Web Service calls. Even though sockets and web service calls are allowed for WSA, there is no way to make them work toward an end point on the same machine (except during development for testing purpose).

Is it possible to go beyond the new contracts? Well… To allow WSAs and DAs to communicate, it is still possible to use two mechanisms that existed for a very long time in the Windows Shell and that are supported by WinRT: file and protocol associations. Both associations allow either a WSA or a DA to start a WSA/DA with parameters: file(s) for the former and url for the latter. The next post will dig into the details of the file association.

Posted in .NET, C#, Metro, Store App, WinRT | Tagged , , , , , , , | 4 Comments

BUILD conference session about Windows Store Apps and WinRT

While I’m finishing a post about Inter-Process Communication in WinRT, here is a list of sessions related to Windows Store Application for those who were not lucky enough to attend the last BUILD conference in Redmond. For each, you’ll find the Powerpoint presentation and the videos from the Channel9 site.


UI Design

The Microsoft design language

Tips on self-evaluating the UX of your appTips on self-evaluating the UX of your app

Guidance for shopping apps


WinRT

Developing a Windows Store app

Windows Store: how does it work?

1+1=3: Using app contracts to integrate with Windows 8 experiences

Alive with activity: tiles, notifications, and background tasks

The story of state: AppData, settings, and the process lifecycle

The Windows Runtime Q&A

Tips and tricks for developing connected applications

Building mixed-language apps

Building Windows 8 LOB apps

Touchscreen and stylus and mouse, oh my!

Analytics for Windows Store apps

The developer’s guide to the SkyDrive API

Windows 8 Connectathon with Windows Azure Mobile Services

Building Rich Media Applications on Windows 8 with Windows Azure Media Services

Using media extensions to build great video playback apps

Designing rich media scenarios in your Windows Store app

Key technologies for building advanced media apps

Security in Windows Store apps

Bing Maps for Windows apps

Graphics at the core of Windows 8 and your app

Core technologies for Windows 8 games

Powering your apps with Microsoft accounts

Xbox Live on Windows 8 Deep Dive

Key technologies for shopping apps

Key technologies for Windows Store business apps

Shopping app case studies

Making money with your app on the Windows Store

Monetizing your Windows 8 app with advertising

Top tips for iOS devs building Windows Store apps

Developing, deploying, and monetizing Windows Store games with Unity


C#/XAML

Introduction to creating Windows Store apps using XAML

Performance tips for Windows Store apps using XAML

Building world-ready Windows Store apps with XAML

XAML list controls

Easy Asynchrony with C#: No More Callbacks!

Designing awesome XAML apps in Visual Studio and Blend for Windows 8 and Windows Phone 8

Tips for building a Windows Store app using XAML and C++: The Hilo project

How to Leverage your Code across WP8 and Windows 8 (Repeat)

Create Cross-platform Apps using Portable Class Libraries

Unit Testing Windows Store Apps

Happy watching!

Posted in .NET, C#, Metro, Store App, WinRT | Tagged , , , , , | 1 Comment

WSALs + Guidelines and Requirements for Windows Store Apps Development

During the past months, I’ve been involved in many Windows Store App reviews. This work is based on Microsoft guidelines and requirements that are scattered all over MSDN. This post provides a few links from which you will quickly find what you’re looking for during your development.

Before looking at these links and get lost into the guidelines, you should know that Microsoft organizes a program called the “Windows Store App Labs” where skilled engineers and designers are there to help you; both with all these guidelines but also with UI Design and technical questions you might have. It is also accessible if you want to update an already published App

You can directly register after you have selected your country on the map.
Don’t miss this free opportunity   :^)

From Design guides to Checklists

The first link to keep in your favorite points to the Windows 8 app certification
requirements page where mandatory implementation détails are listed. Failures in the Store validation report will points to the sections of this page. For example, one of the most important source of rejection from the Windows Store was the lack of Privacy Policy both during the Store submission but also at runtime from the Settings pane if the App requires Internet or network access.

Due to the high number of UI changes brought by Modern UI supported by Windows Store Apps, most of the guideline violations are related to User Experience requirements. The Index of UX guidelines for Windows Store apps and Make great Windows Store apps pages are where you should start your search: use them as a fast directory-like access to all UI features.

One of the first decision you have to make when you design your Windows Store App is to define the type of navigation that will be used by the user. The Navigation design for Windows Store apps page is a must read for the Design phase (a .pdf version is also available) as well as the Commanding design for Windows Store apps where all rules related to AppBar commands and errors presentation are detailed.

Beyond these Design guidelines, MSDN provides dual pages for WinRT features, one for Javascript/HTML and the other for CB/C#/C++/XAML. Even if you are interested only by your own technology stack, my recommandation would be to read both. That ways, you get a better understanding about what is expected. In addition, if you can’t read everything, focus on the Dos/Don’ts section: these are the most important for a successful Store validation.

In addition, you will find  a lot of guidelines and checklists related to each Modern UI sections. Each one also directly points to the related sample from the Windows SDK and interesting QuickStarts.

Guidelines and checklists

I hope this helps.

Posted in .NET, C#, Store App, WinRT | Tagged , , , | 2 Comments

ByeBye 1.1 for x64… and x32 now

I’ve been quiet for a long time on this blog because I was working hard on the Windows Store App workshop that Microsoft is now proposing to our Premier customers. Feel free to contact your local Microsoftee for more détails about this service.

With the first beta deliveries of this workshop, a x86 version of ByeBye was needed to demonstrate how Windows 8 automatically terminates Store Apps on 32 bit versions of the OS.

Here is the updated versions (both x86 and x64) without any “Metro” reference in the main window title.

I hope this helps.

Posted in C#, WinRT | Tagged , , , | Leave a comment