Presentation - Windows App Development - II - Mr. Chandan Gupta
Agenda Windows 8/Windows Phone 
In this module, we 
will.... 
Extension 
methods 
Portable Class 
Libraries 
MVVM 
Architecture 
Data Binding Linked files 
A common 
user 
experience 
In this 
module: 
#if 
conditionals
Presentation - Windows App Development - II - Mr. Chandan Gupta
Presentation - Windows App Development - II - Mr. Chandan Gupta
Common Structure
Model-View-ViewModel 
View 
ViewModel 
Commands 
Data 
Binding 
Model
MVVM Benefits 
• Reuse Model and View-Model code 
• Test the ViewModel with unit tests 
• Maintainability 
• Can show design-time data in Expression Blend 
and the Visual Studio designer
Model – View - ViewModel 
public class MyModelItem 
{ 
public int Id { get; set; } 
[DataMember(Name = "text")] 
public string Text { get; set; } 
[DataMember(Name = "complete")] 
public bool Complete { get; set; } 
} 
public class MyModelItem 
{ 
public int Id { get; set; } 
[DataMember(Name = "text")] 
public string Text { get; set; } 
[DataMember(Name = "complete")] 
public bool Complete { get; set; } 
}
Data Service Calls in the ViewModel 
private MobileServiceCollectionView<TodoItem> items; 
private IMobileServiceTable<TodoItem> todoTable = App.MobileService.GetTable<TodoItem>(); 
private void RefreshTodoItems() 
{ 
items = todoTable 
.Where(todoItem => todoItem.Complete == false) 
.ToCollectionView(); 
} 
private async void InsertTodoItem(TodoItem todoItem) 
{ 
await todoTable.InsertAsync(todoItem); 
items.Add(todoItem); 
}
Extract Model and Service Calls
Good MVVM Practice
2 
DataBinding 
(INotifyPropertyChanged)
Data Binding in the ViewModel 
// Create INotifyPropertyChanged property called VisibleItems 
private void MobileServiceCollectionView<TodoItem> RefreshTodoItems() 
{ 
items = todoTable 
.Where(todoItem => todoItem.Complete == false) 
.ToCollectionView(); 
_visibleItems.Clear(); 
foreach (var item in items) 
{ 
_visibleItems.Add(item); 
} 
NotifyPropertyChanged("VisibleItems"); 
}
Improved Structure
“Add as Link”
“Add as Link”
Common APIs 
in Windows 8 
and Windows 
Phone 8
Common APIs
Hardware Implementation: Accelerometer
Hardware Implementation: Accelerometer 
<Canvas x:Name="hostCanvas" Loaded=“canvas_Loaded"> 
Accelerometer _accel; 
private void canvas_Loaded(object sender, RoutedEventArgs e) 
{ 
_accel = Accelerometer.GetDefault(); 
if (_accel != null) 
_accel.ReadingChanged += _accel_ReadingChanged; 
}
Hardware Implementation: Accelerometer 
void _accel_ReadingChanged(Accelerometer sender, 
AccelerometerReadingChangedEventArgs args) 
{ 
double _accelX = args.Reading.AccelerationX; 
double _accelY = args.Reading.AccelerationY; 
// Update the position of the ellipse 
}
Threading Difference
Threading 
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => 
{ 
double _accelX = args.Reading.AccelerationX; 
double _accelY = args.Reading.AccelerationY; 
// Update ellipse location 
}); 
Deployment.Current.Dispatcher.BeginInvoke(() => 
{ 
double _accelX = args.Reading.AccelerationX; 
double _accelY = args.Reading.AccelerationY; 
//Update ellipse location 
});
#if Complier 
Conditionals
#if Conditional Blocks 
#if NETFX_CORE 
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { 
#endif 
#if WINDOWS_PHONE 
Deployment.Current.Dispatcher.BeginInvoke(() => { 
#endif
#if Conditional Blocks
Threading 
#if NETFX_CORE 
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { 
#else 
Deployment.Current.Dispatcher.BeginInvoke(() => { 
#endif 
double _accelX = args.Reading.AccelerationX; 
double _accelY = args.Reading.AccelerationY;
Extension 
Methods
Web Service
HttpWebResponse and HttpWebRequest 
var request = (HttpWebRequest)WebRequest.Create(autoCompleteUri); 
HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); 
// retrieve data using StreamReader
HttpWebResponse and HttpWebRequest 
var request = (HttpWebRequest)WebRequest.Create(autoCompleteUri); 
request.BeginGetResponse(new AsyncCallback(AutoCompleteCallback), request); 
} 
private void AutoCompleteCallback(IAsyncResult callback) 
{ 
HttpWebRequest request = (HttpWebRequest)callback.AsyncState; 
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callback); 
// retrieve data using StreamReader 
}
Extension Methods 
public static Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request) 
{ 
var taskComplete = new TaskCompletionSource<HttpWebResponse>(); 
request.BeginGetResponse(asyncResponse => 
{ 
HttpWebRequest responseRequest = 
(HttpWebRequest)asyncResponse.AsyncState; 
HttpWebResponse someResponse = 
(HttpWebResponse)responseRequest.EndGetResponse(asyncResponse); 
taskComplete.TrySetResult(someResponse); 
}, request); 
return taskComplete.Task; 
}
HttpWebResponse and HttpWebRequest 
#if WINDOWS_PHONE 
using MyExtensionClass 
#endif 
var request = (HttpWebRequest)WebRequest.Create(autoCompleteUri); 
HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); 
// retrieve data using StreamReader
Translating 
User 
Experience
Web Service
UI Differences and XAML
Different Form Factors Require Different UX
Different Form Factors Require Different UX
User Experience Considerations 
One-handed touch most common 
Guaranteed hardware, such as 
camera and accelerometer 
Avoid multiple columns of content 
Scroll vertically for more content 
Very limited room on the app bar 
Hardware back button 
No semantic zoom 
• Windows 8 
One or two-handed touch, mouse 
No guarantee of any specific hardware, 
must check at runtime 
Rows and columns of content are 
normal 
Scroll horizontally for more content 
Significant room on the app bar 
On-screen back button 
Semantic zoom 
Windows Phone 8 
Design the UX separately for each platform!
• Avoid reusing XAML across Windows Phone 8 and Windows 8 
• Major differences in the platforms make this difficult anyway: 
–XAML namespaces 
–XAML controls 
–User experience 
–Screen space 
–Page layout / orientation 
XAML
XAML Namespaces and Controls 
• Windows.UI.Xaml.Controls contains Windows 8 controls 
• Microsoft.Phone.Controls and Microsoft.Phone.Shell contain WP8 
controls 
• System.Windows.Controls contains Windows 8 controls and some shared 
controls 
• Some controls are present on both platforms but in different namespaces 
• Example: Windows.UI.Xaml.Controls.Canvas (Win8), 
System.Windows.Controls.Canvas (WP8)
Different Controls
Different Controls
Different Controls
Different Form Factors Require Different UX
Different Form Factors Require Different UX
Different Form Factors Require Different UX
Translating UX
Translating UX – Details View
Different Form Factors Require Different UX
• Tiles are an entry point for 
Windows 8 and Windows 
Phone 8 apps 
–One primary tile that launches 
the app normally 
–Also, secondary tiles can be 
pinned to the Start screen 
• Create a “Deep link” that takes 
the user to a specific page in the 
app 
• Both platforms support live 
tiles, in which content is 
periodically updated 
Tiles 
Tiles on Windows 8 Tiles on Windows Phone 8
Tiles (cont.) 
Windows Phone 8 Tiles Windows 8 Tiles 
var tile = new SecondaryTile( 
item.UniqueId, // Tile ID 
item.ShortTitle, // Tile short name 
item.Title, // Tile display name 
item.UniqueId, // Activation argument 
TileOptions.ShowNameOnLogo, // Tile options 
uri // Tile logo URI 
); 
await tile.RequestCreateAsync(); 
Both platforms support tiles, but the APIs are completely different 
CycleTileData tileData = new CycleTileData() 
{ 
Title = group.Title, 
SmallBackgroundImage = new 
Uri(group.GetImageUri(), 
UriKind.RelativeOrAbsolute), 
CycleImages = list 
}; 
ShellTile.Create(new Uri(navDataSource, 
UriKind.Relative), tileData, true);
Media Capture 
• With webcams and cell phones, 
capturing photos and videos is prolific 
–Both Windows 8 and Windows Phone 8 
have media capture APIs 
Windows Phone 8 camera app 
Windows 8 camera app
Media Capture (Windows 8) 
• Windows uses CameraCaptureUI to capture images and videos 
• Windows.Media.Capture namespace 
• Enable Webcam and Microphone in the manifest 
private async void OnCapturePhoto(object sender, TappedRoutedEventArgs e) 
{ 
var camera = new CameraCaptureUI(); 
var file = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo); 
if (file != null) 
{ 
// Do something with the result... 
} 
}
Media Capture (Windows Phone 8) 
Windows Phone uses CameraCaptureTask take photos 
Microsoft.Phone.Tasks namespace 
Enable ID_CAP_ISV_CAMERA and ID_CAP_MICROPHONE in the manifest 
Recording video is more complicated, but possible 
private readonly CameraCaptureTask cameraTask; 
public Init() { 
cameraTask = new CameraCaptureTask(); 
cameraTask.Completed += PhotoCaptured; 
} 
public void TakePhoto() { 
cameraTask.Show(); 
} 
private async void PhotoCaptured (object sender, PhotoResult result) { 
await Task.Run(() => { 
// Do something with the result... 
}); 
}
App Bar 
The app bar is a good place to put frequently 
used commands 
The Windows 8 app bar has few technical 
limitations 
Certification standards may limit it 
Phone has limited screen space 
The app bar cannot take up too much space 
Put additional commands on the menu 
A Windows Phone 8 app bar 
with the menu expanded 
A Windows 8 app bar with three buttons
App Bar 
Windows Phone 8 App Bar 
• One app bar at the bottom of the page 
• Only four items allowed 
• Put additional items on the menu 
• No grouping 
• ApplicationBar control inside 
PhoneApplicationPage.ApplicationBar 
• Set Mode to Default to show the app bar 
when the page loads 
• Set IsMenuEnabled to enable the menu 
Windows 8 App Bar 
• Two app bars: one bottom and one top 
• Behaves like any container 
• No menu 
• Can group items in nested containers 
• AppBar control inside Page.BottomAppBar or 
Page.TopAppBar 
• Set IsOpen to true to show the app bar when 
the page loads 
• Set IsSticky to true to force an app bar to 
always remain open
App Bar (Windows 8) 
<Page.BottomAppBar IsOpen="True"> 
<AppBar x:Name="bottomAppBar" Opened="AppBar_Opened" Padding="10,0,10,0"> 
<Grid> 
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left"> 
<Button Style="{StaticResource EditAppBarButtonStyle}" Click="Edit_Click"/> 
<Button Style="{StaticResource RemoveAppBarButtonStyle}" Click="Remove_Click"/> 
<Button Style="{StaticResource AddAppBarButtonStyle}" Click="Add_Click"/> 
</StackPanel> 
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right"> 
<Button Style="{StaticResource RefreshAppBarButtonStyle}" 
Click="Refresh_Click"/> 
<Button Style="{StaticResource HelpAppBarButtonStyle}" Click="Help_Click"/> 
</StackPanel> 
</Grid> 
</AppBar> 
</Page.BottomAppBar>
App Bar (Windows Phone 8) 
<phone:PhoneApplicationPage.ApplicationBar> 
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True" Mode="Default" Opacity="1.0"> 
<shell:ApplicationBarIconButton x:Name="btnTakePicture" 
IconUri="/Assets/Icons/camera.png" Click="btnTakePicture_Click" Text="Take Picture"/> 
<shell:ApplicationBarIconButton x:Name="btnShareTask" IconUri="/Assets/Icons/share.png" 
Click="btnShareShareTask_Click" Text="Share Image"/> 
<shell:ApplicationBarIconButton x:Name="btnStartCooking" 
IconUri="/Assets/Icons/alarm.png" Click="btnStartCooking_Click" Text="Start Cooking"/> 
<shell:ApplicationBarIconButton x:Name="btnPinToStart" IconUri="/Assets/Icons/like.png" 
Click="btnPinToStart_Click" Text="Pin To Start"/> 
</shell:ApplicationBar> 
</phone:PhoneApplicationPage.ApplicationBar>
Launching Built-In Apps 
URI scheme Description 
http:[URL] Launches the web browser and navigates to URL 
mailto:[email address] 
Launches the email app and creates a new message. 
Note that the email is not sent until the user taps send. 
ms-settings-accounts: Launches the Account Settings app. 
ms-settings-airplanemode: Launches the Airplane Mode Settings app. 
ms-settings-bluetooth: Launches the Bluetooth Settings app. 
ms-settings-cellular: Launches the Cellular Settings app. 
ms-settings-emailandaccounts: Launches the email and accounts settings app. 
ms-settings-location: Launches the Location Settings app. 
ms-settings-lock: Launches the Lock Screen settings app. 
ms-settings-wifi: Launches the Wi-Fi Settings app.
Thank You..

