The story of state App data, settings, and the process lifecycle

Post on 09-Feb-2016

41 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

The story of state App data, settings, and the process lifecycle. Kraig Brockschmidt Senior Program Manager, Windows Ecosystem Team Author, Programming Windows 8 Apps with HTML, CSS, and JavaScript 3-126. Agenda. Look at stateful apps from the perspective of state itself - PowerPoint PPT Presentation

Transcript

The story of stateApp data, settings, and the process lifecycleKraig BrockschmidtSenior Program Manager, Windows Ecosystem TeamAuthor, Programming Windows 8 Apps with HTML, CSS, and JavaScript3-126

Look at stateful apps from the perspective of state itselfWhat is its purposeWhere does it liveWhat affects and modifies state

Agenda

The purpose of state is to maintain a consistent app experience acrosssessions, devices, and process lifecycle events

The user experience: apps are statefulApps don’t start in an uninitialized state, even on first runPersistent settings are always in effectSettings that are user-specific but not device-specific can roam across devices (like account setups)The settings charm is where users manage relevant stateTransient session state (like unsubmitted form data and navigation history) is preserved across sessions if and only if Windows terminates an appUser data is more app-independent

State is persistentState exists when apps aren’t running or in memory at allState carries user preferences across sessionsState carries transient session data across suspend, terminate, and restartState can roam across a user’s devicesState can be modified by background tasksState is versioned independently of apps (and less often)

Review of process lifecycle events

Runningapp

Suspendedapp

Suspending Terminatedapp

Low resources

Code gets to run App frozen App not running

Resuming

App gets 5 seconds to

handle suspendApp is not

notified before termination

Apps are notified when they have been resumed

User launches app

Splash screen

Limited background tasks can run

Demo

Stateful apps

The big picture of state

In memory(app changes variables)

Running Suspended Not running System restart Other devices

Local/temp app data (modified by WinRT and other APIs)Includes databases (SQLite, IndexedDB, ESE/Jet) and other facilities built on appdata (HTML AppCache, local storage, third-party libraries)

Roaming app data (modified by WinRT and other APIs), sync’d to cloud (within quota)

Windows.Storage.AccessCache (modified by WinRT API)

Windows.Storage.PasswordVault (modified by WinRT API), sync’d to cloud

