Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

59
wintellect.com debugging design training consulting Basic Windows Phone 8 Application Development with XAML & C# John Garland Senior Consultant [email protected] @ dotnetgator © 2013

description

Related code from the talk can be downloaded from http://sdrv.ms/ZAZNR1

Transcript of Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

Page 1: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Basic Windows Phone 8 Application Developmentwith XAML & C#

John GarlandSenior [email protected]@dotnetgator © 2013

Page 2: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Founded by top experts on Microsoft – Jeffrey Richter, Jeff Prosise, and John Robbins – we pull out all the stops to help our customers achieve their goals through advanced software-based consulting and training solutions.

Consulting & Debugging• Architecture, analysis, and design services• Full lifecycle custom software development• Content creation• Project management• Debugging & performance tuning

Training• On-site instructor-led training• Virtual instructor-led training• Devscovery conferences

Design• User Experience Design• Visual & Content Design• Video & Animation Production

what we do

who we are

how we do it

consulting training debuggingdesign

Page 3: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Topics include:Core ConceptsXAML, Controls, and PagesApplication Lifecycle and StorageContracts and ExtensionsTiles, Toasts, and NotificationsHardware and SensorsDeployment

http://www.syncfusion.com/resources/techportal/ebooks

Free e-book!

Page 4: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• Global Azure Bootcamp– Boston - April 27– http://www.meetup.com/bostonazure

• Granite State WP8 User Group (new!) – Inaugural Meeting - May 16– MSFT Store Rockingham, NH– http://j.mp/GraniteStateWP8

Upcoming Events

Page 5: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• Resources & Concepts• App Structure• UI Elements• App Lifecycle & Storage• Intra-App Interactions• Live Tiles, Toasts, & Notifications• Input (Hardware & Sensors)• Recap

Agenda

Page 6: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Windows Phone 8 Development ResourcesPortals Platform: http://www.windowsphone.com

Dev: http://dev.windowsphone.comWP Toolkit: http://phone.codeplex.com/

Videos //Build 2012 (27 Sessions)http://buildwindows.com

Jump Start Training Videos (21 30-60 minute videos)

Microsoft Virtual Academy:http://aka.ms/WP8-Apps-JS

Channel 9: http://bit.ly/CH9-WP8-Apps-JS

Windows Phone 8 Training Kit(Contoso Cookbook)

http://bit.ly/WP8TrainingKit

API Poster http://bit.ly/WP8Win8ComparisonDoc

Nokia Dev Center http://www.developer.nokia.com (select Windows Phone)

Page 7: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• Windows Phone 8 both is and is not a Windows 8 Phone– A first step on the path to convergence…

• UI– Common Windows Design language (Win as One!)– Use XAML/.NET, but with different XAML dialects and controls– No “1st class” HTML/JavaScript app framework (though frameworks like PhoneGap / Cordova are available)

• Shared Windows 8 Technologies– Common Kernel– Related .NET runtimes– Windows Runtime and Windows Phone Runtime have significant overlap– IE10

• App Platform Differences– App startup, app lifecycle, UI declaration, navigation, some device access, tiles/toasts/notifications

• Windows Store (8) Account is not a Windows Phone (7/8) Store Account– Separate fees

Relationship to Windows 8

Page 8: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Windows Phone 8 API Surface

.NET for Windows

Phone

C#, VB

WP 7.x

Direct3D, XAudio2, MF,

WASAPI, WIN32, COM

C++

WP 8 (56% larger API)

Windows Phone

Runtime

C#, VB, C++

Windows Runtime

Windows Phone

Runtime

Page 9: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• Windows Phone 8 is 99.9% compatible with WP7• If not recompiled, WP7 apps run in “quirks mode”• If recompiled, WP7 apps run without “quirks”• Note - WP8 Apps are “compiled in the cloud”

WP7 Compatibility

WP7.1 App

Quirks

WP8

RecompiledWP7.1 App