More Related Content

PDF
#JavaFX.forReal()
PPTX
Java applet
PDF
Lecture 22
PPT
Android classes in mumbai
PPTX
Java ME - 02 - High Level UI
PPTX
Java ME - 07 - Generic Connection Framework, HTTP and Sockets
PPT
Java swing
PDF
Program imageviewer
#JavaFX.forReal()
Java applet
Lecture 22
Android classes in mumbai
Java ME - 02 - High Level UI
Java ME - 07 - Generic Connection Framework, HTTP and Sockets
Java swing
Program imageviewer

What's hot (10)

PPTX
java Unit4 chapter1 applets
PDF
Desenvolva um game para android ou iPhone
PDF
Automated Testing ADF with Selenium
PDF
3 Mobile App Dev Problems - Monospace
PDF
Laboratorio: Desarrollo para Smart Devices (continuación)
PDF
Introducing PanelKit
PDF
Laboratorio: Desarrollo de aplicaciones Web con GeneXus Evolution 3 y Salto
PPT
Visualizing STEP Files
PDF
Laboratorio: Desarrollo para Smart Devices
PDF
Page Objects Done Right - selenium conference 2014
java Unit4 chapter1 applets
Desenvolva um game para android ou iPhone
Automated Testing ADF with Selenium
3 Mobile App Dev Problems - Monospace
Laboratorio: Desarrollo para Smart Devices (continuación)
Introducing PanelKit
Laboratorio: Desarrollo de aplicaciones Web con GeneXus Evolution 3 y Salto
Visualizing STEP Files
Laboratorio: Desarrollo para Smart Devices
Page Objects Done Right - selenium conference 2014
Ad

