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 3126 Look at stateful apps from the perspective of state itself ID: 391926
Download Presentation The PPT/PDF document "The story of state" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
The story of stateApp 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-126Slide2
Look at stateful apps from the perspective of state itselfWhat is its purpose
Where does it live
What affects and modifies state
AgendaSlide3
The purpose of state is to maintain a consistent
app experience across
sessions, devices, and process
lifecycle events Slide4
The user experience: apps are
stateful
Apps don’t start in an uninitialized state, even on first run
Persistent settings are always in effect
Settings that are user-specific but not device-specific can roam across devices (like account setups)
The settings charm is where users manage relevant state
Transient session state (like
unsubmitted
form data and navigation history) is preserved across sessions if and only if Windows terminates an app
User data is more app-independentSlide5
State is persistent
State exists when apps aren’t running or in memory at all
State carries user preferences across sessions
State carries transient session data across suspend, terminate, and restart
State can roam across a user’s devices
State can be modified by background tasks
State is versioned independently of apps (and less often)Slide6
Review of process lifecycle events
Running
app
Suspended
app
Suspending
Terminated
appLow resources
Code gets to run
App frozen
App not running
Resuming
App gets
5 seconds
to handle suspend
App is
not
notified before termination
Apps are notified when they have been resumed
User
launches app
Splash screen
Limited background tasks can runSlide7
Demo
Stateful
appsSlide8
The big picture of state
In memory
(app
changes variables
)
Running
Suspended
Not runningSystem restartOther devicesLocal/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
d
ata
(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 cloudSlide9
Basic state settings (C#)
using
Windows.Storage;
// Create a simple setting
ApplicationDataContainer
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"
];Slide10
Basic files (C#)
using
Windows.Storage
;
//
Write a file
StorageFolder 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);Slide11
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;Slide12
DataChanged event (C#)
using
Windows.Storage;
// DataChanged is fired when new data has been roamed to this device
applicationData.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 });}Slide13
Access cache (C#)
using
Windows.Storage;
using
Windows.Storage.AccessCache;
// First permission granted by folder picker
StorageFolder 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");Slide14
Credential Locker
For securely storing passwords apps should neither store nor roam passwords independently
On trusted PCs, these are roamed with the user
Also note CredentialPicker API
Sample:
http://bit.ly/OUr8LC
Slide15
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);Slide16
Additional AppData APIs
All languages
SQLite:
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.htmlSlide17
State versioning
Applies to the entire contents of
AppData
Managed through SetVersionAsync
No relationship to app version: many app versions can and will likely use the same version of state
On 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 installedSlide18
Settings UI
Settings is a ubiquitous app feature, hence the charm
Settings charm eliminates need to have specific settings pages within the app’s navigation hierarchy
Use for state and configuration that the user can control
Accounts, preferences, etc.
Specifying what roams and what doesn’t
State 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 stateSlide19
Settings API
App responds to
Windows.UI.ApplicationSettings.CommandsRequested
eventApp populates commandsLinks: help, privacy statement, terms of use, etc.Panels: invoke
flyouts
that change app data
System provides permissions, rate and reviewSettings flyout controlsXAML: Windows.UI.Xaml.Controls.SettingsFlyoutJavaScript: WinJS.UI.SettingsFlyoutSlide20
Demo
SettingsSlide21
Background tasks for state
Maintenance triggers
Run periodically on AC power
Useful for cleaning up temp stateSystem triggers
AC power, non-lock screen
InternetAvailable
, 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)Slide22
Demo
Background tasks for stateSlide23
Best practices for apps
Launch with initial defaults
JavaScript: use
sessionState object as a namespace for variablesC#/VB/C++: Use
SuspensionManager
helpers
Write 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 sizeSlide24
Best practices for apps
Session state: restore if launched after terminated
Typically only a few pieces of data
Session state is not restored if app is launched to service contracts or launch argumentsException: search
Launch arguments means file type activation or secondary tile
Check elapsed time and refresh when resuming
Especially data from online servicesSlide25
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 sessionsSlide26
Application data sample
Launching, resuming, and multitasking
Background task sample
Programming Windows 8 Apps in HTML, CSS, and JavaScript
ResourcesSlide27
Develop:
http
://msdn.microsoft.com/en-US/windows/apps/br229512
Design:
http://design.windows.com/
Samples: http://code.msdn.microsoft.com/windowsapps/Windows-8-Modern-Style-App-SamplesVideos: http://channel9.msdn.com/WindowsResourcesPlease submit session evals by using the Build Windows 8 appor at http://aka.ms/BuildSessionsSlide28