WP8 WP8

WP8 App

Page 10: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

demoHello World

Page 11: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Project Purpose Platform

App General simple Windows Phone App, Single Page 7, 8

Databound App Basic MVVM Master-Details app with a databound LongListSelector with design-time sample data

7, 8

Panorama App Basic MVVM app with a Panorama control showing multiple databound sections using design-time data

7, 8

Pivot App Basic MVVM app with a Pivot control showing different databound sections using design-time-data

7, 8

XAML & Direct3D App

Illustrates hybrid application that is with both managed and native components 8

XAML & XNA App Illustrates hybrid application that combines XAML and XNA elements 7

HTML5 App App with embedded browser control that shows HTML content included in the project 8

Audio Playback Agent

Background Agent for playing audio in the background (when other apps are running) 7, 8

Audio Streaming Agent

Background Agent for streaming audio in the background (when other apps are running) 7, 8

Scheduled Task Agent

Background Agent to perform a periodic or resource intensive task 7, 8

Class Library Reusable class library specific to WP OS 7, 8

* Portable Class Library

Class library where the available APIs are determined by the platform selections made in configuration. Used to share code across platforms without using Linked Files. Not available in Express.Platforms Include: .NET 4+, SL 4+, WP7+, WinStore, Xbox 360

Selectable

Visual Studio Project Types

Page 12: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• Display Name• Start Page• App Icon• Supported Resolutions• Default Tile Title &

Images• Runtime Capabilities• Hardware Requirements• Packaging Details• Phone Integration

Settings

XAML Application Structure

Application XAP File (Zip)

Manifest File Other Content (Binaries, Resources, Pages, etc)

Application Object

• System.Windows.Phone.Application

• Responsible for initialization & lifetime event support

• App Startup sequence concludes with setting the RootVisual element

PhoneApplicationFrame

• App’s RootVisual• Coordinates page-to-

page navigation• Journal of pages that are

visited

Page 13: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• Primary container for app content• Support Portrait or Landscape orientations –

pages can be locked to a particular orientation

• App interaction drives navigation between pages

• Page visits are maintained in a “backstack”• The required hardware “Back” button is

automatically tied into page navigation

Pages & Navigation

Portrait (Default)

Landscape

Page 14: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

OrientationSupported Orientations: SupportedOrientations – Portrait | Landscape | PortraitOrLandscapeOrientation Change: OrientationChanged += (sender, args) => { var newOrientation = args.Orientation; };

NavigationSpecific Page: NavigationService.Navigate(new Uri("/DetailPage.xaml?ID=" + itemId, UriKind.Relative));• URI to the XAML file for the page to be created is identified• URIs must be Relative, it must be specified.• Arguments provided as 1-n QueryString params.• Can tap into UriMapping

Backstack Navigation: if (NavigationService.CanGoBack) NavigationService.GoBack();NOTE: The Windows Phone API supports managing the backstack through the NavigationService.RemoveBackEntry()

protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) protected override void OnNavigatedFrom(NavigationEventArgs e) protected override void OnNavigatedTo(NavigationEventArgs e)

Pages & Navigation

Overridable Navigation Handler Methods

Leading ‘/’ character & UriKind.Relative

Page 15: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Page Navigation Sequence

User Initiates Navigation OnNavigatingFrom

Page Ctor

Cancel?

OnNavigatedFrom

OnNavigatedTo

Navigation Stopped

NoYes

Ctor Needed?YesNo

Page 16: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• LongListSelector– Recommended over ListBox – better performance and virtualization support– Optional List Header & Footer, Custom Grouping, Jumplist UI

• Pivot– Present different sets of related items on a single page with horizontal wraparound

sliding– Panels are all the same width

• Panorama– Present items conceptually related to each other on a single page with horizontal

wraparound sliding– Panels can be individually sized– Optionally set a background image

Important Windows Phone Content Controls

Page 17: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Long List Selector

