45
Building Universal Apps for Windows 10 Devices Jeff Prosise [email protected]

Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise [email protected]

  • Upload
    others

  • View
    16

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Building Universal Apps for Windows 10 Devices

Jeff Prosise

[email protected]

Page 2: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Universal Windows Platform (UWP)

One API for all devices

Guaranteed core API layer across a wide

range of devices

Device families add their own unique

APIs to the guaranteed core API layer

Additional APIs exposed through

extension SDKs

One app package (binary) for all

devices

One Windows Store for all apps

and devices (even Win32 apps)

Page 3: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Your First Universal Windows Platform (UWP) App

Page 4: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

App Structure

Application class derivative represents the app

Derived by Visual Studio in App.xaml and App.xaml.cs

Virtual OnLaunched method called at startup

Window.Current contains reference to app's window

Frame class serves as container for pages and provides navigation API

Override Application.OnLaunched to create a Frame instance and assign it to Window.Current.Content

Page class derivatives represent individual pages

Use "Add New Item" command in Visual Studio to add pages as needed

Optionally override virtual OnNavigatedTo and OnNavigatedFrom methods

Use OnNavigatedTo to retrieve parameters passed to pages when they're navigated to

Use Page.NavigationCacheMode property to control page persistence

Page 5: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Initializing the App

// In App.xaml.csprotected override void OnLaunched(LaunchActivatedEventArgs e){

Frame rootFrame = Window.Current.Content as Frame;

if (rootFrame == null){

rootFrame = new Frame();Window.Current.Content = rootFrame;

}

if (rootFrame.Content == null)rootFrame.Navigate(typeof(MainPage), e.Arguments);

Window.Current.Activate();}

Page 6: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Navigating to Another Page

// Navigate to DetailPage without passing datathis.Frame.Navigate(typeof(DetailPage));

// Navigate to DetailPage and pass datathis.Frame.Navigate(typeof(DetailPage), id);

Typed as Object, but always pass strings

Page 7: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Overriding OnNavigatedTo and OnNavigatedFrom

