Pokazywanie postów oznaczonych etykietą Visual Studio 11. Pokaż wszystkie posty
Pokazywanie postów oznaczonych etykietą Visual Studio 11. Pokaż wszystkie posty

niedziela, 13 maja 2012

Metro w Windows 8 - odtwarzacz open source, UI w najnowszym Visual Studio 11

Tematyka aplikacji Metro jest bardzo pojemna.

Dziś wygrzebałem informację o frameworku multimedialnym na codeplex oraz chciałbym rzucić trochę światła na zagadnienie projektowania interfejsów Metro dla … aplikacji desktopowych (dziś na przykładzie Visual Studio 11, w przyszłości mam nadzieję także oczywiście na o Office 15).

Jak wiemy Microsoft dostarcza dodatkowy framework dla multimediów w przypadku Silverlight i Windows Phone 7 oferując m.in kontrolkę odtwarzacza. Podobnych rozwiązań doczekaliśmy się także w przypadku HTML5 (na strony webowe) oraz dla Windows 8 (w XAML i w HTML5). Koniecznie warto odwiedzić stronę http://playerframework.codeplex.com. Mamy różne fajne funkcjonalności, w przypadku Windows 8 można zauważyć wsparcie dla smoothstreamingu!

Jeśli chodzi o aplikacje typowo desktopowe, to ich rola i znaczenie będą malały. Ale z drugiej strony trudno sobie wyobrazić, że duże i złożone aplikacje (służące do tworzenia oprogramowania, zaawansowanej grafiki, złożonych dokumentów czy projektów technicznych) przeznaczone dla różnych wersji Windows zostaną szybko przepisane na Metro, o ile … zostaną. Ale jakoś za modą należałoby podążać, co robić? Odpowiedzi dostarcza sam Microsoft w przypadku swoich dużych produktów tj. Visual Studio czy Office, których nowe wersje otrzymują zmienione interfejsy użytkownika nawiązujące stylistycznie do stylu Metro. Stosowanie się do reguł Metro w przypadku aplikacji desktopowych wymaga większej pracy niż przy typowych aplikacjach Metro, bo nie ma tu jednoznacznych reguł, tutoriali, gotowych kontrolek. Aplikacje będą zawierały dużo funkcjonalności, a sztuką jest to zrobić taki interfejs by był lekki, nowoczesny, minimalizował pracę użytkownika, a jednocześnie nie przykuwał zbyt bardzo jego oczu i zajmował sam w sobie jak najmniejszą powierzchnię kosztem zawartości np. dokumentu. Ciekawe wpisy można przeczytać na blogu teamu Visual Studio, gdzie opisane są podejmowane decyzje projektowe odnośnie UI - dla bety VS 11 oraz dla niewydanego jeszcze publicznie RC:

Czy wiecie czemu okno Visual Studio 11 RC ma custom chrome?  Po to by zgodnie z regułą Metro pasek okna nie zajmował niepotrzebnie miejsca! Takich przemyśleń, wniosków, analiz jest znacznie więcej. Podane linki jeszcze raz polecam!

poniedziałek, 30 kwietnia 2012

Notatki o Windows 8 Consumer Preview - odc. 19

W dzisiejszym odcinku będzie trochę hardcorowo, a mianowicie pozwolę sobie na cytaty z części niszowych dokumentów poświęconych tworzeniu aplikacji Metro dla urządzeń w ujęciu ogólnym oraz w dedykowanym przypadku dla kamer internetowych. Starałem się wyłapać ogólny sens i różne ciekawostki, które mogą być użyteczne nawet, gdy tylko będziemy korzystać z jakiegoś urządzenia w Windows 8. Niskopoziomowe szczegóły oczywiście zawarte są w dokumentach i przydadzą się producentom urządzeń (ewentualnie pasjonatom).

Metro style Device Apps

A Metro style device app involves several components:

  • Metro style Device Apps  - The Metro style Device App Lifecycle
  • Device Metadata in Windows 8 - Like in Windows 7, device manufacturers can use the device metadata system to deliver a device experience in Devices and Printers and Device Stage for a connected device or the PC. New to Windows 8, the device metadata system can also link the device or PC to Metro style device apps.
  • Device Drivers

Device Categories

  • Printers
  • Mobile Broadband
  • Cameras
  • Networked Entertainment Devices (Play To)
  • Specialized Devices

When the user plugs in or pairs a new device with the PC, Windows will identify the manufacturer and model of the device and then download the remaining components from Microsoft online services like Windows Update and Windows Store automatically. The user can also manually download it from the Windows Store. An Independent Software Vendor (ISV) may create the Metro style device app in partnership with the Independent Hardware Vendor (IHV), which supplies the device metadata and driver.

Device metadata is a set of XML files that create the link between a particular device and its Metro style device app. In addition to UI content for the device (localizable model name, description & photorealistic icons) the device metadata package indicates which app Windows should download. Device Metadata is authored using the Device Metadata Authoring Tool, and submitted to the Windows Hardware Center Dashboard.

Visual Studio 2011 Ultimate is required because it includes the Metadata Authoring Tool. Visual Studio 2011 Express doesn’t include WDK support or the recommended metadata tools.

image

Experience ID is part of the required information that the Windows Store uses when validating the Metro style device app. It is a 128-bit Globally Unique Identifier (GUID). The application developer then specifies in a file named StoreManifest.xml using a <ExperienceId> tag. The GUID is automatically generated by the Metadata Authoring Tool, and can be found in the PackageInfo XML component of the device metadata

image

 

<?xml version="1.0" encoding="utf-8"?>

<StoreManifest

  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:noNamespaceSchemaLocation="StoreManifest.xsd"

  xmlns="http://schemas.microsoft.com/appx/2010/StoreManifest">

 

  <ProductFeatures>

    <DeviceCompanionApplication>

      <ExperienceIds>

        <ExperienceId>F9D916A7-AFD3-445B-8B9C-5B6466831C9E</ExperienceId>

        <ExperienceId>4A393BAA-DE6B-4B9A-A4BC-35FDE4A97FB2</ExperienceId>

      </ExperienceIds>

    </DeviceCompanionApplication>

</ProductFeatures>

 

</StoreManifest>

Each Device Metadata package can only reference a single Metro style device app, but the store manifest for a Metro style device app may list several Device Experience IDs, since many device models may use the same app.

If the Metro style device app is for a specialized device or a mobile broadband device, the app needs to declare the device interface in the application manifest (package.appxmanifest).

You must submit your device driver (if any) and your Metro style device app before you can submit device metadata.

There are three ways by which device software is acquired by the user:

  • Automatic Acquisition - The app is automatically acquired the first time an externally connected device is connected. This is the most common way Metro style device apps are acquired.
  • Windows Store Download - A user may find and purchase the app directly from the Windows Store. This is typically how app updates or additional apps are distributed.
  • OEM Preinstall - An app for a PC internal system component can be preloaded by an OEM as part of a new PC.

Automatic Acquisition

The user opts in to the Recommended Settings during Windows installation. This allows Windows to acquire drivers from Windows Update, metadata from WMIS, and the Metro style device app from the Windows Store.

Uninstalling Device Software

Devices may be uninstalled by the user. Only the driver and metadata are automatically uninstalled as part of device uninstall. The user needs to manually uninstall the Metro style device app. The user may choose to uninstall the Metro style device app without uninstalling the device as well, if they do not feel the app adds value to their experience.

Updating the Device Software Components

Updating Drivers

Driver updates are distributed through Windows Update as optional updates, provided that the user has opted in to receiving updates from Windows Update. Driver updates are not automatically distributed to devices if they have completed device setup, and already have metadata and drivers installed. Driver updates are not coupled to app updates, so driver updates should be designed to ensure compatibility with existing apps. If a driver update is distributed through Windows Update, or if the user manually reinstalls or updates the driver, the app should handle this appropriately.

