Activating Windows 8 contracts in your app

One topic that we’ve demonstrated quite a bit is how apps on a Windows 8 PC can communicate with other apps and web services.  At the start of Windows 8 we chose an approach where apps can be the source or destination for data you want to share—sort of like a clipboard, but with a richer interaction model and clearer semantics. When an app implements a contract, Windows 8 can provide glue between that app and any other apps on the system, and the system itself. You can see this in action when you do something simple like use the Share charm from a web page in the Metro style Internet Explorer—you can share the link via the Mail app, with someone whose contact info you've stored in the People app, and so on. You can search across apps that implement the Search contract. You can open and save files from or to any location that implements the File Open and Save Picker contracts. This innovative approach allows Windows 8 to work with any app/service pair rather than “hardcoding” a single level of support for a given app.  And all of this is supported, if you choose, by your Microsoft account, which you can connect to different services, from Facebook to Twitter to LinkedIn and more.  Over the course of this week, we’ll do a series of posts on the new Microsoft apps, where sharing, connecting, and integration with Windows 8 are key topics. This is a repost of a developer-focused post from our Windows 8 App Developer blog and was authored by Derek Gebhard, a program manager on our User Experience team. --Steven

When you start writing Metro style apps you’ll quickly come across contracts, a new and powerful concept in Windows 8. Metro style apps use contracts to declare interactions they support with other apps and with Windows. You’ve probably already heard about some of them: search, share, etc. Using contracts, apps become better by working with the system or with each other when users install more apps that implement contracts. In this post I’ll walk you through activation, one of the main concepts to think about as you add contracts to your apps.
The Windows activation platform is used to launch Metro Style apps and to notify them of the reason why a user launched them. The reasons vary from a user starting the app using its tile on the start screen to the app being launched for a specific task such as showing a user search results for a query. Windows provides your app with the reason it was launched and if applicable any additional info needed to complete its task. Before our Windows 8 activation platform, you passed this info to apps via command-line parameters. With our new model, we also support passing live objects such as a StorageFile, ShareOperation, etc to provide the app with context. You’ll see that this makes contracts all the more powerful. Let’s jump into the details of what you need to know to support being launched for a contract.
[h=3]Contracts: Launching Metro style apps for a purpose and with context[/h] As you can see in the Windows 8 Consumer Preview demo, Windows 8 contracts are the glue that binds your app to other Metro style apps and to the system UI. For example, the File Open Picker contract allows the user to import files from one app into another. With the Search contract, users are empowered to search an app from anywhere in the system and can quickly transfer a query between multiple apps. In all of these cases, and a lot of other contract scenarios, Windows needs to be able to launch directly to a spot in your app’s UI where the user can complete a specific task quickly and efficiently. This is where our activation platform and API come into play.
Users initiate app interactions in one of two ways:

  1. Through an action that requires the app’s fully immersive view to be in the foreground. This is also called main view activation. An example is the Search contract.​

    7380.mainView3_5F00_2B5DACBC.jpg

    Example of main view activation
  2. Through an action that is hosted inline, without leaving the context of the currently running app. This is also called hosted view activation. Here are two examples, an app participating in the file picker and an app being used as a Share target.​
    2068.pickerHostedView3_5F00_200472B2.jpg

    Example of hosted view activation in the Picker


    Example of hosted view activation for Share targets
    The differences between these two are:
    Main view activation
    Hosted view activation
    Is fully immersive and launches as the main app on screen​
    Renders UI within system chrome​
    Can be used for potentially many different tasks​
    Is used for a short, directed task and code is focused solely on this task​
    Appears in the switch list​
    Never shows up in the switch list​
    Can be closed via the close gesture​
    Doesn’t change the view of the main window for the same app​
    So let’s look at these activation models and apply them to a couple of common scenarios that will help you build your great Metro style apps.
    [h=3]Scenario 1: Integrating Search activation in your app[/h] In Windows 8, adding search through the Search contract lets users search your app's content from anywhere in their system at any time. If your app is the main app on screen, users can search its content immediately by using the Search charm. Otherwise, users can select the Search charm and then pick your app from the list of apps in the Search pane to search it.
    Supporting Search activation means that your app can be launched at any time to show search results for a specific query. Just like being launched from the start screen, being launched from the Search pane falls under main view activation. So, if you support multiple contracts, your app can potentially be activated for many different scenarios. In addition, your app could end up receiving this activation when it is already running, because a user may want to repurpose your main view to handle a specific scenario like showing search results. To make this work, I recommend that you:
    • Delay loading of your code that isn’t essential to the main view contract your app is activated to handle.
    • Separate your general initialization logic that you use for all contracts from the logic that needs to be run for a specific contract.
    • Ensure that any code expected to run only one time at launch isn’t added into your activation handler in such a way that it can execute multiple times.
    • Reload any previous state and settings when being launched from a terminated state so that your app appears to the user as always running and connected.
    Check out the Store and Photos apps. They do a great job of following these recommendations when supporting Search activation.
    0576.storeAppSearch_5F00_thumb_5F00_7390686D.jpg
    Search in the Store app
     ​
    Search in the Photos app
    Let’s take a look at how you can support Search activation properly in your JavaScript and XAML apps.
    [h=3]JavaScript apps[/h] For JavaScript Metro style apps, activation is exposed through the WinJS.Application.onactivated event. This event is fired after DOMContentLoaded completes if the app isn’t already running or isn’t suspended. Otherwise, the event is fired as soon as Windows needs to activate the app. Visual Studio tooling for JavaScript apps takes care of setting up this event registration in default.js and provides an area where you can add code that will run when a generic launch activation occurs, that is when the user launches your app from the start screen.
    To extend support for Search activation in your app:
    1. Add the Search declaration to your manifest using the Visual Studio Manifest Designer.
    2. Place in your JavaScript’s global scope any general initialization code that needs to run every time your app is started irrespective of the reason. If any of this code needs to access the DOM, add the code in a DOMContentLoaded event handler.
    3. Register to handle being activated for Search.
    4. When your app is activated for Search, navigate to your search results page and pass in the queryText you get from the activation event arguments.
    If you are like me, you are probably looking for an easier way than doing this manually. Fortunately you can use Visual Studio tooling for completing most of this by right clicking your project, selecting Add > New Item, and choosing Search Contract in the dialog. Most of the code you see here, and a search UI that displays results in a way that follows our search ux guidelines is automatically created for you. But you must use the WinJS.Navigation framework with this tooling.
    Here is a code snippet from my photo app’s default.js file that shows support for Search activation:

    // Register activated event handler
    WinJS.Application.addEventListener("activated", function (eventObject) {
    ...
    if (eventObject.detail.kind === appModel.Activation.ActivationKind.launch) {
    ...
    } else if (eventObject.detail.kind === appModel.Activation.ActivationKind.search) {
    uri = searchPageURI;
    pageParameters = { queryText: eventObject.detail.queryText };
    }
    // Indicate to the system that the splash screen must not be torn down
    // until after processAll and navigate complete asynchronously.
    if (uri) {
    eventObject.setPromise(ui.processAll().then(function () {
    return nav.navigate(uri, pageParameters);
    }));
    }
    });
    [h=4]XAML apps[/h] For XAML Metro style apps, the Windows.UI.Xaml.Application class does a lot of the work needed for your app to support activation. This class exposes a set of strongly typed activation methods that you can override for supporting common contracts such as Search. For all contract activations that don’t have a strongly typed method, you can override the OnActivated method and inspect the activation kind to determine the contract for which your app is activated.
    New XAML app projects in Visual Studio come with generated code that uses the Windows.UI.Xaml.Application class to make the app capable of being activated for a generic launch. The code for handling this activation is in the class representation for your app, found in the App.xaml.cs/cpp/vb files.
    To extend support for Search activation in your app:
    1. Add the Search declaration to your manifest using the Visual Studio Manifest Designer.
    2. Place in the App constructor of App.xaml.cs/cpp/vb any general initialization code that needs to run every time your application is started irrespective of the reason.
    3. Override the strongly typed OnSearchActivated method in App.xaml.cs/cpp/vb to handle search activation.
    4. Load your Search UI and show search results for the query you receive in the SearchActivatedEventArgs.
    Again, just like for JavaScript apps, there is an easier way than manually doing this work. You can use Visual Studio tooling for completing a lot of this work. Just right click on your project, select Add > New Item, and choose Search Contract in the dialog. Most of the code you see here, and a search UI that displays results in a way that follows our Search UX guidelines is automatically created for you.
    Here are snippets of C# code from my photo app that shows support for Search activation.
    We must override the OnSearchActivated method to support activation for Search:

    protected override void OnSearchActivated(SearchActivatedEventArgs args)
    {
    // Load Search UI
    PhotoApp.SearchResultsPage.Activate(args.QueryText);
    }
    The Activate method of the SearchResultsPage sets up a UI that shows search results for the user’s search query:

    // SearchResultsPage.xaml.cs code snippet
    public static void Activate(String queryText)
    {
    // If the window isn't already using Frame navigation, insert our own frame
    var previousContent = Window.Current.Content;
    var frame = previousContent as Frame;
    if (frame == null)
    {
    frame = new Frame();
    Window.Current.Content = frame;
    }
    // Use navigation to display the results, packing both the query text and the previous
    // Window content into a single parameter object
    frame.Navigate(typeof(SearchResultsPage1),
    new Tuple(queryText, previousContent));
    // The window must be activated in 15 seconds
    Window.Current.Activate();
    }
    The logic and principles showcased here don’t just apply to adding Search activation support. You can use the same techniques when adding support for Protocols, File Associations, and Device AutoPlay as these are also main view activation contracts.
    [h=3]Scenario 2: Integrating File Open Picker activation in your app[/h] A Metro style app can call the file picker to let the user browse their system and pick files or folders for the app to operate on or to let the user save a file using a new name, file type, or location ("Save As"). Apps can also use the file picker as an interface to provide other apps with files, a save location, or even file updates. By incorporating the File Open Picker contract, you can help users pick files from your app directly within another app. Users gain freedom and flexibility to choose files that your app stores and presents.
    Launching an app for the File Open Picker contract falls under hosted view activation. The app’s UI is hosted inside of the file picker and the code that runs for this activation must be solely focused on the task of enabling users to pick their files. It is important that your app is as fast as possible here to give users a great experience. Don’t load any code or libraries that are unnecessary for the specific hosted view activation task.
    I recommend looking at the SkyDrive app because it is a great example of supporting File Open Picker activation and focusing solely on the task of allowing users to pick files.
    File Open Picker support in the SkyDrive app
    Let’s take a look at how you can support File Open Picker activation properly in your JavaScript and XAML apps.
    [h=4]JavaScript apps[/h] For JavaScript Metro style apps, the hosted view activation behaves the same as main view activation, except for one key difference: hosted view activation always occurs in a new window and script context. This means that your code for handling this activation can’t access libraries, global variables, or the DOM of your main app.
    To extending your app to support File Open Picker activation:
    1. Create a new HTML page that is specifically designed to handle only the File Open Picker contract.
    2. Add the File Open Picker declaration in the Visual Studio manifest designer and specify the newly created HTML page as the start page.
    3. Load only JavaScript and other resources in this page that are necessary for supporting the File Open Picker contract to improve performance.
    4. Structure the activation event handler to handle only activation for the File Open Picker contract. This handler is called only once during the lifetime of the file picking task.
    5. Use the activation event arguments to interact with the file picker.
    To save time you can you use Visual Studio tooling for completing this work. Just right click on your project, select Add > New Item, and choose File Picker Contract in the dialog. Most of what you see next is automatically created for you in your project.
    Here is a code snippet from my photo app’s fileOpenPicker.js file for handling File Open Picker activation:

    // Register activated event handler for handling File Open Picker activation
    WinJS.Application.addEventListener("activated", function (eventObject) {
    if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.fileOpenPicker) {
    pickerUI = eventObject.detail.fileOpenPickerUI;
    pickerUI.onfileremoved = fileRemovedFromPickerUI;
    ...
    }
    });

    WinJS.Application.start();
    [h=4]XAML apps[/h] For XAML Metro style apps, you support hosted view activation in your app similarly to main view activation. The biggest difference is that now your app must create a new thread and new window to handle the activation. The Visual Studio template code handles all of the work to create the new thread and new window on your behalf for hosted view activations.
    To handle File Open Picker activation a XAML app must:
    1. Add the File Open Picker declaration to your manifest using the Visual Studio Manifest Designer.
    2. Override the OnFileOpenPickerActivated method in App.Xaml.cs/cpp/vb and load your page that will handle this contract.
    3. Pass in the FileOpenPickerActivatedEventArgs to the page handling this contract so that it can interact with the file picker.
    To save time you can use Visual Studio tooling for completing this work. Just right click your project, select Add > New Item, and choose File Picker Contract in the dialog. Most of what you see next is automatically created for you in your project.
    Here is a snippet of C# code from my photo app for handling File Open Picker activation:

    // App.xaml.cs code snippet
    protected override void OnFileOpenPickerActivated(FileOpenPickerActivatedEventArgs args)
    {
    var fileOpenPickerPage = new PhotoApp.FileOpenPickerPage();
    fileOpenPickerPage.Activate(args);
    }

    // FileOpenPickerPage.xaml.cs code snippet
    public void Activate(FileOpenPickerActivatedEventArgs args)
    {
    this._fileOpenPickerUI = args.FileOpenPickerUI;
    this._fileOpenPickerUI.FileRemoved += FileOpenPickerUI_FileRemoved;

    // Show the user’s photos in the Picker UI
    ...

    Window.Current.Content = this;
    // The window must be activated in 15 seconds
    Window.Current.Activate();
    }
    The logic and principles showcased here don’t just apply to adding File Open Picker activation support. You can use the same techniques when adding support for Share Target, File Save Picker, Contact Picker, Camera Settings, and Print Task Settings as these are also hosted view activation contracts.
    [h=3]In closing[/h] I showed you how Search, File Picker, and other Windows 8 contracts offer the ability to drive users to your app for completing a specific task from other parts of the system and even other apps in certain scenarios. Users will expect these experiences in your app are fast and fluid because Windows and your app are both aware of their intent and the task they are trying to complete. Implementing your app activation correctly is core to creating a great experience for these contracts. Even if you are just working on the core of an app and are not using any contracts, it is good to keep these tips in mind as you set up your generic launch activation. This way you can easily extend your app in the future to support contracts without refactoring your code.
    [h=4]Things to remember:[/h]
    1. Place any general app initialization logic in a location where it will be executed independent of how your app is activated.
    2. Your activation handlers can be executed even when your app is already running or is suspended. Make sure this can’t cause any unintended consequences for your app.
    3. Visual Studio tooling can do a lot of the work for you to support the Search, Share Target, and File Open Picker contracts. All you need to do is right click your project and select Add > New Item.
    4. When receiving a hosted view activation, load only the code necessary for the task associated with the activation.
    To learn more about activation and contracts in Windows 8, you can follow these links or ask questions in our forums:
    [h=4]Documentation[/h] [h=4]Samples[/h] Thanks,
    Derek Gebhard
    Program Manager, Windows User Experience
    Contributions by: Jake Sabulsky, Marco Matos, Daniel Oliver

aggbug.aspx

More...
 
Back
Top