windows 8 bootcamp
DESCRIPTION
A presentation I gave for Microsoft Partners, 19th of September 2012TRANSCRIPT
Developing on Windows 8
Power point template by Colin Eberhardt
Agenda
WinRT Platform Basics
Best practices
Pickers
Contracts
Tiles
Notifications
Process Lifetime Management
Who am I
Einar Ingebrigtsen
[email protected]@einari
http://blog.dolittle.comhttp://www.ingebrigtsen.info
The target
One runtime to rule them all
Old school interop
Your Managed Code
Traditional Windows API
Manually Generated Interop Code
Windows RT style
Your Managed Code Windows 8 API
Windows Runtime
Architecture
Metro style appLanguage Support
(CLR, WinJS, CRT)
Language Projection
Windows Metadata & Namespace
Web Host (HTML, CSS, JavaScript)
Windows Core
Runtime Broker Windows Runtime Core
UI Pickers Controls Media
XAML Storage Network …
Projections
Primitives(strings,
numbers, etc) Interfaces Enums Structs Delegates Classes
Constructors Static Members Methods Properties Events
Collections
IReadOnlyDictionary<K,V>IMapView<K,V>
IEnumerable<T>IIterable<T>
IList<T>IVector<T>
IReadOnlyList<T>IVectorView<T>
IDictionary<K,V>IMap<K,V>
Bridging the gap
FileOpenPicker picker = new FileOpenPicker();picker.FileTypeFilter.Add("*")a;
StorageFile file = await picker.PickSingleFileAsync();
Windows.Storage.Streams.IInputStream inputStream = await file.OpenReadAsync();
System.IO.Stream stream = inputStream.AsStreamForRead();System.IO.StreamReader reader = new StreamReader(stream);
string contents = reader.ReadToEnd();
APIs
FundamentalsApplication
Services Threading/Timers Memory Management Authentication Cryptography Globalization
Devices
Geolocation Portable Sensors NFC
User Interface
SVG Tiles Input Accessibility Printing
HTML5/CSS XAML DirectX Controls Data Binding
Communications & Data
Memory Management XML Networking SMS
Notifications Streams
Contracts Local & Cloud Storage Web
Media
Playback Capture PlayTo Visual Effects
Missing things
Reflection API changedType details through GetTypeInfo() – extension methodEmit namespace practically empty - security
XAML
Originally developed for Windows Vista and exposed as WPF
Defines what you see
Layout is by default not flowing, as in HTML
Can observe changes (Active View)
Tools
Visual Studio 2012
Blend for VS2012
Dependency Object
Contains property bag for DependencyProperties on object
Holds attached Dependency Properties
DataContext aware
Dependency Properties
A bindable property that can hold binding expressions
Registered on a DependencyObject
Callback when data changes
Attached Dependency Properties
Cross cutting properties
Extend other dependency objects with properties they don’t have
DataContext
HierarchicalChildren uses parents datacontext unless explicitly changing it
Container
Button
Container
TextBlock
TextBlock
Set DataContext = “Hello World”
DataContext = “Hello World”
Set DataContext = “Something else”
DataContext = “Something else”
DataContext = “Hello World”
Binding
SourceDefaults to DataContextCan use StaticResource as source
ModeOneWay, TwoWay, OneTime – OneWay default
ValidationValidatesOnExceptionValidatesOnNotifyDataErrors
INotifyDataErrorInfo
Binding
StringFormatStringFormat = ‘MMM.dd.yyyy’
Null and Fallback valuesTargetNullValue=‘(None)’FallbackValue=‘(Data Context Not Set)’
IValueConverter
Element to Element
Can bind directly to other elements properties
Binds by name of element
Active View
INotifyPropertyChanging / INotifyPropertyChanged
INotifyCollectionChanged – ObservableCollection<>
Property / Collection Changes
UI subscriber updates UIRaise an event
ValueConverter
Simple interface; IValueConverterConvertConvertBack
Converts values during databinding
TypeConverter
Converts data from XAML to CLR types and back
XAML will always give string
Can be defined on a DependencyProperty or on an object with attributes pointing to the converter
Events
You still have events as before – buttons can be clicked and raise an event
RoutedEvents – bubbles through the UI
Async
var future = DownloadDataAsync(...); future.ContinueWith(data => ProcessData(data));
DownloadDataAsync
ProcessData
STOP
ProcessDataDownloadData
var data = DownloadData(...);ProcessData(data);
Async Models
Windows Runtime : IAsyncOperation<T>
.NET Framework : Task<T>
C# 5.0 – async / await
Async – C# style
Marked with “async” modifier
Must return void or Task<T>
Use “await” operator to cooperatively yield control – remember to mark with “async”
Feels just like good old synchronous code
Patterns & Practices
MVVMInspired by PresentationModel by Martin FowlerGood for decoupling – promotes testability
Compositioning
Commands
Actions / Triggers / Behaviors
MVVM
Model
ViewModel
View
Observes
Observable
Compositional UIs
HeaderN
avig
ati
on
Main Content
Footer
Event Aggregator
ViewModel 1 ViewModel 2
Aggregator
Tiles
Tap on tile to launch or switch to an app
Static default tile specified in app manifest
Two sizes:
Both sizes can have live updates
Live Tiles
Tiles updates using pre-defined templates
Templates provide rich rendering options
Text-only image-only or combination
JPEG or PNG only, max size 150 KB
Optional “peek” animation
Local or cloud updates
Notification Queuing
Opt-in to automatically cycle tile through last five notifications
By default only last notification shown
Secondary Tiles
Tiles created by “pinning” content from app
Pin initiated by app via simple runtime call
User confirms pin operation via system UI
Exposes a personalized surface for app
Same capabilities as app tiles
Launch leads to relevant content
Process Lifetime Management
System manages application lifetime
One foreground full screen window
Apps are quickly suspended to preserve battery life
Suspend
System resources focused on the app that the user is interacting with in the foreground
Inactive apps have no impact on battery life or responsiveness, they are suspended by the OS
Enables instant switching between apps
Suspend details
Suspended apps are not scheduled by the NT Kernel
No CPU, Disk or Network consumed
All threads are suspended
Apps remain in memory
Kernel ensures apps are not suspended in critical sections that could cause system wide deadlocks
Apps instantly resumed from suspend when brought to foreground
Session State
SuspensionManagerSessionState
Property bag that is automatically serialized and saved when suspendedReloads property bag from disk on activationDoes not reload state if app crashed
Only save and restore user session metadata
Tip: Don’t wait till suspension to put data into SessionState
Session State : Best practices
User using app
Save incrementally
App switch
Save navigation
Launch
Restore session
Resuming
Do nothing
Termination
User explicitly closes the app: soft terminationSystem needs more memoryUser switch occursSystem shutdownApps crash
Apps does not get notified when they are getting terminated
Process State Transitions
RunningApp
SuspendedApp
suspendingTerminated
AppLow Memory
Code gets to run No code runs App not running
resuming
User Launches
App
Splash screen
Splash screen
System provides splash screen mechanism
Shown while Windows launches your app
Presented during activation
Developer provides color and image in app manifest
Apps need to present a window within 15 seconds of activation or the app will be terminated
Background Audio Playback
Apps can play audio in the background
Developers must specify background audio in the app manifest
Each audio stream is given a type (communication, media, game)
Onle one audio stream type may play at a given time
Upload/Download in the background
Use the BackgroundTransfer API to upload or download data over HTTP in the background
Initiate upload / download from the foreground and it can continue though your app is suspended
Background tasks
Trigger / Condition basedSystem events
InternetAvailableNetworkStateChangeOnlineIdConnectedStateChangeSmsReceivedTimeZoneChange
Background tasks for lock screen capable appsControl ChannelTimerPush Notifications
System events for lock screen-capable appsUserPresentUserAwayControlChannelResetSessionConnectedLockScreenApplicationAddedLockScreenApplicationRemoved
Background tasks : resources
CPU resource quota Refresh period
Lock screen app 2 CPU seconds 15 minutes
Non-lock screen app 1 CPU second 2 hours
Windows Notification Service
Enables delivery of tile and toast notification over the internet
Tile updates and notifications shown to the user even if your app is not running
WNS handles communication with your app
Scales to millions of users
WNS is a free service for your app to use
Push Notification Overview
Windows 8 Cloud Service
Windows Push Notification
Service
Metro Style App
Notification
Client Platform
2
3
1 3
1. Request Channel URI
2. Register with your Cloud Service
3. Authenticate & Push Notification
Toast Notifications
Toast notifications deliver transient messages outside the context of the app
Use toast notifications to get user’s attention immediately
User is in control and can permanently turn off toast notifications from your app
Allows quick navigation to a contextually relevant location in your app
Toast notifications are easy to invoke from your app or from the cloud
Toast Templates
Uses same template architecture as Live Tiles
Rich set of rendering options available
Contracts
Contracts enable integrating the Windows 8 experience into your app
Yields a consistent UI for all apps
Search
Enables your app to interact and respond to
SuggestionsSearch Query
Settings
Consistently given one place to get searchContext sensitive to the front facing app
Share
Your app can share anything (text, images, binaries)Automatically filters available applications to share to
Your app can be a share target – receive sharing from othersAdd sharing target as a capability and you can receive share requests
Play To
Ability to stream media to compatible devices
Data
Isolated Storage is the key http://metrostoragehelper.codeplex.com
DatabaseSQL Lite
http://timheuer.com/blog/archive/2012/05/20/using-sqlite-in-metro-style-app.aspx
Summarized
Windows RT is a huge leap, both in faith but also technically
Consistent API that feels mature from day one
Well architected solutions putting the user first
Makes us as developers focus on adding the business value
Resources
The samples of todayhttp://github.com/einari/toodeloo
INPC Weaverhttp://github.com/SimonCropp/NotifyPropertyWeaver
WinRT Toolkit http://jupitertoolkit.codeplex.com
Tiny IoC container - WinRT Compatiblehttp://microsliver.codeplex.com/
Resources
MVVM Lighthttp://mvvmlight.codeplex.com/
Setting up push notifications – registering your apphttps://manage.dev.live.com/build
WAT for Windows 8 + WnsRecipehttp://watwindows8.codeplex.com/releases/view/73334
Calisto – UI Framework for WinRThttps://github.com/timheuer/callisto
Get into the store – register as a deveveloperhttp://msdn.microsoft.com/en-us/windows/apps/
Thanks for your attention