Updating Device Metadata

The metadata that’s distributed by WMIS may be updated to point to a new or different Metro style device app.

Approximately 8 to 15 days after the submission of updated metadata that indicates a new app, new devices that are connected and set up for the first time will get the new app.

However, a new app indicated in updated metadata is not automatically distributed to PCs for which the device setup is already complete, because the users have previously received device metadata for the device. The Metro style device app is automatically downloaded only once, when the device is initially set up.

If the device metadata is updated to point to a different app, the old Metro style device app should advertise the new one to the user, so that users can acquire it from the Windows Store manually. Eventually, the old app should be removed from the Windows Store.

Users can also get to the new app, if they go to the Settings > Devices Page and click the ‘Get app’ link for that device.

Updating the Metro style Device App

Metro style device app updates are manually triggered by users, just like any other Metro style app updates. The Windows Store shows all available application updates to the user. The user manually chooses to update the app.

You should design apps to be compatible with older metadata and drivers. The device metadata or driver might not be up-to-date with the app, since manual installation of a Metro style device app from the Windows Store doesn’t automatically trigger distribution of metadata or drivers.

Metro style Device Apps for Cameras

image

Links

Your camera’s driver must use the AvStream driver model.

Windows 8 offers IHVs and system OEMs the ability to create video processing plug-ins in the form of a Media Foundation Transform (MFT). This special MFT is known as the driver MFT. It is also known as MFT0 to indicate it is the first MFT to operate in the source reader. A separate instance of MFT0 is attached to every pin on the capture source. For some system OEMs, the AVStream capture driver must support a preview pin, a capture pin, and a still pin. This means that there may be three instances of MFT0.

Two popular functions for MFT0 are:

  • Analyzing the video stream to provide feedback to the camera for improved capture (such as host-based auto focus and auto exposure).
  • Adding video effects.

Additionally, there are two final compounding factors:

  • Each instance of the MFT0 may be created or shut down at any time.
  • The Metro style device app is only connected to one instance of the MFT0, currently the one associated with the preview pin.

When your camera’s Metro style device app is registered with Windows, the features it implements are automatically made available to any Metro style apps that call the Windows.Media.Capture.CameraOptionsUI.Show API to display a camera options user interface.

image

The Driver MFT is the Media Foundation Transform (MFT) that implements the effects. This media extension that provides the effects is an implementation of IMediaTransform. This MFT is the first transform applied to the video stream coming out of the driver.

A Metro style device app for camera can be launched in two different contexts: the Start experience (when the app is launched from the app tile in the Start screen), and the Options experience.

image

 

image

 

A Metro style device app that is declared as a camera settings extension can be activated by Windows when a user clicks the Options button or an app calls Windows.Media.Capture.CameraOptionsUI.Show. The Metro style device app then handles the event that is raised when the app is activated

image

var activatedHandler = function (eventArgs) {

        var kind = eventArgs.detail.kind;

        var activationType =

            Windows.ApplicationModel.Activation.ActivationKind;

        if (kind === activationType.cameraSettings)

        { 

           // Initialize logic for the flyout that provides camera

           // effects here.

 

        } else if (kind === activationType.launch)

        {

           // Do not provide settings or effects if launched.

           // Instead, you may provide support, services,

           // or other functionality that does not apply effects.   

 

        }

}

WinJS.Application.start();

WinJS.Application.addEventListener("activated", activatedHandler, false);

namespace CameraMetrostyleDeviceApp

{

    public partial class App

    {

        public App()

        {

            InitializeComponent();

        }

 

        protected override void OnLaunched(

             LaunchActivatedEventArgs args)

        {

            // Initialize the start page

            Window.Current.Content = new StartPage();

            Window.Current.Activate();

        }

 

 

        protected override void OnActivated(IActivatedEventArgs args)

        {

            if (args.Kind == ActivationKind.CameraSettings)

            {

                base.OnActivated(args);

                MainPage page = new MainPage();

                Window.Current.Content = page;

 

           // The args object contains properties for

           // controlling the device settings                      

              page.Initialize((CameraSettingsActivatedEventArgs)args);

 

                Window.Current.Activate();

            }

        }

    }

}

Type Windows.ApplicationModel.Activation.CameraSettingsActivatedEventArgs exposes two properties for controlling the camera.

  • The VideoDeviceController property provides methods for adjusting standard settings. It is an object of type Windows.Media.Devices.VideoDeviceController.
  • The VideoDeviceExtension is a pointer to the Driver MFT interfaces for applying custom settings.

var videodev = null;

var videoext = null;

var lcWrapper = null;

 

function activatedHandler(eventArgs) {

    if (eventArgs.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.cameraSettings) {

        videoext = eventArgs.detail.videoDeviceExtension;

        videodev = eventArgs.detail.videoDeviceController;

 

        if (videoext !== null) {

            initializeExtension(videoext);

        }

 

        if (videodev !== null) {

            initializeSlider();

            // do other initialization here…

        }

    }

}

 

WinJS.Application.start();

WinJS.Application.addEventListener("activated", activatedHandler, false);

 

function initializeExtension(mft0) {

    lcWrapper = Wrapper.WinRTComponent();

    lcWrapper.initialize(mft0);

}

 

// Initialize a slider element using the VideoDeviceController object