Similar to Presentation - Windows App Development - II - Mr. Chandan Gupta (20)

KEY
Titanium appcelerator my first app
PPTX
pebble - Building apps on pebble
PDF
Windows phone 7 series
PPTX
Iasi code camp 12 october 2013 adrian marinica - windows 8 and windows phon...
PPTX
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
PDF
22Flutter.pdf
PPTX
AIR2.5 Hands On - Flash on the Beach 2010
PPTX
Deeper into Windows 10 Development
PDF
Do iOS Presentation - Mobile app architectures
PDF
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
KEY
Intro To webOS
PDF
Modernize Your Real-World Application with Eclipse 4 and JavaFX
PDF
PPTX
SoCal Code Camp 2011 - ASP.NET MVC 4
PDF
Play Framework
PPT
Android tutorial (2)
PDF
Clean Architecture @ Taxibeat
PDF
Building Accessible Apps using NET MAUI.pdf
PPTX
Electron - cross platform desktop applications made easy
PPTX
Apache Cordova In Action
Titanium appcelerator my first app
pebble - Building apps on pebble
Windows phone 7 series
Iasi code camp 12 october 2013 adrian marinica - windows 8 and windows phon...
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
22Flutter.pdf
AIR2.5 Hands On - Flash on the Beach 2010
Deeper into Windows 10 Development
Do iOS Presentation - Mobile app architectures
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Intro To webOS
Modernize Your Real-World Application with Eclipse 4 and JavaFX
SoCal Code Camp 2011 - ASP.NET MVC 4
Play Framework
Android tutorial (2)
Clean Architecture @ Taxibeat
Building Accessible Apps using NET MAUI.pdf
Electron - cross platform desktop applications made easy
Apache Cordova In Action
Ad

More from MobileNepal (20)

