This document provides a 3 sentence summary of the Basic Windows Phone 8 Application Development with XAML & C# document:
The document outlines the core concepts and structure for developing basic applications for Windows Phone 8 using XAML and C#, including an overview of pages, controls, navigation, and the application lifecycle. It also covers important UI elements like the LongListSelector, Pivot, and Panorama controls as well as data storage options and the application bar.
2. what we do
consulting training design debugging
who we are
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.
how we do it Training
• On-site instructor-led training
Consulting & Debugging • Virtual instructor-led training
• Architecture, analysis, and design services • Devscovery conferences
• Full lifecycle custom software development
• Content creation Design
• Project management • User Experience Design
• Debugging & performance tuning • Visual & Content Design
• Video & Animation Production
consulting training design debugging wintellect.com
3. Free e-book!
Topics include:
Core Concepts
XAML, Controls, and Pages
Application Lifecycle and Storage
Contracts and Extensions
Tiles, Toasts, and Notifications
Hardware and Sensors
Deployment
http://www.syncfusion.com/resources/techportal/ebooks
consulting training design debugging wintellect.com
4. Upcoming Events
• 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
consulting training design debugging wintellect.com
6. Windows Phone 8 Development Resources
Portals Platform: http://www.windowsphone.com
Dev: http://dev.windowsphone.com
WP 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 http://bit.ly/WP8TrainingKit
(Contoso Cookbook)
API Poster http://bit.ly/WP8Win8ComparisonDoc
Nokia Dev Center http://www.developer.nokia.com (select Windows Phone)
consulting training design debugging wintellect.com
7. Relationship to Windows 8
• 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
consulting training design debugging wintellect.com
8. Windows Phone 8 API Surface
WP 7.x
WP 8 (56% larger API)
.NET for Windows Phone Direct3D,
Windows Phone Runtime XAudio2, MF,
WASAPI, WIN32,
COM
Windows Windows
Runtime Phone
Runtime
C#, VB C#, VB, C++ C++
consulting training design debugging wintellect.com
9. WP7 Compatibility
• 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.1 App Recompiled
WP8 App
WP7.1 App
Quirks
WP8 WP8 WP8
consulting training design debugging wintellect.com
10. demo
Hello World
consulting training design debugging wintellect.com
11. Visual Studio Project Types
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. Selectable
Used to share code across platforms without using Linked Files. Not available in Express.
Platforms Include: .NET 4+, SL 4+, WP7+, WinStore, Xbox 360
consulting training design debugging wintellect.com
12. XAML Application Structure
Application XAP File (Zip)
Manifest File Other Content (Binaries, Resources, Pages, etc)
• Display Name
• Start Page Application Object
• App Icon
• Supported Resolutions • System.Windows.Phone.Application PhoneApplicationFrame
• Responsible for initialization &
• Default Tile Title & Images lifetime event support • App‟s RootVisual
• Runtime Capabilities • App Startup sequence concludes • Coordinates page-to-page
• Hardware Requirements with setting the RootVisual element navigation
• Packaging Details • Journal of pages that are
• Phone Integration Settings visited
consulting training design debugging wintellect.com
13. Pages & Navigation
• 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 Portrait (Default)
automatically tied into page navigation
Landscape
consulting training design debugging wintellect.com
14. Pages & Navigation
Orientation
Supported Orientations: SupportedOrientations – Portrait | Landscape | PortraitOrLandscape
Orientation Change: OrientationChanged += (sender, args) => { var newOrientation = args.Orientation; };
Navigation
Specific 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
Leading „/‟ character & UriKind.Relative
Backstack Navigation: if (NavigationService.CanGoBack) NavigationService.GoBack();
NOTE: The Windows Phone API supports managing the backstack through the NavigationService.RemoveBackEntry()
Overridable protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
Navigation Handler protected override void OnNavigatedFrom(NavigationEventArgs e)
Methods protected override void OnNavigatedTo(NavigationEventArgs e)
consulting training design debugging wintellect.com
15. Page Navigation Sequence
User Initiates
OnNavigatingFrom
Navigation
Navigation Yes No
Cancel?
Stopped
No Yes
Ctor Needed?
Page Ctor
OnNavigatedFrom
OnNavigatedTo
consulting training design debugging wintellect.com
16. Important Windows Phone Content Controls
• 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
consulting training design debugging wintellect.com
17. Long List Selector
Simple Grouped Jumplist (Grid)
List Header
Group Header
Jumplist Style
List Footer
consulting training design debugging wintellect.com
18. Long List Selector
<phone:LongListSelector x:Name="DemoLongListSelectorGrouped"
LayoutMode="List"
ListHeaderTemplate="{StaticResource LongListSelectorHeaderTemplate}"
ListFooterTemplate="{StaticResource LongListSelectorFooterTemplate}“
ItemsSource="{Binding GroupedSampleItems}"
ItemTemplate="{StaticResource LongListSelectorItemTemplate}" When grouping is
GroupHeaderTemplate="{StaticResource LongListSelectorGroupHeaderTemplate}" enabled, source
JumpListStyle="{StaticResource LongListSelectorJumpListStyle}" items should be a
IsGroupingEnabled ="true" list-of-lists
HideEmptyGroups ="true">
</phone:LongListSelector>
consulting training design debugging wintellect.com
19. Pivot
Title
Header
Pivot
Item
Panning
consulting training design debugging wintellect.com
20. Pivot
If Locked, the Pivot
<phone:Pivot Title="WP8 DEMO“ IsLocked=“false”> control won‟t respond to
<phone:PivotItem Header=“header 1"> panning gestures.
<!-- content -->
</phone:PivotItem>
<phone:PivotItem Header=“header 2">
<!-- content -->
</phone:PivotItem>
</phone:Pivot>
consulting training design debugging wintellect.com
21. Panorama
Title
Panel
Headers
Panorama
Item
Panning
consulting training design debugging wintellect.com
23. Application Bar
• 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!
consulting training design debugging wintellect.com
24. Application Bar
Collapsed Expanded
Collapsed
Expanded
AppBarIconButtons MenuItems
consulting training design debugging wintellect.com
25. Application Bar
<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>
Contains custom button or
menu objects that are
visually rendered by the OS.
consulting training design debugging wintellect.com
26. demo
UI Elements
consulting training design debugging wintellect.com
27. Windows Phone App Lifecycle
Not Running
User uses the back App is started from
button from the first Closing Launching tile, toast, or via a
page in the backstack file/protocol
association
Running
App loses primary
User uses back button to
focus via Start Screen,
re-enter app, or selects
Activating Deactivating Lock Screen, Toast,
app from running app
file/protocol
list (see ActivationPolicy)
association
App receives no
Dormant
execution cycles
App instance unloaded
Tombstoned
from memory
consulting training design debugging wintellect.com
28. Windows Phone App Management
System App History Stack
Running App Entry: App 1 Running App Entry: App 2 Running App Entry: App 2
Page Page Page
Page
Backstack Page
Backstack Page
Backstack
Page
Backstack App State Page
Backstack App State Page
Backstack App State
Running apps 1…n Backstack Storage Backstack Storage Backstack Storage
App In Memory App In Memory App In Memory
True: Went from dormant to active
App Activated event: args.IsApplicationInstancePreserved
False: Went from tombstoned to active
Defaults to
<DefaultTask Name=“_default” NavigationPage=“MainPage.xaml” ActivationPolicy=“Resume”/> Replace if
omitted
consulting training design debugging wintellect.com
29. Data Storage Options
• 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.)
consulting training design debugging wintellect.com
30. Page State
• 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
consulting training design debugging wintellect.com
31. Application State
• 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
consulting training design debugging wintellect.com
32. State Storage
Page State
State[“Key"] = value;
if (State.ContainsKey(“Key"))
{
value = State[“Key"];
}
Application State
PhoneApplicationService.Current.State[“Key"] = value;
if (PhoneApplicationService.Current.State.ContainsKey("Key"))
{
value = PhoneApplicationService.Current.State["Key"];
}
consulting training design debugging wintellect.com
33. Isolated Storage API (Legacy WP7)
• 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
consulting training design debugging wintellect.com
34. Isolated Storage
Application Settings
IsolatedStorageSettings.ApplicationSettings["Key"] = value;
if (IsolatedStorageSettings.ApplicationSettings.Contains(“Key"))
{
value = IsolatedStorageSettings.ApplicationSettings[“Key"];
}
Files
var store = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream stream = store.OpenFile(…);
store.CreateDirectory(…); Typical File IO
store.CreateFile(…); Operations
Etc.
consulting training design debugging wintellect.com
35. WinRT ApplicationData API
• 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
consulting training design debugging wintellect.com
36. WinRT StorageFile
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
}
consulting training design debugging wintellect.com
38. Launchers & Choosers
• 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.
consulting training design debugging wintellect.com
39. Launchers, Pt1
Launcher Purpose
Allows an application to launch the Bing Maps application, specifying a starting location or an ending location, or both, for
BingMapsDirectionsTask which driving directions are displayed.
Allows an application to launch the Bing Maps application centered at the location specified with the Center property or at
BingMapsTask 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.
Allows an application to launch the email application with a new message displayed. Use this to allow users to send email
EmailComposeTask from your application.
Allows an application to launch the Maps settings application. Use this to allow users to download map data for offline
MapDownloaderTask use.
Allows an application to launch the Maps application, specifying a starting location or an ending location, or both, for
MapsDirectionsTask which driving directions are displayed.
Allows an application to launch the Maps application centered at the location specified with the Center property or at the
MapsTask user‟s current location. If SearchTerm is set, locations matching the search term are tagged on the map.
Allows an application to launch the Maps settings application. Use this to allow users to update offline map data they have
MapUpdaterTask previously downloaded.
MarketplaceDetailTask Allows 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.
consulting training design debugging wintellect.com
40. Launchers, Pt2
Launcher Purpose
MarketplaceReviewTask Allows an application to launch the Store client application and display the review page for the specified product.
MarketplaceSearchTask Allows 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.
PhoneCallTask Allows an application to launch the Phone application. Use this to allow users to make a phone call from your application.
Allows an application to launch the calendar application with a new appointment displayed. Use this to allow users to add
SaveAppointmentTask an appointment to their calendar from your application.
SearchTask Allows an application to launch the Web Search application.
ShareLinkTask Allows an application to launch a dialog that enables the user to share a link on the social networks of their choice.
ShareMediaTask Allows an application to launch a dialog that allows a user to share a media file on the social networks of their choice.
Allows an application to launch a dialog that enables the user to share a status message on the social networks of their
ShareStatusTask choice.
SmsComposeTask Launches the Messaging application with a new SMS message displayed.
WebBrowserTask Allows an application to launch the web browser application.
consulting training design debugging wintellect.com
41. Choosers
Launcher Purpose
Allows an application to launch the Contacts application. Use this to obtain the physical address of a contact selected by
AddressChooserTask the user.
Allows an application to launch the Wallet application. The provided Wallet item is displayed to the user and the user can
AddWalletItemTask choose to add the item to his or her Wallet.
CameraCaptureTask Allows an application to launch the Camera application. Use this to allow users to take a photo from your application.
Allows an application to launch the Contacts application. Use this to obtain the email address of a contact selected by the
EmailAddressChooserTask user.
GameInviteTask Allows an application to show a game invite screen that allows the user to invite players to a multiplayer game session.
Allows an application to launch the Contacts application. Use this to obtain the phone number of a contact selected by the
PhoneNumberChooserTask 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.
Allows an application to launch the contacts application. Use this to allow users to save an email address from your
SaveEmailAddressTask application to a new or existing contact.
Allows an application to launch the contacts application. Use this to allow users to save a phone number from your
SavePhoneNumberTask application to a new or existing contact.
Enables an application to launch the ringtones application. Use the SaveRingtoneTask to allow users to save a ringtone
SaveRingtoneTask from your application to the system ringtones list.
consulting training design debugging wintellect.com
42. Launchers & Choosers
Launchers
var task = new ChosenTask { Property = value, Property = value };
task.Show();
Choosers
FIELD:
private readonly ChosenTask _task;
CTOR:
_task = new ChosenTask { Property = value, Property = value };
_task.Completed += (sender, result) =>
{
Check the result type:
if (result.TaskResult == TaskResult.OK)
OK, Cancel, None.
{
// process task results
}
};
consulting training design debugging wintellect.com
43. demo
Intra-Application Interactions
consulting training design debugging wintellect.com
44. Live Tiles
• 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
consulting training design debugging wintellect.com
45. 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
consulting training design debugging wintellect.com
46. Iconic Template
• 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
• BackgroundColor is an ARGB color – Medium title is ~19 chars
• If A = 255, color is used • Content
• Otherwise, theme color is used – Wide text is 3 lines @ ~33 chars ea.
consulting training design debugging wintellect.com
47. Cyclic Template
• 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.
consulting training design debugging wintellect.com
48. Updating Primary Tiles & Creating Secondary Tiles
var tileData = new (FlipTileData | IconicTileData | CyclicTileData)
{
// Set Tile Properties according to the tile type
Title = "Tile Title",
// etc.
}; The Primary Application tile is ALWAYS
the first in the list (visible or not) and
// Update Primary Tile cannot be deleted.
var firstTile = ShellTile.ActiveTiles.First();
firstTile.Update(tileData);
Tile updates must use the same type of
template as was used to create the tile.
// Secondary Tile
var uri = new Uri("/DeepLinkPage.xaml?id=data&unique=somethingunique", UriKind.Relative);
ShellTile.Create(uri, tileData, true);
Secondary tiles‟ navigation targets MUST
be unique or an exception will be thrown.
consulting training design debugging wintellect.com
49. demo
Live Tiles
consulting training design debugging wintellect.com
50. Customizing Keyboard Behavior
• Configure the Software Input Panel (SIP) to display keys appropriate to
the purpose of the input being collected.
Phone Number URL
Text & Chat
Digits Street Address Email
consulting training design debugging wintellect.com
51. Scoping Your SIP
InputScope values are from the
<TextBox InputScope="TelephoneNumber"/>
InputScopeNameValue enumeration.
Illustrated description of keyboard options and special keys„ functions:
http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh393998(v=vs.105).aspx
consulting training design debugging wintellect.com
52. Hardware and Sensors
• 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
consulting training design debugging wintellect.com
53. Location
// Requires ID_CAP_LOCATION & user Opt-In notification (PII)
var geoLocator = new Windows.Devices.Geolocation.Geolocator(); Replaces GeoCoordinateWatcher
geoLocator.MovementThreshold = 10; from System.Device.Location
geoLocator.DesiredAccuracy = PositionAccuracy.High;
// Single-shot
Geoposition position = await geoLocator.GetGeopositionAsync();
// Continuous
geoLocator.PositionChanged += (geolocator, args) =>
{
Dispatcher.BeginInvoke(() => When handling events, be sure
{ to marshall to the UI thread
Geocoordinate coordinate = args.Position.Coordinate;
Map.Center = coordinate.ToGeoCoordinate();
});
};
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.)
consulting training design debugging wintellect.com
54. Sensors
• 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()
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
}
consulting training design debugging wintellect.com
55. Camera APIs
• 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
consulting training design debugging wintellect.com
56. Windows Phone 8 Camera Options
_cameraTask = new CameraCaptureTask();
_cameraTask.Completed += (o, e) => Note: With “Choosers”, you must
{ declare the instance as a field and
if (e.TaskResult == TaskResult.OK)
hook the event in the constructor to
{
photoImage.Source(BitmapImage(new Uri(e.OriginalFileName))); properly support suspend/tombstone.
}
}
_cameraTask.Show();
PhotoCamera camera; <Rectangle Width="320" Height="240“
camera = new PhotoCamera(); HorizontalAlignment="Left" >
viewFinderBrush.SetSource(camera); <Rectangle.Fill>
camera.CaptureImage(); <VideoBrush x:Name="viewfinderBrush" />
camera.CaptureImageAvailable += (o, e) => </Rectangle.Fill>
{ </Rectangle>
... (e.ImageStream)
}
Be sure to call Dispose on the camera so
camera.Dispose(); other parts of the app can access the device.
consulting training design debugging wintellect.com
57. demo
Input
consulting training design debugging wintellect.com
58. Recap
• App Structure Other Concepts
• UI Elements –
–
WP Toolkit Controls
Touch & Gestures
– File Type & Protocol
Associations
• App Lifecycle & Storage – Status Bar –
–
Calendar & Contacts API
Notification Services
– Working with Maps
• Intra-App Interactions – Hybrid DirectX Apps – Phone UX Integration (Picture &
– Speech API Search Hubs, Lenses, Wallet)
• Live Tiles – VOIP API – Lock Screen Integration
– Customizing app‟s Kids‟ Corner
• Hardware & Sensors – NFC
behavior
– Local Database API
– Company App Stores
– Media Storage
– Trial Modes
– SD Card access
– In-App Purchases
– Encryption
– Showing Ads
– Background Transfers
– More!
– Background Audio
– Background Agents
– Alarms & Reminders
– Scheduled Tile Updates
consulting training design debugging wintellect.com
Start high level – dev concepts, project structure and pivotal elements. Get into UI elements featuring the Page and Page Navigation, then controls that are specific to WP dev.From there, once you have an app, you need to consider Application Lifecycle and, as a natural extension, data storageFrom there, the idea of enhancing the app by providing extensibility with OS-managed contentNext is the idea of Tiles, Toasts, and a natural progression to NotificationsFinally, discuss Hardware and Sensors for interacting with the World
Windows Phone Toolkit - New home for both WP7 and WP8 toolkitsThe MVA is a free program delivering structured learning paths for IT Professionals on various Microsoft products and solutions.Nokia Premium Developer Program$99 – includes Dev center account (worth $99), TelerikRadControls (worth $99), Buddy.com Cloud APIs (up to $1200), and 2 Nokia Tech Support Tix ($198)If you’re developing Windows Phone Apps, See Lance McCarthy – Nokia Evangelist! He may be able to offset these costs AND supply devices!!!!!Honorable Mention – Nokia Virtual Device testing site (online VM’s of different phone models)
Common Kernel – Unless you’re developing drivers, you do not really care
API Crossover:Networking, Proximity, In-App Purchase, Sensors, Location, File System,Core app model, ThreadingSpecific to Phone:Speech, VOIP
Vast majority of WP7 apps work without changeSome changes are not quirked and require WP7 apps to be updated for Windows Phone 8FM radio API is no longer supported (but is apparently coming back)Local database no longer supports read-only connection strings except in installation folderPivot and Panorama controls no longer fire ManipulationCompleted eventsAnd many morehttp://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206947(v=vs.105).aspx
Create a simple app, show the project structure (manifest, app, page), show the simulator, simulator options, Expression Blend, animation (spinning head)We’ll look at the project types and Structure in just a sec
Categories – Apps, Games, HTML App, Agents (which are satellite assemblies – they must go along with an app to do anything), Class LibrariesFocused on XAML/C#The HTML/JavaScript story is very different (WinJSvsPhoneGap/et al)C++/managed also has a story, but out of scope
Manifest Requires app capabilities in the manifest prior to the use of restricted APIs Can indicate minimum HW requirements for install(NFC, Front/Rear Camera, Magnetometer, Gyroscope)App Note that the app object in WP apps is implied, whereas in Win8 apps, it is specifically identified. Windows Phone apps MUST start and present a UI to the user in X seconds or the OS will kill them
Note – It is popular to use the VisualStateManager to handle layout changes when the orientation changesNote – NavigationService is a page property…it is NOT fronted by an interface.Note – One contrast with Win8 apps is that in Win8, orientation preferences are set app-wide (though any one page can override them, but must remember to set them back or risk side-effects.) Also, in Win8, Snapped can not be disabled.
When grouping is enabled, the group break happens at each new inner list. The data context is the inner list item, so properties added to it can be bound to and displayed. This often means that the inner list is a subclass of list with a key property appended: class InnerList<T>: List<T> { public String Key {get; set;}}
Can lock a panel with the IsLocked property. This is useful if there is horizontally scrolling content on the page. Lock the page, enable the control’s horizontal scroll attribute. When done, disable the control’s h-scroll and unlock the pivot control.
NOTE – Mode = Minimized does not work (ignored) when horizontal
Lifecycle Requirements:First screen must render within 5 seconds after launchApp must be responsive to user input within 20 secs after launchSplash screen is optional (SplashScreenImage.jpg – if there, it is shown)Compile in the cloud?Progress must show a “progress/busy” indication if an operation makes it unresponsive for > 3 secs.App events must be fielded within 10 seconds
Baseline stateSwitch active apps (Start button, launch tile)Memory pressure or > 8 apps causes app to be tombstonedUse Long-Press Back button to re-access App 1Note that the need to restore serialized state can be determined from Activated event argLaunch App 2 from the Tile/Shortcut (Replace)Note that this behavior can be changed in app manifestIn Activated, e.IsApplicationInstancePreserved True: went from dormat Active, False: went from Tombstoned Active
Because data is in-memory, it is 30-50% faster access time
Because data is in-memory, it is 30-50% faster access timeStorage size limit has been observed to be (1.5MB?)TODO – Confirm the size limit with new OS, tools…
No quotas, no other scopes (desktop has several, Silverlight has app and site)
Mention Isolated Storage Browser Command-Line Tool (and XAMLSpy)Note that Async file manipulation methods for ISO Storage Files are also now available
Note that there may be some async issues if writing file during lifecycle event handlers…
Mention deferral issue…Mention better to save as you go – both systems maintain “death clocks” – 10 seconds
Flip switches between “front” and “back” views - similar to only option available in WP7.1Flip Tile template for Windows Phone 8http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206971(v=vs.105).aspxFlip Tile template design guidelines for Windows Phonehttp://msdn.microsoft.com/en-us/library/windowsphone/design/jj662925(v=vs.105).aspxChar counts are approx., as font is variable-sized Segoe WP
Iconic Tile template for Windows Phone 8http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207009(v=vs.105).aspxIconic Tile template design guidelines for Windows Phone http://msdn.microsoft.com/en-us/library/windowsphone/design/jj662924(v=vs.105).aspxChar counts are approx., as font is variable-sized Segoe WP
Cycle Tile template for Windows Phone 8http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207036(v=vs.105).aspxCycle Tile template design guidelines for Windows Phonehttp://msdn.microsoft.com/en-us/library/windowsphone/design/jj662923(v=vs.105).aspxChar counts are approx., as font is variable-sized Segoe WP
For unique navigation targets, it is enough if the query string contains the difference (so it is possible to use ticks or some “salt-like” value to prevent collisions.)Tile Update only affects properties that are specified (null values are ignored); no way to look at properties of “previous item”
This is not .NET code – it cannot be exposed/shared through PCLsAvailable sensors include:Accelerometer (G-Forces in X,Y,Z) (Guaranteed on all phones)Compass (Degrees from True/Magnetic North)Gyroscope (Angular velocity X/Y/Z)Inclinometer (Pitch, Roll, Yaw) (technically derived from several sensors)Orientation (Rotation Matrix & Quaternion) – Combines/Fuses several sensors
In PhotoCamera,viewFinderBrush.SetSource initializes the camera. The camera cannot be asked to take a picture until its initialization has completed (there’s an Initialized event that’s raised.)