Mobile Application Trends - Marketing and Monetization by Biswas Dhakal - Nce...
Presentation - Windows App Development - II - Mr. Chandan Gupta
1.
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
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);
}
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
}
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
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)
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
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
And we can see our linked classes in our Windows Phone 8 application. Perfect. Nice, healthy shared code between both projects.
So lets look at implementing common APIs between Windows 8 and Windows Phone 8
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.
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.
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.
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…
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…
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”.
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.
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.
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.
So we can handle this threading dispatcher issue using compiler conditionals and now we have fully functioning accelerometer code that works on both platforms.
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.
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.
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.
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.
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.
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.
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…
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.
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.
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.
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.
Even though both Windows 8 and Windows Phone 8 both use XAML for the user interface design,
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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
Note that only four ApplicationBarIconButton elements are allowed on the phone ApplicationBar. Also, no containers are placed within the ApplicationBar element.
Note that only four ApplicationBarIconButton elements are allowed on the phone ApplicationBar. Also, no containers are placed within the ApplicationBar element.