protected override void OnNavigatedTo(NavigationEventArgs e){

base.OnNavigatedTo(e);var parameter = e.Parameter; // Parameter passed in Navigate's second parameter

// TODO: Do anything necessary to initialize the page each time it's displayed}

protected override void OnNavigatingFrom(NavigatingCancelEventArgs e){

base.OnNavigatingFrom(e);

// TODO: Do anything necessary to clean up before the user navigates// to another page

}

Page 8: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Going Backward and Forward

// Go backif (this.Frame.CanGoBack)

this.Frame.GoBack();

// Go forwardif (this.Frame.CanGoForward)

this.Frame.GoForward();

Page 9: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

SystemNavigationManager

Windows.UI.Core class for handling back-navigation events without adding

extension SDKs or writing adaptive code

GetForCurrentView method returns reference to SystemNavigationManager instance

AppViewBackButtonVisibility property controls visibility of system-provided Back button

In window title bar on desktop apps

No effect on phone apps

BackRequested event fires when Back button is clicked

Software Back button in desktop apps

Hardware Back button in phone apps

Use it in individual pages, or provide global implementation in App.xaml.cs

Page 10: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Handling the Back Button

SystemNavigationManager.GetForCurrentView().BackRequested += (s, e) =>{

if (this.Frame.CanGoBack){

e.Handled = true;this.Frame.GoBack();

}};

Page 11: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Displaying a Back Button on Non-Mobile Devices

SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =AppViewBackButtonVisibility.Visible;

Page 12: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

SystemNavigationManager

Page 13: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

UWP Controls

Universal Windows Platform includes

numerous controls designed to work with

various types of input and present well

on a variety of screens and devices

Pseudo-controls (derive from class other than

control)

Controls (derive from Control)

Content controls (derive from ContentControl)

Items controls (derive from ItemsControl)

One UI, many devices

Page 14: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

SplitView Control

"Hamburger" menu control

featured in many built-in apps

DisplayMode property controls layout

Inline

Overlay

CompactInline

CompactOverlay

IsPaneOpen opens and closes pane

Intended as quick-navigation aid

No default UI

Page 15: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

DisplayMode="CompactInline | Overlay", IsPaneOpen="False"

Page 16: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

DisplayMode="CompactInline", IsPaneOpen="True"

Page 17: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

DisplayMode="CompactOverlay", IsPaneOpen="True"

Page 18: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Using SplitView

<SplitView DisplayMode="CompactOverlay" IsPaneOpen="False"CompactPaneLength="48" OpenPaneLength="200" PaneBackground="#C33D27">

<SplitView.Pane><!-- Declare menu items, including "hamburger," here -->

</SplitView.Pane>

<SplitView.Content><!-- Declare SplitView content here, or insert Frame in App.xaml.cs -->

</SplitView.Content>

</SplitView>

Page 19: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

SplitView Controls

Page 20: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Adaptive UIs

UWP apps adapt their UIs to the screens they're running on

UWP provides state triggers and other tools for building adaptive UIs

Page 21: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

State Triggers

Used with Visual State Manager to trigger changes in the UI

Visual State Manager updated to support setters

No more having to describe state changes with animations

UWP preview contains one state trigger: AdaptiveTrigger

Triggers changes based on window/screen width

Triggers changes based on window/screen height

Custom triggers are easily written by deriving from StateTriggerBase

Orientation triggers, device-family triggers, and many more

Page 22: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Using AdaptiveTrigger

<VisualState x:Name="WideState"><VisualState.StateTriggers><AdaptiveTrigger MinWindowWidth="600" />

</VisualState.StateTriggers><VisualState.Setters><Setter Target="LayoutRoot.Background" Value="LightYellow" />

</VisualState.Setters></VisualState><VisualState x:Name="NarrowState"><VisualState.StateTriggers><AdaptiveTrigger MinWindowWidth="0" />

</VisualState.StateTriggers><VisualState.Setters><Setter Target="LayoutRoot.Background" Value="LightGreen" />

</VisualState.Setters></VisualState>

Page 23: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Adaptive Triggers

Page 24: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Per-Device-Family Views

Views that are specific to device families

Views are XAML files without code-behind files

Use Add New Item -> XAML View in Visual Studio

Views reside in specially named folders which currently

must be created manually

DeviceFamily-Desktop for desktop apps

DeviceFamily-Mobile for mobile apps

One code-behind file, multiple views

The ultimate in adaptive UIs

Page 25: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Per-Device Family Views

Page 26: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

HttpClient

Windows.Web.Http class for HTTP networking

Supercedes Windows 8's System.Net.Http.HttpClient class

Fetch content from the Web, call REST services, and more

Supports GET, POST, PUT, and DELETE

Supports chainable request filters

Supports progress events

Supports HTTPS

No cross-domain/cross-origin restrictions

Page 27: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Calling a REST Service

var client = new HttpClient();var response = await client.GetAsync(new Uri("..."));

if (response.IsSuccessStatusCode){

// Assumes response contains a string (e.g., JSON)var result = await response.Content.ReadAsStringAsync();

}

Page 28: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Specifying a Time-Out

var cts = new CancellationTokenSource();cts.CancelAfter(5000); // Wait up to 5 seconds

try{

var client = new HttpClient();var response =

await client.GetAsync(new Uri("...")).AsTask(cts.Token);}catch(OperationCanceledException){

// Operation timed out}

Page 29: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

POSTing JSON to a REST Service

var json = "{\"firstName\":\"Bill\",\"lastName\":\"Gates\"}";

var client = new HttpClient();var content = new HttpStringContent(json);content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json");var response = await client.PostAsync(new Uri("..."), content);

if (response.IsSuccessStatusCode){

// Assumes response contains a string (e.g., JSON)var result = await response.Content.ReadAsStringAsync();

}

Page 30: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

WebAuthenticationBroker

Windows.Security.Authentication.Web class that enables seamless authentication

with online identity providers

AuthenticateAsync method authenticates with remote provider

Displays provider's login UI unless told not to

Supports OAuth and OpenID protocols

Amazon, Dropbox, Evernote, Facebook, Flickr, FourSquare, GitHub, Google, Instagram, LinkedIn, Reddit,

Tumblr, Twitter, Yammer, and many others

Allows app to gain access to secure sites without having to solicit, transmit, or

cache login credentials

Authentication token can be saved for future access

Page 31: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Consuming REST Services

Page 32: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

UWP App Lifecycle

UWP apps not in the foreground are suspended

On a phone, suspension occurs when the user switches away from the app

On a desktop device, suspension occurs when the app is minimized

Application.Suspending event precedes suspension

Suspended apps can be terminated at any time

e.g., system needs the memory the app consumes

If reactivated, a terminated app should appear as if it was not terminated

Save state before app is suspended and restore it when app is reactivated

Use LocalFolder, LocalSettings, or both to persist state

Page 33: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Handling Application.Suspending Events

// In App.xaml.cspublic App(){

this.InitializeComponent();this.Suspending += this.OnSuspending;

}

private void OnSuspending(object sender, SuspendingEventArgs e){

var deferral = e.SuspendingOperation.GetDeferral();// TODO: Save state, using async methods if neededdeferral.Complete();

}

Page 34: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Determining Whether an App was Suspended and Terminated

// In the OnLaunched override in App.xaml.csif (e.PreviousExecutionState == ApplicationExecutionState.Terminated){

// TODO: Restore state saved when previous app instance was suspended}

Page 35: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Navigation State

In multipage apps, navigation state should be preserved

Return user to page they were on before suspension and termination

Restore the back stack to the state it was in before suspension and termination

Frame object tracks the navigation state and provides API for getting and setting it

Frame.GetNavigationState method returns serialized string containing current navigation state

Frame.SetNavigationState accepts serialized string containing navigation state

Persist the current navigation state in response to Application.Suspending events

Restore the navigation state in Application.OnLaunched if app was suspended and

terminated

Page 36: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Saving Navigation State

// In App.xaml.cspublic App(){

this.InitializeComponent();this.Suspending += this.OnSuspending;

}

