New video post about what’s new in Windows 8.1 for a C# developer

Live from //build conference at San Francisco,

CNS_4101

a new video post has been released to detail what the new features of Windows 8.1 Preview mean for a C# developer: don’t miss it!

 

I hope this helps

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

Listing Windows 8.1 Preview additions to WinRT

The Preview of Windows 8.1 has been released during the Microsoft //Build conference at San Francisco. Everyone is now able to download the Preview, update their machine and start to explore the new features with Visual Studio 2013 Preview.

How to list new WinRT types?

As a developer, I would highly recommend you to download the updated Windows 8.1 SDK Samples for a wide coverage of the new APIs. If, like me, you really want to get the exact list of the new types in WinRT, my WinmdDiff tool is for you!

WinmdDiff

I leverage the same unmanaged IMetaDataDispenser API that I used for my BCLDiff tool but Instead of loading managed .dll, .winmd files are loaded. As I explained in a previous post, these files contain the metadata that describes WinRT namespaces, types and members.

The Windows SDK installs one single windows.winmd file under C:\Program Files (x86)\Windows Kits\8.x\References\CommonConfiguration\Neutral\ with x either 0 for Windows 8 or 1 for Windows 8.1. However, you could also get the .winmd files installed with Windows under the Windows\System32\WinMetaData folder. Note that you could also use this tool with your own WinRT components.

When the Diff button is clicked, all .winmd files in the Old and New folders are loaded. The types that appear in the metadata files from the new folder but not from the old folder are kept and sorted under their corresponding namespaces. That way, you end up with the list of types that are new to Windows 8.1!

In addition to the windows.winmd file, the Windows SDK also installs a windows.xml file that contains the documentation of each namespace, type and member. The WinmdDiff tool parses this file to extract raw summary when possible and displays the text corresponding to the selected element.

I hope this helps.

Resources

Posted in .NET, C#, Store App, Windows 8, Windows 8.1, WinRT | Tagged , , , , , | 7 Comments

Suspend and Resume in WinRT – new video post!

The next episode of our Windows Store Apps Development series is out with a lot of video demos and code related to Suspend/Resume with WinRT.

Enjoy and see you soon at //build for Windows 8.1 Preview!

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

How to deploy a line of business app with Intune – new video available

The new episode of our Windows Store Developers video blog series is available: go and see a demo of Intune by one of the Program Manager to deploy line of business apps without going through the Store.

The next one will be out next week about Suspend/Resume tips and tricks.
You should expect more posts while I’ll be at /build    ;^)

Posted in Store App, WinRT | Tagged | Leave a comment

Inter-Process Silent Communication in WinRT – Part 4

The previous posts detailed how file and protocol associations allow Windows Store Apps and Desktop Apps to activate each other. There is one drawback in both mechanisms: the end user switches back and forth from Desktop and Modern UI mode when each application gets activated.

Let’s take a simple example: imagine that you want to build a calculator with a Modern UI that relies on a Desktop App to process the computations. The latter will implements a custom protocol/file association to receive the requests sent by the former. This WSA will implements its own custom protocol/file association to be notified back with the result of the processing. However, the screen will switch from the WSA to the DA when the request is sent and from the DA to the WSA when the computed result is send back. This is clearly not acceptable for the user.

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.

Silent activation architecture

The notion of “silent activation” behind the title of this post hides several technics required to let a WSA send requests to a DA without switching the user back and from between Modern UI and the Desktop.

  • The DA should be notified when the WSA creates a request but without leaving the Modern UI
  • The DA should run behind the scene and the WSA should know if this is not the case
  • The WSA should be notified when the DA has computed the result

Here is the solution I’m proposing for a line of business application

Silent Activation Architecture

  1. The DA registers a file system watcher for .wsaCalculator files in the WSA local data folder
  2. The WSA creates a .wsaCalculator file in its local application data and waits for the DA to process the request
  3. The DA activates the WSA and passes the request/result as a query string to its custom protocol
  4. The WSA has a timeout to detect if the DA is not processing requests

