the windows runtime (winrt) is the shared runtime and api space used by store apps across the...

51

Upload: donald-richard

Post on 02-Jan-2016

239 views

Category:

Documents


2 download

TRANSCRIPT

Build for Both: Building Universal apps for Windows Phone and Windows 8.1Andy WigleyTechnical Evangelist, Microsoftt: andy_wigley b: http://andywigley.com

WIN-B363

TopicsUniversal Apps OverviewConvergence summaryTurning a project universal

Sharing StrategiesShared project and/or PCL?

Code sharingConditional compilationPartial classesDependency Injection

XAML sharingState sharing

What are Universal Apps?

API convergence across the Windows platform The Windows Runtime (WinRT) is

the shared runtime and API space used by store apps across the Windows platform (phone and client)

5

CommonWinRT APIs

Phone-specificWinRT APIs

Windows-specificWinRT APIs

Dramatic convergence in 8.1• Goal is 100% convergence for dev scenarios• In 8.0, we had ~30% API convergence• With 8.1, we move well past 90%+ convergence

HTML

Win32

JavaScript Code

WinRT

C++ Code C#/VB Code

HTML XAML XAML

Windows Runtime XAML

WinJS.NET for Windows

Store

Windows & Phone 8.1 apps

C#/VB Code

Silverlight XAML

Silverlight .NET

Windows Phone Silverlight XAML

Windows & Windows Phone Windows Phone Only

: Universal Apps

Universal AppsApplications on the converged Windows 8.1 and Windows Phone 8.1 platforms

Supported for Windows Runtime XAML with C#, VB or C++, and HTML with Javascript/WinJS

Create universal apps using project templates or convert to universal from an existing Windows Phone 8.1 or Windows 8.1 app

Existing Windows 8.1 app can add Windows Phone 8.1 with shared project (and vice versa)

Convert Project to Universal

Demo:Building a Universal App

Windows Phone 8.1 App Windows 8.1 App

XAML ViewPhone UI

XAML ViewWindows UI

Shared Code, Images, Files

WinRT

‘Universal’ is still two apps, sharing more

Sharing Strategies

Windows Phone 8.1 App Windows 8.1 App

XAML ViewXAML UI

XAML ViewXAML UI

How Much Can I Share?

View

ViewModel

Model

Logic Logic

Data Data

?

Logic

Data

Shared Project FilesMost File Types

Portable Class LibraryLibraries & Windows Runtime Components

“Add As Link”

Code Sharing Options

The ‘Shared’ ProjectAllow sharing source between converged appsNo binary outputSupports all items

Code files

XAML

Images

XML/JSON

RESW

Portable Class LibrariesFor Windows Universal Apps

Supports WinRT APIs

Output Windows Runtime Component Expose libraries to C++, Javascript apps

Portable Class LibrariesFor Windows Universal Apps

Supports WinRT APIs

Output Windows Runtime Component Expose libraries to C++, Javascript apps

Broad Targeting for WP8, .NET

“Add As Link”Similar to Shared project

Compiler conditionals to share across additional platforms

Code Sharing Architecture Separation of Concerns

Decouple UI from logic

UI In the Windows/Windows Phone projectsplus platform specific API sets (some geolocation, media,

sensors)

Logic in Shared projectplus XAML components that “make sense”

Demo:Universal App + PCL

Working with shared Code files

Windows 8.1 Windows Phone 8.1

Common WinRT APIs

some common APIs may have different behaviour across Windows/Phone

Windows Only WinRT

e.g. search contracte.g. multiple windowse.g. resizable windowse.g. printing support

Phone OnlyWinRT

e.g. action centere.g. status bare.g. back key handling

WinRT across Windows+Phone 8.1

files & settings: local, temp, roaming, pickers…

network: http, websockets, sockets…

notifications: tiles, toasts, badges, push

store: app purchases, receipts…

sensors: gps, geofencing, gyro, compass…

lifecycle: launch, suspend, resume, background tasks

localisation: resource resolution from XAML/code…

Unified WinRT APIs for Windows+PhoneExamples:

For some WinRT APIs, Usage Differs‘AndContinue’ APIs: e.g. FileOpenPicker//Create the picker objectFileOpenPicker openPicker = new FileOpenPicker();openPicker.ViewMode = PickerViewMode.Thumbnail;openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;

