windows phone 8 guide for android developers

102
Microsoft Open Technologies, Inc. 8/1/2013 Rev 1.0 Windows Phone 8 Guide for Android Application Developers

Upload: khai-le

Post on 27-Jan-2015

110 views

Category:

Technology


3 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Windows phone 8  guide for android developers

Microsoft Open Technologies, Inc. 8/1/2013 Rev 1.0

Windows Phone 8 Guide for Android

Application Developers

Page 2: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Table of Content

Table of Content ................................................................................................................................2

About this Development Guide .................................................................................................... 4

Chapter 1: An Introduction to Windows Phone Platform for Android Application

Developers ..........................................................................................................................................5

The Developer Tools ...................................................................................................................................5

Windows Phone Architecture ...................................................................................................................5

Comparing the Programming Stack of Windows Phone with the Android Stack ...................... 7

Summary ....................................................................................................................................................... 11

Related Resources ....................................................................................................................................... 11

Chapter 2: User Interface Guidelines for the Windows Phone ............................................ 12

Designing the Application Interface ...................................................................................................... 13

Application User Interface Design ......................................................................................................... 14

Comparing Windows Phone and Android Navigation .................................................................... 19

Windows Phone Frame and Page Structure ...................................................................................... 20

Application Templates .............................................................................................................................. 21

Summary ..................................................................................................................................................... 22

Related Resources ..................................................................................................................................... 22

Chapter 3: An introduction to Windows Phone Developer and Designer Tools ........... 24

A Comparison of Android and Windows Phone Tools .................................................................. 24

Visual Studio is not only a powerful IDE but it can also be extended in a variety of ways. It

allows the ability to add macros, options, menus and toolbar commands, visualizers and

other tools. In addition, Visual Studio supports NuGet, a package manager, to add, remove

and manage libraries and tools in Visual Studio and the .NET Framework. ............................. 25

Windows Phone tools l ............................................................................................................................ 26

Tool for coding .......................................................................................................................................... 26

Tools for designing ................................................................................................................................... 27

Building Application ................................................................................................................................. 37

Debugging .................................................................................................................................................. 38

Summary ..................................................................................................................................................... 43

Chapter 4: An Introduction to C# programming for Java developers ............................. 44

Managed Programming .......................................................................................................................... 45

A

Page 3: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Comparison between C# and Java Features ..................................................................................... 46

Key features compared ........................................................................................................................... 57

Summary ..................................................................................................................................................... 66

Related Resources ..................................................................................................................................... 66

Chapter 5: Application Lifecycle Differences Between Windows Phone and Android . 67

Android and Windows Phone Application Lifecycle ........................................................................ 67

Programming for application States and navigation ...................................................................... 69

Windows Phone Application LifeCycle ................................................................................................ 69

Comparing Life-cycle Methods ............................................................................................................. 70

Windows Phone 8 Application LifeCycle and Tombstoning Example ........................................ 72

Summary ..................................................................................................................................................... 77

Related Resources ..................................................................................................................................... 77

Chapter 6: Storage on Windows Phone ................................................................................... 78

IsolateStorageSettings lets you save any serializable object to the settings store. ................. 83

Managing the IsolatedStorage Space ................................................................................................. 83

Sharing Data Between Applications ..................................................................................................... 83

Content producers.................................................................................................................................... 84

Summary ..................................................................................................................................................... 84

Related Resources ..................................................................................................................................... 84

Chapter 7: XML Support in Windows Phone and Android .................................................. 85

Traversing XML .......................................................................................................................................... 89

Summary ...................................................................................................................................................... 91

Related Resources ...................................................................................................................................... 91

Appendix A: Migration Sample .................................................................................................. 92

In-App Advertisements............................................................................................................................ 93

Appendix B: Using the API Mapping Tool .............................................................................. 101

What’s the API Mapping tool ............................................................................................................... 101

How to use the tool ................................................................................................................................. 101

What's next? .............................................................................................................................................. 101

Page 4: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

About this Development Guide

If you have been developing Android applications and are

interested in building your applications for Windows Phone, this

guide is for you.

The guide covers what you need to know to add Windows Phone

development to your skill set, while leveraging what you have

already learned building Android applications.

Page 5: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 1: An Introduction to Windows Phone Platform for Android Application Developers 5

Chapter 1: An Introduction to Windows

Phone Platform for Android Application

Developers

In late 2010, Microsoft announced the release of Windows Phone 7 which was followed by

the release of Windows Phone 8 in late 2012. A large number of devices running Windows

Phone operating system are available from a variety of manufacturers all over the world.

Over a hundred thousand apps are available on the Windows Phone Store.

For Windows Phone, Microsoft went back to the drawing board to figure out what phone

users really want, and built a phone from the ground up. The operating system, the user

experience, and the application development platform have all been engineered with users in

mind. The revenue opportunities in the Windows Phone marketplace, accompanied by a

great set of development tools, make Windows Phone a very attractive platform for

developers to build applications and games.

The Developer Tools

Microsoft has released a set of tools as part of the Windows Phone Software Development Kit

(SDK) 8.0 for developing Windows Phone applications. The SDK is free and can be

downloaded from here. The Windows Phone SDK 8.0 includes:

Visual Studio Express 2012 for Windows Phone, an IDE for developers

Blend for Visual Studio 2012, a User Interface design tool for designers

A Windows Phone emulator to test and debug applications

The tools can help you develop consumer applications, business applications or games. While

the emulator must be installed on Windows 8 pro edition on a CPU supporting Second Level

Address Translation (SLAT) for running Hyper-V, you can still use the SDK to develop

Windows Phone 8 apps even if your computer doesn’t support the emulator. See System

requirements for Windows Phone Emulator for more information.

Windows Phone Architecture

Like Android OS, Windows Phone OS is designed to run on multiple phones from multiple

vendors. To provide a consistent user experience and features that developers can rely on,

Windows Phone defines a minimum set of hardware specifications that all phones must meet.

Page 6: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 1: An Introduction to Windows Phone Platform for Android Application Developers 6

Minimum hardware specifications include an ARM7 CPU, a DirectX capable GPU, a camera,

and a multi-touch capacitive display. Standard sensors include: an A-GPS, an accelerometer,

a compass, proximity and light sensors. There are three standard physical buttons on the

phone – back, start and search. As we will see in a subsequent chapter, these buttons provide

an easy and natural navigation model for the user.

Most of the Windows Phone 8 apps are built as managed apps using XAML with C# or VB.

Windows Phone 8 games are built using Direct3D using C++. It is also possible to render 3D

graphics within a XAML UI. It is also possible to build a Direct3D game using a thin XAML

wrapper. For more information, see Developing apps for Windows Phone. Windows Phone 8

adopts many of the components of Windows 8, providing better compatibility between the

two.

Figure 1 Windows Phone 8 Programming APIs

.NET API for Windows Phone

Windows Phone Runtime

Win32 & COM

C# / VB C++

Apps with XAML Apps with XAML

and Direct3D Games with Direct3D

Page 7: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 1: An Introduction to Windows Phone Platform for Android Application Developers 7

Comparing the Programming Stack of Windows Phone

with the Android Stack

The Application Model shown above provides services for managing the application lifecycle

such as installation and update. The UI model helps to manage the application user interface.

Applications are built using various Windows Phone Application Programming Interfaces,

APIs, known collectively as the Windows Phone API

This table gives an overview of the Windows Phone 8 frameworks that provide features

comparable to the Android programming layers.

Android Frameworks Functionality Windows Phone 8

Frameworks

Android Application

Framework

Application UI, Device

integration (sensors, camera) Windows Phone API

Graphics, Animation, Media Direct3D or XAML media and

graphics for others

Android Libraries Base services, Networking, Text,

XML, storage Windows Phone API

Android runtime

(Dalvik)+ Linux kernel Operating System Windows Phone 8 OS

Page 8: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 1: An Introduction to Windows Phone Platform for Android Application Developers 8

Android and Windows Phone Stacks Side by Side

This table compares the Android and Windows Phone 8 Frameworks side by side.

Managed Code

On Android, you have been developing applications primarily using Java and some native

components using C++. On Windows Phone 8 you have the option of using C# or Visual

Basic (“managed code”) for XAML applications or C++ for Direct3D game development

Execution of C# or Visual Basic (VB) code is managed by the .NET Common Language

Runtime (CLR). . Similar to Dalvik VM on Android, CLR is the Virtual Machine (VM) on

Windows Phone OS. Similar to Java, C# and VB do not require memory management; CLR

handles garbage collection.

Android Frameworks Windows Phone Frameworks

Ap

plicatio

n U

I and

Ph

on

e

Multi-tasking

Java

C#

, VB

, or C

++

Multi-tasking Ap

plicatio

n U

I and

Ph

on

e integratio

n

Application UI Application UI

Device integration Device integration

Telephony Telephony

Browser Control Browser Control

Notifications Notifications

Peer to Peer Gaming

XA

ML

Direct3

D

Two

Ap

plicatio

n Typ

es

Controls & Gestures Controls & Gestures