function initializeSlider() {

    try {

        var bValue = 0;

        var bAuto = 0;

        var slider;

            if (videodev != null) {

                bValue = videodev.brightness.tryGetValue();

                slider = document.getElementById("slBrt");

                slider.value = bValue.value;

                slider.min = videodev.brightness.capabilities.min;

                slider.max = videodev.brightness.capabilities.max;

            }

}

If your Metro style device app is more than 560 pixels in height, the user may slide or scroll to view parts of the app that are above or below the viewable area. A Metro style device app should not exceed 340 pixels in width.

Suggested effects
  • Color effects, such as grayscale, sepia tone, or solarizing the entire picture.
  • Face-tracking effects - these are often overlays, where a face is identified in the picture and an overlay, such as a hat or a pair of glasses, is added on top of it.
  • Scene modes - these are preset exposure and focus modes for different lighting conditions.
Suggested settings
  • Your Metro style device app can provide a switch to enable hardware-implemented settings, such as color correction schemes. Some examples of color correction schemes are TrueColor and RightColor.
  • Implement basic properties that supplement the other settings exposed by your Metro style device app. For example, many devices may expose controls for adjusting brightness, contrast, flicker, focus, and exposure, but a device that implements TrueColor to automatically adjust the brightness and contrast may not need to provide these settings.

Restrictions

  • Do not show a user interface for selecting settings or effects if the app is launched from its tile in Start rather than from a capture app. Settings will not persist from the Start experience.
  • Do not provide a preview or otherwise take ownership of the video stream from inside your Metro style device app.
  • Do not adjust resolution in your Metro style device app.
  • Do not attempt to display pop-ups, notifications, or dialogs outside of the area intended for the Metro style device app’s Options experience
  • Do not declare the Webcam, Microphone, SMS device capabilities

image

The Metro style device app for camera runs in a different process than the app that is capturing from the camera.

Note that the Driver MFT is not strictly required for a Metro style device app, but it supplies the custom settings and effects. A device manufacturer may choose to implement a Metro style device app without a Driver MFT, simply to provide a differentiated user interface containing branding for their hardware, without applying custom effects to the video stream.

The Driver MFT implements IMFTransform. It also must be exposed to the Windows Runtime, so it must also implement IInspectable.

A Driver MFT is registered with Windows as a COM interface so that the transform it implements can be applied to the media stream coming out of a specific device, such as a camera. When an app initiates a video capture, a Media Foundation Source Reader is instantiated to provide the video stream. This media source reads a registry value from the device registry key. If the CLSID of the Driver MFT’s COM class is found in the registry value, the source reader instantiates the Driver MFT and inserts it into the media pipeline.

In addition to Metro style device apps, the Driver MFT functionality can be accessed when the device associated with it is used to capture video using the following APIs:

  • HTML5 <video> tags in a Metro style app using HTML.
  • Windows.Media.MediaCapture API in a Metro style app using the Windows Runtime

To write a Metro style device app in C# or JavaScript that interacts with a Driver MFT, you need to create an additional component in the Metro style device app’s Visual Studio project. This component is a wrapper that exposes the Driver MFT interfaces in a Windows Runtime Component that is visible to the Metro style device app.

 

KSCATEGORY_VIDEO_CAMERA:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\DeviceClasses\{E5323777-F976-4f5b-9B55-B94699C46E44}\##?#USB#VID_045E&PID_075D&MI_00#8&23C3DB65&0&0000#{E5323777-F976-4f5b-9B55-B94699C46E44}\#GLOBAL\Device Parameters]

"CLSID"="{17CCA71B-ECD7-11D0-B908-00A0C9223196}"

"FriendlyName"="USB Video Device"

"RTCFlags"=dword:00000010

"CameraPostProcessingPluginCLSID"="{3456A71B-ECD7-11D0-B908-00A0C9223196}"

Internal cameras embedded inside a portable computer do not have their Metro style device app downloaded, because there is no act of connecting the camera to trigger the download.

You submit your camera’s Metro style device app to the Windows Store or preinstall it, in the case of internal cameras.

sobota, 28 kwietnia 2012

Notatki o Windows 8 Consumer Preview - odc. 17

Jutro miną dwa miesiące od wydania Windows 8 Consumer Preview, a jednocześnie dzieli nas nieco ponad miesiąc od wydania Windows 8 Release Preview.

8329

Tyle tytułem wstępu, ale zostawmy już te terminy i przejdźmy do kolejnej porcji informacji o platformie “ósemki” w wersji Consumer Preview, a konkretnie do manifestu aplikacji oraz jej debugowania, wgrywania, analizy jakości kodu, testowania za pomocą testów jednostkowych, analizy wydajności.

W przypadku manifestu można dostrzec pewne zmiany w kontraktach, nazywanych coraz częściej deklaracjami - np. pojawiły się nowe, pewne zniknęły itp. - czy w atrybutach samego pakietu.

Przy debugowaniu dostajemy nieco więcej informacji o debugowaniu na zdalnej maszynie. Wgrywanie aplikacji dokonuje się automatycznie przy debugowaniu lub możemy dokonać tego sami (aczkolwiek też przy pomocy narzędzi związanych z debugowaniem). Przy wgrywaniu możemy wybrać dwie opcje - zdjęcie standardowej restrykcji na komunikację z adresem loopback oraz włączanie debugowania nie od razu, a dopiero po uruchomieniu aplikacji np. z ekranu start lub przez jakiś kontrakt. Możliwe jest również attachowanie do procesu aplikacji.

W analizie jakości kodu czy testowaniu nie widać zbytniej różnicy do wcześniejszego wydania. Dostajemy natomiast opis jak badać wydajność aplikacji napisanej w Java Script oraz w .NET/C++.

Packaging

Manifest designer

Capabilities

Declarations

  • Account Picture Provider - Registers the app as an account picture provider.
  • AutoPlay Content - Registers the app for content events, such as when a DVD is inserted.
  • AutoPlay Device - Registers the app for device events, such as when a web cam is attached.
  • Background Tasks - Enables the app to specify the class name of an inproc server DLL that runs application code in the background in response to external trigger events. When the event triggers, the Run method of the given class is invoked.
  • Cached File Updater - Registers the app as a cached file updater so that the app can update files that other Metro style apps access.
  • Camera Settings - Enables the app to provide custom control panels for web camera devices.
  • Certificates - Enables the app to install digital certificates, such as trusted root certificates. The certificates are used during secure connections to web services over SSL.
  • Contact Picker - Registers the app as a contact picker, which makes the app contacts available to other apps.
  • File Open Picker - Declares an app extensibility point of type windows.fileOpenPicker. If you set this declaration, users can choose and open the specified types of files.
  • File Save Picker - Declares an app extensibility point of type windows.fileSavePicker. If you set this declaration, users can choose the file name, extension, and storage location for the specified types of files.
  • File Type Associations - Registers File Type Associations (for example, .jpeg) on behalf of the app.
  • Game Explorer - Registers the app with the Windows Parental Control system using a Game Definition File (GDF). The GDF contains metadata that describes, for example, its rating in regional systems such as PEGI and ESRB.
  • Print Task Settings - Enables the app to replace the basic print settings.
  • Protocol - Registers URL protocols (for example, mailto) on behalf of the app.
  • Search - Enables the app to provide search capability.
  • Share Target - Registers the app as a share target, which allows the app to receive shareable content.
Content URIs - The URIs that your app can or can’t access.

Packaging

  • Package Name
  • Package Display Name
  • Logo
  • Publisher  - This must match the subject field of the certificate used to sign the package manifest
  • Certificate
  • Publisher Display Name - The name of the Publisher that appears on the certificate.
  • Package Family Name - A unique name that comprises the package name and a hash of the publisher string and that identifies the package on the system. The name is updated whenever the package name or publisher string changes.

Debugging and testing Windows Metro style apps

Running Windows Metro style apps on a remote machine

To debug on a remote device:

  • The remote device and the Visual machine must be connected over a network or connected directly through an Ethernet cable. Debugging over the internet is not supported.

  • The remote device must be running the remote debugging components.

  • You must be an administrator on the remote device to configure the firewall during installation. You must have user access to the remote device to run or connect to the remote debugger.

By default, the remote debugger uses Windows Authentication. You can also choose to run the remote debugger in No Authentication mode, but this mode is strongly discouraged.

To connect directly to a remote device, connect the two machines with a standard Ethernet cable. If the device does not have an Ethernet port, you can use a USB to Ethernet adapter to connect to the cable.

Visual Studio Windows 8 Consumer Preview Remote Debugger

Debugging is not supported on ARM devices in Visual Studio 11 Beta.

By default, the remote debugger is always running after you start it for the first time. It broadcasts its identity on the local sub-net of the network, which allows a Visual Studio machine on the same sub-net to know that the remote device is available as a remote debugging target. You can turn the remote debugger on and off and set various options, such as setting a timeout interval and setting permissions for access.

You control the remote debugger from the classic desktop on the remote device. When you install the remote debugger, a short-cut is placed on the desktop Start menu and a tile is placed on the Metro style Start screen. The Remote Debugging Monitor dialog box displays the current status and activity of the debugger and allows you to change debugger options. When the remote debugger is running, you can open the Remote Debugging Monitor and perform other tasks by using the remote debugger icon in the system tray.

You specify the remote device to connect to in the properties of the project. The procedure differs depending on the programming language. You can type the network name of the remote device, or you can select it from the Select Remote Debugging Connection dialog box. The Select Remote Debugger Connection dialog box displays the devices on the local network subnet and any device that is directly connected to the Visual Studio machine by an Ethernet cable.

Managed project properties for remote debugging

C++ project properties for remote debugging

Select Remote Debugger Connection dialog box

Deploying Windows Metro style apps from Visual Studio

Deployment is automatic when you debug your app from Visual Studio by using the Start Debugging option (Keyboard: F5) or the Start Without Debugging option (Keyboard: CTRL + F5). You can also deploy your app manually.

Manually deploying an app is a simple process:

  1. If you are deploying to a remote device, specify the name or IP address of the device in the property project page of the app's startup project.

  2. On the debugger Visual Studio toolbar, choose the deployment target from the drop-down list next to the Start Debugging button.

  3. On the Build menu, choose Deploy.

To deploy an app to a remote device:

  • A developer's license must be installed on the remote device.

  • The Visual Studio Remote Tools must be installed on the remote device and the Remote Debugging Monitor must be running.

    Deployment uses the remote debugger network channel to send the app files to the remote device.

Deployment options

You can set the following deployment options on the Debug property page of the startup project.

  • Allow Network Loopback
  • Do not launch, but debug my code when it starts (C# and VB) / Launch Application (JavaScript and C++) - to automatically start a debugging session when the app is launched.

Debugging Windows Metro style apps

How to start a debugging session (JS)

By default, Visual Studio immediately starts the app when you start debugging. You can also start a debug session but delay the start of your app. The app is launched in the debugger when it is launched from the Start menu or by an activation contract, or when it is started by another process or method.

You specify whether to delay the launch of your app in the Launch Application list on the Debugging property page of the app project. Choose one of these options:

  • Choose No to delay the launch of your app.

  • Choose Yes to launch the app immediately.

How to start a debugging session (.NET, C++)

To delay the launch of your app, you can:

  • For Visual C# and Visual Basic apps, select Do not launch, but debug my code when it starts on the Debugging property page.

  • For Visual C++ apps, choose Yes from the Launch Application list on the Debug property page.

Attach the debugger to a running app

To attach the debugger to a Metro style app, you must use the Debuggable Package Manager to set the app to run in debug mode. The Debuggable Package Manager is installed with the Visual Studio Remote Tools.

Attaching the debugger to an app is useful when you need to debug an already-installed app, such as an app that was installed from the Windows store. Attaching is required when you have the source files for the app, but you do not have a Visual Studio project for the app. For example, you might have a custom build system that does not use Visual Studio projects or solutions.

To attach to an app:

  1. Set the app to run in debug mode. This must be done when the app is not running.

  2. Start the app. You can start the app from the Start menu, an execution contract, or some other method.

  3. Attach the debugger to the running app.

Set the app to run in debug mode
  1. Install the Visual Studio Remote Tools on the device where the app is installed.

  2. On the Start menu, search for Debuggable Package Manager and then start it. A PowerShell window properly configured for the AppxDebug cmdlet appears.

  3. To enable debugging of an app, you must specify the PackageFullName identifier of the app. To view a list all apps that includes the PackageFullName, type Get-AppxPackage at the PowerShell prompt.

  4. At the PowerShell prompt, enter Enable-AppxDebug PackageFullName where PackageFullName is the PackageFullName identifier of the app.

Attach the debugger

JavaScript apps run in an instance of the wwahost.exe process. If other JavaScript apps are running when you attach to the app, you will need to know the numeric process id (PID) of the wwahost.exe that the app is running in.

Debugging Java Script apps

DOM Explorer

DOM Explorer

Attributes tab

JavaScript Console

JavaScript Console window

Interactive debugging & breaking mode

When a program that's running in the debugger encounters a breakpoint, the debugger temporarily suspends execution of the program.

How to inspect CSS rules

The Styles tab in DOM Explorer

How to view and edit the layout

Layout tab of DOM Explorer

How to view event listeners

The Events tab of DOM Explorer shows the events that are associated with a DOM element. Each top node represents an event that has active subscribers. The top node contains subnodes that represent the registered event listeners for the specific event. In addition to viewing the event listeners, you can use this tab to navigate to the location of the event listener in the JavaScript code.

The list on the Events tab is static, so if you add an event while the app is running, the new event won’t appear there. Event listeners for code elements that aren't DOM elements, such as xhr, don't appear on the Events tab.

Analyzing the performance of Windows Metro style apps

How to collect JavaScript performance data for Windows Metro style apps on a local machine

Stop Profiling

  • Start Performance Analysis  - to start your app and start profiling immediately
  • Stop profiling
  • Start Performance Analysis Paused - to start your app with profiling suspended

How to collect JavaScript performance data for Windows Metro apps on a device that does not have Visual Studio installed

Profiling with VSPerf.exe is useful when you want to test the performance on a variety of devices with different capabilities, such as processing speed, screen resolution, or abilities to process different kinds of input gestures.

With VSPerf.exe, you can profile an app that is started from the Start menu or by another process or procedure. You can focus your performance profiling on specific scenarios by pausing and resuming data collection. Once you have finished profiling, you copy a single file to your Visual Studio machine to analyze the data.

The following requirements are necessary to use VSPerf.exe on a remote device.

  • The app to be profiled must be deployed on the remote machine before you start profiling.

  • You must have administrator privileges on the remote device.

  • Visual Studio must be installed on a Windows 8 machine to analyze performance data collected from Metro style apps.

The remote profiling tool is installed with the Visual Studio Remote Tools, along with the remote debugging components.

Profiling is not supported on ARM devices in Visual Studio 11 Beta.

  • vsperf /listapps
  • vsperf /app:BouncingSquares
  • vsperf /package:54fb8cc2-1f58-4fe5-adb1-a246dd54ffa6_1.0.0.0_neutral__fsyyfg9a7tqy4

To profile JavaScript code, you must include the /js option in the command that starts the profiling session. You can not attach the profiler to the app to collect JavaScript performance data.

  • vsperf /app:{AppName} /file:{OutFile} /js
  • vsperf /package:{PackageFullName} /file:{OutFile} /js
  • vsperf /stop
  • vsperf /detach
  • vsperf /app:{AppName} /file:{OutFile} /js /pause
  • vsperf /package:{PackageFullName} /file:{OutFile} /js /pause
  • vsperf /pause
  • vsperf /resume

Analyzing JavaScript performance data in Metro Style apps

How to collect Visual C++, Visual C#, and Visual Basic performance data for Windows Metro style apps on a device that does not have Visual Studio installed

You can use VSPerf.exe to collect performance data for Visual C++, Visual C#, and Visual Basic from the following types of Metro style apps:

  • An app written using XAML and Visual C++, Visual C#, or Visual Basic.

  • An app written using HTML5 and JavaScript that contains components that are written in Visual C++, Visual C#, or Visual Basic.

vsperf /attach:{PID|ProcessName} /file:{OutFile} [/noclr]

Analyzing performance data for Visual C++ , Visual C#, Visual Basic, and code in Windows Metro style apps

czwartek, 12 kwietnia 2012

Notatki o Windows 8 Consumer Preview - odc. 10

Tym razem postaram się streścić w kilku zdaniach całkiem sporą dawkę nowych ciekawych informacji na temat aplikacji utrzymujących cały czas łączność z siecią, nawet wtedy gdy się nie wykonują lub gdy system Windows 8 sprawia wrażenie wyłączonego, a precyzyjniej gdy jest w stanie “Connected Standby” (uśpienie z dostępem do sieci, o tym wprowadzonym w Windows 8 stanie można więcej się dowiedzieć choćby oglądając sesję Understanding Connected Standby z konferencji BUILD, nie licząć różnych artykułów w sieci). Mamy możliwość napisania własnej aplikacji do prowadzenia rozmów tekstowych i VoIP czy klienta pocztowego powiadamiającego o przychodzących mailach.

Sporą zmianą jest podejście do koncepcji notyfikacji push typu raw. O ile w Windows Phone 7 mogą być odbierane tylko przez działającą aplikację (jako foreground), o tyle w Windows 8 notyfikacje raw mogą uruchamiać taska wykonującego się w tle! Służy ku temu dedykowany rodzaj triggera. Wprowadzono pojęcie aplikacji lock-screen (jak wiadomo z wcześniejszej wersji takie aplikacje zawierają taski wykonujące się w tle). O ile notyfikacje tile, badge, toast mogą też być odbierane przez wszystkie aplikacje, o tyle notyfikacje raw są zastrzeżone jedynie dla aplikacji lock-screen. Za pomocą notyfikacji raw możemy wysyłać maksymalnie 5kB danych.

Scenariusze real-time uzyskujemy

  • korzystając z notyfikacji push aktualizujących kafelki, wyświetlających notyfikacje na ekranie lub uruchamiających kod z tle. Mamy tu WNS (Windows Notification Service) z utrzymywanym przez system ciągłym połączeniem. Zyskujemy wydajność - jedno połączenie obsługuje wiele aplikacji, nie obciążamy naszego serwera trzymanymi połączeniami, nie wysyłamy keep-alive pomiędzy naszym serwerem i klientem - oraz w wielu przypadkach prostotę - nie musimy pisać tasków w tle chyba że użyjemy notyfikacji raw. Aczkolwiek potrzebujemy dostępu do Internetu, mogą być problemy z firewallami, nie mamy gwarancji dostarczenia, nie każdy protokół da się opakować w WNS np. Microsoft Exchange, czasami chcemy zachować prywatność wysyłanych powiadomień i czasami lepiej jest wybrać inny sposób lub zastosować ich kombinację.
  • za pomocą network triggera, który potrafi wywoływać kod w tle w momencie przyjścia danych lub pakietu keep-alive. Mamy tutaj gwarancję odbioru, ponieważ jest utrzymywane połączenie pomiędzy naszym serwerem i klientem. Mamy kompatybilność z istniejącymi protokołami wymagającymi trwałego połączenia. Z drugiej strony to podejście jest bardziej złożone, mamy też ograniczenie do 5 network triggerów w aplikacji.
  • za pomocą triggera czasowego lub triggerów systemowych. Korzystając z time triggera możemy np. sprawdzać czy nie ma nowych maili na serwerze pocztowym co jakiś okres (minimum 15 minut). Eventy systemowe również może być przydatne - np. gdy w momencie zalogowania się do systemu użytkownika chcielibyśmy, aby w naszej aplikacji zostały pobrane przeznaczone dla niego wiadomości.

Wywoływanie kodu przez trigger dla notyfikacji push typu raw oraz przez network trigger nie jest wspierane przez aplikacje napisane w Java Script! W tym przypadku musi to być C#, VB.NET lub C++.

Aplikacja przypięta do zablokowanego ekranu może prezentować użytkownikowi informacje poprzez zmianę zawartości kafelka (tile) lub znajdującego się na nim znaczka (badge) albo poprzez wyświetlenie notyfikacji na ekranie (on-screen notication). Do zablokowanego ekranu użytkownik może przypiąć maksymalnie 7 aplikacji. Aplikacja poprzez API może poprosić użytkownika o przypięcie (dostajemy status mówiący o tym czy mamy pozwolenie i jaki jego rodzaj - z komunikacją real-time czy bez niej), można ją też dodać lub usunąć poprzez sekcję Personalize w ustawieniach, wreszcie system z uwagi na małą liczbę zasobów może usunąć aplikację z zablokowanego ekranu.

Są dwa rodzaje network triggera:

  • push notification – reakcja na przyjście danych do socketu, nawet jeśli aplikacja jest uśpiona
  • keep-alive – wysyłanie pakietów keep-alive przez uśpioną aplikację, aby serwer nie zamknął połączenia

Aplikacja lock-screen korzystająca z network triggera musi korzystać z obu rodzajów.

Dla network triggera możemy wyróżnić dwa typy zasobów - tzw. sloty software i hardware. Domyślnym typem jest software, wtedy trigger nie zadziała, gdy system będzie w stanie Connected Standby. Slot hardware zapewnia działanie triggera także w tym stanie! Aczkolwiek slot hardware mają tylko urządzenia sprzętowo przystosowane do obsługi trybu Connected Standby. Użycie network triggerów ze slotami hardware zostało dodatkowo ograniczone - trzy pierwsze aplikacje, które zarejestrują się na typ hardware mają możliwość używania trzech triggerów z tym rodzajem slotów. Pozostałe aplikacje mają do dyspozycji tylko typ software.

BTW triggery nie działają przy stanie hibernacji, uśpienia systemu oraz jak jest wyłączony.

Jeśli nasza aplikacja “zaobserwuje” dużo zrywanych połączeń, możemy wywołać w niej metodę triggera sieciowego o nazwie DecreaseNetworkKeepAliveInterval. Nie należy jej nadużywać, ale dzięki niej możemy wymusić, aby system skrócił okres keep-alive dla danego kanału.

Możemy również odczytać bieżącą wartość keep-alive przyjętą przez system, co w niektórych przypadkach może być przydatne.

Na koniec kilka nowych uwag o testowaniu i debugowaniu komunikacji sieciowej. Z uwagi na izolację godny odnotowania jest fakt, że komunikacja sieciowa między różnymi procesami z adresem loopback jest zablokowana. Aczkolwiek w celach testowych za pomocą odpowiednich narzędzi możemy nadać (lub odebrać) pozwolenie na komunikację z adresem loopback dla danej aplikacji. Visual Studio 11 automatycznie przydziela takie uprawnienie.

Niejako przy okazji mamy podane miejsce w rejestrze, gdzie zapisywany jest identyfikator aplikacji.

 

How to set background connectivity options

Lifecycle model for Metro style apps

This new model provides a mechanism for apps that must work in the background (such as Voice over Internet Protocol (VoIP), instant messaging (IM), and email) to provide an always-connected experience for the end user. This means that an app that depends on a long-running connection to a remote endpoint server can still work when the app is suspended.

In order to enable real-time networking scenarios for a Metro style app that needs to be always connected, several new features have been introduced:

  • Windows Push Notification Services (WNS)
  • Background tasks
  • System trigger for session start
  • Time triggers
  • Push notification triggers (raw push notifications)
  • Network triggers

These features provide support for always connected apps that need to receive incoming network packets or raw push notifications when a Metro style app is suspended.

Other background tasks features can also be used by a network app. Some other triggers available for use by a Metro style app include the following:

  • Maintenance triggers (periodic time events for maintenance)
  • System triggers for users and sessions (user session connected/disconnected, user present/away, and online ID change)
  • System triggers for networking status (network state change, internet available/not available)
  • System triggers for lock screen (app add/remove)

A time trigger could be used when an app does not require real-time connectivity but needs to run for a brief time at some interval. A system trigger could be used when the app needs to be aware of events (for example, the availability of Internet connectivity or user presence).

Once a Metro app is suspended, any existing network connections are closed and incoming network packets are dropped. To be always connected, an app also needs to be a lock screen app. A lock screen app is a special type of app that can display notifications on the lock screen and run code in the background when the app is not in the foreground. Only apps that use one or more background tasks may be lock screen apps.

Lock screen apps have some special abilities:

  • Able to receive a raw push notification from WNS that can run code when the notification is received.
  • Able to maintain a persistent transport connection in the background to a remote service and run code when data or a keepalive packet is received using the network trigger features.
  • Able to run code when a time trigger occurs.
  • Able to run code when a user session is started.

Apps pinned to the lock screen can present information to the user when in the background by updating and displaying a badge icon on the lock screen when there is new information. These apps can also display an on-screen notification when a message arrives. If the notification is tapped or clicked, the user is asked to unlock the device. When the device is unlocked, the app corresponding to the notification is launched with context information.

A user can have a maximum of seven lock screen apps at any given time. A user can add or remove an app from the lock screen at any time. If the system runs short on resources, the system can also remove an app from the lock screen.

Several mechanisms discussed below can be used to enable real-time scenarios for apps that are placed on the lock screen. Each has its benefits and tradeoffs. The mechanisms are not mutually exclusive and can be combined in some apps.

Using WNS in Metro style apps

WNS is a cloud service hosted by Microsoft for Windows 8 that can be used by Metro style apps to receive notifications that can execute code, update a live tile, or raise an on-screen notification. In order to use WNS, the local computer must be connected to the Internet so that the WNS service can communicate with it.

When a push notification is delivered to a lock screen app, the app can run code in response to the notification. WNS use can be more power efficient than using network trigggers.

WNS offers a number of benefits:

  • WNS offers the most power-efficient mechanism for delivering real-time notifications to lock screen apps.
  • WNS simplifies the developer model for your app. In most scenarios, developers do not have to write any background tasks, because the operating system renders the tiles or toast. In a small subset of scenarios, if your app must run a background task, it need only register the raw trigger and the background task itself.
  • No persistent socket connection needs to be maintained between the client app and a remote server because Windows maintains the connection to WNS. As a result, the overhead of sending keep-alive messages is not required.
  • A single WNS connection between the client and the cloud service can support all apps on the local computer, which translates to potential battery life efficiency for the client.
  • Cost is reduced on the server side because there is no need to maintain many parked TCP socket connections.
  • The operational cost for your service may be lower, because there is no parked connection between the client and the remote service.
  • Your app does not have to reside in memory at all times, because it can be terminated and still have WNS update the tile, raise a toast, or trigger a background task to run upon receipt of an incoming raw notification.
  • Background tasks that do not use raw push notifications can be written in JavaScript, C#, VB.NET, and C++. The network trigger feature and raw push notifications are not available in JavaScript.

WNS can also be blocked by some network firewalls even when Internet access is available.

Given the advantages, we recommend that developers who build VoIP, IM, or email apps consider using WNS notifications for lock screen apps, but consider alternatives if they do not meet your requirements.

There is no need to build a lock screen app if you simply want to have a live tile update or raise a toast using WNS. A lock screen app is required while using WNS only when the app requires a raw push notification to trigger a background task to run.

Using network triggers in Metro style apps

The System.Net.Sockets.ControlChannelTrigger class implements the network trigger feature available for apps that must maintain a persistent transport connection in the background. This is typically needed for connectivity to servers running an older protocol that cannot be modified to use WNS, or when there are concerns about privacy or message service-level agreements (SLAs).

For example, an email client that uses a Microsoft Exchange server and is deployed widely within an enterprise cannot be modified to use WNS to send notifications when an email message arrives. The client must maintain a direct TCP connection to the Microsoft Exchange server.

The ControlChannelTrigger class can be used by instances of the following classes in the Windows.Networking.Sockets that establish a TCP connection:

The ControlChannelTrigger class can also be used by instances of the following that establish a TCP connection:

  • The HttpClient and HttpClientHandler classes in the System.Net.Http namespace in the .NET Framework 4.5. Custom classes that derive from these classes are also supported.
  • The IXMLHTTPRequest2 interface. The IXMLHTTPRequest2 interface is an extension to XMLHttpRequest object defined in several working drafts published by the World Wide Web Consortium (W3C)

The network trigger feature offers a number of benefits:

  • Compatibility with existing client/server protocols that require persistent transport connections.
  • Message delivery guarantees, because the app maintains connection state between the client and the server.

There are also some drawbacks with using the network trigger feature:

  • Using the network trigger feature is more complex than WNS because it requires additional components to maintain the transport connection.
  • An app is limited to a maximum of five network triggers.
  • Apps using the network trigger feature with other background tasks need to be written in C# , VB.NET, or C++.

    Note The ControlChannelTrigger class and related classes are not supported in a Metro style app using JavaScript.

Using time triggers or system event triggers in Metro style apps

Lock screen apps can be configured to run code periodically using a time trigger with a minimum interval of 15 minutes. One example is needing to poll for new e-mail messages, possibly when an app is connected to a POP3 or IMAP email server.

Lock screen apps can also use a system event trigger to run code when the user logs on to the local computer (system trigger for session start). One example is signing in the user in to an instant message service when they start a user session, so instant messages can be received.

Creating a lock screen app

You must set the appropriate capabilities in the app manifest so that your app requests to be placed on the lock screen. Your app must also include code to request to be added to the lock screen.

To get onto the lock screen, an app must get consent from the user. The consent prompt appears when the lock screen request API is called. If the user does not give your app permission to run on the lock screen, then you will not be able to prompt for permission again. However, if the user accidently dismisses the dialog you will be able to prompt again.

If users denies your app permission to be a lock screen app, they can add the app to the lock screen at a later time via the system permissions fly-out for your app. Users can also manually add your app to the lock screen from the Personalize section of PC settings.

Register to become a lock screen app

Ensure that your app’s tile has a wide logo associated with it in the app manifest. Ensure that the app manifest has set the WideLogo attribute on the DefaultTile element. Under <VisualElements>:

<DefaultTile ShowName="allLogos" WideLogo="images\tile.png" />

Indicate your app's intention to use a background task. The app manifest must also specify the executable file that contains the background task and the class name where the entry point of the baskground task is implemented.

If you are building a lock screen app that uses push notifications with WNS, specify the pushNotification background task type. This will ensure that your app will receive WNS push notifications.

If you are building a lock screen app that uses the network trigger feature, specify the realTimeCommunication background task type. This will ensure that your app will receive network trigger notifications.

<Extensions> <Extension Category="windows.backgroundTasks" Executable="$targetnametoken$.exe" EntryPoint="Background.RawPushNotifyTask"> <BackgroundTasks> <Task Type="pushNotification" /> </BackgroundTasks> </Extension> <Extension Category="windows.backgroundTasks" Executable="$targetnametoken$.exe" EntryPoint="Background.ReceivePacketTask"> <BackgroundTasks> <Task Type="controlChannel" /> </BackgroundTasks> </Extension> </Extensions>

Since your app will be on the lock screen, it must also have a lock screen icon that can be used to display missed notifications. To enable this, update your app manifest to include the LockScreen element.

<LockScreen Notification="badge" BadgeLogo="Images\badgelogo.png" />

The Background.BackgroundExecutionManager.RequestAccessAsync methods present the user with a dialog box that requests that an app be added to the lock screen. If the user approves the request, your app can run in the background and place notifications on the lock screen.

bool lockScreenAdded = false; async void ClientInit() { // Lock screen is required to let in-process RealTimeCommunication related // background code to execute. // if (lockScreenAdded == false) { BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync(); Diag.DebugPrint("Lock screen status" + status); switch (status) { case BackgroundAccessStatus.AllowedWithRealTimeConnectivity: // // App is allowed to use RealTimeConnection broker // functionality even in low power mode. // lockScreenAdded = true; break; case BackgroundAccessStatus.AllowedWithoutRealTimeConnectivity: // // App is allowed to use RealTimeConnection broker // functionality but not in low power mode. // lockScreenAdded = true; break; case BackgroundAccessStatus.Denied: // // App should switch to polling mode (example: poll for email based on time triggers) // Diag.DebugPrint("As Lockscreen status was Denied, App should switch to polling mode such as email based on time triggers."); break; } } return; }

If you are building a WNS-based lock screen app, the BackgroundAccessStatus for your app will be set to allowedWithoutRealtimeConnectivity after permission has been granted. The real-time connectivity option is used for network trigger feature and does not affect WNS-based lock screen apps.

If you are building a lock screen app using the network trigger feature, the BackgroundAccessStatus for your app will be set to allowedWithRealtimeConnectivity after permission has been granted.

Using WNS to deliver notifications to a lock screen app

Some examples of a background task that can be activated by a WNS notification include the following:

  • Call the notification badge API to increment a badge icon for an email app on the lock screen to indicate that a new email message has arrived.
  • Call the modification toast API to raise a notification for a VoIP app signaling an incoming phone call for the user.

There are four types of push notifications:

  • Tile update
  • Badge update
  • Toast notification
  • Raw notification

All Metro style apps can use the first three push notifications when in the foreground. Only lock screen apps can receive raw push notifications from WNS.

Channels expire after 30 days, so there are best practices:

  • Register to get a new push notification channel every time your app starts, and send it to your server to replace the channel previously tied to the user.
  • For a local computer that is always powered, run a background task to renew the channel every once in a while before the channel expires. This is known as a maintenance timer.

The app must also register the background task to be activated when a push notification is received.

// Register the apps background task with the trigger for push notification task. // private void RegisterBackgroundTask() { BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder(); PushNotificationTrigger trigger = new PushNotificationTrigger(); taskBuilder.SetTrigger(trigger); // Background tasks must live in separate DLL, and be included in the package manifest // Also, make sure that your main application project includes a reference to this DLL taskBuilder.TaskEntryPoint = SAMPLE_TASK_ENTRY_POINT; taskBuilder.Name = SAMPLE_TASK_NAME; BackgroundTaskRegistration task = taskBuilder.Register(); task.Completed += BackgroundTaskCompleted; }

The following sample shows how to handle a raw push notification when in the background.

public sealed class SampleBackgroundTask : IBackgroundTask { public void Run(IBackgroundTaskInstance taskInstance) { // Get the background task details ApplicationDataContainer settings = ApplicationData.Current.LocalSettings; string taskName = taskInstance.Task.Name; Debug.WriteLine("Background " + taskName + " starting..."); // Store the content received from the raw push notification so it can be retrieved from the UI. RawNotification notification = (RawNotification)taskInstance.TriggerDetails; settings.Values[taskName] = notification.Content; Debug.WriteLine("Background " + taskName + " completed!"); } }

The maximum amount of data that can be included in the raw notification payload is 5KB.

Using a network trigger to deliver notifications to a lock screen app

The network trigger feature supports two network trigger types:

  • The pushnotification network trigger provides the capability for a Metro style app to process incoming network packets on a connected TCP socket even if the app is suspended. The connected TCP socket is sometimes referred to as the transport object or control channel. For the notification to reach the client app, this control channel must exist between the remote endpoint and the client. This control channel must be created by the client app in order for incoming network packets on this channel to trigger a background task. You can think of a control channel as a persistent TCP transport connection that is maintained by Windows and is maintained even when your application is in the background.

    Note The pushnotification trigger type is not related at all to push notifications and WNS.

  • The keep-alive network trigger provides a capability for the app to be suspended and send a keep-alive packet to the remote endpoint. This is important to help maintain the transport connection so the remote endpoint server does not close the connection. There is also a variant where a server-initiated keep-alive can also keep the control channel alive.

A lock screen app that uses the network trigger feature must register for the pushnotification trigger and should register for the keep-alive trigger. Together this ensures connectivity between the client and remote endpoint when the app is suspended.

The network trigger feature supports two possible resource types for a pushnotification or keep-alive network trigger:

  • Hardware slot
  • Software slot

This notion of slot is integral to the network trigger and is not required for WNS.

One of the options to specify while registering for the network trigger feature is the hardware or software slot resource type. This resource type capability provides a way for your app to be triggered by an incoming notification even if the device is in low power mode. By default, a software slot is selected if the developer does not specify an option. A software slot allows your app to be triggered when the system is not in connected standby. This is the default on most computers.

On the other hand, a hardware slot allows your app to be triggered at all times including when the system is in connected standby. Only systems with network devices that support connected standby will have a hardware slot. Note that the app cannot be triggered through a software or hardware slot when the system is in Sleep or Hibernate mode, or is shut down.

An app can create and use a maximum of 5 network triggers. There is also an additional system limitation on number of network triggers that specify hardware slots. The first 3 lock screen apps that register for a hardware slot for a network trigger can use a maximum of 3 hardware slots per app. Any other lock screen apps beyond the first three apps registered for hardware slots are limited to only software slots for their network triggers.

Register a background task to activate from a network trigger

The control channel trigger must be registered from a non-foreground app context, specifically a non-UI thread of the app. Note that creating a control channel in the UI thread will negatively impact the client app so it should be avoided.

Creating your control channel trigger

  1. Create a control channel.
  2. Open the transport connection.
  3. Associate the transport connection with the control channel.
  4. Connect the socket to the endpoint server. For some transports, this may be a connect operation. For some transports, this may be a send operation.
  5. Establish a transport connection to your remote endpoint server. After a successful connection to the server, finally synchronize the transport created by your app with lower layers of the operating system by using a specific API as shown in the following code snippet. This API allows the hardware or software slot to be registered with all the underlying layers of the stack that will handle an incoming data packet, including the network device driver.

private bool RegisterWithRTCBroker(StreamSocket sock) { ControlChannelTriggerStatus status; // // Step 1: Create the control channel object. // This.channel = new ControlChannelTrigger( "channelOne", // Channel ID to identify a control channel. 15, // Server-side keep-alive in minutes. ControlChannelTriggerResourceType.RequestHardwareSlot); // Request a hardware slot. // // Create a control channel trigger. // BackgroundTaskBuilder controlChannelBuilder = new BackgroundTaskBuilder(); controlChannelBuilder.Name = “ReceivePacketTaskChannelOne”; controlChannelBuilder.TaskEntryPoint = controlChannelBuilderActivationClassName; controlChannelBuilder.SetTrigger(channel.PushNotificationTrigger); controlChannelBuilder.Register(); // // Step 2: Open a socket connection (not shown here). // // // Step 3: Tie the transport object to the notification channel object. // channel.UsingTransport(sock); // Step 4: Connect the socket (not shown here). // // Step 5: Synchronize with lower layer to register the transport. // status = channel.WaitForPushEnabled(); }

The WaitForPushEnabled method is not related at all to push notifications and WNS.

It is important to note that a control channel trigger object will not accept a loopback connection. Hence, the transport connection must be established to another machine.

When a transport connection closes gracefully or due to abortive disconnect, it will result in the cleanup of hardware and software slots. When this happens there will be no further incoming notifications on this channel. The control channel trigger object itself can be reused for a new transport connection.

The second aspect of a network trigger–based lock screen app is to maintain the control channel through transient intermediate network devices and the destination server. This is done by sending periodic keep-alive messages on the persistent transport.

The control channel allows incoming messages to be delivered to apps. In order for this control channel path to be preserved between a client and the remote endpoint server, a keep-alive message must be sent at periodic intervals to the remote server. The keep-alive can be initiated from the server or the client. There are two variables in this path, the network keep-alive interval and the server keep-alive interval. The network keep-alive interval is the time for which intermediate network devices (such as NATs and proxy devices) will preserve the connection state when there is no traffic on the connection. The keep-alive helps ensure that traffic happens to prevent the socket from being closed.

Similarly, the server keep-alive interval is the frequency with which the server endpoint needs to hear from connected clients to consider that the client is still connected.

The registration for the keep-alive trigger can be done as part of the control channel registration.

Maintaining your control channel

// // Create control channel task (shown in previous snippet). // // Create keep-alive task. BackgroundTaskBuilder keepAliveBuilder = new BackgroundTaskBuilder(); keepAliveBuilder.Name = “KeepAliveTaskChannelOne”; keepAliveBuilder.TaskEntryPoint = KeepAliveTaskActivationClassName; keepAliveBuilder.SetTrigger(channel.KeepAliveTrigger); keepAliveBuilder.Register(); // // Step 2: Open a socket connection (not shown here). //

Windows will determine the optimal network keep-alive interval based on heuristic measurements for a given network. However, the server keep-alive interval must be provided by the app while registering the control channel trigger. The minimum server keep-alive time that can be provided by an app is 15 minutes. If a value lower than 15 minutes is provided, the system will assume a default value of 15 minutes.

The operating system accounts for both these values and chooses an optimum rate at which to send keep-alives for a given app on a given network that will preserve the control channel connection between client and the remote endpoint.

Note that the network keep-alive interval can be much lower than the server keep-alive provided by the app, because the operating system determines the optimal network keep-alive interval and chooses the lower of the two values. This optimal value is used for the keep-alive interval by the operating system to coalesce app use of CPU and network in order to improve battery life.

The keep-alive can be initiated by the client or the server. If the keep-alive is initiated by the server, the incoming notification message on the control channel will trigger a control channel trigger background task. This works well as long as the control channel is open; if the network connection is lost the app would not be aware of this loss, because it will be waiting for the incoming packet. To avoid this, an app can use the keep-alive trigger as a fallback to check for connectivity and re-establish the control channel if necessary.

Note that the keep-alive specified here is the app-level keep-alive, and is different from the TCP keep-alive, which is not used in this keep-alive trigger.

If your app has too many network connection losses, it is possible that the keep-alive interval chosen for the app is too long. In order to enable an app to provide this feedback, the DecreaseNetworkKeepAliveInterval method is provided as part of the ControlChannelTrigger object.

When an app calls DecreaseNetworkKeepAliveInterval, the operating system will reduce the keep-alive interval for the network triggers created for the corresponding channel ID. It will cache this value in a per-network location for a month. The app should call DecreaseNetworkKeepAliveInterval only if it determines that there is frequent connection loss. If necessary, the app may invoke the DecreaseNetworkKeepAliveInterval method more than once to request that Windows further lowers the keep-alive interval. However, Windows enforces a minimal value for the interval. If even after invoking DecreaseNetworkKeepAliveInterval the app continues to see connection losses on a given network, it may choose to not provide real-time connectivity options to its user. Since apps are sandboxed in terms of CPU and network I/O, frequently invoking this function will affect app performance.

Some apps may prefer to know the current keep-alive interval that is used by Windows. For such apps, the CurrentKeepAliveIntervalInMinutes property can be used to retrieve this information.

The CurrentKeepAliveIntervalInMinutes property returns the keep-alive interval in minutes. One example of an app using this value is for server-side keep-alive. The client app can use a value lower than the current keep-alive interval to set its server-side keep-alive interval. This way if the server does not respond within this interval, the client keep-alive timer will fire and the app can re-establish its control channel.

Writing your background task

The next step in making the app always reachable is to provide the app code that executes on a trigger. For example, in the case of VoIP, an incoming packet needs to execute app code to establish the VoIP call and potentially raise a notification to the user. This processing is done in the background task.

public sealed class controlChannelBuilderActivationClassName : Windows.AppModel.Background.IBackgroundTask{ public void Run(Windows.AppModel.Background.IBackgroundTaskInstance taskInstance) { IControlChannelTriggerEventDetails channelEventArgs = (IControlChannelTriggerEventDetails)taskInstance.TriggerDetails; ControlChannelTrigger channel = channelEventArgs.ControlChannelTrigger; string channelId = channel.ControlChannelTriggerId; string messageReceived = "Network packet received"; //InvokeSimpleToast(messageReceived); InvokeRingingToast(messageReceived); Channel.FlushTransport(); }}

The lifetime of the background task is controlled by the Run method. If an app exits the Run method, the app is suspended.

When an app background task is triggered, the operating system ensures that appropriate synchronization delivers the data on the transport connection to the app. Similarly, at the end of the background task an app must call the FlushTransport method to ensure that any pending data is sent before the app is suspended.

Remarks

There are several types of keep-alive intervals that may relate to network apps. At the lowest level, an app can set a TCP keep-alive option to send TCP keep-alive packets between a client app and a server to maintain an established TCP connection that is not being used. The KeepAlive property on the StreamSocketControl class allows an app to enable or disable this TCP keep-alive option on a StreamSocket. The default behavior for a StreamSocket is that TCP keep-alive is disabled. The MessageWebSocket, StreamSocketListener, andStreamWebSocket classes do not have an option to enable TCP keep-alive and this option is disabled by default. Similarly, the HttpClient class and the IXMLHTTPRequest2 object do not have an option to enable TCP keep-alive and this option is disabled by default.

In the context of the ControlChannelTrigger class, there are two other keep-alive intervals that have an impact.

  • Server keep-alive interval - This refers to a keep-alive interval in minutes that the network app registers with the system on how often to be woken up when the app has been suspended. The system will wake up the app based on the value set for this keep-alive interval. This value is represented by the ServerKeepAliveIntervalInMinutes property on a ControlChannelTrigger class and is set by the constructors to initialize a new ControlChannelTrigger instance. This value is considered a server keep-alive interval since a network app might normally set this based on known behavior of the server to which the app has established a TCP connection. For example, if it is known that a Web server will disconnect and drop TCP connections if there is no data sent by the app for 30 minutes, the network app could set this server keep-alive interval to say 25 minutes.
  • Network keep-alive interval - This refers to an internal keep-alive timer maintained by low-level network components in the TCP stack based on current network conditions. This value represents the value needed by network intermediaries to keep the TCP connection intact. These network intermediaries represent hardware and devices such as network proxies and network address translators. A network app cannot set this value, since this value is determined dynamically by low-level system components in the TCP stack . However, a network app can indicate to the system that the network keep-alive timer should be decreased if established TCP connections are regularly dropped by calling the DecreaseNetworkKeepAliveInterval method on a ControlChannelTrigger class.

Troubleshooting and debugging network connections

Note that the default policy in Windows 8 is to pick the unrestricted network over the metered network and the faster network over the slower network.

An app can register for network status change notifications (onNetworkStatusChanged) so it is notified when these network changes occur. If the connection the app was using is no longer available (indicated by an error), the app may need to do one of the following:

  • Retry the operation. If this fails, then wait for another NetworkStatusChanged notification.
  • Check the network cost and try to connect to a different network.

For instance, do not retry the operation if authentication fails, but retry the operation if a wireless network you were communicating with disappeared because another wireless network may be available. Many errors simply disappear when the operation is retried.

When you are testing your application and find errors that are not immediately obvious, you can enable ETW tracing to collect more details on the issue.

A built in diagnostic tool, CheckNetIsolation.exe, is provided to help developers test, diagnose and troubleshoot an app that requires network capabilities.

It has two main options:

LoopbackExempt

View a list of installed apps that are exempt from IP loopback restrictions and allowed access to loopback addresses. This option also allows adding access to IP loopback addresses for a specific app when testing.

Debug

Determines the enabled capabilities that are used by an app and any enabled capabilities that are unused. Any enabled capabilities that are not used make the app less secure. This option can also provides information on network traffic that was dropped,

Some CheckNetIsolation.exe options require the app name or the app ID be provided. Once an app is deployed on a target computer, the app name can be found under the c:\Program Files\Applications folder. This is the name used to start the app. This is the package family name displayed when using Microsoft Visual Studio 11 Beta and represents the App Container. The app ID can be found in the registry under the following key:

HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppContainer

Enable loopback for network access

Network communications using an IP loopback address cannot be used for interprocess communication (between two different apps) since this is restricted by network isolation. Network communication using an IP loopback address is allowed within an app within the same process for communication purposes.

A developer may want to use loopback for testing or debugging purposes, even though that capability will not be available for customers. For example, an app may want to download data from a web service. For development purposes, the developer wants to test the app on a single computer that is configured with the web service locally on 127.0.0.1.

To enable access to loopback addresses, a developer must configure network isolation to exempt the app from loopback restrictions. For packets to be received by a network service, the listener on a TCP or UDP port also needs to be allowed by firewall rules.

Apps developed in Visual Studio will automatically be registered as being exempt from the loopback restrictions.

Debug network isolation issues

The debug option is used to generate a report of network capabilities that are used by an app.

The debug option provides a way to identify if an app is using all the capabilities that are declared in the app manifest. When the debug option is used, the system is instructed to track which of the declared capabilities the app is using and which declared capabilities are not used.

A detailed traffic report also lists the source and destination IP address used for network access.

Więcej szczegółów na How to enable loopback and troubleshoot network isolation.