private void OnSuspending(object sender, SuspendingEventArgs e){

Frame rootFrame = Window.Current.Content as Frame;ApplicationData.Current.LocalSettings.Values["NavState"] =

rootFrame.GetNavigationState();}

Page 37: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Restoring Navigation State

// In the OnLaunched override in App.xaml.csif (e.PreviousExecutionState == ApplicationExecutionState.Terminated){

if (ApplicationData.Current.LocalSettings.Values.ContainsKey("NavState")){

string navstate = (string)ApplicationData.Current.LocalSettings.Values["NavState"];rootFrame.SetNavigationState(navstate);

}}else{

ApplicationData.Current.LocalSettings.Values.Clear();}

Page 38: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Preserving State

Page 39: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Adaptive Code

All devices implement all APIs in the Universal device family

Targeting other APIs (e.g., Mobile device family) requires adaptive code

if (ApiInformation.IsTypePresent("Windows.Phone.UI.HardwareButtons"){

Windows.Phone.UI.HardwareButtons.CameraPressed += (s, e) =>{

// TODO: Respond to presses of the phone's camera button};

}

Page 40: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Extension SDKs for Device Families

Core UWP APIs are available on all Windows 10 devices

Roughly 90% of all APIs available on Windows 10 devices

Additional APIs are made available by adding device-family extension SDKs

Microsoft Desktop Extension SDK for PCs

Microsoft Mobile Extension SDK for mobile devices (phones)

HoloLens, Xbox Live, IoT, and more

UWP apps adapt their code to the device families they're running on

UWP provides the APIs for doing so

Page 41: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Microsoft Desktop Extension SDK Assemblies (Partial List)

Windows.ApplicationModel.Calls.LockScreenCallsContract

Windows.ApplicationModel.Search.SearchContract

Windows.ApplicationModel.Wallet.WalletContract

Windows.Devices.Printers.PrintersContract

Windows.Devices.Scanners.ScannerDeviceContract

Windows.Devices.SmartCards.SmartCardDeviceContract

Windows.Security.ExchangeActiveSyncProvisioning.EasContract

Windows.System.UserProfile.UserProfileContract

Windows.Media.Capture.CameraCaptureUIContract

Page 42: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Microsoft Mobile Extension SDK Assemblies

Windows.ApplicationModel.Calls.CallsPhoneContract

Windows.ApplicationModel.Wallet.WalletContract

Windows.Devices.SmartCards.SmartCardBackgroundTriggerContract

Windows.Devices.SmartCards.SmartCardEmulatorContract

Windows.Phone.PhoneContract

Windows.Phone.StartScreen.DualSimTileContract

Windows.Security.ExchangeActiveSyncProvisioning.EasContract

Windows.System.UserProfile.UserProfileContract

Windows.UI.WebUI.Core.WebUICommandBarContract

{ Windows.ApplicationModel }

{ Windows.Media.Capture }

{ Windows.Media.Effects }

{ Windows.Media.SpeechRecognition }

{ Windows.Phone }

{ Windows.Phone.ApplicationModel }

{ Windows.Phone.Devices.Notification }

{ Windows.Phone.Devices.Power }

{ Windows.Phone.Media.Devices }

{ Windows.Phone.PersonalInformation }

{ Windows.Phone.Speech.Recognition }

{ Windows.Phone.System }

{ Windows.Phone.System.Power }

{ Windows.Phone.System.Profile }

{ Windows.Phone.UI.Input }

{ Windows.Phone.UI.ViewManagement }

...

Page 43: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Windows.Foundation.Metadata.ApiInformation

Static class for writing adaptive code via run-time API discovery

Method Description

IsApiContractPresent Indicates whether the specified contract is present on this device

IsEnumNamedValuePresent Indicates whether the specified value is present on a specified enum

IsEventPresent Indicates whether the specified event is present on the specified type

IsMethodPresent Indicates whether the specified method is present on the specified type

IsPropertyPresent Indicates whether the specified property is present on the specified type

IsReadOnlyPropertyPresent Indicates whether the specified read-only property is present on the specified type

IsTypePresent Indicates whether the specified type is present on this device

IsWriteablePropertyPresent Indicates whether the specified write-only property is present on the specified type

Page 44: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Using ApiInformation.IsApiContractPresent

if (ApiInformation.IsApiContractPresent("Windows.ApplicationModel.Calls.CallsPhoneContract")

{// TODO: Use Windows.ApplicationModel.Calls.CallsPhoneContract types and type members

}

Page 45: Building Universal Apps for Windows 10 Devicessddconf.com/brands/sdd/library/Building_Universal_Apps...Building Universal Apps for Windows 10 Devices Jeff Prosise jeffpro@wintellect.com

Using ApiInformation.IsTypePresent

if (ApiInformation.IsTypePresent("Windows.Phone.UI.HardwareButtons"){

Windows.Phone.UI.HardwareButtons.BackPressed += (s, e) =>{

// TODO: Respond to the phone's hardware Back button};

}