Simple Grouped Jumplist (Grid)

List Header

List Footer

Group HeaderJumplist

Style

Page 18: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

<phone:LongListSelector x:Name="DemoLongListSelectorGrouped" LayoutMode="List" ListHeaderTemplate="{StaticResource LongListSelectorHeaderTemplate}" ListFooterTemplate="{StaticResource LongListSelectorFooterTemplate}“ ItemsSource="{Binding GroupedSampleItems}" ItemTemplate="{StaticResource LongListSelectorItemTemplate}" GroupHeaderTemplate="{StaticResource LongListSelectorGroupHeaderTemplate}" JumpListStyle="{StaticResource LongListSelectorJumpListStyle}" IsGroupingEnabled ="true" HideEmptyGroups ="true"></phone:LongListSelector>

Long List Selector

When grouping is enabled, source items should be a list-of-lists

Page 19: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

PivotTitle

PivotIte

m

Header

Panning

Page 20: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

<phone:Pivot Title="WP8 DEMO“ IsLocked=“false”> <phone:PivotItem Header=“header 1"> <!-- content --> </phone:PivotItem>

<phone:PivotItem Header=“header 2"> <!-- content --> </phone:PivotItem></phone:Pivot>

PivotIf Locked, the Pivot control won’t respond to panning gestures.

Page 21: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Panorama

Panning

Title

Panel Header

s

Panorama Item

Page 22: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

<phone:Panorama Title="wp8 demo"> <phone:Panorama.Background> <ImageBrush ImageSource="/Assets/DotNetGatorDark.png"/> </phone:Panorama.Background>

<phone:PanoramaItem Header=“panel header" Orientation="Horizontal"> <!-- content --> </phone:PanoramaItem> <phone:PanoramaItem Header=“panel header"> <!-- content --> </phone:PanoramaItem>

…etc…</phone:Panorama>

Panorama

Specify Horizontal Orientation to allow variable widths

Optional background image that spans panels

Page 23: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• Provide Command Bar and Command Menu functionality• Always resides alongside the hardware buttons• Up to 4 buttons, recommended up to 5 menu items• App bar elements are NOT visual elements – they cannot

participate in data binding, and cannot be referenced directly by control-name in code!

Application Bar

Page 24: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Application Bar

Collapsed Expanded

AppBarIconButtons

MenuItems

Colla

pse

dExpanded

Page 25: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

<phone:PhoneApplicationPage.ApplicationBar> <shell:ApplicationBar StateChanged="HandleApplicationBarStateChanged"> <shell:ApplicationBar.MenuItems> <shell:ApplicationBarMenuItem IsEnabled="True“ Text="Reset Text“

Click="HandleOnResetTextClicked"/> </shell:ApplicationBar.MenuItems> <shell:ApplicationBarIconButton Text="Bigger" IconUri="/Assets/AppBar/new.png“ Click="HandleOnMakeTextBiggerClicked"/> <shell:ApplicationBarIconButton Text="Smaller" IconUri="/Assets/AppBar/minus.png“ Click="HandleOnMakeTextSmallerClicked"/> </shell:ApplicationBar></phone:PhoneApplicationPage.ApplicationBar>

Application Bar

Contains custom button or menu objects that are visually rendered by the OS.

Page 26: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

demoUI Elements

Page 27: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Windows Phone App Lifecycle

Activating Deactivating

Not Running

Running

Closing Launching

Dormant

Tombstoned

User uses the back button from the first page in the

backstack

App is started from tile, toast, or via a file/protocol association

App loses primary focus via Start Screen, Lock Screen, Toast, file/protocol association

User uses back button to re-enter

app, or selects app from running app list (see ActivationPolicy)

App instance unloaded from

memory

App receives no execution cycles

Page 28: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Defaults to Replace if omitted

<DefaultTask Name=“_default” NavigationPage=“MainPage.xaml” ActivationPolicy=“Resume”/>

Running apps 1…n