// Users expect to have a filtered view of their folders openPicker.FileTypeFilter.Add(".jpg");openPicker.FileTypeFilter.Add(".png");

// Open the picker for the user to pick a fileStorageFile file = await openPicker.PickSingleFileAsync();

if (file != null){ // Do something with the file...}

Windows

//Create the picker objectFileOpenPicker openPicker = new FileOpenPicker();

// On Windows Phone, setting Filtering to image types // causes Picker to show Camera RollopenPicker.FileTypeFilter.Add(".jpg");

openPicker.FileTypeFilter.Add(".png");

// Open the picker for the user to pick a fileopenPicker.PickSingleFileAndContinue();

Windows Phone

App suspended, may be terminated

App activated when file picked

For a few WinRT APIs, it’s just differentMapping and GeoLocation convergence

Universal app is possible, but need to introduce platform-specific data conversions and map rendering

Geolocation 100%

Geofencing 100%

Geodata No: Location (Windows) vs. Geopoint (WP)

Map control No: Bing Maps (Windows) vs. WinRT Map control (WP)

#if Compiler ConditionalsInheritancePartial classes

Techniques for handling platform differences

In code that is shared, use #if to conditionally include code to handle differences between Windows and PhoneWindows = WINDOWS_APPWindows Phone = WINDOWS_PHONE_APP

Example: Hardware back button is Windows Phone only

#if Compiler Conditionals

#if WINDOWS_PHONE_APP Windows.Phone.UI.Input.HardwareButtons.BackPressed += this.HardwareButtons_BackPressed;#endif

Sharing Code: InheritanceShared functionality in base classIn the Shared project

Platform specific code in sub-classIn the platform-specific project

Great for separating features that are specific to individual platforms

Can make base class abstract to enforce platform specific implementations

Sharing Code: Partial Classes & MethodsShared functionality in one code filee.g.: DataSource.cs in the shared project

Platform specific code in additional code filee.g.: DataSource.WP.cs in the platform-specific project

Classes are marked as partial and compiled into a single classSeparates platform specific featuresCan use partial methods as a mechanism to separate out platform specific logic

Sharing Code: Partial Classes & Methods/// <summary>/// DataSource.cs/// </summary>public partial class DataSource :IDataSource { public async Task<IEnumerable<IFolder>> RetrieveFolders(IFolder root) { ... // other logic var folders = await LoadFolders(root); ... // other logic return folders }}

/// <summary>/// DataSource.WP.cs/// </summary>public partial class DataSource { private async Task<IEnumerable<IFolder>> LoadFolders(IFolder root) { ... }}

Demo:Handling platform-specific code

Sharing XAML

HERE maps on Windows (8.1)/Phone (8.0)

Reminder: form factor and usage matter

common, same rendering

Button

Slider

ToggleSwitch

ProgressBar

etc (many more)

common, different content

Hub

ListViewGridViewetc.

common, different rendering

DatePicker

TimePickerCommandBarAppBaretc.

unique

SearchBox

PivotContentDialogAutoSuggestBoxetc.

XAML controls on Windows+Phone 8.1

Shared XAML ComponentsUser ControlsComplete XAML pages

One technique:Use Visual State Manager to handle layout changes#if WINDOWS_APP var result = VisualStateManager.GoToState(this, "Windows", false);#elif WINDOWS_PHONE_APP var result = VisualStateManager.GoToState(this, "WindowsPhone", false);#endif

Platform-specific XAML techniquesUse platform-specific Resource DictionariesContains platform-specific styles and Data templates

Merge dictionaries in App.xaml:<Application x:Class="FlickrSearch.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:FlickrSearch"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="CustomDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources></Application>

Define Plat-specific Styles and Templates <ResourceDictionary

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:FlickrSearch"> <Style x:Key="MonTextblock" TargetType="TextBlock"> <Setter Property="Foreground" Value="DeepPink"></Setter> </Style> <DataTemplate x:Name="APhotoTemplate"> <Grid> <Image Source="{Binding Path}" VerticalAlignment="Top" /> <TextBlock TextWrapping="Wrap" Text="{Binding Title}" FontSize="28" Margin="10"/> </Grid> </DataTemplate></ResourceDictionary>

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:FlickrSearch"> <Style x:Key="MonTextblock" TargetType="TextBlock"> <Setter Property="Foreground" Value="Red"></Setter> </Style> <DataTemplate x:Name="APhotoTemplate"> <Grid> <Image Source="{Binding Path}" VerticalAlignment="Top" /> </Grid> </DataTemplate></ResourceDictionary>

FlickrSearch.Windows/CustomDictionary.xaml

FlickrSearch.WindowsPhone/CustomDictionary.xaml

FlickrSearch.Shared/MainPage.xaml

<TextBlock Text="{Binding Title}" Style="{StaticResource MonTextblock}"/> <FlipView ItemsSource="{Binding Items}" ItemTemplate="{StaticResource APhotoTemplate}">

Demo:Sharing XAML

Sharing state across devices:Roaming Data and OneDrive

Roaming Data

WP 8.1 App – PFN 12345

Roaming

Local Temp

Windows App – PFN 12345

Roaming

LocalTemp

PFN 12345

Roamingfolder

App writes data using standard file/settings APIs.

Sync engine transfers data periodically based on triggers (user idle, battery, network, etc.)

OneDrive stores up to 100kb of roaming data per app (not included in user quota). If app exceeds the limit, sync stops.

Other clients are notified of updated data via Windows Notification Service. If app is running when sync occurs, an event is raised.

Roamingsettings

Using the Roaming settings

The RoamingSettings are exposed as a key-value dictionary into which an application can save dataThe data is persisted on the device and also shared with other devices

Note: On Windows 8.1, there is a special HighPriority setting. This has no effect on Windows Phone.

Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;

// saving settings... roamingSettings.Values["userName"] = someData;

// fetching settings... if (roamingSettings.Values.ContainsKey("userName")) { userName = roamingSettings.Values["userName"].ToString(); }

Receive notification on roaming data updateThe DataChanged event fires when the roaming data has changedWindows.Storage.ApplicationData.Current.DataChanged += Current_DataChanged;...

void Current_DataChanged(ApplicationData sender, object args){ // Refresh your settings...}

The event is only fired if the application is active at the time of the changeYou should still load up all your data when your app starts

Tips on using roaming dataApplications can store data in the roaming folder as they would any other folder on the device, or in roaming settings in the same way as local settingsThe synchronisation takes place in the backgroundGood for app customisation settings, most recent activity, partially completed workBad for synchronising large amounts of data or “instant syncing” scenariosLast writer winsHighPriority setting is available on Windows for quick sync, but has no effect on Windows Phone

Demo:Sharing state through Roaming Data

OneDrive for more…Download Live SDKControls and APIs that enable apps to access information from OneDrive

Live SDK enables access to users’ identity profile info and allows your apps to:Upload and download photos, videos, documents, and other files in OneDrivePersonalize your users’ experienceTake advantage of single sign-on using Microsoft Account in Windows 8.1 and Windows Phone 8.1Create, read, and update contacts, calendars, and events in Outlook.com

Summary…Universal Apps OverviewConvergence summaryTurning a project universal

Sharing StrategiesShared project and/or PCL?

Code sharingConditional compilationPartial classesDependency Injection

XAML sharingState sharing

Breakout SessionsWIN-B210 The New Windows Phone Application Model

DEV-B333 Sharing Code and UI with Universal Projects and Windows Library for JavaScript

WIN-B322 From 4 to 40 inches: Developing Windows Applications across Multiple Form Factors

WIN-B217 Deploying and Managing Enterprise Apps on Windows and Windows Phone

WIN-B218 Multi-tasking and Event-Triggered Background Processing for Windows Apps

Related content

Find Me At Ask The Experts – Wednesday evening

Windows Enterprise windows.com/enterprise windowsphone.com/business  

Windows Track Resources

Windows Springboard microsoft.com/springboardMicrosoft Desktop Optimization Package (MDOP)

microsoft.com/mdop Windows To Go microsoft.com/windows/wtg

Windows Phone Developer developer.windowsphone.com

Resources

Learning

Microsoft Certification & Training Resources

www.microsoft.com/learning

msdn

Resources for Developers

http://microsoft.com/msdn

TechNet

Resources for IT Professionals

http://microsoft.com/technet

Sessions on Demand

http://channel9.msdn.com/Events/TechEd

Complete an evaluation and enter to win!

Evaluate this session

Scan this QR code to evaluate this session.

© 2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, 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.