DA – How to detect that a request has been issued?

Because I don’t want the WSA to activate the DA in order to process a request, I need to find another way to communicate with it. I simply create a file with a specific extension into the WSA local data folder and wait for the result. Based on the package family name

Package Family Name In Manifest

I know where these files are stored on the file system:

C:\Users\<user>\AppData\Local\Packages\ChristopheNasarre.WSACalculator_2g303v4t3xrhw\LocalState

So, the DA creates a FileSystemWatcher to be notified when such a file gets created and then processes the request.

Why not creating the request files in the Documents library?  Well… I do not want to add garbage files without any meaning into the user folder; this is only implementation details that should not be visible to the user. In addition, the WSA would have needed to be associated to the extension without any good reason to be activated when the user double-click one of the files.

DA – How to send the result back to the WSA?

The request parameters are read one line after the other from the file by the DA which then executes the computation. The next step to send the result back to the WSA is easy: just activates it with its associated protocol and pass the request/result as a query string as shown in the previous post.

On the other side, the WSA receives the query string in the ProtocolActivatedEventArgs.Uri.Query passed to its application OnActivated override. The result is extracted from the string and the UI is updated accordingly. However, what if the DA never answers? The WSA will wait forever!

WSA – How to detect DA presence?

In order to avoid this kind of situation, you need to ensure that the DA runs. You could activate the DA when the WSA starts but with a UI glitch when Windows switches back and forth. It is also possible to ask Windows to automatically start the DA when the user logs in. However, it is still possible that the DA contains a bug that would end up to an unhandled exception and would be terminated by Windows. The simpler solution is to start a timer just after the request file is created and if it expires, the WSA knows that something went wrong.

You can see an implementation of this two steps request in MainPage.OnActivated where a “ping” request is created and a PeriodicTimer is started.

Timer For Timeout

The code triggered by the timer expiration runs in a worker thread from which it is not possible to update the UI. This is why it needs to be run asynchronously by the application dispatcher. This code tests whether or not the PingWasAnswered field has been set by the OnActivated application override.

Wrap-up – building an async/await kind of API with the RequestManager

This architecture is working fine but if you want to issues several different requests at the same time, it is just not scalable. Here is the kind of code I would like to write:

string result = await app._requestManager.SendRequestAsync(request);
if (result == null)
{
    // timeout
}
else
{
    // the DA processes the request and returns result
}

The RequestManager class implements a SendRequestAsync method that makes everything simple.

Request Manager Architecture

Each request has a guid that is used in two ways:

  1. as filename of the .wsaCalculator file that contains the parameters
  2. as a key in a dictionary to be able to map a request to the result computed by the DA when it will come back. In addition to the expected result, the RequestInfo associated to the key in the dictionary provides a ManualResetEvent EventToSignal property

The ManualResetEvent is created non-signalled and associated to the request in the dictionary. Next, the guid.wsaCalculator file is filled with the parameters to be processed by the DA. Instead of using a timer, the code simply waits for the event to be signalled or of the given timeout expires. Since I don’t want to freeze the UI thread by waiting for the event, this code is executed by a Task

bool hasTimedOut = await Task.Run<bool>(() => mre.WaitOne(Timeout));

When the DA activates the WSA with the result, the OnActivated override calls the CompleteRequest RequestManager method to find the RequestInfo associated to the processed request received in the query string of the custom protocol. The computation is stored in the Result property and the ManualResetEvent stored in the EventToSignal property is set to let the Task return false.

Last but not least, it is possible to register a handler to the RequestTimedOut and ResponseAfterTimeOut events. The former is called when a request has not been answered by the DA before the time expires and the latter runs if the DA answers after the timeout expires.

Simple isn’t it?

Download source code for DA and WSA

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

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 , , , , , | 6 Comments