PPT
Mr. Tomi Ahonen Mobile Digital - Ncell App Camp 2014
PPTX
Pitfalls in mobile apps marketing Mr. Karun Thapa
PPTX
Presentation - Mr. Tomas Martunas
PPTX
Debriefing of finals - Mr. Bibhusan Bista
PPTX
Effective Presentation and Pitching - Mr. Sohan B. Khatri
PPTX
Presentation - Windows app development - I - Mr. Chandan Gupta
PPTX
Presentation - Android App Development - Mr. Samrakchan
PPTX
Presentation - iOS - UI and UX - Mr. Samesh & Mr. Neetin
PPTX
Presentation Slides - Training on Business Development - Mr. Sohan Babu Khatri
PPTX
Training on iOS app development - Samesh Swongamikha & Neetin Sharma
PPTX
Training on SMS App - Anjesh Tuladhar
PPTX
Technology, Performance and Scalability - Presentation - Anjesh Tuladhar
PPTX
Designing for Android - Anjan Shrestha
PDF
Design in UI: Visuals and Aesthetics - Swapnil Acharya
PDF
Design Theory - Ankur Sharma - Presentation
PPTX
Presentation - Corporate Solutions - Keynote - Mr. Erim Taylanlar
PPTX
Presentation - Education - Keynote - Ncell App Camp 2014 - Mr. Anil Chitrakar
PPTX
Keynote speech tourism mr. bibhusan bista
PPTX
Presentation - Keynote Speech - Ncell App Camp 2014 - Mr. Dinesh Gautam
PPTX
Mobile Application Trends - Marketing and Monetization by Biswas Dhakal - Nce...
Mr. Tomi Ahonen Mobile Digital - Ncell App Camp 2014
Pitfalls in mobile apps marketing Mr. Karun Thapa
Presentation - Mr. Tomas Martunas
Debriefing of finals - Mr. Bibhusan Bista
Effective Presentation and Pitching - Mr. Sohan B. Khatri
Presentation - Windows app development - I - Mr. Chandan Gupta
Presentation - Android App Development - Mr. Samrakchan
Presentation - iOS - UI and UX - Mr. Samesh & Mr. Neetin
Presentation Slides - Training on Business Development - Mr. Sohan Babu Khatri
Training on iOS app development - Samesh Swongamikha & Neetin Sharma
Training on SMS App - Anjesh Tuladhar
Technology, Performance and Scalability - Presentation - Anjesh Tuladhar
Designing for Android - Anjan Shrestha
Design in UI: Visuals and Aesthetics - Swapnil Acharya
Design Theory - Ankur Sharma - Presentation
Presentation - Corporate Solutions - Keynote - Mr. Erim Taylanlar
Presentation - Education - Keynote - Ncell App Camp 2014 - Mr. Anil Chitrakar
Keynote speech tourism mr. bibhusan bista
Presentation - Keynote Speech - Ncell App Camp 2014 - Mr. Dinesh Gautam
Mobile Application Trends - Marketing and Monetization by Biswas Dhakal - Nce...

