Top Banner
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
28

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

Feb 09, 2016

Download

Documents

Skylar

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
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: The story of state App data, settings, and the process lifecycle

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

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

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

Agenda

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

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

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

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

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

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)

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

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

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

Demo

Stateful apps

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

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

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

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"];

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

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);

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

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;

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

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 });}

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

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");

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

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

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

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);

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

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

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

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

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

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

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

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

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

Demo

Settings

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

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)

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

Demo

Background tasks for state

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

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

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

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

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

• 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

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

© 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.