Running App Entry: App 2

Page Backstack

Page Backstack

Page Backstack

App StateStorage

Running App Entry: App 2

Page Backstack

Page Backstack

Page Backstack

App StateStorage

Running App Entry: App 1

Page Backstack

Page Backstack

Page Backstack

App StateStorage

App In Memory App In MemoryApp In Memory

System App History Stack

Windows Phone App Management

App Activated event: args.IsApplicationInstancePreserved

True: Went from dormant to activeFalse: Went from tombstoned to active

Page 29: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• State Dictionaries– Easy-to-access in-memory storage of limited key-value data during the

lifetime of the application instance• File Storage APIs

– Isolated Storage - compatible with previous versions of Windows Phone (and Silverlight), wrapper layer on top of newer storage API

– WinRT ApplicationData - new implementation of StorageFile-based data storage, asynchronous only

• Local Database– Using LINQ-to-SQL to store and retrieve data in a SQL Server CE

database file– Using other abstractions over local storage (SQLite, Sterling, etc.)

Data Storage Options

Page 30: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• Exposed as State property on the PhoneApplicationPage object• IDictionary<String, Object>• Objects must be serializable• 2MB max per page, 4MB max per app.• Only available:

– Within/after OnNavigatedTo– Within/before OnNavigatedFrom

• Data stored in-memory and flushed with app instance• Primarily used to store on-page control state

Page State

Page 31: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• Exposed as PhoneApplicationService.Current.State• IDictionary<String, Object>• Objects must be serializable• Storage size limited, but not published• Only available:

– Within or after the application’s Activated event– Within or before the application’s Deactivated event

• Data stored in-memory and flushed with app instance• Useful for app-wide per-session data, data too big for query

strings, saving state for use in Chooser success events

Application State