CoreWindow (PointerPressed

Med

ia

Media Framework Media Media Foundation, XAudio2, WASAPI

Animation Animation Direct3D

Graphics Graphics

Direct3D

OpenGL-ES

File System IsolatedStorage

Win

do

ws P

ho

ne A

PI

SQLLite

Location Location

XML XML, LINQ

Networking Networking, Windows Communication Foundation

Libc, Dalvik VM CLR Base Classes

Android runtime + Linux kernel

Windows Phone OS

Page 9: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 1: An Introduction to Windows Phone Platform for Android Application Developers 9

While most Windows Phone apps are written in C# or VB, you may want to use native C++

code for the following reasons:

1. Portability: This is useful if you are targeting multiple platforms you can write core

login in C++.

2. Direct3D: If you want to use Direct3D esp. to develop games, you must use C++.

3. Performance: For some scenarios, you may achieve higher performance using native

code.

In this paper we are going to focus on managed code.

Base Services

Windows Phone Base Class Library classes roughly correspond to those provided in the

Android Core Libraries. Android core libraries include functionality for media services such as

audio and video, graphics and animation using OpenGL and SGL, SQLite for database

support and networking services. It also includes LibC and interface libraries to interact with

Dalvik VM and the Linux kernel.

The Windows Phone Base Class Library layer includes base classes, collections, threading, text

processing and IO. The base class library also includes networking stacks, such as HTTP and

the Windows Communication Foundation (WCF). WCF provides an easy interface with XML

and SOAP services across the web, with support for XML data transfer,

serialization/deserialization and XML parsing.

While Windows Phone 8 does not have a pre-installed local database such as SQLite,

developers can use SQLite in their own application or use Language Integrated Query (LINQ).

LINQ support SQL-like queries in C# to query data loaded in memory,stored in isolated

storage (see below), or in remote databases such as SQL Azure.

Application UI and Device Integration

You have a choice of two different stacks in Windows Phone media applications, namely,

XAML and Direct3D. XAML for Windows Phone provides controls that are similar to Android

standard widgets.

It is recommended that you use XAML for Windows Phone for consumer or business

applications and Direct3D for games, although you can certainly also develop games using

XAML animation. It is also possible to mix XAML and Direct3D to take advantage of specific

features available in the two stacks.

Page 10: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 1: An Introduction to Windows Phone Platform for Android Application Developers 10

Android applications

Windows Phone counterparts

UI using activity(contains

widgets) with navigation

between them

Windows Phone Applications:

XAML apps with pages connected by flows

2D or 3D games built with

OpenGL-ES

Direct3D games

Direct3D for Games

Windows Phone 8 supports Direct3D for gaming and enables hardware accelerated 3D

rendering and graphics. For a high performance game, Direct3D is the right option.

Controls and Media

You have been using Android controls in your application, , corresponding controls and

support for multi-touch are available via XAML. Extensible Application Markup Language

(XAML) is a declarative language used to design UI. Windows Phone controls are specifically

designed for the primary interaction with touch on a small form factor device. Developers

can use separate code-behind files, written in C# or VB, to respond to events or to

manipulate the controls.

Windows Phone provides high performance audio and video using a variety of CODECs. It

supports both vector and bitmap graphics with hardware acceleration. As opposed to a file

system, Windows Phone provides sandboxed storage, called Isolated Storage, to store

application-specific data. With the isolation of storage, one application cannot affect other

applications that are running on the phone.

Windows Phone Platform Features

If you need to use HTML in your application, you can use the Internet Explorer based browser

control for HTML UI. Windows Phone Framework layer also provides interfaces to various

sensors, such as the accelerometer or the camera. Similar to Google Cloud Messaging

Microsoft provides a push notification service, called Microsoft Push Notification Service.

Page 11: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 1: An Introduction to Windows Phone Platform for Android Application Developers 11

Similar to multitasking in Android, Windows Phone supports multi-tasking. Windows Phone

multi-tasking supports fast application switching which allows users to rapidly switch between

applications. Multi-tasking also supports running scheduled tasks such as alarms and

reminders, background music, GPS tracking and remote communication. If you have used

ADMob API to publish advertisements in your Android application, you will find similar

functionality in the Microsoft Advertising SDK for Windows Phone.

Summary

In this chapter we looked at the Windows Phone 8 architecture and the Android and

Windows Phone 8 programming stacks. Now that you have a high-level idea of mapping

between the two, we are now going to go one level deeper. In the next section, we will look

at the user interface guidelines of Windows Phone 8 applications.

Related Resources

To learn more, visit:

Windows Phone Dev Center. Getting started, download tools and read all about

Windows Phone development

Building Apps for Windows Phone 8 Jump Starts. Video series tailored for developers

to build Windows Phone apps.

Windows Phone Developer Forums

Developing for Windows Phone Jumpstart Series on Channel 9

Developer Documentation

Windows Phone Code Samples

Other Resources you may find useful:

1. Overview of the Windows Phone Application Platform

2. Windows Phone team blog.

3. Windows Phone Programming: Programming guide and reference documents.

4. Visual C#

5. XAML for Windows Phone

Page 12: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 2: User Interface Guidelines for the Windows Phone 12

Chapter 2: User Interface Guidelines for the

Windows Phone

Microsoft’s Windows Phone uses a novel user interface that sets itself apart with its clean and

simple design, emphasis on color and typography. In contrast to the application-focused

design of Android, Windows Phone uses an information-centric design. Instead of an array of

application icons, the start screen of a Windows Phone consists of dynamic tiles that display

critical information at a glance to the user. The tiles are dynamic in the sense they

continuously display the up-to-date status of the applications. For example, the Calendar app

tile shows you the next appointment, the email tile shows the number of new emails waiting

for your attention. Users can personalize their phones by pinning the tiles that they care most

about.

Windows Phone introduces a new paradigm called “hubs”. Hubs bring related information

together. There are six hubs, namely, People, Pictures, Music + Videos, Marketplace, Office,

and Games. The People hub, is more than an address book. It aggregates your address book

contacts, as well as people and their updates from Facebook, Twitter, and LinkedIn.

Page 13: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 2: User Interface Guidelines for the Windows Phone 13

Designing the Application Interface

While Windows Phone user interface is different from that of the Android, there are

similarities in the core design principles.

Similar Application Design Goals

Like Android, Windows Phone developers have to keep in mind the compact screen, lower

CPU and limited memory while designing the applications. Users can use one application at a

time, with just one screen visible. Both Android and Windows Phone are supported on variety

of devices with differing screen resolutions and hardware support. Developers must keep this

in mind while designing their application. For additional details on how to built multi-

resolution apps, read this article. In both Android and Windows Phone, usability and UI

design are not after thoughts, but are the primary goals behind. Applications need to be

simple and focus on key scenarios that most users care about.

Visual Elements and Direct Manipulation

Like Android, visual elements and direct manipulation of objects by touch are the key

characteristics of the Windows Phone application. Windows Phone provides a complete set

of UI controls designed for the phone that can be manipulated using touch. The controls

provide functionality similar to those on Android. It utilizes similar set of core multi-touch

gestures as Android with similar semantics – these include tap, double tap, pan, flick, touch

and hold, and pinch and stretch.

Implications of the Similarities for the Developers

For the most part, the application planning process is similar on both the platforms. While

designing your Windows Phone application, you will focus on the same information that is

critical to the user. Your key design principles from the Android application will get carried

over: direct manipulation with multi-touch, the need for immediate feedback and aesthetic

appeal, will still remain the same.

Page 14: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 2: User Interface Guidelines for the Windows Phone 14

Application User Interface Design

While there are similarities in the design principles of the applications on both platforms, pay

close attention to the Windows Phone application user interface. It is best to take advantage

of the unique features and strengths of the Windows Phone platform.

Design Guidelines

Windows Phone provides clear design guidelines, and recommends consistent UI controls,

colors, typography and images. Together, they provide a consistent user experience. This can

be contrasted with Android which, for a long time, did not encourage simplicity and

consistency among application designs.. Unlike Android, Microsoft strongly encourages you

to follow the design guidelines so that the users have a consistent user experience.

XML and XAML

Android UI elements such as widgets and layouts may be specified using XML or created

programmatically at runtime or both. Windows Phone uses a similar mechanism. Typically,

you use XAML to develop Windows Phone applications. , Extensible Application Markup

Language (XAML)is an XML-based markup language used for visual representation of

applications in Windows Phone.

While both Android and Windows Phone use XML based languages to specify the UI

elements, designing Windows Phone UI is much easier thanks to XAML support in Windows

Phone design tools namely, Visual Studio and Blend. Both tools support WYSIWYG UI design

and produce common XAML code.

Controls and the Application Interface

The Windows Phone 8 development tools and SDK include a rich collection of controls for

Windows Phone that are designed specifically for usability and aesthetics. While you can

create your own controls, it is best to use the standard controls wherever possible. These

standard controls respond to theme changes and provide a consistent user interface.

The following table shows the mapping between Android controls and corresponding

Windows Phone 8 controls.

Android control Windows Phone control Notes

Border Border

ButtonView Button

Page 15: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 2: User Interface Guidelines for the Windows Phone 15

Android control Windows Phone control Notes

AbsoluteLayout Canvas

CheckBox CheckBox

GridView Grid

HyperlinkButton

ImageView Image

ListView ListBox

MediaController MediaPlayerLauncher

MediaPlayer MediaElement

MultiScaleImage

ViewGroup Panel

EditText PasswordBox

ProgressBar ProgressBar

RadioButton,

RadioGroup

RadioButton, ToggleSwitch* ToggleSwitch avail on

CodePlex

ScrollView ScrollViewer

SeekBar Slider

LinearLayout StackPanel

EditText TextBlock

EditText TextBox

MapView Map

WebView WebBrowser

Panorama

Page 16: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 2: User Interface Guidelines for the Windows Phone 16

Android control Windows Phone control Notes

Pivot

TimePicker TimePicker* Available on Codeplex

DatePicker DatePicker* Available on Codeplex

ExpandableListView

Spinner ListBox

TableLayout Grid Layout

ViewFlipper

ZoomControl

TabHost PivotControl

RatingBar

Toggle button ToggleSwitch*

* ToggleSwitch and Datepicker/Timepicker control are part of the Windows Phone Toolkit

available on Codeplex:

As you can see, Windows Phone offers controls that correspond to many Android controls.

While the look and feel is different, they provide similar functionality.

New Controls in Windows Phone

Windows Phone introduces a few controls that have no counterpart on Android. Here are

some of the examples:

A multi-scale image control allows the user to zoom in and pan a photo.

Panorama control is a multi-screen page spanning horizontally beyond the width

of the phone. It allows a large amount of related information to be presented. The

People hub is a great example of this control.

The Pivot control, shown below, is useful to manage views and display information

that is logically divided into sections.

Page 17: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 2: User Interface Guidelines for the Windows Phone 17

Notifications

Both Android and Windows Phone provide notification service, but notifications play a key

role in Windows Phone. Windows Phone provides number of different means to show

notifications to users – via status bar update, a dialog, as a toast, or live tile notifications. It is

the tile notifications that make Windows Phone come alive. Windows Phone sets itself apart

with live tiles that show critical information at a glance. Live tiles are used to display non-

critical information without disrupting what the user is doing. If you are using status bar

notifications in Android, you can use tile notification as a replacement in Windows Phone to

show critical information. However, tiles have the ability to provide far more information,

including photos, a message and a number.

The notification service also displays toast notifications that provide time sensitive

information, such as an SMS. Toast notifications are shown for about 10 seconds and the user

may choose to ignore them or click to launch the app directly. These are similar to Android

toast notifications.

The following table shows the Windows Phone notifications that are closest to various

Android notification mechanisms. While you may replace status bar notifications with Tile

notifications, tile notifications provide much richer functionality. Additionally, tile notifications

do not require user response.

Page 18: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 2: User Interface Guidelines for the Windows Phone 18

Android Functionality Windows Phone

Status bar

notification

Persistent information that requires user

response.

Tile notifications

Toast notification Time sensitive non-persistent data that

the user may not respond to.

Toast Notifications

ActionBar vs. Application Bar

In Android, the ActionBar identifies the application and user location. It also shows actions

available to the user as well as navigation such as tabs. The status bar on Android shows the

device status and various notifications. While both Status bar and ActionBar are at the top of

the screen, action bar may be split and may also be shown at the bottom of the screen.

A: Status bar

B: Action bar

The status bar on Windows Phone provides functionality similar to Android status bar. On

Windows Phone, Page or application menus are supported using a versatile application bar

shown at the bottom of the screen on Windows Phone. The application bar can include up to

4 of the most common views or application tasks. You can also use application bar menus for

additional context-sensitive tasks. Application bar does not provide navigation nor tabbed

views as provided by the ActionBar.

A: Status bar

B: Title, Navigation

Page 19: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 2: User Interface Guidelines for the Windows Phone 19

C: Appbar

Android Functionality Windows Phone

Status bar Device status and

notifications

Status bar

Action bar Navigation, Title,

Buttons for views or

actions

Back button for back

navigation

Page title

ActionBar Buttons for views or

actions App bar

Comparing Windows Phone and Android Navigation

Windows Phone apps are a collection of pages. Like Android, the user navigates through

pages using controls such as buttons and links. Like Android, all Windows Phones have a

Back button on them. On Windows Phone the back button behaves much like the back

button in the browser allowing the user to navigate between pages of an app or even across

apps. For example, consider that the user clicked a link in the email application to launch the

browser. With the Back button, the user would return back to the email application. The Back

button also closes menus and dialogs. As a developer, you should consider what the Back

button means to your user and plan to override it appropriately. For example, you may

decide to pause a game by using the Back button on the Phone.

The other two hardware buttons on the Windows phone, namely, Search and Home, have

fixed behaviors. The Home button takes the user to the Windows phone main page, much

like Android. Unlike Android where search button provides context sensitive search, the

Windows Phone search button performs a web search using Bing.

Page 20: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 2: User Interface Guidelines for the Windows Phone 20

Windows Phone Frame and Page Structure

Each Windows Phone application has a single frame. It includes areas for:

A page where application content is rendered. This is the content where controls or

graphics are rendered.

A reserved space for the status bar and application bar. It also exposes certain

properties, such as orientation, to the application.

Status Bar and Application Bar

On Windows Phone, the status bar includes indicators for a variety of system-level status

information items such as connection status. The application bar includes the area for the

most common application menus, which may include various data views or tasks. The

application can manipulate the status bar to change its visibility, opacity or the color. The

application can use it to show progress.

Page 21: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 2: User Interface Guidelines for the Windows Phone 21

Page Structure of a Windows Phone Application

The following diagram shows the structure of a typical Windows Phone data-bound

application, which resembles the structure of a navigation-based Android application.

When the user first starts the application, he or she is presented with a splash screen,

designed to welcome the user, as well as to create the perception of a fast response. Splash

screens are usually an image file of the size of the display.

Usually the application starts with the home page, the main navigation page, with links for

search, and other page controls. Consider an application that shows information about

baseball teams and their players. The primary content page, marked as the widgets page in

the above diagram, will have the content of interest, for example, a list of all baseball teams.

However, depending on requirements, the home page can also be the primary content page.

The user can click on one of the team links to visit the team details page (“widget details

page”) which can provide multiple views. The page may employ a pivot control or a

panorama to display different views such as the team summary and the list of all players (“list

of gadgets”) from that team. Selecting one of the baseball players will take the user to the

page with player statistics (“Gadget Details page”). Such a page may use controls such as

textblocks, multi-scale images, or other multimedia using a MediaElement control.

Users may also use the search page to search and directly access the team page

(“widget details”) or the player page (“gadget details”)

Application Templates

Page 22: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 2: User Interface Guidelines for the Windows Phone 22

Visual Studio Express 2012 for Windows Phone provides a variety of templates for developing

Windows Phone 8 applications. Visual Studio templates create the appropriate structure of

the application automatically.

Functionality Android Activity Template Visual Studio Template

Information drilldown

applications

Master/Detail Flow, Blank

Activity

Windows Phone Data-bound App,

Pivot App, Panorama App

Utility applications.

For example, Bubble

Level

Fullscreen Activity, Blank

Activity

Windows Phone App

Games Fullscreen Activity, Blank

Activity

Windows Phone Direct3D App (Visual

C++) app

Flexible template to

design any

application

Blank Activity Windows Phone App

You can choose the Windows Phone application template to either create an application with

functionality similar to the view-based or the window-based Android application type.

Summary

In this chapter we looked at the similarities between the application design goals of the

Android and Windows Phone 8 platforms. When you plan your Windows Phone 8

application, you will be able to leverage your existing work on Android applications.

Revisit the application interface design to make sure you are taking advantage of the

Windows Phone controls and Windows Phone design and interface guidelines. You will find

that the Windows Phone 8 offers a large library of controls and gestures that have close

counterparts on Android. This chapter also showed you the use of innovative controls like

Panorama and explored the use of live tiles in building an engaging Windows Phone 8

experience.

Related Resources

To learn more, visit:

Windows Phone User Interface Guidelines

Windows Phone SDK ToolsWindows Phone toolkit on Codeplex

Other Resources you may find useful:

Page 23: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 2: User Interface Guidelines for the Windows Phone 23

App page model for Windows Phone

In-app navigations for Windows Phone

Page 24: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 24

Chapter 3: An introduction to Windows

Phone Developer and Designer Tools

Along with the release of the Windows Phone OS , Microsoft published the user-friendly,

high productivity Visual Studio Development environment for Windows Phone 8

development. Developers who have used Visual Studio will find themselves in a familiar

environment. An Android application developer who is familiar with Eclipse will find it easy to

quickly migrate to Windows Phone 8 developer tools and quickly become productive.

A Comparison of Android and Windows Phone Tools

Visual Studio Express 2012 for Windows Phone is a full-featured Integrated Development

Environment (IDE). Visual Studio 2012 facilitates designing, developing, and debugging of

Windows Phone applications. Other Windows Phone 8 tools that can help you in the

development cycle of the Windows Phone 8 application are:

Blend for Visual Studio

Windows Phone Emulator

Compared to Android developer tools, the Windows Phone 8 developer tools offer richer

functionality. The following table gives an overview of the functionality of each of these tools.

The table also indicates the equivalent tools that you would use for Android application

development.

Functionality Audience Android tools Windows Phone tools

Application

development

(coding)

Programmers Eclipse Visual Studio Express 2012 for

Windows Phone

Game

development

(coding)

Programmers Eclipse Visual Studio Express 2012 for

Windows Phone

Testing /

Emulation

Testers Android Emulator Windows Phone Emulator in

Visual Studio Express 2012

UI design UI designers

and

programmers

Defined in

XML(Some

Visual Studio Express 2012

and Blend for Visual Studio

Page 25: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 25

As you plan to develop applications for Windows Phone 8, you can continue to leverage the

skillsets in your team. Your development team structure and overall development process

can remain the same. The Windows Phone 8 toolset ensures that the entire team of

designers, developers, and testers familiar with Android development tools will find it easy to

migrate to the Windows Phone 8 toolset.

Visual Studio is not only a powerful IDE but it can also

be extended in a variety of ways. It allows the ability to

add macros, options, menus and toolbar commands,

visualizers and other tools. In addition, Visual Studio

Primary UI

design: Colors,

gradients, and

animation

UI designers WYSIWYG support

via ADT plug-in)

Pixel accurate WYSIWYG

layout using Blend for Visual

Studio

Page 26: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 26

supports NuGet, a package manager, to add, remove

and manage libraries and tools in Visual Studio and the

.NET Framework.Windows Phone tools l

Windows Phone development tools facilitate a close collaboration between designers and

developers through the use of Blend and Visual Studio. The UI for a Windows Phone app is

created using XAML, a declarative XML-based language. Both Blend and Visual Studio can be

used to edit the XAML file, allowing designers and developers to use tools targeted toward

their discipline

Tool for coding

The file structure of a Windows Phone app

Like Eclipse, Visual Studio Express 2012 for Windows Phone is a full-featured IDE. It allows

you toorganize the source files s. as a collection of projects, i.e. separate functional units.

The organization of the codebase into projects makes it easy to manage manage the work

among team members. Visual Studio integrates a compiler and a debugger, both of which

can be invoked either interactively or via the command line.

In this chapter we will walk through the creation of a simple Shopping List app in order to

illustrate the Windows Phone development tools and steps. Let us create a sample

application

1. Start Visual Studio Express for Windows Phone from the Windows Start menu.

2. In Visual Studio Express, click File.

Page 27: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 27

3. Click New Project.

4. In the New Project dialog expand Installed -> Templates -> Visual C# -> Windows

Phone Select Windows Phone App.

5. In the Name text box, enter “ShoppingList” as the name of the project, and click OK.

Visual Studio Express will prompt you select the OS you want to target. Select “Windows

Phone OS 8.0” and Visual Studio will create the new project as shown below.

The Solution Explorer pane displays the solution that you have created. This solution has only

one project, also named ShoppingList. The project contains the sources code and other files.

Note: Visual Studio Express 2012 for Windows Phone does not provide integration with

source control systems. The Visual Studio Professional edition provides features such as

integration with various source control systems like Subversion. Alternatively, organizations

can use the Visual Studio Team System, an edition designed particularly for greater

communication and collaboration among

software development teams, for developing your Windows Phone application

Tools for designing

The Windows Phone 8 developer toolset includes two UI design tools:

Visual Studio UI Designer

Blend for Visual Studio

Page 28: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 28

Compared to Eclipse ADT UI plugin, Visual Studio UI design tool is much simpler and richer.

Android application developers migrating to Windows Phone 8 developer tools will find the

task of designing an application UI much easier.

The main page for our ShoppingList solution, MainPage.xaml, is already opened in the Visual

Studio UI designer tool for editing (shown above). Let us change the title of the application,

as well as the title of the current page. Right click on the title, “MY APPLICATION” and select

Properties. In the properties window, select Text and type “SHOPPING LIST.” Similarly, change

the title of the page by typing “my list” in the Text property of the title.

Let us design the interface of the main page of the application.

1. Open the Toolbox window (View -> Other Windows -> Toolbox) if not already open,

drag a TextBlock and drop it on the page in the designer window. Position it so that it is

at the top left. Click and select the TextBlock and update its Text property to “Item:” in the

Properties window.

Page 29: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 29

2. Drag a TextBox from the toolbox and place it underneath the text block created in the

previous step.

3. Update the Textbox’s Text property to delete any existing entry.

4. In the Properties window for the textbox, enter “txtItem” in the name field to set the

Name of the text box to txtItem. The properties pane in the VS UI is in sync with the

XAML code in the code editor window. You can set properties for controls manually in

XAML or set them in the UI using properties panel.

5. Resize the text box by dragging its lower right corner so that its width is 300.

6. Drag a Button to the right of the TextBox.

7. Change the button’s Content property to “Add”, and its Name to “btnAdd”.

8. Resize the button so that its width is 140.

9. Drag another TextBox and place it underneath the txtItem textbox.

10.Resize the new TextBox so that it covers the rest of the phone screen.

11.Update the Name of the new TextBox to “txtList”.

12.Update the Text property of the new TextBox to “Nothing here yet!”

At this point, your application should look something like this:

13.Click F5, or Debug and Start Debugging, to compile the application and launch it.

Page 30: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 30

This will start the Windows Phone 8 emulator, deploy the ShoppingList application and run it.

You can click on Add, but nothing will happen as we have not written any logic yet.

Blend for Visual Studio

Blend for Visual Studio is a full featured visual UI design tool created for designers. There is

no exact counterpart to this in the Android development toolset. Similar to the Visual Studio

design tool, Blend also allows drag and drop to design the UI. The tool, shown below, allows

pixel accurate layout of controls. They can easily create and use color palettes and gradients,

as well as special effects such as reflections and shadows. The tool can import Photoshop

files, which makes it easy to bring your Android application resources to your Windows

Phone application. Designers can also use the tool to define application behavior, as well as

certain animations, without any programming.

Page 31: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 31

You will need to use Visual Studio to code your application logic, but you can create the UI

in VS UI or Blend. Both tools include the same control set that provides accurate fidelity to

their run time visual representation, making it easy to visualize the application.

Page 32: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 32

Editing Code

Visual Studio has a simple to use, full-featured, configurable source editor. The editor has

various features that are familiar to Eclipse users. These include flexible search, rich editing,

code formatting, and the ability to outline/hide code.

Let us now proceed to add some logic to our application. :

1. Stop the running application by clicking Debug, then click Stop Debugging. Leave the

emulator running so that it doesn’t need to start up again the next time you debug.

This speeds up the subsequent debug sessions.

2. Double click the “Add” button which will open MainPage.xaml.cs with a method

btnAdd_click in the MainPage class.

3. To add logic for adding items to the shopping list, edit the btnAdd_click method.

Enter the following code:

string tStr = txtItem.Text;

Unlike Android where objects must be dereferenced in Java using getViewById, in XAML,

objects created in XAML are accessible in code-behind C# or VB files. The

specified x:Name or Name attribute of a XAML object becomes the name of a field that is

created in the underlying code when XAML is processed. This allows us to access the

textbox using txtItem, its x:Name attribute.

IntelliSense in Visual Studio

Page 33: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 33

When you enter "t" for "txtItem", Visual Studio displays the auto-completion dialog box. The

Visual Studio equivalent for Eclipse auto-completion content assistant is called Intellisense.

4. Enter the following code in the btnAdd_click method:

if (!string.IsNullOrEmpty(tStr))

When you type "string", Visual Studio displays the auto-completion dialog box. When you

type "Is", Visual Studio displays the class methods of the String class. As you see below, it

provides a synopsis of the IsNullOrEmpty method.

IntelliSense has a rich feature set. It uses history, code context, and .NET reflection for

intelligent auto-completion. IntelliSense can suggest and complete variable names,

parameters, classes, and method names. IntelliSense can also generate appropriate code

where needed, as shown in the code below:

To complete the event hookup, it will also generate an empty stub for the event handler, in

this case, the button1_click method.

Page 34: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 34

Page 35: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 35

You will find the generated event handler in the C# code

void button1_Click(object sender, RoutedEventArgs e) { throw new NotImplementedException(); }

The default code would throw an exception if you forgot to implement necessary logic for

this handler.Subsequently, we will implement the logic to handle the button click.

Code Snippets in Visual Studio

Visual Studio provides another very useful feature called Code Snippets, similar to code

templates in Eclipse, allowing you to insert code fragments with a few clicks. Visual Studio

contains a large number of snippets and developers can create their own library of snippets.

They can also be indexed and searched using user defined terms.

Type ctrl+k ctrl+x to bring up the Insert Snippet prompt. Select Visual C#, followed by “i” to

select a code snippet for “if statement”, which will insert an if-statement in the code.

The inserted snippet identifies the parts the user needs to complete:

Type the remaining code, so that the body of the method is as follows:

string tStr = txtItem.Text; if (!string.IsNullOrEmpty(tStr)) { if (!initialized) { txtList.Text = ""; } txtList.Text += txtItem.Text + "\n"; txtItem.Text = ""; }

Page 36: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 36

Make sure that you declare and initialize a variable called initialized as follows. public partial class MainPage : PhoneApplicationPage {

bool initialized = false;

Visual Studio supports various refactoring mechanisms. You can select any piece of code and

right-click the code to access the refactoring menu.

The Visual Studio editor is highly customizable. Developers can easily define various

keyboard shortcuts or create their own macros. Macros help you to automate repetitive

actions by combining a series of commands and instructions.

The following table provides various functions and corresponding keyboard shortcuts in both

Eclipse and Visual Studio.

Tool

Run Ctrl+f11 Ctrl+f5

Debug f11 f5

Toggle breakpoint Ctrl+shift+b f9

Switch editor tabs Ctrl+f6 Ctrl+f6

Source code management

Comment line/block Ctrl+/ Ctrl+k Ctrl+c

Uncomment line/block Ctrl+/ Ctrl+k Ctrl+u

Rename Ctrl+shift+r f2

Refactor Ctrl+shift+t Ctrl+R+..

Autocompletion Ctrl+space Automatic

Organize imports Ctrl+Shift+o Ctrl+.

Format source code Ctrl+shift+f Ctrl+e, f

Search

Find Ctrl+f Ctrl+f

Page 37: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 37

Replace Ctrl+f Ctrl+h

Find next Ctrl+k f3

Find previous Ctrl+shift+k Shift+f3

Find in files Ctrl+h Ctrl+shift+f

Replace in files Ctrl+h Ctrl+shift+h

Navigation

Goto Line Ctrl+l Ctrl+g

Goto Definition Ctrl+click F12

Eclipse users can easily customize Visual Studio Editor to use shortcuts and keyboard

combinations with which they are familiar.

Developers can change the way various windows are laid out to suit their need. They can also

change the way in which various windows are docked within the Visual Studio Shell.

Building Application Similar to Eclipse, Visual Studio Express 2012 for Windows Phone allows you to build a Visual

Studio solution on demand. Further, each project that is part of the solution can be built

separately.

Visual Studio uses an XML based, declarative build system called MSBuild which can be

compared to Ant or Nant. Builds can be invoked interactively or via a command line for

batch processing. This system is flexible and allows you to build a specific target either as a

debug build or as a release build.

Page 38: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 38

Tool for Testing

Windows Phone 8 developer tools include an emulator that can be used effectively for

testing applications. It provides features that are comparable to the Android simulator

included in the developer tools.

The Windows Phone 8 emulator provides a virtualized environment in which you can deploy,

debug and test applications. The Windows Phone Emulator is designed to provide

comparable performance to an actual device and meets the peripheral specifications

required for application development. As you can see below, the emulator allows emulation

of accelerometer as well as device location. It can be invoked from Visual Studio to load an

application package [.xap] within the emulator.

Debugging

Page 39: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 39

Visual Studio Express 2012 for Windows Phone includes a very powerful symbolic debugger

that can be used with the Windows Phone 8 emulator or with a remote device. Once the

application breaks into the debugger, the developer can view the variables in the application

and control the execution.

Let us look at the debugger in action. Press F5 to launch the application again. Type

“napkins” in the textbox and click Add Napkins is added to our list.

Now add, “milk” but find that “napkins” gets removed - not something we expected.

In Visual Studio, click in the light blue area to the left of the “string tStr = txtItem.Text;” line in

the code window. This will insert a breakpoint at that line.

Enter “milk” and click Add. When the application breaks into the debugger, use “Step over” or

(f10) to enter the outer if block. Hover over initialized variable in the code as shown and

Visual Studio shows its value as false something we did not expect Step through to find that

the execution enters the inner if and resets txtList.Text to blank again – therein lies our bug.

After adding first item to the list, we should have set the value of initialized to true.

Page 40: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 40

Fix the bug by adding, initialized = true; in the inner if statement and restart the

application.

You can inspect any variable, its type, its fields and properties while debugging. For

example, hover over txtList and click + to inspect various properties of txtList.

Page 41: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 41

You can set a “watch” on certain variables to inspect them continuously. Right click txtList,

followed by Add Watch. The watch window will show the variable txtList througout.

In the debugger, the developer can use the Visual Studio ‘immediate mode’ where one can

write managed code instructions to modify or view the variables or execute some code to

help with debugging.

Update the code and re-launch the application. Test it by adding couple of items to the

shopping list.

Page 42: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 42

Similar to Java applications using Eclipse with ADT, the Windows Phone 8 application

debugging is done entirely at the application source code level. Overall, you will find that,

with the power of Visual Studio and C#, debugging a Windows Phone 8 application is very

easy whether you are running the application in the emulator or an actual device.

In addition to the above debug facilities, the .NET Framework includes two specific classes,

Debug and Trace, that make it easy to write run-time debug messages to the output window.

C# also supports an assert statement, which is evaluated at run time. If the statement

evaluates to true, nothing happens, but if the statement returns false, the program breaks

into a debugger.

Page 43: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 3: An introduction to Windows Phone Developer and Designer Tools 43

Summary

In this chapter we looked at the Windows Phone Developer Toolset. The tool set includes rich

tools that are designed to support every step in the entire application development lifecycle.

The design, development, and testing tools are amenable to the existing Android team roles

and processes. The tight integration between the Windows Phone 8 development tools helps

you to streamline the design, develop the workflow, and test the workflow. These tools

provide end-to-end functionality and are highly customizable, with the power to make your

team quickly productive.

Page 44: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 44

Chapter 4: An Introduction to C#

programming for Java developers

In the previous chapter, we looked at the user interface guidelines for Windows Phone 8

applications. We will now dive deeper into what it takes to implement a Windows Phone 8

application.

In this chapter, we will look at the various C# features that map to the most common Java

features. We will provide code snippets which will ease the transition into C# code. We will

point to the key C# features that help you write safe code and enhance productivity.

Page 45: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 45

Managed Programming

Windows Phone 8 supports managed programming in C# or VB as well as C++. In this

chapter, we will only look at C# and compare it with Java. Before we jump into the details of

C#, let us briefly review the .NET programming environment.

Figure 2 Managed Application Execution Flow

The C# compiler (and similarly, the VB compiler) compiles the C# (or VB) code in an

intermediate language (IL) byte code and metadata. The Common Language Runtime (CLR)

executes the byte code. C# uses metadata to manage type safety, exception handling, and

run-time validations such as checking array bounds . The CLR also manages memory and

performs garbage collection. This is similar to Android where the Java code is compiled into a

.dex file which is then executed by the Dalvik VM.

Page 46: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 46

A Comparison between C# and Java Features

There are many many similarities between Java and C#. They both

Are object-oriented and based on C and C++.

support single inheritance and allow classes to implement multiple interfaces.

have objects as reference types.

create instances of a class are created on the heap and do not support explicit delete.

Implement automatic garbage collection. Instances that are no longer accessible, are

automatically garbage collected.

type safe languages and require type declaration for all variables. As you will see

below, recently C# has started supporting implicitly typed variables where the

compiler infers the type automatically.

support built-in threading and synchronization allowing developers to write

concurrent programs.

However, there are also many subtle and important differences between the two as we will

see below.

Class Declaration

Like Java, C# does not separate class definition from class implementation. The compiler

derives the metadata about the class from the class implementation. As in Java, we can

define multiple class definitions in the same file. However, unlike Java, more than one class in

a file can be public and the name of the file may be different from the public class in the file.

In the example, the public signature of the class Person consists of the age property and the

constructor. The rest of the class implementation is opaque.

using System; // This is similar to java import except //.NET directives are for the whole namespace namespace FirstApplication // scope for classes. Similar to package in Java // Unlike C#, namespace does not force directory { class Person // Like Java, only uses class defined // implementation not declaration. { private DateTime birthDate; // a private field accessible within this class private int ageOn(DateTime date) // a private method accessible in class { TimeSpan span = date.Subtract(birthDate); //like Java uses a .notation to invoke

return span.Days; //Unlike Java, C# supports properties }

Page 47: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 47

} public int age //Unlike Java, C# supports properties. { Get // just a getter; it’s a read-only property { return this.ageOn(DateTime.Now); } } public Person( DateTime dob) // instance constructor similar to Java { birthDate = dob; } } class Program //Unlike Java, another class in the same file. { static void Main(string[] args) // main entry point into the program { Person p = new Person(new DateTime(1973,11,12)); //construct an instance System.Console.WriteLine("The age is is" + p.age.ToString()); DateTime dt = p.birthDate; //error in compilation birthDate is private } } }

Instead of using the import statement in Java, C# employs a using statement to refer to

the metadata of other classes. The namespace declaration that is shown at the top of the file

is used to declare the scope, which avoids name conflict and organizes the code. You can

access a class in another namespace by referring to its fully-qualified name. See the reference

to System.Console.WriteLine in the example above, where console is in the System

namespace.

Strong Typing

Both Java and C# are strongly typed languages. The types must be specified for variables

and input/output parameters1. The compiler enforces the types. In the section on generics,

you can see how C# uses strong typing for collection classes.

Strong typing works similarly for all classes. The code example below shows the strong typing

for primitive types.

int a = 5; int b = a + 2; //OK bool test = true; // OK int c = a + test; // Error. Operator '+' cannot mix type 'int' and 'bool'.

Class Constructors

1 C# 4.0 introduced a concept of “var”, i.e. implicitly typed variables. While the developer does not declare the

type of such variables, the compiler figures out the actual type variables using the right hand side expression.

Page 48: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 48

Like Java, C# uses instance constructors to create and initialize instances. For example: p is an

instance of the Person class. You can construct and initialize p with a given birthdate, in a

single statement.

Person p = new Person(new DateTime(1973,11,12));

Properties

Unlike Java which has no class properties, C# classes can have properties. Properties provide

a natural syntax for accessing members. Properties help to abstract away from directly

accessing the members of a class. This technique is similar to using accessors (getters) and

modifiers (setters) in Java, but is more natural to read and compact. The properties can be

defined as read-only, write-only or read-write. You can make the C# property read-only by

providing the getter, write-only by providing the setter, or read-write by providing both

getter and setter. In the above example, “age” is implemented as a read-only property since

it only exposes a getter and not a setter. You often need to decide whether to implement a

member as a property or a method. As a general rule, use properties when you need to

access data. To take any action on the data, use methods.

Parameter Types

Like Java, C# uses value parameters by default. Parameters that are passed by value cannot

be modified in the method. But unlike Java, C# also allows the passing of reference

parameters by using the ref modifier. You can pass parameters by ref where you want to

change the value of the actual parameter. In some cases, you need to use reference

parameters for better efficiency since they avoid data copying.

void Foo (ref int x, int y)

{

x = 0;

y = 0;

}

..

int a = 5;

int b = 8;

Foo (ref a, b); //a is zero and b is still 8

C# also provides the parameters with an out modifier. The out modifier represents the

parameters that must be initialized by the called method before returning. This design

pattern is often used to return the error in addition to the value of the function.

Access Privileges

Page 49: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 49

Like Java, C# allows access privileges for class members. Access privileges can be specified

on fields (for example, birthDate), methods (for example, ageOn) and properties (for

example, age). C# uses public, private, and protected as modifiers to denote the three

different levels of access privileges.

In the above example, the compiler gives an error on p.birthDate since that variable is

private. Therefore, p.birthDate is not accessible from the Program class. Similarly, the ageOn

method is also private and inaccessible from the Program class. Similar to Java, C# protected

members are accessible from derived classes.

Methods with Multiple Parameters

Both Java and C# support methods with multiple parameters. While C# traditionally uses

positional and unnamed parameters, the latest version of C# also includes named

parameters. The following example shows the comparative syntax for Java and C#.

Java C#

void addEmployee(string name,

int id, int age);

Method

signature

void addEmployee(string name,

int id, int age);

Off.addEmployee("Phil",2345,

23);

Positional

and unmamed

parameters

Off.addEmployee("Phil",2345,

23);

No named parameters Named

parameters

Off.addEmployee(name: "Phil",

age:23, id:2345);

Like Java, C# explicitly supports method overloading. Both Java and C# use method name

and parameter types for defining method signatures and for differentiating between

methods. The following code sample shows how C# differentiates between methods that

have the same name.

void insert (myClass obj, int index);

void insert (myClass obj, myClass before);

The method insert may be called with both these signatures:

list.insert (myObj1, 4);

list.insert ( myInstanceNew, myInstanceOld);

Inheritance

Like Java, C# uses a single inheritance mechanism. Inheritance is specified by listing the

parent class after the class name as shown below. In this example, the class Rectangle inherits

from the class Shape, and the class Square inherits from the class Rectangle.

class Rectangle : Shape

Page 50: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 50

class Square : Rectangle

Similar to Java, in C#, the no parameter constructor of the base class is automatically invoked

when you construct an instance of a derived class. Similarly, a derived class in C# can invoke

a specific constructor of the base class if needed. You can see this in the constructor of the

Square class.

public Square(double s): base(s, s) //constructor. Calls parent

constructor explicitly

Unlike Java, a C# derived class may not override a method by just redefining it. The class

must use the keyword override in its method definition to explicitly override the definition in

the parent class. Override modifier is used to modify the abstract or virtual implementation of

an inherited method or property. An abstract modifier is intended to denote that a class,

method or property. Members marked abstract or included in an abstract class must be

implemented by a derived class. A virtual member denotes that it may be overridden in a

derived class.

The following code sample shows inheritance and how methods can be overridden in a

derived class:

using System;

namespace SecondApplication

{

struct Point // In contrast to Java C# provides structs

{

public double x; // struct fields can also have access

modifiers

public double y;

public Point(double p1, double p2) //a constructor for the struct

{

x = p1;

y = p2;

}

}

interface IThreeDShape // an interface, like a Java interface

{ // defines the behavior

double volume

{

get; // Volume is a read-only property. no

setter

}

}

abstract class Shape // this class is marked abstract, i.e. may

not be instantiated.

{

protected Point origin; // only derived classes may access.

Similar to Java protected variables

protected static int counter = 0; // similar to Java class variables

public string ID;

protected Shape() //a constructor. Same name as the class

name

{

counter++; // class variable being updated

}

public Point Origin

Page 51: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 51

{

set

{

origin = value;

}

}

public abstract double Area //denotes that this property must be

overridden in a derived class

{

get;

}

public abstract bool contains(Point p); // this method must also be

overridden

}

class Rectangle : Shape // Inheritance. Similar to Java ‘extends’

{

public double length; //field accessible from others

public double width;

public Rectangle(Point o, double l, double w) //a public constructor

{

ID = "Rectangle_" + counter.ToString();

origin = o;

length = l; width = w;

} public Rectangle(double l, double w) // one constructor using another

constructor

//creates a rectangle at the origin

: this(new Point(0, 0), l, w)

{

}

public override double Area // Subclass must implement abstract

methods of parent class

// unlike Java, overridden method must

{ // use override keyword

get

{

return length * width;

}

}

public override bool contains(Point p)

{

if ((origin.x < p.x && origin.x + length > p.x) || (origin.x > p.x &&

origin.x - length < p.x))

if ((origin.y < p.y && origin.y + length > p.y) || (origin.y > p.y &&

origin.y - length < p.y))

return true;

return false;

}

}

class Square : Rectangle

{

public double side;

public Square(double s)

: base(s, s) //constructor

{

ID = "Square_" + counter.ToString();

side = s;

}

} class Cube : Shape, IThreeDShape //similar to Java, class implements

interface

{

public double side;

Page 52: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 52

public Cube(double s)

{

ID = "Cube_" + counter.ToString();

side = s;

}

public override double Area

{

get

{

return 6 * side * side;

}

}

public double volume

{

get

{

return side * side * side;

}

}

public override bool contains(Point p)

}

class SecondProgram

{

static void printVolume(IThreeDShape tdShape)

{

Console.WriteLine("The volume is " + tdShape.volume);

}

static void Main(string[] args)

{

Rectangle r = new Rectangle(5.0, 3.0);

Cube c = new Cube(4.0);

SecondProgram.printVolume(c);

double a = r.Area;

Console.WriteLine("The area of rectangle " + r.ID + " is " +

a.ToString());

bool b = r.contains(new Point(1, 2));

Console.WriteLine("The point is in " + b.ToString()); // will print

TRUE

}

}

}

Protected Access

Like Java, in C#, you can use the protected modifier to limit access to fields, properties, and

methods. Protected members are accessible only to derived classes. You can implement

protected variables in C# by using the protected access modifier, as shown in the code

sample below:

protected Point origin;

protected static int counter=0;

Instance vs. Class Level Access

Page 53: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 53

Like Java, C# uses a static modifier to denote class level methods, fields, and properties.

Other members without static modifier are at an instance level. In the above code example,

counter is a class level variable.

protected static int counter=0;

Abstract Classes

Abstract classes in C# are similar to Java abstract classes in that they cannot be instantiated.

The class Shape defined in the above C# code sample is an abstract class. It requires that

both the Area property and the contains method must have an override in any derived

classes.

abstract class Shape

{

public abstract double Area

{

get;

}

public abstract bool contains(Point p);

Interfaces

Interfaces are similar in Java and C#. In the sample code shown below, Interface

IThreeDShape is implemented by the Cube class. In both languages an Interface defines a

contract consisting of method signatures, but no implementations. A class that implements

an interface must implement all methods defied in the interface.

interface IThreeDShape

{

double volume

{

...

class Cube : Shape, IThreeDShape

Polymorphism

Both Java and C# provide polymorphism via class inheritance. A class can be used as more

than one type - as its own type, as a base type or as one of the interfaces it implements. You

can pass a C# derived class as a parameter to a method that expects a base class. Similarly, if

a method expects an interface parameter, you can pass an instance of a class that

implements that interface. The following sample code shows how to pass an instance of the

class Cube as a parameter, where the method expects an object of the class IThreeDShape.

static void printVolume(IThreeDShape tdShape)

Page 54: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 54

{

Console.WriteLine(“The volume is ” + tdShape.volume);

}

Cube c = new Cube(4.0);

SecondProgram.printVolume(c); // Since Cube implements IThreeDShape interface, this

is legal

Structs

Unlike Java, C# provides structs as first class language primitives. In C# structs are similar to

classes except that they are a value-type. C# structs can use modifiers and can have

constructors, methods, and properties. However, a struct does not implement inheritance.

struct Point

{

public double x;

public double y;

}

Object Lifecycle: Creation and Deletion of Objects

Both Java and C# performs automatic memory management. Both languages use the new

operator to create objects, i.e. class instances, and initialize them. However, unlike C++,

neither of them provide object deletion. Objects are automatically ‘deleted’. When the code

execution reaches a place where an object is outside the scope, i.e. it can no longer be

accessed, the object becomes eligible for garbage collection. In C#, the garbage collection is

implemented using .NET. The .NET CLR garbage collector periodically frees up the memory

for the objects that are no longer accessible. Unlike C++, developers do not need to ref

count objects nor free up unused objects.

In rare circumstances, you may need to perform a cleanup at the time that an object is

destroyed. C# allows the use of destructors, which are similar to Java finalizers, but in practice

this is rare.

Type Checking vs. Reflection

Reflection is the ability to discover the members of a class and to invoke methods at runtime.

Both Java and C# support reflection. You can use reflection to:

Get information about the type from an existing object.

Dynamically create an instance of a type.

Bind the type to an existing object, access its methods, and access its fields and

properties.

Page 55: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 55

The following table maps the dynamic type checking in Java with its corresponding C#

reflection features.

Java Reflection Explanation C# Reflection

Constructor ct = cls.getConstructor();

Object retobj = ct.newInstance();

Create an instance Activator.CreateInstance(typeof(Class));

If (obj instanceof MyClass)

If (MyClass instnceof BaseClass)

Is Object a subclass or

member?

type.IsSubclassOf(typeof(BaseClass))

object.getClass() Get class

object.getType() or typeof

search from

Method[] methods = c.getMethods();

Does the object

implement the

method?

type.GetMethod(MethodName)

Method methlist[]

= cls.getDeclaredMethods();

for (int i = 0; i <

methlist.length;

i++) {

Method m = methlist[i];

System.out.println("name

= " + m.getName());

Does the class

respond to the

method?

type.GetMethod(MethodName)

Method.invoke(..) Invoke a method

type.InvokeMember(…)

Exception Handling

C# and Java support formal exception handling and they have many similarities. They use

very similar syntax for declaring exceptions; try blocks delineate guarded regions, catch blocks handle exceptions and finally blocks release any resources. Exceptions can be

caught and re-thrown. You can either catch specific exceptions or use a catch-all statement.

Unlike Java, C# does not have checked exceptions. In Java, checked exceptions are declared

using the “throws” keyword and that must be handled by calling code. In C#, all exceptions

are unchecked and there is no counterpart to the throws declaration for the method

signature.

try

{

//block of code

}

//Most specific:

Page 56: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 56

catch (ArgumentNullException e)

{

Console.WriteLine(“{0}First exception caught.”, e);

}

//Least specific

catch (Exception e)

{

Console.WriteLine(“{0}First exception caught.”, e);

}

Page 57: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 57

Key features compared

Strings

C# provides a comprehensive string class, which offers you all the features that you associate

with this class.

Java Feature C# Notes

String String greeting = “Hello WP!”;

Int length = greeting.Length;

Comparison String color = “pink”;

If (color == “red”)

System.Console.WriteLine(“Matchin

g colors!”);

string name = “Joe”;

if (string.compare(name, “Jack”)

> 0)

System.Console.WriteLine(name +

“ comes later”);

Strings are compared using ==.

They are compared

lexicographically using compare.

Concatenation System.Console.WriteLine

(greeting + " You rock!") Strings can be concatenated with

the ‘+’ operator. (This is called

operator overloading.)

Splitting string rainbow = "Violet, Indigo,

Blue, Green, Yellow, Orange,

Red";

string[] rainbowColors =

rainbos.Split(',');

foreach (string color in

rainbowColors)

System.Console.WriteLine

(color);

Page 58: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 58

Arrays

Arrays in C# are almost like arrays in Java. Both support jagged arrays, i.e., arrays of arrays. In

addition, C# also supports multi-dimensional arrays which are rectangular.

Java Feature C# Notes

Arrays of primitive

types such as int,

float

int[] table;

table = new int[3];

string[] names = new string[3]

{"Peter", "Paul", "Mary"};

Array size is not a part of the

array declaration.

Arrays can be explicitly

initialized.

Multi-dim arrays of

primitive types

Int[,] mAray;

Int[][] jaggedArray;

string[][] singers = {new string[]

{"Peter", "Paul", "Mary"}, new

string[]{“Paul”,“Art”}};

C# supports jagged arrays,

or arrays of arrays, and they

need not be rectangular.

Note: Arrays of strings, i.e.

objects, work the same way.

Mutable array of

objects

List<string> colors = new

List<string>; //list of strings

Colors.Add(“Red”);

Colors.Add(“Green”);

Colors.Insert(1,”White”);

String myColor = Colors[0]; //”Red”

Colors[colors.IndexOf(“Red”)] =

“Pink”; // replace Red with pink

You can use Lists as a

replacement for mutable

arrays.

You may also use ArrayLists.

Dictionaries

C# provides a generic dictionary class that is similar to the HashMap functionality in Java. The

generic dictionary class allows you to add, lookup, and remove objects from the dictionary.

Since the dictionary class uses Generics, it also utilizes strong typing.

Page 59: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 59

Java C# Notes

HashMap Dictionary<string, int> d = new

Dictionary<string, int>();

d.Add("Honda", 124);

d.Add("Toyota", 95);

d.Add("Ford", 135);

// See if Dictionary contains

string

if (d.ContainsKey("Ford")) //

True

{

int v = d["Ford"];

Console.WriteLine(v);

}

Page 60: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 60

Generics

Both Java and C# support generics. Generics introduce the notion of type parameters that

make it possible to design classes that are type safe, even though the actual type is deferred

till the object’s instantiation. Java implements generics using erasure, i.e. type information is

used only at compile time and not at runtime. This introduces certain limitations in Java

generics.

C#, on the other hand, implements generics using explicit support in .NET CLR. The

generated intermediate language (IL) supports the notion of generics.

The following code shows how to define a generic stack in C#:

Stack<int> intStack = new Stack<int>(); // intStack is a

stack of int

intStack.Push(1); // OK

intStack.Push(2); // OK

int number = intStack.Pop(); // this is a

type safe assignment

Stack<string> strStack = new Stack<string>(); //the type of

strStack is different from type of intStack

strStack.Push("green"); // OK

strStack.Push(23);

The Stack<T> uses T as a type parameter, thus allowing you to instantiate a stack of any

type. For example: Stack<int> or Stack<string>. You can use them in a type safe manner.

Page 61: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 61

Operator Overloading

Operator overloading is not supported in Java. In C#, Operator overloading allows you to

define the implementation of operators for user-defined classes. Use of operators can often

improve the readability of the program. Consider the following example of a complex

number struct. Operator Overloading allows you to define a + operation that uses a natural

syntax.

public struct Complex

{

public int real;

public int imaginary;

// Declare which operator to overload (+), define how it

is computed

public static Complex operator +(Complex c1, Complex c2)

{

return new Complex(c1.real + c2.real, c1.imaginary +

c2.imaginary);

}

Complex c1 = new Complex(3.0, 4.0);

Complex c2 = new Complex(4.0, 5.0);

Complex cSum = c1 + c2;

Page 62: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 62

Delegates

There is no concept of delegates in Java. The functionality of delegates in C# is like the

function pointers in C. However, unlike function pointers, C# delegates are strongly typed

and as a result improve program safety and readability.

In this design pattern, a class delegates another method with the same signature as the

delegate even though the actual method is not known at compile time.

using System; namespace DelegateExample { public class ConsoleLogger { public static void WriteString(string s) { Console.WriteLine("Writing to console log: {0}", s); } } public class FileLogger { public static void LogString(string s)

{ // File.WriteAllText(@"logfile.txt","Logging to file log: "+ s); } } public class DelegatesTest { public delegate void StringDelegate(string s); //Signature for the delegates.

// All StringDelegates must have same signature public static void Main() { StringDelegate Writer, Logger; // define twp StringDelegate objects

// Create delegates with appropriate methods Writer = new StringDelegate(ConsoleLogger.WriteString); Logger = new StringDelegate(FileLogger.LogString); Writer("Warning message 1\n"); // Send to Console Writer delegate method Logger("Warning message 2\n"); // Send to File Logger delegate method StringDelegate MultiLogger; // to act as the multicast delegate MultiLogger = Writer + Logger; // combine the two delegates, MultiLogger("Warning message 3"); // This should get sent to both delegates } } }

In the above code example, StringDelegate is defined as a function that takes a string as a

parameter and returns void. Writer, logger, and multiLogger are constructed by passing

methods that have the same signature as the StringDelegate declaration.

Calling Writer invokes the writeString method of ConsoleLogger to print the message to the

console. Calling Logger invokes the logString method of FileLogger to log the message to

the file. Delegates achieve indirection while providing type safety. Delegates may be

concatenated as shown by MultiLogger, which logs the message to both loggers.

Such a design pattern can only be implemented using reflection in Java. However it does not

provide the type safety that delegates provide.

Events

Page 63: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 63

Both Java and C# support event handling though there are significant differences. There is

no general mechanism for events in Java though specific design patterns and classes may be

used for events.

Events are useful in the pub-sub (publisher and subscriber) design pattern and are useful for

asynchronous programming. C# events are implemented using delegates. In C#, the event is

used to automatically specify that a field within a subscriber is a delegate that will be used as

a callback during an event-driven situation. An object can publish an event that a subscriber

can subscribe to. When the publisher raises an event, all subscribers are notified without

publisher knowing who the listeners are.

using System;

namespace EventExample

{

public class ConsoleLogger

{

public void WriteString(string s)

{

Console.WriteLine("Writing to console log: {0}", s);

}

}

public class FileLogger

{

public void LogString(string s)

{

Console.WriteLine("Logging to file log: {0}", s);

}

}

public class DelegatesTest

{

public delegate void LogEventHandler(string s); // definition of

the delegate.

public static event LogEventHandler logEvent; // the signature

of the event.

public static void Main()

{

ConsoleLogger cl = new ConsoleLogger(); // create the

first subscriber

FileLogger fl = new FileLogger(); // the second

subscribe

logEvent += new LogEventHandler(cl.WriteString); // subscribe the

event and hook up the

logEvent += new LogEventHandler(fl.LogString); // event handlers

logEvent("A new event"); // raise event

which will invoke handlers

Console.ReadLine();

}

}

}

Page 64: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 64

Comparing API Documentation Tools

JDK contains an API documentation generation tool called Javadoc. Javadoc automatically

generates documentation from the comments that are added to the java source code file.

There are a variety of document generation tools that are available for .NET, namely,

NDoc, Sandcastle, Doxygen, Doc-O-Matic.

. In comparison to Javadoc which produces HTML documentation, NDoc can generate

documentation in several formats, including:

MSDN style HTML Help format (.chm)

Visual Studio .NET Help format (HTML Help 2)

MSDN online style web pages

Unlike Java doc comments which are written in HTML, C# doc comments use XML as shown

below.

public class MyClass() {

///<summary>

///

///</summary>

///<param name=”s”></param>

Public MyClass(string s) {}

}

Implicitly Typed Variables

There are no implicitly typed variables in Java; all variables must be declared explicitly.

However, for C# local variables can be given an inferred "type" instead of an explicit type.

The “var” keyword instructs the compiler to infer the type of the variable from the expression

on the right side of the initialization statement. These are still strongly typed variables but

they are late bound. There is no counterpart to this in Java.

// i is compiled as an int

var i = 5;

// a is compiled as int[]

var a = new[] { 0, 1, 2 };

// londonCustomers is compiled as IEnumerable<Customer>

// or perhaps IQueryable<Customer>

var londonCustomers =

from c in customers

where c.City == "London"

select c;

Page 65: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 65

// If a query produces a sequence of anonymous types,

// then use var in the foreach statement to access the properties.

var upperLowerWords =

from w in words

select new { Upper = w.ToUpper(), Lower = w.ToLower() };

// Execute the query

foreach (var ul in upperLowerWords)

{

Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower);

}

This is particularly useful for LINQ query expressions as shown above where the type of the

result is based on the query.

Async Programming using Async and Await

In Visual Studio 2012, C# introduced async programming with compiler and runtime support,

which makes it easy to write code that does asynchronous processing. Asynchronism is

essential for operations that would otherwise be blocking such as accessing remote data

from the web. Using asynchronous programming, activities that do not depend on remote

data can continue, thereby improving response time of such operations. There is no

counterpart to this in Java.

Asynchronous processing in C# uses the keywords “async” and “await”.

A method can call other asynchronous methods and can use await to designate a

suspension point beyond which it cannot continue until the awaited asynchronous process is

complete. Meanwhile, control returns to the caller of the async method. This async method

can itself be waited on by methods that call it.

The await operator for a method call signifies a suspension point where the calling method

waits for the called asynchronous method to return the results.

An async method typically returns a Task or Task<TResult> which represents an ongoing

work in progress. The Task encapsulates the state of the asynchronous process, and

eventually, either the final result or the exception that was raised.

async Task WriteLogAsync(string filename, string message) { // Get a reference to the Local Folder Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; // Create the file in the local folder, or if it already exists, just open it Windows.Storage.StorageFile storageFile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists); Stream writeStream = await storageFile.OpenStreamForWriteAsync(); using (StreamWriter writer = new StreamWriter(writeStream)) { await writer.WriteAsync(message); }

}

Page 66: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 4: An Introduction to C# programming for Java developers 66

private async void btnAdd_Click(object sender, RoutedEventArgs e) { … Task writeLog = WriteLogAsync("logfile.txt", "btnAdd clicked"); DoLocalWork(); await writeLog; }

In the above example, WriteLogAsync is an asynchronous method. It creates a file in the

LocalFolder and writes to it asynchronously. Notice the await keyword before

writer.WriteAsync(). On the other hand, btnAdd_Click method calls WriteToLogAsync

method asynchronously and while the writing is getting completed, continues to do some

local work (captured in the DoLocalWork method). Once the local work is complete, it awaits

the return from WriteLogAsync method.

Summary

In this chapter, we looked at C# programming from the perspective of a Java developer. Java

and C# have many similarities and yet have some subtle differences. The knowledge of Java

and object oriented programming will help you master C# quickly.

Related Resources

To go deeper into C# and Java, visit:

C# and Java: Comparing Programming Languages

http://www.25hoursaday.com/CsharpVsJava.html

To go deeper into NDocs, visit:

http://ndoc.sourceforge.net/

http://shfb.codeplex.com/ – Sandcastle Summary

Page 67: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 5: Application Lifecycle Differences Between Windows Phone and Android 67

Chapter 5: Application Lifecycle Differences

Between Windows Phone and Android

In this chapter, we look at the application lifecycle of the Windows Phone and compare it

with that of Android. We will examine the various application states needed to support the

navigation model, and what the developer needs to do to support those application states

and the transitions between them.

Android and Windows Phone Application Lifecycle

Both Windows Phone 8 and Android have a limit of one application running in the

foreground. They both support multitasking which allows other applications to run in the

background. They both provide an illusion that applications are always running and allow

application to be restarted “instantaneously.”

Android Application Lifecycle

When the user clicks the “home” button or launches another application, instead of

terminating the running application, Android moves the foreground activity to the

background. The background application remains alive in the phone memory and continues

to execute. It can do what it needs to even though it does not have focus. For example, if it

has a thread running in the background to download data, it can continue to do so.If the

user returns to that activity, the activity is resumed or restarted. However, if there is memory

pressure, Android destroys the activity and subsequently the activity must be restarted.

In addition, Android applications may include a service, a component that performs long

running operations such as background music or data transfer. A service does not present

user interface. A service may also be terminated in low memory situations.

Windows Phone Application Lifecycle

Windows Phone too supports multitasking and provides very similar features as Android. It

supports fast application switching and background processing. When the user presses the

start button while using an application, that application is deactivated and moved to

background and kept intact in memory, in a state referred to as dormant. When the user

navigates using the back button on the phone, this application is reactivated. Since the

application was in memory, the reactivation is instantaneous. As the user invokes other apps,

the Windows Phone OS reclaims memory by terminating dormant apps.

Consider that the user is composing a blog post, using the WordPress application, and then

hits the start button to reach the Start screen, at which time the WordPress application is

made dormant in which the application state is preserved in memory. The user then opens

Page 68: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 5: Application Lifecycle Differences Between Windows Phone and Android 68

up the Facebook application. At this time, the Facebook application is launched. The user can

hit the back button while in the Facebook application, to first reach the Windows Phone Start

screen, and hit the back button again to go back to the WordPress application. The

WordPress application would open with the compose screen, exactly how and where the user

left it. The back button on Windows Phone behaves like browser back button. It not only

allows the user to move through application pages but also through apps.

In addition to using back button, user can switch to another application in a number of ways.

This includes fast switching to a dormant app by long pressing the back button, launching

another app from the start button, or clicking on a toast or tile.

The following table describes the user events and compares the corresponding behavior in

Android and Windows Phone.

User Action or Event Android Behavior Windows Phone Behavior

An incoming phone

call or SMS that user

answers

Running application is moved to

the background, current activity

is paused but the application is

still in memory

Running application is

deactivated and made

dormant

User presses the Home

button on the phone

Running application is moved to

the background but application is

still in memory and attached to

window manager. Any

background thread such as

downloading data will continue

to run.

Running application is

deactivated and made

dormant

User starts another

application from the

multitasking menu

Backround app is moved to

foreground, If the activity was

destroyed, it must be recreated

and previous state restored.

Running application is

deactivated and made

dormant. Background

application is moved to

foreground and reactivated

in its original state.

User navigates

between applications

Backround app is moved to

foreground, If the activity was

Dormant application is made

active again with its state

intact. If the app was

Page 69: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 5: Application Lifecycle Differences Between Windows Phone and Android 69

using the Back button

on the phone

destroyed, it must be recreated

and previous state restored..

tombstoned it is activated

and the app needs to

recreate its state

User launches

application by clicking

on a toast

Running application is moved to

the background, current activity

is paused but the application is

still in memory.

Running application is

deactivated and then put

into dormant state

Programming for application States and navigation

As the application makes state transitions in response to various actions or events, Android

makes callbacks on the application. In response, the application has to save appropriate state

or load it depending on the event. Similarly, Windows Phone OS raises different events in

response to which the app has to save or load app state.

Android support for multitasking

In order to support Android multitasking, Android application developers have certain

responsibilities. When the application is moved to the background, they need to save the

application state, which must then restored if the activity is recreated. If the activity is

resumed or restarted, the state is intact and there is no need to recreate the state.

In particular, the application moving to background will receive a callback, onPause(), at

which time the application should commit unsaved changes to persistent state and reduce

any CPU intensive tasks such as animations. This processing should be quick since another

activity is not started till onPause of the previous activity completes. When the activity is no

longer visible to the user, onStop() is called at which time, the activity should stop all UI

operations. When the system destroys the activity to reclaim memory, onDestroy() is called.

When activity is created for the first time, the activity should restore previously frozen state.

When the activity becomes visible to the user, system called onStart() method whereas when

it comes to foreground, the system calls onResume().

Windows Phone Application LifeCycle

Windows Phone Application State Transition Diagram

The following state diagram shows the various states and explains what the developer should

do in response to various events.

Page 70: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 5: Application Lifecycle Differences Between Windows Phone and Android 70

See App activation and deactivation for Windows Phone for details of application states and

transitions.

Comparing Life-cycle Methods

We can compare the Android lifecycle method with Windows Phone 8’s state-change events

and Page methods. Note that these mappings are approximate since Android provides

different ways to save and restore state.

Android Methods Windows Phone

Application Events

Windows Phone Page

Methods

onCreate() Application_Launching

Page 71: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 5: Application Lifecycle Differences Between Windows Phone and Android 71

onStart(),

onResume() NavigatedTo

onPause(),onSaveInstanceSta

te

NavigatedFrom

onStop(),

onSaveInstanceState

Application_Deactivated

onRestart() Application_Activated

onDestroy() Application_Closing

In Android, you can use the onCreate() method to initialize the activity, to setup or recreate

the activity state. In Windows Phone 8, application initialization is performed in response to

application_launching event. Windows Phone application should also load any persistent

state, state that should be preserved between instances of the application, at that time.

In Android, if a user launches a new application, the application in the foreground receives

onPause and onStop callbacks. You need to commit the application data to the persistent

storage or database as part of onPause (or during onSaveInstanceState). In Windows Phone

8, if a user launches a new application, the current foreground application is deactivated. At

the time of deactivation, the application receives the Application_Deactivated event and you

need to save the application’s state in its event handler. You have 10 seconds to complete the

processing.

When application is resume, Android makes onRestart and onResume callback methods. If

the activity was in background, there is no need to restore state, . However, if the activity was

destroyed, persistent state must be restored. In Windows Phone 8, when a user starts a

dormant or tombstoned application, the Application_activated event is raised. If the

application is reactivated from a dormant state as indicated by

IsApplicationInstancePreserved property, the application need not do anything. Otherwise,

you should restore the application state from the State object where the state is saved during

deactivation.

In Android, when one Activity replaces another, the current Activity receives the onPause and

onStop callbacks. This behavior is similar to the Page to Page navigation in Windows Phone

8. While moving from one page to another, the current page receives the NavigatedFrom()

event and the new page receives the NavigatedTo() event.

Page 72: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 5: Application Lifecycle Differences Between Windows Phone and Android 72

Windows Phone 8 Application LifeCycle and

Tombstoning Example

Let us look at a simple example that illustrates the Windows Phone 8 state transitions and

tombstoning. This is a one page shopping list application where the user can add items to

the list. When the user leaves the application, the shopping list is saved automatically.

Saving the Application State

On Android, you may be saving application persistent state in a number of different ways

such as SharedPreferences, using device internal storage or SQLite database..

To save the persistent state of the application on Windows Phone 8, i.e., the shopping list, we

are going to use isolatedStorage. isolatedStorage is a sandboxed storage that is accessible

only to that application. It ensures that one application cannot affect another application. To

save the state, we first get the isolatedStore for the application. We then create a file in

isolatedStorage, in which to save the persistent state.

To save the shopping list, we first serialize the list and then save it to the file.

public static void SaveShoppingList(ShoppingListInfo shoppingListInfo, string fileName)

{

//Get the isolatedStore for this application

using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())

{

// create a new file

using (IsolatedStorageFileStream fs = isf.CreateFile(fileName))

{

//and serialize data and save it

XmlSerializer xmlSer = new XmlSerializer(typeof(ShoppingListInfo));

xmlSer.Serialize(fs, shoppingListInfo);

}

}

}

In order to save transient state, Windows Phone 8 provides another class called

PhoneApplicationService.State. We will see the use of this object below.

Application Launching

When the application is launched from the Start screen, the application received the

Application_Launching event. This is equivalent to the activity onCreate, onStart and

onResume methods being called.

To improve the application startup time, application should do as little work as possible and it

should avoid loading application state from isolated storage or from remote servers.

In our application, we do no work and leave it to the appropriate page.

// Code to execute when the application is launching (eg, from Start) // This code will not execute when the application is reactivated private void Application_Launching(object sender, LaunchingEventArgs e)

Page 73: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 5: Application Lifecycle Differences Between Windows Phone and Android 73

{

}

Application Activation

When the user uses back button to navigate into the application, the application receives the

Application_Activated event. Like the Launching event, doing resource intensive

work in response to this event will delay the app from resuming. Just like

Application_Launching, do as little work as possible.

// Code to execute when the application is activated (brought to foreground) // This code will not execute when the application is first launched private void Application_Activated(object sender, ActivatedEventArgs e) { if (e.IsApplicationInstancePreserved) { return; } // Check to see if the key for the application state data is in the State dictionary. if (PhoneApplicationService.Current.State.ContainsKey("ApplicationDataObject")) { // If it exists, assign the data to the application member variable. ApplicationDataObject = PhoneApplicationService.Current.State["ApplicationDataObject"] as ShoppingListInfo; }

}

The IsApplicationInstancePreserved property of ActivatedEventArgs lets your app know if the

app is returning from a dormant state or if it was tombstoned. Memory of the dormant

application is preserved and as a result, we need not do anything.

Next we check if the application state is available in the state dictionary and load it in the

AppliccationDataObject, a serialized string of the application state.

Page 74: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 5: Application Lifecycle Differences Between Windows Phone and Android 74

Application Deactivation

Let us examine what happens when the user navigates forward from the application.e.g. by

hitting the start button while running the application. When the user hits the home button

on Android the onResume of the activity is called. On Windows Phone 8, the application will

receive the Application_Deactivated event. The application would be made

dormant and moreover, it may also be tombstoned. As a result, we save the application

persistent state both in the application state dictionary as well as in isolateStorage. If this

application is reactivated, we will restore either from the state dictionary or from the

isolatedStorage.

// Code to execute when the application is deactivated (sent to background) // This code will not execute when the application is closing private void Application_Deactivated(object sender, DeactivatedEventArgs e) { // If there is data in the application member variable... if (ApplicationDataObject != null) { // Store it in the State dictionary. PhoneApplicationService.Current.State["ApplicationDataObject"] = ApplicationDataObject; // Also store it in isolated storage, in case the application is never reactivated. SaveShoppingList(ApplicationDataObject, "myDataFile.txt"); }

}

Application Closing

Page 75: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 5: Application Lifecycle Differences Between Windows Phone and Android 75

This event is raised when the user uses the back button to navigate backward past the first

page, after which the app is terminated. The user must re-launch the application to use it. As

a result, you should save any persistent data but not the transient data.

// Code to execute when the application is closing (eg, user hit Back) // This code will not execute when the application is deactivated private void Application_Closing(object sender, ClosingEventArgs e) { if (ApplicationDataObject != null) { // Also store it in isolated storage, so that we can restore the shopping list SaveShoppingList(ApplicationDataObject, "myDataFile.txt"); }

}

This event is comparable to the onDestroy method of the activity.

Page Operations

In addition to the above application events, each page needs to override certain methods to

implement Fast Application Switching.

OnNavigatedFrom

OnNavigatedFrom method is called whenever the user navigates away from the page, i.e.

forward or back. In our method implementation, we determine if the user navigated forward,

we save the transient state of the page. This transient state is stored in the application state

dictionary. And we save the rest of the page state in the applications data object which will

be saved to isolatedStorage if the user leaves the application. The transient state is used if the

navigates back to the same page using back button.

protected override void OnNavigatedFrom(NavigationEventArgs e) { if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back) { PhoneApplicationService.Current.State["ShoppingListItem"] = txtItem.Text; } (Application.Current as ShoppingList.App).ApplicationDataObject.ItemsList = shoppingItems;

}

OnNavigatedTo

OnNavigatedTo method is called whenever the user navigates to a page. In this method, we

check _isNewPageInstance to see if this is a new instance of the page or if the user is

navigating to a page that is already in memory. If it is a new page, and we have restored

application state, we load the page UI from the application state. Otherwise, we load the

Page 76: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 5: Application Lifecycle Differences Between Windows Phone and Android 76

page by using a method called GetDataAsync. This method loads the application state

asynchronously so that the page is responsive to user as we load it.

Once we have loaded the persistent state of the page, we load the transient data if any data

is stored in the application state. If any transient state is available in the state dictionary, we

load it and populate the page controls.

protected override void OnNavigatedTo(NavigationEventArgs e) { // If _isNewPageInstance is true, the page constructor has been called, so // state may need to be restored. if (_isNewPageInstance) { // If the application member variable is not empty, // set the page's data object from the application member variable. if ((Application.Current as ShoppingList.App).ApplicationDataObject != null) { UpdateApplicationDataUI(); } else { // Otherwise, call the method that loads data. (Application.Current as ShoppingList.App).GetDataAsync(); } } if (PhoneApplicationService.Current.State.ContainsKey("ShoppingListItem")) { // If it exists, assign the data to the application member variable. txtItem.Text = PhoneApplicationService.Current.State["ShoppingListItem"] as string; } // Set _isNewPageInstance to false. If the user navigates back to this page // and it has remained in memory, this value will continue to be false. _isNewPageInstance = false;

}

Page 77: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 5: Application Lifecycle Differences Between Windows Phone and Android 77

Summary

In this chapter we had a look at the different states of application life cycle in Android and

Windows Phone. We also compared methods for saving application state data in Android

and Windows Phone.

Related Resources

To learn more about the execution model for Windows Phone, visit:

Launching, resuming, and multitasking for Windows Phone

Implementing the Model-View-ViewModel pattern in a Windows Phone app

App structure and navigation models for Windows Phone

App manifest file for Windows Phone

Asynchronous Programming For Windows Phone 8

Quickstart: Working with settings in Windows Phone

Page 78: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 6: Storage on Windows Phone 78

Chapter 6: Storage on Windows Phone

Windows Phone features a comprehensive system of managing data for applications on the

phone. This section compares the data management features of Windows Phone 8 and

Android.

Let us look at how Android and Windows Phone store data locally:

1. Application settings

2. Files and folders

3. Database

Purpose Android Windows Phone

Application Settings SharedPreferences IsolatedStorageSettings

Files and Folders File in Internal storage IsolatedStorage, StorageFolder

Relational Database SQLite *2 local database of SQLite

Windows phone uses IsolatedStorage to store data supported by the above abstractions. We

will look at each of the Windows Phone features in detail below.

Windows Phone Isolated Storage

Local folder is the root folder of your app’s data store. This store, also called IsolatedStorage,

provides application specific storage. Local folder is isolated from other apps and as a result

data belonging to an application can only be accessed by that application. Local folder or

IsolatedStorage can be compared with files stored in Android’s internal storage which are

also private to each application. Android allows an application to share its internal data with

other applications using an abstraction called content provider. This feature is not available

on Windows Phone.

The following diagram shows the folder structure for application storage in Windows Phone:

2 While no database is preinstalled on Windows Phone, app developers can use bundle and use SQLite as part

of their app.

Page 79: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 6: Storage on Windows Phone 79

Page 80: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 6: Storage on Windows Phone 80

The following table compares the Data Storage Methods in Windows Phone and Android:

Storage Features Windows Phone Android

Storage

Store application data in local

folder

Store the application data in the

phone’s internal storage

Isolation Local folder isolates files

belonging to an application from

other applications. Applications

cannot access files belonging to

other applications..

Files stored in internal storage

area are private to each

application. Other applications

cannot access that data.

Sandbox Windows Phone restricts all Input

and Output (I/O) operations to

local folder and installation

folder3 and prevents the I/O

operations from accessing

operating system files. This

Windows Phone feature prevents

unauthorized access and data

corruption.

Android prevents unauthorized

data access by restricting I/O

operations to the same

application. However, you have

an option to make app data

public by writing to external

storage.

To learn more about data storage on Windows Phone, visit:

Data for Windows Phone

3 Installation folder is a read-only folder.

Page 81: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 6: Storage on Windows Phone 81

In both operating systems, the application developer has to manage the data that gets

stored during application installation or reinstallation. The developer has to modify and

migrate data if the application is updated; the OS does not manage data for the application.

Both operating systems delete the application files and folders in the private store when the

application is uninstalled.

Files and Folders

Android applications can create and use files and folders within the internal storage that is

private to an application. Similarly, Windows Phone 8 applications can create files and folders

using StorageFolder. It uses use StorageFolder and StorageFile classes for folder and file

operations. StreamReader and StreamWriter classes may be used for reading and writing to

files created in local folder.

The following table shows how various file operations are accomplished on the two

platforms.

Android Windows Phone

Access application

specific storage

Windows.Storage.ApplicationData.Current.LocalFolder

Create File or open

File

Context.openFileInput,

Context.openFileOutput

StorageFolder.CreateFileAsync StorageFolder.OpenStreamForReadAsync StorageFolder.OpenStreamForWriteAsync

File IO FileOutputStream.write

FileInputStream.read

StreamWriter.Write StreamReader.Read

Get or Create

Directory

Context.getDir StorageFolder.CreateFolderAsync StorageFolder.GetFolderAsync

Using files from local folder is similar to using regular files. The only difference is that you

have to first access application specific local folder. Here is an example of how you can use

local folder to write to files. In the first line, we retrieve local folder for the calling application.

We create a file in that storage and use a StreamWriter to write to the file. This may be

compared to opening a private file in Android using MODE_PRIVATE mode. Note that most

file and folder operations are asynchronous. The methods ReadFile and WriteToFile are also

marked using async keyword. These methods return a Task which represents an async

operation.

Page 82: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 6: Storage on Windows Phone 82

private async Task WriteToFile() { // Get the local folder. StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder; // Create a new folder name DataFolder. var dataFolder = await local.CreateFolderAsync("DataFolder", CreationCollisionOption.OpenIfExists); StorageFile newFile = await dataFolder.CreateFileAsync("logfile.txt", CreationCollisionOption.ReplaceExisting); using (StreamWriter writer = new StreamWriter(await newFile.OpenStreamForWriteAsync())) { await writer.WriteLineAsync("new log"); writer.Close(); } // Write the data from the textbox.

}

The following code snippet that shows how to read data from files in local folder. The

structure of this code is similar to the above code.

private async Task ReadFile() { // Get the local folder. StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder; if (local != null) { // Get the DataFolder folder. var dataFolder = await local.GetFolderAsync("DataFolder"); // Read the data. using (StreamReader streamReader = new StreamReader(await dataFolder.OpenStreamForReadAsync("logfile.txt"))) { string text = streamReader.ReadToEnd(); } }

}

Application Settings

Most applications need to store and use application settings, options, and user data, such as

user language preference, or last used time stamp.

In Android, you can store application settings and data by using the SharedPreferences class.

The SharedPreferences class stores the key value pair of primitive data types. On Windows

Phone 8, you can save such data using the IsolatedStorageSettings class. This is the most

convenient way to store the data. The application can store its settings by using the following

code:

Page 83: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 6: Storage on Windows Phone 83

The value object is serialized to disk when you call the Save() method. You can read the data

back by using the following code:

List<string> mydata =

(List<string>)IsolatedStorageSettings.ApplicationSettings["some_property"];

IsolateStorageSettings lets you save any serializable object to the settings store.

Managing the IsolatedStorage Space

While Windows Phone 8 OS does not impose a quota on the size of the application’s

IsolatedStorage, each application should make efficient use of available storage space. It is

important to use available space carefully since it is a shared resource. Saving minimal

amount of data can also speed up the launch of the application.

The techniques used in managing application state are the same in both platforms. An

Android application and a Windows Phone 8 application should save minimal amount of

data to application specific storage.

Sharing Data Between Applications

Android data sharing

On Android, you can save files to a shared external storage in an Android compatible device.

The shared external storage can also include the internal removable storage. Android allows

you to access and modify the files that are saved to the external storage by connecting to a

computer.

In Android, ContentProviders make data accessible to other applications. There are a number

of content providers for common data types such as audio, video, calendar and contacts.

While Android does not provide shared data storage on internal storage, ContentProviders is

another way to share data across applications.

Windows Phone data sharing

Unlike Android, Windows Phone 8 does not support access to external storage. By limiting

the use of external storage, Windows Phone 8 provides the application with a safe-sandbox,

and prevents unpredictable behavior caused by missing external storage or corruption of

data by other applications.

IsolatedStorageSettings.ApplicationSettings.Add(“some_property”, value);

IsolatedStorageSettings.ApplicationSettings.Save();

Page 84: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 6: Storage on Windows Phone 84

Content producers

Windows Phone applications cannot directly access information from other information

stores, such as the contacts list or data managed by other applications.

Windows Phone 8 uses a mechanism called Launchers and Choosers which allow one

application to invoke other applications to access data managed by the phone or by other

applications, such as contacts and photos. This avoids the risk of unsafe data access and data

corruption.

Launchers and Choosers

Launchers

A Launcher allows you to programmatically invoke another built-in application to accomplish

some task. If your application needs to make a phone call, you can use launchers API to

invoke the PhoneCallTask with a phone number as a parameter. Windows Phone 8 OS

invokes the Phone application with the supplied number and makes the requested call.

When the invoked application completes, the invoking application is reactivated. The called

application does not return any data resulting from the user’s actions.

Choosers

A Chooser is similar to a launcher except that a Chooser returns data back to the calling

application.

For example, consider that in your app you want the user to select a photo from the photo

gallery. Instead of allowing your app to access photo gallery, Windows Phone allows your

app to invoke the built-in PhotoChooserTask and select a photo. Then the Chooser returns

that photo to your app. .

Summary

In this chapter we compared data storage and access mechanisms for Windows Phone and

Android. We also looked at the file and folder storage APIs in Windows Phone and Android

as well as for application settings. We looked at launchers and choosers from Windows

Phone 8 which allow one app to invoke another without allowing direct data sharing among

apps.

Related Resources

To learn more, visit:

Launchers and Choosers for Windows Phone

Page 85: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 7: XML Support in Windows Phone and Android 85

Chapter 7: XML Support in Windows Phone

and Android

This chapter discusses the XML parsing methods in Windows Phone 8 and compares them

with the XML parsing methods in Android.

XML Support in Android

With its use of Java, the Android SDK includes rich support for handling XML. In particular,

Android supports Java's Simple API for XML (SAX) and the Document Object Model (DOM)

parser. In addition, Android support a pull parser that works similar to Java StAX. Windows

Phone 8 supports an efficient DOM

XML Support in Windows Phone

While the SAXParser and the DOMParser are not available in Windows Phone 8, Windows

Phone 8 provides a comparable, if not richer, mechanism for handling XML using two

separate mechanisms, namely, XMLReader and LINQ to XML. XMLReader is similar to

Android pull parser i.e. it reads the XML document node one at a time and parses it. Both

XMLReader and LINQ to XML provide read-only functionality; XML cannot be inserted or

deleted. Unlike DOM parser, iXMLReader does not load the entire document at once. Unlike

SAXParser, XMLReader is not event driven.

XML Parsing Using XMLReader

XMLReader provides a forward-only and read-only access to a stream of XML data.

The following C# snippet illustrates how to use XmlReader and query the XML data stream to

determine the current node type. It also shows the use of XMLWriter to write an XML

document.

StringBuilder output = new StringBuilder(); String xmlString = @"<?xml version='1.0'?> <!-- This is a sample XML document --> <Items> <Item >test with a child element <more/> stuff</Item> </Items>"; // Create an XmlReader // Uses StringReader which reads from string using (XmlReader reader = XmlReader.Create(new StringReader(xmlString))) { // XmlWriterSettings specifis options on XmlWriter, i.e. Indent = true XmlWriterSettings ws = new XmlWriterSettings(); ws.Indent = true;

Page 86: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 7: XML Support in Windows Phone and Android 86

// XmlWriter is used to produce XML document using (XmlWriter writer = XmlWriter.Create(output, ws)) { // Parse the file and display each node. // In Android, following iteration is done in handler //implementation while using SAXParser while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: // This is similar to XmlPullParser.START_TAG writer.WriteStartElement(reader.Name); break; case XmlNodeType.Text: // Similar to XmlPullParser.TEXT writer.WriteString(reader.Value); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: writer.WriteProcessingInstruction(reader.Name, reader.Value); break; case XmlNodeType.Comment: writer.WriteComment(reader.Value); break; case XmlNodeType.EndElement: // This is similar to XmlPullParser.END_TAG writer.WriteFullEndElement(); break; case XmlNodeType.Attribute: // In Android, attribute would be read using getAttribute break; default: break; } } } }

Page 87: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 7: XML Support in Windows Phone and Android 87

As you can see above, handling XML in Windows Phone has many similarities with XMLPullPa

rser in Android.

Handling XML using LINQ to XML

Windows Phone provides another technology called LINQ to XML that makes it very easy to

handle XML. It provides a versatile in-memory XML programming API. With LINQ to XML,

you can read, write and manipulate XML. It helps you to:

Read and parse XML from memory, a local file or from a communication channel

Manipulate an XML document by inserting or deleting XML elements

Create an XML document or Save XML to a file or XmlWriter

Like the Document Class of the DOM parser, the XDocument Class in Windows Phone 8

represents an in-memory representation of the XML document.

Create an XML Document

Let us look at an example that shows how to create an XML document using LINQ to XML.

The following code creates a document then adds a comment and element to the document.

The sample code also creates another document using the results of a query. The XElement

class, used in the sample code, is similar to the Element class in Android.

In the following example, we use LINQ to query an XML Document to extract all nodes

whose value starts with “C” and construct another document.

String xmlString1 = @"<Items> <Item>Beer</Item> <Item>Chips</Item> <Item>Salsa</Item> <Item>Cheesecake</Item> </Items>"; XDocument srcTree = XDocument.Parse(xmlString1); XDocument doc = new XDocument( new XComment("This is a list of items"), new XElement("ItemsWithC", // The following query is similar to a SQL select statememt // from all children of “Items”, select those that start with C from el in srcTree.Element("Items").Elements() where ((string)el).StartsWith("C") select el ) ); // In Android to parse the XML tags using DOM, the equivalent code is // root.getElementsByTagName(ITEM); output1.Append(doc + Environment.NewLine);

Page 88: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 7: XML Support in Windows Phone and Android 88

We use the following LINQ query to all children of “Items” node to extract those that start

with “C”.

from el in srcTree.Element("Items").Elements() where ((string)el).StartsWith("C") select el

You can compare this functionality with the DOMParser in Android where you can build an

XML document from bottom-up. You create the document and add XML elements to the

document.

Functional Construction

LINQ to XML supports functional construction to construct XML using a single statement.

Functional construction uses the XElement and XAttribute constructors to build an XML tree.

For example, consider the following XML Data:

<contacts>

<contact>

<name>Patrick Hines</name>

<phone type="home">206-555-0144</phone>

<phone type="work">425-555-0145</phone>

<address>

<street1>123 Main St</street1>

<city>Mercer Island</city>

<state>WA</state>

<postal>68042</postal>

</address>

<netWorth>10</netWorth>

</contact>

<contact>

<name>Gretchen Rivas</name>

</contact>

</contacts>

The following example constructs an XML tree by using LINQ to XML functional construction:

XElement contacts =

new XElement("Contacts",

new XElement("Contact",

new XElement("Name", "Patrick Hines"),

new XElement("Phone", "206-555-0144",

new XAttribute("Type", "Home")),

new XElement("phone", "425-555-0145",

new XAttribute("Type", "Work")),

Page 89: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 7: XML Support in Windows Phone and Android 89

new XElement("Address",

new XElement("Street1", "123 Main St"),

new XElement("City", "Mercer Island"),

new XElement("State", "WA"),

new XElement("Postal", "68042")

)

)

);

Traversing XML This section demonstrates the use of LINQ to XML for navigating an XML tree.

XDocument contacts = XDocument.Load("contacts.xml");

That is all it takes to load XML in a Windows Phone 8 application. Once loaded, you can

query the XML document to not only parse it, but select appropriate nodes from it.

Let us see what it takes to query the above XML document and look for all contacts in the

document. We can search for the descendants of the top element that are of type contact.

The trailing “select c” is used to select the entire node with “contact” tag.

var query = from c in contacts.Descendants( "contact" ) select c;

We can add filters to the query using a "where" clause on the attribute state. Here we select

all contact where state is WA.

var query1 = from c in contacts.Descendants("contact") where c.Element("address").Element("state").Value == "WA"

select c;

But, if you do not want the entire node, you can select only certain attributes. For example, in

this example, we create new nodes with just name and networth elements.

var query2 = from c in contacts.Descendants("contact") where c.Element("address").Element("state").Value == "WA" select new { Name = c.Attribute("name").Value, Networth = c.Attribute("netWorth").Value

};

Page 90: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 7: XML Support in Windows Phone and Android 90

Getting the Children of an XML Element

LINQ to XML offers ways to traverse the XML tree by accessing children or descendents of a

node. As we saw above, it is possible to get all descendents of a node, i.e. children at any

level, using the Descendents() method. It is possible to get just the child nodes of a node

using Nodes property. On the other hand, if you only want to get child elements of a node,

use Elements() method. To access all children of a node, you can use the Nodes() method.

Querying XML using LINQ to XML

As seen above, LINQ to XML not only provides a way to construct XML documents but also

provides a way to query XML and traverse it the way you want.

You can use the following operators to query the data:

Where

Select

SelectMany

OrderBy

GroupBy

For example, the following query retrieves all contacts from location Washington and sorts

the contacts by name and returns just the name of the contact. The data is returned as string

and is displayed in the IEnumerable<string> format.

from c in contacts.Elements("contact") where (string) c.Element("address").Element("state") == "WA" orderby (string) c.Element("name") select (string) c.Element("name");

In the following example, contacts that have a networth that is greater than the average

networth are retrieved.

from c in contacts.Elements("contact"), average = contacts.Elements("contact"). Average(x => (int) x.Element("netWorth")) where (int) c.Element("netWorth") > average select c;

Page 91: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Chapter 7: XML Support in Windows Phone and Android 91

Summary

In this chapter we compared XML processing technologies available on Android and

Windows Phone. Windows Phone OS provides two different mechanisms: XMLReader, a fast

forward only XML parser, and LINQ to XML, a powerful query mechanism to query XML

documents.

Related Resources

To learn more about XML data, visit:

http://msdn.microsoft.com/en-us/library/2bcctyt8.aspx

To learn more about LINQ to XML for Windows Phone, visit:

http://msdn.microsoft.com/en-

us/library/windowsphone/develop/system.xml.linq(v=vs.105).aspx

To learn more about processing XML data with LINQ to XML:

http://msdn.microsoft.com/en-us/library/bb387098.aspx

Page 92: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Appendix A: Migration Sample 92

Appendix A: Migration Sample

This section contains sample Android and Windows Phone applications along with

documentation.

The content within is intended to aid you in the process of migrating your Android

applications over to Windows Phone by providing a look at the differences and similarities of

each platform. Through analysis, you'll see how to implement the same functionality on

Windows Phone as you have within your Android application.

Page 93: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Appendix A: Migration Sample 93

In-App Advertisements

Introduction

Advertising in smartphone applications is a proven way to generate revenue from your paid,

trial, and free applications. Each phone platform has frameworks available for presenting ads

with little effort on the developer’s part. For Android phones, developers can use AdMobTM,

a platform from Google.

You can use Microsoft Advertising platform and SDK for showing ads in your Windows

Phone application. This allows Microsoft AdCenter as well as various other ad networks to bid

for the right show ads in your applications. . In this chapter, we are going to look at the use

of Microsoft Advertising SDK.

Phone Platform UI Comparisons

As you can see in the Android (Figure 1) and Windows Phone (Figure 2) screen captures, the

advertisement UI is nearly identical. A rectangular area presents ads above other elements.

The ads for Android have a glossy button look with some icon images. The Microsoft

Advertising control instead uses a less obtrusive design and follows the design guidelines for

the Windows Phone. You can choose the best layout and placement for the ad controls just

like with any other UI control.

Page 94: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Appendix A: Migration Sample 94

Figure 1 – Android Figure 2 – Windows Phone

In Windows Phone ads can be text- or image-based. Ads are rotated automatically by the

AdControl. The rate at which the ads rotate is controlled by the setting on the AdControl. A

subtle animation helps make those rotations visible but not too jarring while the main part of

the application is being used. A simple vertical motion in the ad content happens as new ad

text appears from the top and the old ad text fades towards the bottom of the control.

Windows Phone uses the AdControl control to present the ads, but the only options that you

have over visuals is to set the BorderBrush property (there are other visual properties that

you may see for this control, but they are inherited from the Control class and will have no

effect). Note that this could be specified in code, but is more commonly specified in the

XAML:

<UI:AdControl Height="80" Width="480" BorderBrush="Blue" />

It is recommended that the ad control be positioned at the top or bottom of the Windows

Phone screen. Place the AdControl outside any scroll viewer’ otherwise, the ad will scroll on

and off the page. Similarly, ads placed inside Panorama or Pivot control will scroll out of view.

If you want the ad to remain visible, place the AdControl outside these controls.

While AdControl allows sizes of 350x50 and 480x80, the recommended size is 480x80 with

matching ad unit selected in Microsoft pubCenter. If the ad unit in pubCenter is smaller than

Page 95: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Appendix A: Migration Sample 95

the size of AdControl, the ad will be centered in the available space. In fact, if you use any

other size for AdControl, ads may not display in your application. When testing or

debugging your app, you should set the ApplicationId and AdUnitId properties to the test

values so that a test ad is displayed.

Comparison of ads between Android and Windows Phone

There are three steps in showing ads in your Windows Phone application.

1. Add the Microsoft AdControl to your application. Set a couple of properties in the

AdControl to identify your app and ad location, and start showing ads in your

application.

2. Join Windows Phone Dev Center which will allow you to publish your applications to

Windows Phone Store.

3. Sign up on the Microsoft pubCenter portal and register your application. Register

your application, create an ad unit with ad unit and use it with the AdControl.

Using AdControl in your app

To show the ads, you need to use Microsoft AdControl control in your application. AdControl

is part of the Windows Phone SDK 8.0.

Follow steps outlined earlier to create a new Windows Phone App project. Drag and drop

AdControl control on the surface. Position the AdControl at the bottom of the screen as

shown.

Page 96: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Appendix A: Migration Sample 96

An instance of AdControl is added to the MainPage.xaml file as shown below.

<UI:AdControl ApplicationId="test_client" AdUnitId="Image480_80" HorizontalAlignment="Left" Height="80" Margin="0,527,0,0" VerticalAlignment="Top" Width="480"/>

Additionally, the following namespace is declared in the ApplicationPage node. xmlns:UI="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"

This is analogus to including AdView control in the activity’s XML layout file.

At this point, you have a fully-functional ad control. App Manifest Settings

In addition to setting up your PubCenter account and embedding the control, you also need

to make sure that the app is configured properly for ads. In particular, you must declare app

capabilities. Capabilities are set in the WMAppManifest.xml file,

Page 97: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Appendix A: Migration Sample 97

You must include following capabilities to serve ads in your Windows Phone 8 app:

<Capabilities> <Capability Name="ID_CAP_IDENTITY_USER" /> <Capability Name="ID_CAP_MEDIALIB_PHOTO" /> <Capability Name="ID_CAP_NETWORKING" /> <Capability Name="ID_CAP_PHONEDIALER" /> <Capability Name="ID_CAP_WEBBROWSERCOMPONENT" /> </Capabilities>

Failure to set these capabilities will result in no ads being served in your app.

Now, run your app in the emulator to see the Ad Control in action. Your app shows a test ad

from Microsoft Advertising as shown below.

Page 98: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Appendix A: Migration Sample 98

Before you receive real ads on your app, you must register the app with pubCenter and

acquire an ApplicationId for the app. You must also register an Ad Unit. However, you can

test the app without registering them. When the AdControl was added to the page, it was

initialized with two attributes, namely, ApplicationId and AdUnitId.

ApplicationId="test_client" AdUnitId="Image480_80"

These values are used only for test purposes. ApplicationId must be “test_client” as shown

below and AdUnitId “Image480_80” for a 480x80 size image.

Windows Phone Dev Center

You will need to join Windows Phone Dev Center to publish and offer your applications in the

Windows Phone Store. Your subscription to dev center includes a personal dashboard to

track your applications and your earnings.

Follow steps listed in Registration Info to register to become a member of Windows Phone

Dev Center.

Register the application in pubCenter

To show ads in your application, you must register each application at Microsoft pubCenter.

For the Android ads, you may have signed up for the AdMob account at www.admob.com.

Page 99: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Appendix A: Migration Sample 99

Follow Getting started instructions listed in Microsoft pubCenter to Create an account and

register the application.

To display the ads, you need to create mobile application ad unit which defines the size and

categories of ads that appear in the Windows Phone app. Select the target categories

appropriate for your app.

Once you have registered your app and ad units (targeted ad content), enter the values of

ApplicationId and AdUnitIId in the AdControl control in your app.

<UI:AdControl ApplicationId="f807XXXXX-bXXd-4XX1-bXX5-37fcXXXX5e6" AdUnitId="123456" HorizontalAlignment="Left" Height="80" Margin="0,527,0,0" VerticalAlignment="Top" Width="480"/>

With this change, you can deploy your application to a device and get real advertisements to

show up in your application.

Ad Targeting

Similar to AdMob ad filters that allow the publisher to set categories, and filters, pubCenter

ad units allow you to create customizable targeted ad categories as well as filters consisting

of URLs and keywords. The targeting categories may include Travel and Automtive. You can

select up to three categories per ad unit. Also, like URL exclusions in Like AdMob filters, you

can exclude URLs to certain web sites, for example, your competitor’s site. For best results,

you will want to create an ad unit that targets the users of your app.

An advantage of ad units is that multiple similar apps can (though don’t need to) share the

same ad unit to simplify management.You can also specify ID_CAP_LOCATION capability to

enable location based targeting that can improve quality and relevance of ads shown to your

users. You may specify latitude, logitude, postal code and country or region for better

location-based targeting. This is similar to Android AdView which allows you to specify

latitude, longitude.

Refresh Interval

AdControl includes a property IsAutoRefreshEnabled that creates a background timer to

refresh ads automatically. This property is set to true by default. The default refresh interval

of ads is sixty seconds for the Microsoft AdControl. For iOS, the refresh interval is a server

setting in your iAd account.

To increase the number of advertisements, and potential revenue from ads, you may want to

decrease the refresh interval. In AdControl, turn of auto refresh by setting

IsAutoRefreshEnabled to false and refresh the ad by calling Refresh() on the AdControl.

Location-Based Personalization

Page 100: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Appendix A: Migration Sample 100

The Microsoft Advertising platform allows you to personalize ads based on the user’s current

location via postal code, latitude/longitude, or country name. Note that performing location-

based customization requires extra steps to actually determine the location. You also need

to notify the user that you are doing this, with the ability to opt-out, and you will need to add

the ID_CAP_LOCATION capability to the manifest file.

Summary

You can easily monetize your Windows Phone applications by using the Microsoft

Advertising controls. Just create your pubCenter account, register your application, register

an ad unit, and embed the AdControl. For more information about Microsoft AdCenterTM

you are encouraged to read the link article “Monetize your Windows Phone Apps” at

http://advertising.microsoft.com/mobile-apps.

References & Downloads

Download the In-App Advertisements Android Sample

Advertising in apps for Windows Phone

Make Money with the Microsoft Ad Control

Microsoft Advertising SDK for Windows Phone

API Documentation for Windows Phone Ad SDK on MSDN

Page 101: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Appendix B: Using the API Mapping Tool 101

Appendix B: Using the API Mapping Tool

What’s the API Mapping tool

Windows Phone API mapping tool helps developers find their way around the code in the

Windows Phone platform. Think of the API mapping tool as being like a translation

dictionary. For example, let's say that you're planning a vacation to France. Since you don't

speak the language, you'll bring a pocket travel dictionary. Having this tool will surely help

you to get some idea about what you are ordering from a restaurant menu but you'll have

no idea what the actual recipe is - nor will you be able to have a conversion in French with

the server! But it is a great learning tool to make the first steps.

With this tool, developers can grab their apps, pick out the API calls, and quickly look up the

equivalent classes, methods and notification events in Windows Phone . A developer can

search a given API call and find the equivalent Windows Phone API call along with links to

the API documentations for both platforms. All Windows Phone 8 API documents are pulled

in from MSDN.

How to use the tool

Go to: http://WP7mapping.interopbridges.com/

And you start by simply browsing the tree on the left pane. One you’ve reach a mapped

item, you’ll see on the right pane the equivalent class, method, or event with links to the

Windows Phone documentation.

What's next?

Of course, this is a work in progress, coverage will expand and more APIs will be mapped

soon. So, please consider using the mapping tool in your porting efforts, and provide

feedback on the dedicated forum, where you can also suggest new mapping APIs to include:

http://WP7mapping.uservoice.com

Page 102: Windows phone 8  guide for android developers

Windows Phone Guide for Android Application Developers

Appendix B: Using the API Mapping Tool 102

Revision History

Rev 1.0:

Creation

This document is provided “as-is.” Information and views expressed in this document,

including URL and other Internet Web site references, may change without notice. This

document does not provide you with any legal rights to any intellectual property in any

Microsoft product. You may copy and use this document for your internal, reference

purposes. You may modify this document for your internal, reference purposes.

Distributed under Creative Commons Attribution-Noncommercial-No Derivative Works 3.0