Basic state settings (C#)using Windows.Storage;

// Create a simple settingApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;localSettings.Values["message"] = "Hello World";

Object value = localSettings.Values["message"];

// Create a setting in a containerApplicationDataContainer container = localSettings.CreateContainer( "exampleContainer", ApplicationDataCreateDisposition.Always);

localSettings.Containers["exampleContainer"].Values["message"] = "Hello World";Object value = localSettings.Containers["exampleContainer"].Values["message"];

Basic files (C#)using Windows.Storage;

// Write a fileStorageFolder roamingFolder = ApplicationData.Current.roamingFolder;StorageFile file = await roamingFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

await FileIO.WriteTextAsync(file, counter.ToString());

// Read a fileStorageFile file = await roamingFolder.GetFileAsync(filename);string text = await FileIO.ReadTextAsync(file);

Composite + HighPriority roaming (C#)using Windows.Storage;

ApplicationDataContainer roamingSettings = ApplicationData.Current.RoamingSettings;ApplicationDataCompositeValue composite = new ApplicationDataCompositeValue();

composite["readerSet"] = "Liam's Books";composite["page"] = 524;roamingSettings.Values["HighPriority"] = composite;

DataChanged event (C#)using Windows.Storage;

// DataChanged is fired when new data has been roamed to this deviceapplicationData.DataChanged += new TypedEventHandler<ApplicationData, object> (DataChangedHandler);

async void DataChangedHandler(Windows.Storage.ApplicationData appData, object o){ // DataChangeHandler may be invoked on a background thread, so use the // Dispatcher to invoke the UI-related code on the UI thread. Not needed // in JavaScript. await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Handle new data });}

Access cache (C#)using Windows.Storage;using Windows.Storage.AccessCache;

// First permission granted by folder pickerStorageFolder folder = await folderPicker.PickSingleFolderAsync();if (folder != null){ // Remember permission for future access to the folder // (including other sub-folder contents) StorageApplicationPermissions.FutureAccessList.AddOrReplace( "PickedFolderToken", folder);}

// Retrieve cached permission (in a later session)StorageFolder folder2 = await StorageApplicationPermissions.FutureAccessList .getFolderAsync("PickedFolderToken");

Credential LockerFor securely storing passwords apps should neither store nor roam passwords independentlyOn trusted PCs, these are roamed with the userAlso note CredentialPicker APISample:http://bit.ly/OUr8LC

Credential Picker & Locker (C#)using Windows.Security.Credentials;using Windows.Security.Credentials.UI;

CredentialPickerOptions credPickerOptions = new CredentialPickerOptions();// Set options like captions, messages, protocol, etc.var res = await CredentialPicker.PickAsync(credPickerOptions);

PasswordVault vault = new PasswordVault();

// Password typically encrypted already from UI...but this is good for plain textPasswordCredential c = new PasswordCredential("myCreds", res.CredentialUserName, res.CredentialPassword);vault.Add(c);

// To retrieve later onPasswordCredential cred = vault.Retrieve("myCreds", userName);

Additional AppData APIsAll languagesSQLite: http://bit.ly/MuzL1e (Tim Heuer’s blog)ESE/Jet APIs (Win32): http://bit.ly/ToslcK (reference); for JavaScript needs a WinRT componentJavaScript onlyIndexedDB: http://bit.ly/RyT9uk (reference) http://bit.ly/P5H292 (sample)HTML5 localStorage: http://www.w3.org/TR/webstorage/ HTML5 AppCache: http://dev.w3.org/html5/spec/offline.html

State versioningApplies to the entire contents of AppDataManaged through SetVersionAsyncNo relationship to app version: many app versions can and will likely use the same version of stateOn launch, app should migrate old state if found, and call SetVersionAsync to update the versionCloud service for roaming data maintains multiple versions until all apps have upgradedCan use ServicingComplete background task trigger to migrate state when an app update is installed

Settings UISettings is a ubiquitous app feature, hence the charmSettings charm eliminates need to have specific settings pages within the app’s navigation hierarchyUse for state and configuration that the user can controlAccounts, preferences, etc.Specifying what roams and what doesn’tState that app maintains silently doesn’t need to appear hereApp’s settings flyouts are just pieces of UI with unique means of invoking them; typically write to persistent state

Settings APIApp responds to Windows.UI.ApplicationSettings.CommandsRequested eventApp populates commandsLinks: help, privacy statement, terms of use, etc.Panels: invoke flyouts that change app dataSystem provides permissions, rate and reviewSettings flyout controlsXAML: Windows.UI.Xaml.Controls.SettingsFlyoutJavaScript: WinJS.UI.SettingsFlyout

Demo

Settings

Background tasks for stateMaintenance triggersRun periodically on AC powerUseful for cleaning up temp stateSystem triggersAC power, non-lock screenInternetAvailable, NetworkStateChange for connectivityServicingComplete: perfect time to migrate app state versionsLock screen triggers (AC or battery power)Session Connected, UserPresent, UserAway, TimeTriggerAll tasks subject to CPU and network activity quotasIndependent of main app (can use mixed languages)

Demo

Background tasks for state

Best practices for appsLaunch with initial defaultsJavaScript: use sessionState object as a namespace for variablesC#/VB/C++: Use SuspensionManager helpersWrite session and persistent state incrementally as it changesDon’t leave this for the suspending event unless necessaryAlways save file references in access cache—never save pathsSome files/folders don’t come from the file system!Always save passwords in the Credential LockerUse encryption for security, compression to minimize size

Best practices for appsSession state: restore if launched after terminatedTypically only a few pieces of dataSession state is not restored if app is launched to service contracts or launch argumentsException: searchLaunch arguments means file type activation or secondary tileCheck elapsed time and refresh when resumingEspecially data from online services

• 10/31 145p – Kodiak – Introduction to creating Windows Store apps using XAML (3-116)

• 10/30 215p – Kodiak – Introduction to creating a Windows Store App using HTML and JavaScript (3-115)

• 11/1 830a – Kodiak – Alive with activity: Tiles, notifications, and background tasks (3-101)

Related sessions

© 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

top related