Page 32: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Page StateState[“Key"] = value;

if (State.ContainsKey(“Key")){ value = State[“Key"];}

Application StatePhoneApplicationService.Current.State[“Key"] = value;

if (PhoneApplicationService.Current.State.ContainsKey("Key")){ value = PhoneApplicationService.Current.State["Key"];}

State Storage

Page 33: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• Scoped to the Application• Capacity limited only by device’s available storage• Storage is freed upon uninstallation• IsolatedStorageSettings

– Data must be serializable– IDictionary<String, Object>– IsolatedStorageSettings.ApplicationSettings– Written to __ApplicationSettings file

• IsolatedStorageFile– Stream-based access to files and folders

Isolated Storage API (Legacy WP7)

Page 34: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Application SettingsIsolatedStorageSettings.ApplicationSettings["Key"] = value;

if (IsolatedStorageSettings.ApplicationSettings.Contains(“Key")){ value = IsolatedStorageSettings.ApplicationSettings[“Key"];}

Filesvar store = IsolatedStorageFile.GetUserStoreForApplication();IsolatedStorageFileStream stream = store.OpenFile(…);store.CreateDirectory(…);store.CreateFile(…);Etc.

Isolated Storage

Typical File IO Operations

Page 35: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• Asynchronous API for interacting with Files and Folders• Only LocalFolder is usable in WP8

– LocalSettings, RoamingSettings, RoamingFolder, TemporaryFolder will throw exceptions if used.

– SetVersion is also not implemented in WP8• Isolated Storage and ApplicationData APIs both write to the

same location

WinRT ApplicationData API

Page 36: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

var localFolder = ApplicationData.Current.LocalFolder;

var storageFile = await localFolder.CreateFileAsync(“FileName.txt", CreationCollisionOption.ReplaceExisting);

using (var writer = new StreamWriter(await storageFile.OpenStreamForWriteAsync())){ // Write file contents}

var storageFile = await localFolder.GetFileAsync("FileName.txt");using (var reader = new StreamReader(await storageFile.OpenStreamForReadAsync())){ // Process file contents}

WinRT StorageFile

Page 37: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

demoApplication Lifetime Management & Storage

Page 38: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• Launchers – Allow an app to launch one of the built-in applications to accomplish a discrete task.– Compose an email, share content to a social network, browser to a

specific website• Choosers – Allow an app to launch one of the built-in

applications to retrieve app-specific data or to perform a task and receive status information upon its completion.– Select a picture, an email address, saving a ringtone.

Launchers & Choosers

Page 39: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Launcher PurposeBingMapsDirectionsTask

Allows an application to launch the Bing Maps application, specifying a starting location or an ending location, or both, for which driving directions are displayed.

BingMapsTask

Allows an application to launch the Bing Maps application centered at the location specified with the Center property or at the user’s current location. If SearchTerm is set, locations matching the search term are tagged on the map.

ConnectionSettingsTask

Allows an application to launch a Settings dialog that allows the user to change the device’s network connection settings.

EmailComposeTaskAllows an application to launch the email application with a new message displayed. Use this to allow users to send email from your application.

MapDownloaderTaskAllows an application to launch the Maps settings application. Use this to allow users to download map data for offline use.

MapsDirectionsTaskAllows an application to launch the Maps application, specifying a starting location or an ending location, or both, for which driving directions are displayed.

MapsTask

Allows an application to launch the Maps application centered at the location specified with the Center property or at the user’s current location. If SearchTerm is set, locations matching the search term are tagged on the map.

MapUpdaterTaskAllows an application to launch the Maps settings application. Use this to allow users to update offline map data they have previously downloaded.

MarketplaceDetailTaskAllows an application to launch the Store client application and display the details page for the specified product.

MarketplaceHubTask Allows an application to launch the Store client application.

Launchers, Pt1

Page 40: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Launchers, Pt2Launcher PurposeMarketplaceReviewTask

Allows an application to launch the Store client application and display the review page for the specified product.

MarketplaceSearchTaskAllows an application to launch the Store client application and display the search results from the specified search terms.

MediaPlayerLauncher Allows an application to launch the media player.

PhoneCallTaskAllows an application to launch the Phone application. Use this to allow users to make a phone call from your application.

SaveAppointmentTaskAllows an application to launch the calendar application with a new appointment displayed. Use this to allow users to add an appointment to their calendar from your application.

SearchTask Allows an application to launch the Web Search application.

ShareLinkTaskAllows an application to launch a dialog that enables the user to share a link on the social networks of their choice.

ShareMediaTaskAllows an application to launch a dialog that allows a user to share a media file on the social networks of their choice.

ShareStatusTaskAllows an application to launch a dialog that enables the user to share a status message on the social networks of their choice.

SmsComposeTask Launches the Messaging application with a new SMS message displayed.

WebBrowserTask Allows an application to launch the web browser application.

Page 41: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

ChoosersLauncher Purpose

AddressChooserTaskAllows an application to launch the Contacts application. Use this to obtain the physical address of a contact selected by the user.

AddWalletItemTaskAllows an application to launch the Wallet application. The provided Wallet item is displayed to the user and the user can choose to add the item to his or her Wallet.

CameraCaptureTaskAllows an application to launch the Camera application. Use this to allow users to take a photo from your application.

EmailAddressChooserTask

Allows an application to launch the Contacts application. Use this to obtain the email address of a contact selected by the user.

GameInviteTaskAllows an application to show a game invite screen that allows the user to invite players to a multiplayer game session.

PhoneNumberChooserTask

Allows an application to launch the Contacts application. Use this to obtain the phone number of a contact selected by the user.

PhotoChooserTask Allows an application to launch the Photo Chooser application. Use this to allow users to select a photo.

SaveContactTask Provides methods and events for launching the contacts application and enabling a user to save a contact.

SaveEmailAddressTaskAllows an application to launch the contacts application. Use this to allow users to save an email address from your application to a new or existing contact.

SavePhoneNumberTaskAllows an application to launch the contacts application. Use this to allow users to save a phone number from your application to a new or existing contact.

SaveRingtoneTaskEnables an application to launch the ringtones application. Use the SaveRingtoneTask to allow users to save a ringtone from your application to the system ringtones list.

Page 42: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Launchersvar task = new ChosenTask { Property = value, Property = value };task.Show();

ChoosersFIELD:private readonly ChosenTask _task;

CTOR:_task = new ChosenTask { Property = value, Property = value };_task.Completed += (sender, result) =>{ if (result.TaskResult == TaskResult.OK) { // process task results }};

Launchers & Choosers

Check the result type:OK, Cancel, None.

Page 43: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

demoIntra-Application Interactions

Page 44: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• 3 Templates: Flip, Iconic, Cycle• Windows Phone supports creating multiple tiles for an app

(secondary tiles)– Tiles include a Navigation Uri with query params for deep linking

• Tiles can be updated directly (must use the same template)• Tiles can also be updated via scheduled updates, background

tasks, or through push notifications

Live Tiles

Page 45: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Flip Template• Image

– Wide image is 691 x 336– Medium image is 336 x 336– Small image is 159 x 159

• Title & Back Title– Wide title is ~39 chars– Medium title is ~19 chars

• Back Content– Medium text is 3 lines ~13

chars ea.– Wide text is 3 lines ~27 chars

ea.• Count: 0-99. If zero, it is not

shown

Page 46: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• Image– Small & Wide icon are 110 x 110

max• Best is 130 x 202

– Medium icon is 202 x 202 max• Best is 70 x 110

• Title– Wide title is ~39 chars– Medium title is ~19 chars

• Content– Wide text is 3 lines @ ~33 chars

ea.

Iconic Template

• BackgroundColor is an ARGB color• If A = 255, color is used• Otherwise, theme color is used

Page 47: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• Images– Up to 9 images– Wide images are 691 x 336– Medium images are centered to

show 336 x 336– Small image is 159 x 159

• Title– Wide title is ~39 chars– Medium title is ~19 chars

• Count– 0-99. If zero, it is not shown.

Cyclic Template

Page 48: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

var tileData = new (FlipTileData | IconicTileData | CyclicTileData) { // Set Tile Properties according to the tile type

Title = "Tile Title",// etc.

};

// Update Primary Tilevar firstTile = ShellTile.ActiveTiles.First();firstTile.Update(tileData);

// Secondary Tilevar uri = new Uri("/DeepLinkPage.xaml?id=data&unique=somethingunique", UriKind.Relative);ShellTile.Create(uri, tileData, true);

Updating Primary Tiles & Creating Secondary Tiles

The Primary Application tile is ALWAYS the first in the list (visible or not) and cannot be deleted.

Tile updates must use the same type of template as was used to create the tile.

Secondary tiles’ navigation targets MUST be unique or an exception will be thrown.

Page 49: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

demoLive Tiles

Page 50: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• Configure the Software Input Panel (SIP) to display keys appropriate to the purpose of the input being collected.

Customizing Keyboard Behavior

URL

Text & Chat

Street AddressDigits

Phone Number

Email

Page 51: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

<TextBox InputScope="TelephoneNumber"/>

Illustrated description of keyboard options and special keys‘ functions:http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh393998(v=vs.105).aspx

Scoping Your SIP

InputScope values are from the InputScopeNameValue enumeration.

Page 52: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• Location & Motion Sensors– 2 Largely Parallel APIs– Windows Phone Runtime API Windows.Devices– .NET API in Microsoft.Devices

• Consider for code reuse if targeting both WP7 & WP8

• Restricted behavior when the app is Idle & in Background Agents

Hardware and Sensors

Page 53: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Location

Note – The Bing Maps control is being deprecated for the phone. The Nokia map control is now part of the Phone SDK – Microsoft.Phone.Map (Using the Map control requires setting the ID_CAP_MAP capability in the Manifest.)

// Requires ID_CAP_LOCATION & user Opt-In notification (PII)var geoLocator = new Windows.Devices.Geolocation.Geolocator(); geoLocator.MovementThreshold = 10;geoLocator.DesiredAccuracy = PositionAccuracy.High;

// Single-shotGeoposition position = await geoLocator.GetGeopositionAsync();

// ContinuousgeoLocator.PositionChanged += (geolocator, args) => { Dispatcher.BeginInvoke(() => { Geocoordinate coordinate = args.Position.Coordinate; Map.Center = coordinate.ToGeoCoordinate(); }); };

Replaces GeoCoordinateWatcher from System.Device.Location

When handling events, be sure to marshall to the UI thread

Page 54: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• Sensors are available through WinRT Windows.Devices.Sensors namespace• Requires setting the ID_CAP_SENSORS capability in the Manifest• Sensors – Windows.Devices.Sensors (7.1 API available in Microsoft.Devices.Sensors)

– <SensorName>.GetDefault()– <Instance>.ReportInterval (Must be set to non-zero to start event-based readings.)– <Instance>.ReadingChanged event– <Instance>.GetCurrentReading()

Sensors

Compass compass = Compass.GetDefault();if (compass != null){ compass.ReportInterval = _compass.MinimumReportInterval; // Set up for reading by setting to nonzero compass.ReadingChanged += CompassReadingChangedEventHandler; CompassReading reading = compass.GetCurrentReading(); // reading.HeadingMagneticNorth, reading.HeadingTrueNorth}

Page 55: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

• External– CameraCaptureTask (Chooser) – External to the app

• In-App– Requires setting the ID_CAP_ISV_CAMERA capability in the Manifest– PhotoCamera – capture photos/stream videos– PhotoCaptureDevice/AudioVideoCaptureDevice – advanced

• Lenses– Custom camera apps that can be accessed from the OS Camera app– Identified in manifest

Camera APIs

Page 56: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Windows Phone 8 Camera Options_cameraTask = new CameraCaptureTask();_cameraTask.Completed += (o, e) => { if (e.TaskResult == TaskResult.OK) { photoImage.Source(BitmapImage(new Uri(e.OriginalFileName))); }}_cameraTask.Show();

PhotoCamera camera;camera = new PhotoCamera();viewFinderBrush.SetSource(camera);camera.CaptureImage();camera.CaptureImageAvailable += (o, e) =>{... (e.ImageStream)}

camera.Dispose();

<Rectangle Width="320" Height="240“ HorizontalAlignment="Left" > <Rectangle.Fill> <VideoBrush x:Name="viewfinderBrush" /> </Rectangle.Fill></Rectangle>

Note: With “Choosers”, you must declare the instance as a field and hook the event in the constructor to properly support suspend/tombstone.

Be sure to call Dispose on the camera so other parts of the app can access the device.

Page 57: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

demoInput

Page 58: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

Other Concepts

Recap• App Structure• UI Elements• App Lifecycle & Storage• Intra-App Interactions• Live Tiles• Hardware & Sensors

– WP Toolkit Controls– Touch & Gestures– Status Bar– Working with Maps– Hybrid DirectX Apps– Speech API– VOIP API– NFC– Local Database API– Media Storage– SD Card access– Encryption– Background Transfers– Background Audio– Background Agents– Alarms & Reminders– Scheduled Tile Updates– File Type & Protocol

Associations– Calendar & Contacts API– Notification Services– Phone UX Integration

(Picture & Search Hubs, Lenses, Wallet)

– Lock Screen Integration – Customizing app’s Kids’

Corner behavior– Company App Stores– Trial Modes– In-App Purchases– Showing Ads– More!

Page 59: Nashua Cloud .NET User Group - Basic WP8 App Dev With XAML and C#, April 2013

wintellect.comdebuggingdesigntrainingconsulting

© 2013

John GarlandSenior [email protected]@dotnetgator

Questions?