Presentation - Windows App Development - II - Mr. Chandan Gupta

  • 2. Agenda Windows 8/Windows Phone In this module, we will.... Extension methods Portable Class Libraries MVVM Architecture Data Binding Linked files A common user experience In this module: #if conditionals
  • 6. Model-View-ViewModel View ViewModel Commands Data Binding Model
  • 7. MVVM Benefits • Reuse Model and View-Model code • Test the ViewModel with unit tests • Maintainability • Can show design-time data in Expression Blend and the Visual Studio designer
  • 8. Model – View - ViewModel public class MyModelItem { public int Id { get; set; } [DataMember(Name = "text")] public string Text { get; set; } [DataMember(Name = "complete")] public bool Complete { get; set; } } public class MyModelItem { public int Id { get; set; } [DataMember(Name = "text")] public string Text { get; set; } [DataMember(Name = "complete")] public bool Complete { get; set; } }
  • 9. Data Service Calls in the ViewModel private MobileServiceCollectionView<TodoItem> items; private IMobileServiceTable<TodoItem> todoTable = App.MobileService.GetTable<TodoItem>(); private void RefreshTodoItems() { items = todoTable .Where(todoItem => todoItem.Complete == false) .ToCollectionView(); } private async void InsertTodoItem(TodoItem todoItem) { await todoTable.InsertAsync(todoItem); items.Add(todoItem); }
  • 10. Extract Model and Service Calls
  • 13. Data Binding in the ViewModel // Create INotifyPropertyChanged property called VisibleItems private void MobileServiceCollectionView<TodoItem> RefreshTodoItems() { items = todoTable .Where(todoItem => todoItem.Complete == false) .ToCollectionView(); _visibleItems.Clear(); foreach (var item in items) { _visibleItems.Add(item); } NotifyPropertyChanged("VisibleItems"); }
  • 17. Common APIs in Windows 8 and Windows Phone 8
  • 20. Hardware Implementation: Accelerometer <Canvas x:Name="hostCanvas" Loaded=“canvas_Loaded"> Accelerometer _accel; private void canvas_Loaded(object sender, RoutedEventArgs e) { _accel = Accelerometer.GetDefault(); if (_accel != null) _accel.ReadingChanged += _accel_ReadingChanged; }
  • 21. Hardware Implementation: Accelerometer void _accel_ReadingChanged(Accelerometer sender, AccelerometerReadingChangedEventArgs args) { double _accelX = args.Reading.AccelerationX; double _accelY = args.Reading.AccelerationY; // Update the position of the ellipse }
  • 23. Threading Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { double _accelX = args.Reading.AccelerationX; double _accelY = args.Reading.AccelerationY; // Update ellipse location }); Deployment.Current.Dispatcher.BeginInvoke(() => { double _accelX = args.Reading.AccelerationX; double _accelY = args.Reading.AccelerationY; //Update ellipse location });
  • 25. #if Conditional Blocks #if NETFX_CORE Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { #endif #if WINDOWS_PHONE Deployment.Current.Dispatcher.BeginInvoke(() => { #endif
  • 27. Threading #if NETFX_CORE Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { #else Deployment.Current.Dispatcher.BeginInvoke(() => { #endif double _accelX = args.Reading.AccelerationX; double _accelY = args.Reading.AccelerationY;
  • 30. HttpWebResponse and HttpWebRequest var request = (HttpWebRequest)WebRequest.Create(autoCompleteUri); HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); // retrieve data using StreamReader
  • 31. HttpWebResponse and HttpWebRequest var request = (HttpWebRequest)WebRequest.Create(autoCompleteUri); request.BeginGetResponse(new AsyncCallback(AutoCompleteCallback), request); } private void AutoCompleteCallback(IAsyncResult callback) { HttpWebRequest request = (HttpWebRequest)callback.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callback); // retrieve data using StreamReader }
  • 32. Extension Methods public static Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request) { var taskComplete = new TaskCompletionSource<HttpWebResponse>(); request.BeginGetResponse(asyncResponse => { HttpWebRequest responseRequest = (HttpWebRequest)asyncResponse.AsyncState; HttpWebResponse someResponse = (HttpWebResponse)responseRequest.EndGetResponse(asyncResponse); taskComplete.TrySetResult(someResponse); }, request); return taskComplete.Task; }
  • 33. HttpWebResponse and HttpWebRequest #if WINDOWS_PHONE using MyExtensionClass #endif var request = (HttpWebRequest)WebRequest.Create(autoCompleteUri); HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); // retrieve data using StreamReader
  • 37. Different Form Factors Require Different UX
  • 38. Different Form Factors Require Different UX
  • 39. User Experience Considerations One-handed touch most common Guaranteed hardware, such as camera and accelerometer Avoid multiple columns of content Scroll vertically for more content Very limited room on the app bar Hardware back button No semantic zoom • Windows 8 One or two-handed touch, mouse No guarantee of any specific hardware, must check at runtime Rows and columns of content are normal Scroll horizontally for more content Significant room on the app bar On-screen back button Semantic zoom Windows Phone 8 Design the UX separately for each platform!
  • 40. • Avoid reusing XAML across Windows Phone 8 and Windows 8 • Major differences in the platforms make this difficult anyway: –XAML namespaces –XAML controls –User experience –Screen space –Page layout / orientation XAML
  • 41. XAML Namespaces and Controls • Windows.UI.Xaml.Controls contains Windows 8 controls • Microsoft.Phone.Controls and Microsoft.Phone.Shell contain WP8 controls • System.Windows.Controls contains Windows 8 controls and some shared controls • Some controls are present on both platforms but in different namespaces • Example: Windows.UI.Xaml.Controls.Canvas (Win8), System.Windows.Controls.Canvas (WP8)
  • 45. Different Form Factors Require Different UX
  • 46. Different Form Factors Require Different UX
  • 47. Different Form Factors Require Different UX
  • 49. Translating UX – Details View
  • 50. Different Form Factors Require Different UX
  • 51. • Tiles are an entry point for Windows 8 and Windows Phone 8 apps –One primary tile that launches the app normally –Also, secondary tiles can be pinned to the Start screen • Create a “Deep link” that takes the user to a specific page in the app • Both platforms support live tiles, in which content is periodically updated Tiles Tiles on Windows 8 Tiles on Windows Phone 8
  • 52. Tiles (cont.) Windows Phone 8 Tiles Windows 8 Tiles var tile = new SecondaryTile( item.UniqueId, // Tile ID item.ShortTitle, // Tile short name item.Title, // Tile display name item.UniqueId, // Activation argument TileOptions.ShowNameOnLogo, // Tile options uri // Tile logo URI ); await tile.RequestCreateAsync(); Both platforms support tiles, but the APIs are completely different CycleTileData tileData = new CycleTileData() { Title = group.Title, SmallBackgroundImage = new Uri(group.GetImageUri(), UriKind.RelativeOrAbsolute), CycleImages = list }; ShellTile.Create(new Uri(navDataSource, UriKind.Relative), tileData, true);
  • 53. Media Capture • With webcams and cell phones, capturing photos and videos is prolific –Both Windows 8 and Windows Phone 8 have media capture APIs Windows Phone 8 camera app Windows 8 camera app
  • 54. Media Capture (Windows 8) • Windows uses CameraCaptureUI to capture images and videos • Windows.Media.Capture namespace • Enable Webcam and Microphone in the manifest private async void OnCapturePhoto(object sender, TappedRoutedEventArgs e) { var camera = new CameraCaptureUI(); var file = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo); if (file != null) { // Do something with the result... } }
  • 55. Media Capture (Windows Phone 8) Windows Phone uses CameraCaptureTask take photos Microsoft.Phone.Tasks namespace Enable ID_CAP_ISV_CAMERA and ID_CAP_MICROPHONE in the manifest Recording video is more complicated, but possible private readonly CameraCaptureTask cameraTask; public Init() { cameraTask = new CameraCaptureTask(); cameraTask.Completed += PhotoCaptured; } public void TakePhoto() { cameraTask.Show(); } private async void PhotoCaptured (object sender, PhotoResult result) { await Task.Run(() => { // Do something with the result... }); }
  • 56. App Bar The app bar is a good place to put frequently used commands The Windows 8 app bar has few technical limitations Certification standards may limit it Phone has limited screen space The app bar cannot take up too much space Put additional commands on the menu A Windows Phone 8 app bar with the menu expanded A Windows 8 app bar with three buttons
  • 57. App Bar Windows Phone 8 App Bar • One app bar at the bottom of the page • Only four items allowed • Put additional items on the menu • No grouping • ApplicationBar control inside PhoneApplicationPage.ApplicationBar • Set Mode to Default to show the app bar when the page loads • Set IsMenuEnabled to enable the menu Windows 8 App Bar • Two app bars: one bottom and one top • Behaves like any container • No menu • Can group items in nested containers • AppBar control inside Page.BottomAppBar or Page.TopAppBar • Set IsOpen to true to show the app bar when the page loads • Set IsSticky to true to force an app bar to always remain open
  • 58. App Bar (Windows 8) <Page.BottomAppBar IsOpen="True"> <AppBar x:Name="bottomAppBar" Opened="AppBar_Opened" Padding="10,0,10,0"> <Grid> <StackPanel Orientation="Horizontal" HorizontalAlignment="Left"> <Button Style="{StaticResource EditAppBarButtonStyle}" Click="Edit_Click"/> <Button Style="{StaticResource RemoveAppBarButtonStyle}" Click="Remove_Click"/> <Button Style="{StaticResource AddAppBarButtonStyle}" Click="Add_Click"/> </StackPanel> <StackPanel Orientation="Horizontal" HorizontalAlignment="Right"> <Button Style="{StaticResource RefreshAppBarButtonStyle}" Click="Refresh_Click"/> <Button Style="{StaticResource HelpAppBarButtonStyle}" Click="Help_Click"/> </StackPanel> </Grid> </AppBar> </Page.BottomAppBar>
  • 59. App Bar (Windows Phone 8) <phone:PhoneApplicationPage.ApplicationBar> <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True" Mode="Default" Opacity="1.0"> <shell:ApplicationBarIconButton x:Name="btnTakePicture" IconUri="/Assets/Icons/camera.png" Click="btnTakePicture_Click" Text="Take Picture"/> <shell:ApplicationBarIconButton x:Name="btnShareTask" IconUri="/Assets/Icons/share.png" Click="btnShareShareTask_Click" Text="Share Image"/> <shell:ApplicationBarIconButton x:Name="btnStartCooking" IconUri="/Assets/Icons/alarm.png" Click="btnStartCooking_Click" Text="Start Cooking"/> <shell:ApplicationBarIconButton x:Name="btnPinToStart" IconUri="/Assets/Icons/like.png" Click="btnPinToStart_Click" Text="Pin To Start"/> </shell:ApplicationBar> </phone:PhoneApplicationPage.ApplicationBar>
  • 60. Launching Built-In Apps URI scheme Description http:[URL] Launches the web browser and navigates to URL mailto:[email address] Launches the email app and creates a new message. Note that the email is not sent until the user taps send. ms-settings-accounts: Launches the Account Settings app. ms-settings-airplanemode: Launches the Airplane Mode Settings app. ms-settings-bluetooth: Launches the Bluetooth Settings app. ms-settings-cellular: Launches the Cellular Settings app. ms-settings-emailandaccounts: Launches the email and accounts settings app. ms-settings-location: Launches the Location Settings app. ms-settings-lock: Launches the Lock Screen settings app. ms-settings-wifi: Launches the Wi-Fi Settings app.

Editor's Notes

  • #2: Welcome to Cross Development for Windows 8 and Windows Phone 8. In the next hour we’re going to go over the best practices, tips and tricks for developing applications that will delight users across devices powered by both Windows 8 and Windows Phone 8.
  • #3: In this talk we’re going to cover the most important technologies and strategies for writing applications that run in both Windows 8 and Windows Phone 8. To give a quick preview of what we’ll be covering… We’re going to walk through some basic MVVM architecture and we’ll talk about how DataBinding lets us use multiple UI elements against the same ViewModel. Then we’ll talk about sharing code using linked files and setting code customized for both platforms using #if compiler condiitonals. We will write an extension method that bridges some implementation gaps and then we’ll talk about which parts of our code are appropriate to place into Portable Class Libraries for quick and easy sharing. Then, lastly, we’ll talk about how we can implement a common user experience across our applications to bring the highest quality application experiences to our users.
  • #4: The first question we need to ask is “Is there anywhere I can download code that does the same thing in Windows 8 as in Windows Phone 8”? As a matter of fact there is.
  • #5: If you go to windowsazure.com, you can sign up for a free account and start a new free mobile service instance. This takes about 5 minutes of your free time and you can download 3 free applications with access to your free mobile service baked into them. So download your free Windows Store project and your free Windows Phone 8 project and let’s see how these two projects do the same thing.  
  • #6: Right off the bat, we can see we have a similar structure. App.xaml handles our resource management, App.xaml.cs handles launching, suspension and general application lifecycle, the MainPage.xaml page contains the UI and has been set to the initial screen on startup. The big difference between these two projects is that the Windows Phone 8 version has been prepared to make localization a little easier, which is why it has a resources folder and LocalizedStrings.cs But the bulk of the functionality that we want to look at is in the MainPage.xaml.cs
  • #9: If we open that we can take a look at the data we’re dealing with. This is the “Model” side of the Model View ViewModel (or MVVM)architecture. As you can see, we’re looking at the exact same code. OK, this is a good start.
  • #10: OK, now let’s look at how the data service provided in the application is implemented. There is more in the actual application, but in this snippet we can see that our Windows 8 version simply grabs a collection of items from our service and gives us a clean asynchronous way of adding another item. And we see the exact same code in Windows Phone 8. So we’re using the exact same data model and the exact same service calls. This is a helpful start.
  • #11: OK, now let’s look at how the data service provided in the application is implemented. There is more in the actual application, but in this snippet we can see that our Windows 8 version simply grab a collection of items from our service and gives us a clean asynchronous way of adding another item. And we see the exact same code in Windows Phone 8. So we’re using the exact same data model and the exact same service calls. This is a helpful start. But right now all this is in the code behind of the MainPage.xaml.cs of each project. We’ll want to extract the Model to its own class and take these service calls and put them in the ViewModel.
  • #12: The reason for doing this is because the service calls update our data and we want our data updates to use data binding. If we implement databinding appropriately, we won’t have to worry about telling our UI to update when we get new data… it will update automatically. This also allows us the maximum flexibility in our UI so that we don’t tie down our user’s experience to a specific control or XAML structure.
  • #14: The change we’ll make in the ViewModel is that we’re going to channel that data into an ObservableCollection so that we can bind to it in our XAML. We’ve now decoupled our UI from the inner logic of our data. We can bind this list of items to ListBox, a ComboBox, a GridView, a SemanticZoom control, anything that can be bound to a list. This is not only an MVVM best practice, but it makes us flexible in how we build our Windows 8 and Windows Phone 8 applications.
  • #15: Let’s say we’ve done this in our Window 8 project. We now have a Model that holds our data structure and a ViewModel that can handle all our service logic and push the results to a bindable property. Now we need to copy this code over to Windows Phone 8.
  • #16: But no! Because we’re going to add the files as links into our Windows Phone 8 project. We just right click in our project, add an existing item and make sure that we “Add as Link” instead of a simple “Add”. If we have both our projects in the same solution, we can also do an “add as link” by Alt-dragging the file from one project into the other. This way when we change the file, all the changes will be implemented in both application and we won’t be stuck going back and forth copying code between our apps.
  • #17: And we can see our linked classes in our Windows Phone 8 application. Perfect. Nice, healthy shared code between both projects.
  • #18: So lets look at implementing common APIs between Windows 8 and Windows Phone 8
  • #19: What kind of common code can we expect to have across our projects? The commonalities include the .NET Base Class Library, as well as Hardware and Storage APIs. This is where we see the common Windows Runtime Kernel running across Windows 8 and Windows Phone paying off. But we’ll need to pause when we’re using launchers, choosers and sharing APIs that push us out to functionality that reaches beyond our application. These have been implemented differently in Windows 8 and in Windows Phone 8 because they are going to have different launcher and chooser applications and native capabilities. And the way we share and launch external functionality has been carefully designed to create the best user experience on each platform.
  • #20: So lets see how something like the accelerometer might be implemented. We’ll jump back into our project a little further down the path. I’ve added a UserControl called GameSurface. The basic idea is we have this little ball, which is dynamically sized depending on the dimensions of the UserControl. We want to control the ball by tilting the device. The UserControl code behind (the xaml.cs file) handles the movement. Our data object has been modified so that we can save the location of the ball, how long the user has been playing and how many times the ball has bounced along the side. This way we can save the game on our phone and pick back up right where we left off on our tablet. So lets go ahead and implement the accelerometer in both apps.
  • #21: We launch our accelerometer when our Canvas object loads so we know that we can manipulate the ellipse object that is our ball. In the loaded event handler we assign our accelerometer and start listening for when the reading changes.
  • #22: And when we get a fresh reading, we update the inner workings of our application accordingly. And is exactly the same code on Windows 8 as it is in Windows Phone so when we run it…
  • #23: We get an Unauthorized Access Exception error because for performance purposes the accelerometer readings coming back off the UI thread. If we want to update anything on the UI thread, we need to add something. Unfortunately, we can now see the problem…
  • #24: The thread-handling dispatchers are different on Windows Phone and Windows 8. In windows 8, we use an element of the UI Core while in Windows Phone, we have a dispatcher that has been assigned to our app deployment. So, if you’re anything like me, you say “well it was worth a shot, time to give up”.
  • #25: So you can see our ball moves around just fine on both platforms using the same code. But remember how we can save the game and recall it later on another device? Let’s try doing that.
  • #26: No, of course not. If we have a situation where there are small difference in code compatibilities, we can use compiler conditional statements to separate the incompatible lines. In the case of Windows 8 development we would say #if NETFX_CORE and for Windows Phone we have the slightly more obvious #if WINDOWS_PHONE. We should consider using this implementation when there are small differences, this isn’t a catch-all approach. If we over use it, we can make our code unreadable, unmaintainable and just plain ugly. But it is perfect for situations where you require a specific namespace for your app (for example the Windows.UI.Xaml namespace which exists in Windows 8 but not in Windows Phone) or if there are small method differences.
  • #27: No, of course not. If we have a situation where there are small difference in code compatibilities, we can use compiler conditional statements to separate the incompatible lines. In the case of Windows 8 development we would say #if NETFX_CORE and for Windows Phone we have the slightly more obvious #if WINDOWS_PHONE. We should consider using this implementation when there are small differences, this isn’t a catch-all approach. If we over use it, we can make our code unreadable, unmaintainable and just plain ugly. But it is perfect for situations where you require a specific namespace for your app (for example the Windows.UI.Xaml namespace which exists in Windows 8 but not in Windows Phone) or if there are small method differences.
  • #28: So we can handle this threading dispatcher issue using compiler conditionals and now we have fully functioning accelerometer code that works on both platforms.
  • #29: So you can see our ball moves around just fine on both platforms using the same code. But remember how we can save the game and recall it later on another device? Let’s try doing that.
  • #30: We have to add a name for our app and, well, this is on a phone and I hate having to do all that typing so I think we should add a simple web service that can go out and get some suggestions for us while we type.
  • #31: In Windows 8, we can hit that web service using the very elegant async-await model. GetResponseAsync and all our async goodness is handled for us. We don’t need a callback, we don’t need to fire any events or construct any listeners, we can just await the response.
  • #32: But in Windows Phone 8, we don’t have that option. This isn’t really a problem that can be solved using compiler conditionals because that would require a very impressive kind of code gymnastics. We need the Windows Phone version of the HttpWebResponse and HttpWebRequest to work in an async manner.
  • #33: For this we can use Extension methods to encapsulate the functionality of the HttpWebRequest in such a way as to make it async. Using the TaskCompletionSource, we can wrap the HttpWebRequest in such a way that it returns a task. We give it the same name… GetResponseAsync()… that it has in Windows 8.
  • #34: And now our Web Service works exactly the same using exactly the same async-await model across both platforms. This compatibility trickles down through our application so that now, because our HttpWebRequest is awaitable, so is our service and we can use it the same way in our ViewModel when we want to get new data.
  • #35: So you can see our ball moves around just fine on both platforms using the same code. But remember how we can save the game and recall it later on another device? Let’s try doing that. We have to add a name for our app and, well, this is on a phone and I hate having to do all that typing so I think we should add a simple web service that can go out and get some suggestions for us while we type.
  • #36: So let’s just take the XAML that we used for our Windows Phone UI and move it over to our Windows 8 project and…
  • #37: Huh. We may wonder what went wrong here. The answer is “nothing”. The XAML is acting just the way it is supposed to act. It compiles, it runs, everything from the default styling to the user interactions all work. However, let’s take one step back and talk about the most important element of cross development between Windows 8 and Windows Phone 8.
  • #38: We need to keep in mind we’re looking at two very different form factors. Windows Phone runs at 3 resolutions, on phone screens from 3.5 inches to 4.8 inches. Windows 8 runs on screen resolutions to 1024x768 to 2,560 x 1,440 although this is by no means a limit. Windows 8 powers 10 inch tablets and 82 in screens that take up the entire wall.
  • #39: The same goes for orientation. Windows Phone supports portrait and landscape mode, but Windows 8 supports Portrait, landscape and the third-screen snapped mode. Each of these modes requires consideration in design, spacing, an interaction.
  • #40: This is a comparative list of some significant differences that impact the UX on the two platforms. All of these considerations mean that each platform requires a separate UX design.
  • #41: Even though both Windows 8 and Windows Phone 8 both use XAML for the user interface design,
  • #43: To aid in these considerations, Windows 8 and Windows Phone 8 have unique controls that have been designed with their particular form factors in mind. Some of the specialized controls for Windows 8 include GridView: (groupable) tile array. Also possible to dynamically size items in the grid. The GridView comes with built in styles for input and selection SemanticZoom: Allows for quick jump through large lists of grid items FlipView: Browsing view optimised for touch to pane left-right through sequential items.
  • #44: To aid in these considerations, Windows 8 and Windows Phone 8 have unique controls that have been designed with their particular form factors in mind. Some of the specialized controls for Windows 8 include GridView: (groupable) tile array. Also possible to dynamically size items in the grid. The GridView comes with built in styles for input and selection SemanticZoom: Allows for quick jump through large lists of grid items FlipView: Browsing view optimised for touch to pane left-right through sequential items.
  • #45: To aid in these considerations, Windows 8 and Windows Phone 8 have unique controls that have been designed with their particular form factors in mind. Some of the specialized controls for Windows 8 include GridView: (groupable) tile array. Also possible to dynamically size items in the grid. The GridView comes with built in styles for input and selection SemanticZoom: Allows for quick jump through large lists of grid items FlipView: Browsing view optimised for touch to pane left-right through sequential items.
  • #46: On the Windows Phone side of things, we have controls customized to a phone experience. The Panorama control is designed to give users a sort of “landing” space where they can get a feel for the content of the application explore that content in an open interactive environment.
  • #47: If the Panorama is the open, casual inviting control for introducing the user to the content, think of the pivot as the no-nonsense control for delivering content. With the Panorama, the user can see what is just around the corner, so to speak, but with the Pivot control, the focus is on the content in front of me right this moment. We still have quick easy access to additional content, but the focus is a little different.
  • #48: New to Windows Phone 8 is the LongListSelector control. This is the recommended control for list-based UI’s, replacing the ListBox. It is optimized for scrolling speed, but also implements a “group selection” interface so that the user can move quickly between grouped items in a very long list. Here we can see that group selection applied to an alphabetical list, but you could define a set of groups and then use the group selection to navigate between them.
  • #49: So what does this mean practically? It means that when we’re thinking about how we’re going to design our two applications, we should consider making use of the customized UI features of either Windows 8 or Windows Phone 8. For example, the semantic zoom control lets us see groups of items at a high level and then drill into them until we select one. That behaviour is similar in many ways to what the pivot control does. We should consider using the Pivot for the Phone and the SemanticZoom for Windows 8.
  • #50: And when we select an item? Windows 8 has a very powerful paradigm of horizontal scrolling, but it’s a paradigm that doesn’t make sense in the context of a phone. So instead of mimicking the horizontal scrolling UI we see in Windows 8, we should translate that into a vertical scrolling UI that fits the phone more appropriately.
  • #51: And if we have a long list of grouped items in Windows Phone 8, we might want to consider implementing them as a GridView in Windows 8. We just need to keep in mind that this is less about mimicking
  • #53: This is a side-by-side code comparison secondary tile creation. On Windows Phone 8 , the ShellTile class provides a static interface for creating (and removing) secondary tiles. You can provide it with one of several classes that encapsulate a tile’s data: StandardTile, CycleTileData, FlipTileData, or IconicTileData. Windows 8 has only one data structure to define a secondary tile (SecondaryTile). Tile creation is done with an asynchronous request, which asks the user if they would like to pin the tile to the Start screen.
  • #55: Both Windows Phone and Windows support capturing images and videos, but, as with other features we have seen, the APIs are different. Both the CameraCaptureTask (Windows Phone) and the CameraCaptureUI (Windows) show a system interface for media capture. The camera capability must be declared in the manifest for apps on either platform to capture photos.
  • #56: Capturing photos on the Windows Phone 8 is a task handled by the OS. You can register a callback to handle the result when the user exits the camera UI. You may or may not have a photo as a result, so check before using it. Video recording is not built-in to the camera capture task, so it requires some more work. This MSDN article explains in detail how to create a video recording app: http://msdn.microsoft.com/en-us/magazine/hh708750.aspx.
  • #58: Windows 8 app bars are much more powerful than Windows Phone 8 app bars. Commonly needed actions, such as adding, editing, and deleting items can be placed on an app bar. An app can be notified when the user opens or closes an app bar by handling the Opened and Closed events.
  • #59: Notice that two stack panels are used to group the buttons, with one group on the left and the other on the right. Here are some guidelines for app bars for Windows 8 apps: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/Hh781231(v=win.10).aspx
  • #60: Note that only four ApplicationBarIconButton elements are allowed on the phone ApplicationBar. Also, no containers are placed within the ApplicationBar element.
  • #62: Note that only four ApplicationBarIconButton elements are allowed on the phone ApplicationBar. Also, no containers are placed within the ApplicationBar element.