SlideShare a Scribd company logo
1 of 99
Download to read offline
Windows Phone 7
Guide for Android
Application
Developers




  Microsoft
  6/6/2011
  Rev 1.0
Windows Phone 7 Guide for Android Application Developers




About this Document ............................................................................ 4
Target Audience ................................................................................... 4
Conventions Used in this Document ........................................................ 4
Chapter 1: Introducing Windows Phone 7 Platform to Android Application
Developers .......................................................................................... 5
 The Developer Tools ........................................................................... 5
 Windows Phone 7 Architecture ............................................................. 5
 Comparing the Programming Stack of Windows Phone 7 with Android ...... 7
 Summary ........................................................................................ 11
 Related Resources ............................................................................ 11
Chapter 2: User Interface Guidelines..................................................... 12
 Designing the Application Interface .................................................... 13
 Application User Interface Design ....................................................... 14
 Comparing Windows Phone 7 and Android Navigation ........................... 18
 Windows Phone 7 Frame and Page Structure ....................................... 19
 Application Templates ....................................................................... 21
 Summary ........................................................................................ 21
 Related Resources ............................................................................ 21
Chapter 3: The Developer and Designer Tools ........................................ 23
 A Comparison of Android and Windows Phone 7 Tools .......................... 23
 Development Life Cycle and Windows Phone 7 Developer Tools ............. 24
 The UI Design Tools ......................................................................... 26
 Building Applications ........................................................................ 33
 Debugging ...................................................................................... 34
 Summary ........................................................................................ 38
Chapter 4: C# programming ................................................................ 39
 Managed Programming ..................................................................... 40
 A Comparison between C# Features and Java Classes .......................... 41
 A Comparison of Important Class Libraries .......................................... 51
 The New features of C# .................................................................... 54
 Comparing API Documentation Tools .................................................. 58
 NDoc .............................................................................................. 58
 NDocs vs. Javadoc ........................................................................... 61
 Summary ........................................................................................ 61
 Related Resources ............................................................................ 62




                                                                                                     2
Windows Phone 7 Guide for Android Application Developers



Chapter 5: A Comparison of Application Life Cycles in Windows Phone 7 and
Android ............................................................................................. 63
 Multitasking in Android and Windows Phone 7...................................... 63
 Tombstoning of Applications in Windows Phone 7 ................................. 64
 Life Cycle of a Windows Phone 7 Application ........................................ 64
 Role of Handlers in an Application‟s Life Cycle ...................................... 66
 Comparing Life-cycle Methods ........................................................... 68
 Tombstoning and Windows Phone 7 Life Cycle ..................................... 69
 Summary ........................................................................................ 74
 Related Resources ............................................................................ 74
Chapter 6: Storing Data and Preferences ............................................... 75
 Isolated Storage in Windows Phone 7 ................................................. 75
 Use Cases ....................................................................................... 78
 Managing the IsolatedStorage Space .................................................. 79
 Why Windows Phone 7 Does Not Use External Storage ......................... 80
 Managing Content across Applications ................................................ 81
 Comparing Intent API with Launchers and Choosers API ....................... 82
 Summary ........................................................................................ 85
 Related Resources ............................................................................ 85
Chapter 7: XML Parsing in Windows Phone 7 and Android ........................ 86
 XML Parsing in Windows Phone 7 ....................................................... 86
 XML Namespaces for Windows Phone 7 ............................................... 86
 XML Parsing Using XMLReader ........................................................... 86
 TRAVERSING XML ............................................................................ 95
 Summary ........................................................................................ 99
 Related Resources ............................................................................ 99




                                                                                                      3
Windows Phone 7 Guide for Android Application Developers




About this Document
If you have been developing Android applications and are interested in building
your applications for Windows Phone 7, this guide is for you.
The guide covers what you need to know to add Windows Phone 7 development to
your skill set, while leveraging what you have already learned building Android
applications.




Target Audience
This document is for Android application developers willing to develop applications
for Windows Phone 7.




Conventions Used in this Document

Term                             Abbreviation

Windows Phone 7                  WP7

Application Programming
                                 API
Interface

Integrated Development           IDE
Environment




                                                                                      4
Windows Phone 7 Guide for Android Application Developers



Chapter 1: Introducing Windows
Phone 7 Platform to Android
Application Developers
Ever since the release of Windows Phone 7 (WP7) platform, developers from around
the globe rushed to develop applications for this platform. Now, WP7 devices are
available with manufacturers all over the world. A large number of applications are
already available in the WP7 marketplace.
For WP7, 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 WP7 a very attractive
destination for developers to build applications and games.


The Developer Tools
Microsoft recommends using these tools for WP7 application development. This
toolset is free and can be downloaded from here. The toolset includes:
An IDE (for developers): Visual Studio Express for Windows Phone
      A user interface design tool (for designers): Express Blend for Windows
       Phone
      Silverlight for Windows Phone and XNA Game Studio for Windows Phone
      Windows Phone 7 emulator to test and debug applications
The tools are designed to let you develop consumer applications, business
applications, and games.


Windows Phone 7 Architecture
WP7 utilizes a layered architecture. Like Android OS, WP7 runs on multiple phones.
To provide a consistent user experience and features that you can rely on, WP7
defines a minimum set of hardware specifications that all phones must meet. They
include:
      ARM7 CPU
      A DirectX capable GPU
      Camera
      Multi-touch capacitive display
      Standard sensors include:
         o A-GPS
                                                                                    5
Windows Phone 7 Guide for Android Application Developers

          o   Accelerometer
          o   Compass
          o   Proximity and light sensors
There are three standard buttons on the phone: Back, Start, and Search. As we will
see in a subsequent section, these buttons provide an easy and natural navigation
model for the user.
In WP7, Microsoft provides most of the device driver code. A device manufacturer
has to write very little code specific to their device. This improves the consistency
and quality across various devices. WP7 takes advantage of hardware acceleration
through encapsulation layers, such as DirectX or XNA.




WP7 applications use managed programming and run within sandboxed
environments. For more details about WP7 architecture, watch the MIX‟10
presentation by Istvan Cseri, a WP7 architect.




                                                                                        6
Windows Phone 7 Guide for Android Application Developers


Comparing the Programming Stack of Windows Phone 7
with Android
The Application Model shown above provides services, such as installation and
update, for managing the application lifecycle. The UI model helps to manage
application user interface. Applications are built using various WP7 frameworks.
This table gives an overview of the WP7 frameworks that provide features
comparable to the Android programming layers.



Android                  Functionality                 Windows Phone 7
Frameworks                                             Frameworks

                         Application UI, Device        Windows Phone 7 Phone
Android Application
                         integration (sensors,         Framework, Silverlight
Framework
                         camera)                       controls

                                                       XNA for games or Silverlight
Android Application
                         Graphics, Animation, Media    media and graphics for
Framework
                                                       others

                         Base services, Networking,
Android Libraries                                      Common Base Library
                         Text, XML, storage

Android runtime
                                                       Windows Phone 7
(Dalvik)+ Linux kernel




                                                                                   7
Windows Phone 7 Guide for Android Application Developers


Android and Windows Phone 7 Stacks Side by Side
This table compares the Android and WP7 Frameworks side by side.


  Android Frameworks                                               Windows Phone 7 Frameworks

                             Multi-tasking




                                                                                                                    integration
                                                                                                                    UI and Phone
  Application UI and Phone




                                                                                                                      Application
                                                  Java


                                                         C# or VB.NET
                             Application UI                             Application UI
                             Device integration                         Device integration
                             Browser Control                            Browser Control
                             Notifications                              Notifications

                             Peer to Peer                                                              Gamer




                                                                                         Silverlight




                                                                                                                                Two Application Types
                                                                                                                    XNA
                             Gaming                                                                    Services
                             Controls &                                 Controls &
                             Gestures                                   Gestures                       Media
                             Telephony                                  Media
                             Media Framework
  Media




                             Animations                                 Animations                     Animations
                             Graphics                                   Graphics                       Graphics
                             OpenGL-ES                                  Isolated                       Content
                             File System                                Storage
  Core Libraries




                             SQLLite




                                                                                                                          Library
                                                                                                                            Base Class
                             Location                                   Location
                             XML                                        XML, LINQ
                             Networking                                 Networking, Windows
                                                                        Communication Foundation
       Libc, Dalvik VM                                                  CLR Base Classes
  Android runtime +                                                     Windows Phone 7                                       OS
  Linux kernel

Managed Code
In Android, every application runs in its own process, with its own instance of the
Dalvik virtual machine. WP7 only supports “managed code” applications using C# or
VB.net; there is no native access available to the system or the phone hardware.
.NET Common Language Runtime (CLR) manages the execution of such code. CLR
provides garbage collection and there is no memory management to worry about or
pointers to take care of. The WP7 application stack is built on the .NET compact
framework 3.7. As Dalvik virtual machine is optimized for mobile devices, the .NET
compact framework is optimized for resource constrained devices and is designed
to be portable across various hardware platforms.



                                                                                                                                                        8
Windows Phone 7 Guide for Android Application Developers


Base Services
WP7 Base Class Library classes roughly correspond to those provided in the Android
Core Libraries.
      Android core libraries include:
      Media framework for audio and video codec support
      SQLite for database
      Opengl-ES
      SGL for graphics and animation
      Networking stack
      Libc for embedding with Linux kernel
      Dalvik VM
The WP7 Base Class Library layer 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 features supporting the XML data transfer,
       serialization, deserialization and XML parsing.
      Database support: WP7 does not have a local database, such as SQLLite.
       You can write SQL-like queries in C# using Language Integrated Query
       (LINQ) to query XML data, stored in isolated storage (see below), or in
       remote databases such as SQL Azure.

Application UI and Device Integration
You can develop WP7 applications using two libraries: Silverlight and XNA.
Silverlight contains the visual components same as Android standard widgets.
Generally, it is recommended that you use Silverlight for consumer or business
applications and XNA for games. However, you can certainly develop great games
using Silverlight animation.




                                                                                  9
Windows Phone 7 Guide for Android Application Developers




Android applications                     Windows Phone 7 counterparts


UI using activity(contains                    Silverlight applications with pages
widgets) with navigation                      connected by flows
between them




2D or 3D games built                          XNA games with 2D / 3D graphics
with Opengl-ES                                and Xbox connectivity




XNA for Games
For a high performance game, XNA is the right option. XNA framework, originally
developed for XBOX, provides hardware accelerated 2D and 3D rendering and
bitmap graphics. XNA also provides gamer services such as authentication and
connectivity with XBOX Live, as well as Profiles and Leaderboards.

Silverlight Controls and Media
If you use Android activities and widgets, you will find a large set of Silverlight UI
controls specifically designed for the OS. WP7 UI components are designed for
multi-touch. Silverlight uses a declarative language called Extensible Application
Markup Language (XAML) to specify user interfaces. You can use separate code-
behind files, written in C# or VB.NET, to respond to events or manipulate the
controls.
Silverlight provides high performance audio and video with variety of CODECs. It
supports both vector and bitmap graphics with hardware acceleration. As opposed
to a file system, Silverlight provides sandboxed storage, called isolated Storage, to
store the application-specific data. With the isolation of storage, one application
cannot affect other applications that are running on the phone.

Windows Phone Frameworks
If you need to use HTML in your application, you can use the Internet Explorer
based browser control in your application for HTML UI. Windows Phone Framework
layer also provides interfaces to various sensors, such as the accelerometer or the

                                                                                         10
Windows Phone 7 Guide for Android Application Developers

camera. Microsoft provides a push notification service, called Microsoft Push
Notification Service.
In Android, multitasking is supported. In WP7, support for multitasking will be
provided in the next release. In Android, you need to use third-party platforms like
ADMob to publish advertisements in applications. Microsoft has made this task
easier in WP7 by introducing Microsoft Advertising SDK for WP7.
For more information, visit:
Microsoft Advertising SDK for Windows Phone 7


Summary
In this chapter we looked at the WP7 architecture and the Android and WP7
programming stacks. Now that you have a high-level idea of how the WP7
programming stack maps to the Android stack, we are now going to go one level
deeper. In the next section, we will look at the user interface guidelines of WP7
applications.


Related Resources
To learn more about the topics covered in this blog, visit:
      App Hub – Central Place for Windows Phone 7 development. Getting started,
       download tools and read all about Windows Phone 7 development
       MIX ‟10 presentation on Windows Phone 7 Architecture by Istvan Cseri
      Windows Phone 7 Development for Absolute Beginners. Video series that will
       help aspiring Windows Phone 7 developers get started.
      App Hub Jump Start Tutorials
      Introduction to WP7 programming on Codeproject.com
Other Resources you may find useful:
      Overview of the Windows Phone 7 Application Platform
      Windows Phone 7 Team Blog
      Windows Phone 7 Programming




                                                                                    11
Windows Phone 7 Guide for Android Application Developers



Chapter 2: User Interface Guidelines
Microsoft‟s Windows Phone 7 (WP7) uses a novel user interface called Metro. WP7
sets itself apart with its clean and simple design and emphasizes on color and
typography.
In contrast to the application-focused design of Android, WP7 uses an information-
centric design. Instead of an array of application icons, the start screen of a WP7
consists of dynamic tiles that display critical information at a glance to the user.
The tiles are dynamic and they continuously display the up-to-date status of the
applications. For example, they show you the next appointment on your calendar,
or the number of new emails waiting for your attention. Users can personalize their
phones by pinning the tiles that they care most about.
WP7 introduces a new paradigm called hubs. Hubs bring related information
together. There are six hubs, People, Pictures, Music + Videos, Marketplace, Office,
and Games. The People hub, in the instance shown below, aggregates your address
book contacts and Facebook friends.




                                                                                  12
Windows Phone 7 Guide for Android Application Developers


Designing the Application Interface
While the design of the WP7 user interface is different from that of the Android, the
core design principles are very similar. Like Android, in WP7 you need to keep in
mind the compact screen, lower CPU, and limited memory while designing the
applications. In WP7, users use one application at a time, with just one screen
visible.

Similar Application Design Goals
Usability and UI design are not after thoughts, but are the primary goals behind
applications on both the Android and WP7. 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 WP7 application. WP7 provides a complete set of UI
controls designed for the phone.
WP7 utilizes the same set of core multi-touch gestures as the 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 WP7 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: metaphors and direct manipulation with multi-touch. The need for
immediate feedback and aesthetic appeal remains the same.




                                                                                    13
Windows Phone 7 Guide for Android Application Developers


Application User Interface Design
While there are similarities in the design principles of the applications on both
platforms, pay close attention to the user interface of the application for the WP7. It
is best to take advantage of the unique features and strengths of WP7 platform.
For the interface to provide a consistent experience across applications, applications
on WP7 need to adopt the new Metro design guidelines.

XML and XAML
Android uses XML for mapping purposes. A part of the compilation reads the XML,
performs translations, and generates Java. For example, in layout XMLs of Android,
you need to set it as content view in Activity, after defining the whole UI.
In WP7, XAML act as an instantiation language. XAML does not act as a mapping
medium in WP7 as XML does in Android. The XML in a XAML document in WP7
contains the actual code needed for UI and needs not be transformed into code, as
in case of Android.

Controls and the Application Interface
The WP7 development tools and SDK include a rich collection of Silverlight controls
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 WP7 Silverlight controls and
corresponding Android controls.

Android control            Windows Phone 7 control

Border                     Border

ButtonView                 Button

AbsoluteLayout             Canvas

CheckBox                   CheckBox

GridView                   Grid

                           HyperlinkButton

ImageView                  Image

ListView                   ListBox

MediaController            MediaElement


                                                                                    14
Windows Phone 7 Guide for Android Application Developers


Android control          Windows Phone 7 control

                         MultiScaleImage

ViewGroup                Panel

EditText                 PasswordBox

ProgressBar              ProgressBar

RadioButton,             RadioButton
RadioGroup

ScrollView               ScrollViewer

SeekBar                  Slider

LinearLayout             StackPanel

EditText                 TextBlock

EditText                 TextBox

MapView                  Map

WebView                  WebBrowser

                         Panorama

                         Pivot

TimePicker               Timepicker

DatePicker               Datepicker

ExpandableListView

Gallery

ImageSwitcher

Spinner

TableLayout

TextSwitcher

ViewFlipper


                                                           15
Windows Phone 7 Guide for Android Application Developers


Android control            Windows Phone 7 control

ZoomControl

TabHost

SlidingDrawer

RatingBar

Toggle button              ToggleSwitch*

* ToggleSwitch and Datepicker/Timepicker control are part of the Silverlight for
Windows Phone Toolkit available on Codeplex:
http://silverlight.codeplex.com/releases/view/55034
As you can see, WP7 offers controls that correspond to almost all Android controls.
While the look and feel is different, they provide similar functionality.

New Controls in Windows Phone 7
WP7 introduces a few novel controls that have no counterpart on the Android. Here
are some of the examples:
      A multi-scale image, with image data at various resolutions, is appropriate
       for allowing the user when zooming into a photo.
      Panorama control is a multi-screen page and allows a page to span
       horizontally beyond the width of the phone.
      The people hub is another great example. It allows a large amount of related
       information to be presented.
      Pivot control, a novel control that is useful to manage views and display
       information that is logically divided in sections.




                                                                                   16
Windows Phone 7 Guide for Android Application Developers




Notifications
Both Android and WP7 have notification services, but notifications play a key role in
WP7. The 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 WP7 to show critical information.
The notification service also display toast notifications that provide time sensitive
information, such as an SMS. The toast notifications are shown for about 10
seconds, but the user may choose to ignore them. These are the same as Android
toast notification.

Android            Functionality                           Windows Phone
                                                           7

Status bar         Non-critical information that user      Tile notifications
notification       may not respond to. That is
                   informative to user

Toast              Time sensitive data that user may       Toast Notifications
notification       not respond to

Alerts             Modal alerts that the user must         Application
                   respond to                              notifications




                                                                                    17
Windows Phone 7 Guide for Android Application Developers




Tool and Tab Bar vs. Application Bar
WP7 features a versatile application bar. 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. If you are using action sheets in your
Android application, application bar menus give you similar functionality.

Android                      Functionality          Windows Phone 7

Status bar                   Information about      Status bar
                             device

Title bar: to show title     Navigation, Title,     Back button for back
of application or activity   Buttons for views or   navigation
                             actions
                                                    Page title

                                                    View and actions on
                                                    Application bar



Comparing Windows Phone 7 and Android Navigation
WP7 application is a collection of multiple pages. Like on the Android, the user
navigates through different Activities using widgets such as buttons and links.
Like Android, on WP7 the Back button on the phone allows the user to navigate
back between pages within an application, or across applications. It behaves much
like the Back button in a browser. 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 WP7 phone, namely, Search and Home,
have fixed behavior.




                                                                                   18
Windows Phone 7 Guide for Android Application Developers


Windows Phone 7 Frame and Page Structure
Each WP7 application has a single frame, and it includes areas for:
      A page where application content is rendered. This is the content where
       widgets or graphics are rendered.
      A reserved space for the system tray and application bar. It also exposes
       certain properties, such as orientation to the application.




System Tray and Application Bar
On WP7, the system tray includes indicators for various system-level status
information. The application bar includes the area for the most common application
menus, which may include various data views or tasks.




                                                                                   19
Windows Phone 7 Guide for Android Application Developers


Page Structure of Windows Phone 7 Application
The following diagram shows the structure of a typical WP7 data-bound application,
which resembles 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 fast
response. Splash screens are usually an image file of the entire size of the display.
Usually the application starts with the home page, the main navigation page, with
links for search, and other page widgets. 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, have the content of interest. For
example, a list of all baseball teams. However, depending on requirement, the
home page can also be the primary content page.
This is a possible application usage scenario:
      A user clicks one of the team links to visit the team details page (“Widget
       Details Page”) which can provide multiple views. The team details page may
       employ a pivot control or panorama to display different views such as the
       team summary and the list of all players (“List of Gadgets Page”) from that
       team

      A user selects one of the baseball players and the application takes the user
       to the page with player statistics (“Gadget Details page”). The player
       statistics page uses controls such as textblocks, multi-scale images, or other
       multimedia using a MediaElement control

      A user can also use the search widget to search and directly access the team
       page (“Widget Details Page”) or the player page (“Gadget Details Page”)


                                                                                    20
Windows Phone 7 Guide for Android Application Developers


Application Templates
Eclipse does not provide the project template for Android applications. But Visual
Studio provides numerous templates for WP7 application development to make
your life easier.

Functionality                 Visual Studio Template Eclipse

Information drilldown         Data-bound applications        Not available
applications

Utility applications. For     Windows Phone 7 utility        Not available
example, Bubble Level         applications

Games                         Windows Phone 7 Game           Not available
                              (XNA) applications

Flexible template to design   General Windows Phone 7        Not available
any application               applications

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. Lastly, the XNA based games application template gives
you functionality like the OpenGL-ES application.


Summary
In this chapter we looked at the similarities between the application design goals of
the Android platform and the WP7 platform. When you plan your WP7 application,
you will be able to leverage your existing work on Android applications.
We also looked at the application interface design to make sure you are taking
advantage of the WP7 metro design that uses WP7 interface guidelines. You will
find that the WP7 tools offer a large library of controls and gestures that have close
counterparts on the Android.
This chapter also showed you the use of innovative controls like panorama, and
explore the use of live tiles to build an engaging WP7 experience.


Related Resources
To go deeper into the topic discussed, visit:
       Windows Phone 7 User Interface Guidelines
       Windows Phone 7 Developer Tools
       Silverlight for Windows Phone toolkit on CodePlex
       Design resources for Windows Phone

                                                                                     21
Windows Phone 7 Guide for Android Application Developers

Other Resources that you may find useful:
      Application Page Model for Windows Phone 7
      Frame and Page Navigation Overview for Windows Phone




                                                              22
Windows Phone 7 Guide for Android Application Developers



Chapter 3: The Developer and
Designer Tools
With the release of the Windows Phone 7 (WP7) developer tools, Microsoft brings
the user-friendly, high productivity Visual Studio Development environment to WP7.
As Android application developers you are familiar with Eclipse, and you can quickly
migrate to WP7 developer tools and work with ease.


A Comparison of Android and Windows Phone 7 Tools
Visual Studio 2010 Express for Windows Phone is a full-featured Integrated
Development Environment (IDE). Visual Studio 2010 facilitates designing,
developing, and debugging of Windows Phone 7 applications. The other WP7 tools
that help you in the development cycle of the Windows Phone application are:
       Expression Blend
       XNA Game Studio
       Windows Phone Emulator
The WP7 developer tools offer the complete functionality that is provided by the
Android application developer tools. The following table gives an overview of the
functionality of each of these tools. The table also indicates the equivalent tools you
use for Android application development.


 Functionality      Audience        Android          Windows Phone 7 tools
                                    tools

 Primary UI         UI designers    Defined in       Expression Blend
 design: Colors,                    XML, any XML
 gradients, and                     tool
 animation
                                       ADT UI
 UI design          UI designers                     Visual Studio 2010 Express
                                        plug-in
                    and                              and Expression Blend for
                                       Third-
                    programmer                       Windows Phone
                                        party tool
                    s
                                        like
                                        DroidDraw
 Application        Programmers     Eclipse          Visual Studio 2010 Express
 development                                         for Windows Phone
 (coding)

 Game               Programmers     Eclipse          XNA Game Studio
 development
                                                                                    23
Windows Phone 7 Guide for Android Application Developers

 (coding)

 Testing /          Testers        Android          Windows Phone Emulator in
 Emulation                         Emulator         Visual Studio 2010 Express

You can use the Android team structure and overall development process to build
applications for Windows Phone 7. The WP7 toolset ensures that the entire team of
designers, developers, and testers familiar with Android development tools will find
it easy to migrate to the WP7 toolset.


Development Life Cycle and Windows Phone 7 Developer
Tools
Expression Blend 4 and Visual Studio facilitate a close collaboration between
designers and developers.
Both these tools share the same file structure and source files. Expression Blend
uses XAML for UI design and the XAML is consumed by Visual Studio. This system
allows separation of responsibilities between the designer and the developer while
allowing them to work together seamlessly.




Project Management for Windows Phone 7
Like Eclipse, Visual Studio 2010 Express for WP7 is a fully-featured IDE. Visual
Studio 2010 Express allows you to:
      Manage the entire structure of the development project, the source, and the
       resource files
      Configure the application codebase, known as Visual Studio Solution, as a
       collection of projects in a separate functional unit
With Visual Studio 2010 Express, you can manage source files, share code, and
manage the work among team members. Visual Studio integrates a compiler and a

                                                                                   24
Windows Phone 7 Guide for Android Application Developers

debugger. You can access both the compiler and the debugger either from the GUI
or the command line.
To create a sample application, do the following:
   1. Start Visual Studio Express for WP7 from Start menu.
   2. In Visual Studio Express, click File.
   3. Click New Project.
   4. In the New Project dialog box, select Windows Phone Application.
   5. In the Name of the project text box, enter ShoppingList as the name of
      the project, and click OK. Visual Studio Express creates the new project.
The Solution Explorer pane displays the solution that you created. This example
solution has only the ShoppingList project. The project contains the sources,
resources, and properties.




Note: Visual Studio Express for WP7 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. You can also use
Visual Studio Team System, which is designed for greater communication and
collaboration among the development teams.




                                                                                    25
Windows Phone 7 Guide for Android Application Developers


The UI Design Tools
The WP7 developer tools include:
      Expression Blend
      Visual Studio UI Designer
WP7 uses Silverlight and a specific XML markup language for the UI specification.
Visual Studio UI design tool is equivalent to the Eclipse ADT UI plug-in. As Android
application developers you are familiar with Eclipse ADT UI plug-in and you will find
it easy to use this tool. In our example, the main page for the ShoppingList
solution, MainPage.xaml, is already open in the Visual Studio UI Designer tool for
editing.
To change the titles of the application and the current page, do the following:
   1. Right-click the title MY APPLICATION and select Properties.
   2. In the Properties window, select Text and enter SHOPPING LIST.
You can also change the title of the page by entering my list in the Text property of
the title.
To change the title of a page, do the following:




   1. Drag a Text box from the Toolbox and place it above the textblock.
   2. Update the Text box‟s Text property to delete any existing entry.
                                                                                    26
Windows Phone 7 Guide for Android Application Developers

   3. Below Properties, click TextBox1, and enter txtItem to change the ID of
      the textbox to txtItem.
   4. Resize the Text box by dragging its lower right corner so that its width is
      300.
   5. Drag a Button to the right of the TextBox.
   6. Change the button‟s Content property to Add, and its ID to btnAdd.
   7. Resize the button so that its width is 140.
   8. Drag another TextBox and place it underneath the txtItem textbox.
   9. Resize the new TextBox so that it covers the rest of the phone screen.
   10.Update the ID of the new TextBox to txtList.
   11.Update the Text property of the new TextBox to Nothing here yet!.
Your application looks as shown below:




   12.To start debugging, compile the application and launch, press F5 or click
      Debug
The application starts the WP7 emulator, deploys, and runs the ShoppingList
application. You can click Add. But the application does not respond because there
is no code for the button you inserted in the previous steps.




                                                                                    27
Windows Phone 7 Guide for Android Application Developers




Note: You can use the context menus to add the event handlers or to set the
control properties. The emulator‟s integration with Visual Studio allows for a direct
manipulation of controls and makes it easy to add logic to the UI controls.

Expression Blend for Windows Phone 7
Expression Blend for WP7 is a visual UI design tool that is suitable for designers.
There is no exact equivalent to Expression Blend in Android development toolset.
Expression Blend is like VS Design. With Expression Blend, you can:
       Drag and drop UI elements to design the UI
       You can layout the controls accurately up to pixels. You can easily create
        and use color palettes and gradients
       Add special effects, such as reflections and shadows
       Import Photoshop files and Android application resources to the Windows
        Phone application
       Create fine application behavior and animations without any programming




                                                                                      28
Windows Phone 7 Guide for Android Application Developers




Expression Blend is for UI designers and Visual Studio Design is for programmers.
Programmers can also use Visual Studio Design to integrate the application logic to
the UI design. You can also use the Visual Studio UI design tool to design UI for
applications.
Both Expression Blend and Visual Studio Design have:
      A single control set that provides accurate fidelity to their run-time visual
       representation. This feature allows you to easily visualize the application.
      Same project structure and share the same source files for designers and
       developers.
      Use or produce XAML, which is a Silverlight XML declarative markup
       language used for interface design. This feature allows a designer to work on
       the design using Expression Blend while the developer uses Visual Studio to
       design the logic behind the application. You can establish a smooth design
       and development workflow.




                                                                                 29
Windows Phone 7 Guide for Android Application Developers


Visual Studio
Visual Studio has a simple to use, full-featured, and a configurable source editor.
The editor tool has various features that are familiar to Eclipse users. The features
of the editor include:
       Flexible search
       Rich editing
       Format code
       Auto-completion of code
       Outline or hide code
To add logic to the application, do the following:
    1. To stop the running application, click Debug.
    2. Click Stop Debugging.
    3. Double click Add. The dialog displays MainPage.xaml.cs with a method
       btnAdd.
    4. Click the MainPage class.




    5. To add logic to the items that are added to the shopping list, edit the
       btnAdd_click method.
    6. Enter the following code: string tStr = txtItem.Text;.
Note: When you enter t for txtItem, Visual Studio displays the auto-completion
dialog box. The Visual Studio equivalent for Eclipse auto-completion is called
content assistant.


                                                                                    30
Windows Phone 7 Guide for Android Application Developers




   7. Enter the following code in the btnAdd_click method:
       if (!String.IsNullOrEmpty(tStr))
Note: 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.




VS IntelliSense in Visual Studio
VS IntelliSense is a feature of the IDE which uses history, code context, and .NET
reflection for intelligent auto-completion. VS IntelliSense can suggest and complete
variable names, parameters, classes, and method names. VS IntelliSense can also
generate appropriate code where needed, as shown in the code below:



To complete the event hookup, Visual Studio generates an empty stub for the event
handler button1_click method.




                                                                                  31
Windows Phone 7 Guide for Android Application Developers


Code Snippets in Visual Studio
Code Snippets in Visual Studio is equivalent to code templates in Eclipse. Code
Snippets allows you to insert code fragments with a few clicks. Visual Studio
contains a large number of snippets. These snippets help you to create their own
snippets. You can also create an index and search for the code snippets by using
the self-defined terms.
To use a code snippet, do the following:
    1. To start the Insert Snippet prompt, press CTRL+K CTRL+X
    2. To insert a code snippet for an if statement in the code, select Visual C#
       followed by i




The inserted snippet shows the parts of the code that you need to complete.
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
      string tStr = txtItem.Text;
      if (!String.IsNullOrEmpty(tStr))
      {
             if (true)
             {
             }
      }
    3. To complete writing the code for the method, enter the required code so
       that the body of the method is complete as follows:


string tStr = txtItem.Text;
      if (!String.IsNullOrEmpty(tStr))
      {
            if (txtList.Text == “Nothin here yet”)
            {
                  txtList.Text = “”;
            }
            txtList.Text += txtItem.Text + “n”;
            txtItem.Text = “”;
      }
Visual Studio supports various refactoring mechanisms. You can select any piece of
code and right-click the code to access the refactoring menu.
                                                                                    32
Windows Phone 7 Guide for Android Application Developers


Visual Studio Editor
Visual Studio editor is customizable. Visual Studio editor allows you to define
various keyboard shortcuts or create your own macros. Macros help you to
automate repetitive actions by combining a series of commands and instructions.
You can easily customize Visual Studio Editor to use shortcuts and keyboard
combinations with which they are familiar.
Instead of opening a separate window for each file, as in Eclipse, the default view in
Visual Studio uses tabbed windows. You can change this behavior to suit your need.
You can change the way in which various windows are docked within Visual Studio
Shell.


Building Applications
Visual Studio Express for WP7 allows you to build the Visual Studio solution on
demand. It allows you to separately build each project to make a part of the
complete solution.
Visual Studio uses an XML based, declarative build system called MSBuild. MSBuild
is equivalent to Ant and Nant. You can access the builds either from the GUI or by
using the command line for batch processing. MSBuild is flexible and allows you to
create a specific target either as a debug build or as a release build.




Windows Phone 7 Emulator
The WP7 Emulator provides a virtualized environment in which you can deploy,
debug, and test applications. The WP7 Emulator is designed to provide a
comparative performance of an actual device and meets the peripheral
specifications required for application development.
To access the WP7 Emulator from Visual Studio, do any of the following:
      From Deploy menu, click Deploy Solution
      Press F5 in the key board, this starts the Emulator along with the debugger
      Press CTRL+F5, this start only the Emulator

                                                                                   33
Windows Phone 7 Guide for Android Application Developers

The WP7 Emulator is like the Android Simulator. However, these differences are
there:
      In Android emulator you can have access to all the system application like
       Phone Dialer, Contacts, Mail, and Media Gallery. But the WP7 Emulator the
       system applications are not directly accessible to you. Though it can be
       accessed by the Launchers and Choosers.
      Android supports various display height and width. Likewise, you can
       customize the Android emulator for parameters like Screen Height, Width,
       RAM size, and Sensors. As WP7 have specific hardware requirements, you
       cannot modify the WP7 Emulator for these hardware parameters.


Debugging
Visual Studio Express Phone 7 includes a symbolic debugger that you can use with
the WP7 EMULATOR or with a remote device. Once the application loads in the
debugger, you can view the variables in the application and control their execution.
To work with debugger, do the following:
   1. To start the debugger, press F5
   2. In Textbox you previously created, enter napkins and click Add. Refer to
      the image below.




Note: napkins is added after Nothing here yet!
   3. In Visual Studio, click the light blue area to the left of the string tStr =
      txtItem.Text; line.

       Visual Studio inserts a breakpoint at that line.

                                                                                     34
Windows Phone 7 Guide for Android Application Developers




    4. Launch the debugger again using F5. When the application loads into the
       debugger, rest the mouse pointer over txtItem in the code
    5. Click + in the pop-up to view the variable txtItem.

Tracking Variables
You can view the details of the variables such as the Type, Fields, and Properties.
The dialog below shows how you can scroll up and down the Type Hierarchy to
inspect the objects.




You can set a watch on certain variables to keep them under observation
continuously.
To track variables, do the following:
    1. Right-click txtList, and click Add Watch.
       The watch window displays the variable txtList.
    2. Click + icon near txtList, to expand txtList.



                                                                                      35
Windows Phone 7 Guide for Android Application Developers




   3. To ensure that the control does not enter the if statement, press F10 to step
      through the code.
if (txtList.Text == "Nothing here yet")
                 {
                     txtList.Text = "";
                 }


You can observe in the Watch window that the value of txtList.Text is Nothing here
yet. But it gets compared with Nothing here yet (with no exclamation point.) This is
a bug in the code.
Change the statement as shown below to add the exclamation point:
if (txtList.Text == "Nothing here yet!")


Note: While in the debugger, you can use the VS immediate mode where you can
write the managed code instructions to modify or view the variables or execute
code to help with debugging.




   4. Update the code and re-launch the debugger by pressing F5.
   5. To test the application, add items to the shopping list.




                                                                                 36
Windows Phone 7 Guide for Android Application Developers




A Note about Debugging
You will observe that you can easily debug a WP7 application using the managed
programming environment. Like Eclipse, the debugging in WP7 application is done
entirely at the application level using the C# code and types.
Note: The .NET framework includes two classes called Debug and Trace, which help
you 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 returns true,
Visual Studio does not respond. But if the statement returns false, the program
enters the debugger.




                                                                              37
Windows Phone 7 Guide for Android Application Developers


Summary
In this chapter we looked at the Windows Phone 7 Developer Toolset. The Toolset
includes the rich tools that are designed to support every step in the entire
application development lifecycle. The design, development, and the testing tools
are equivalent to the existing Android team roles and processes. The tight
integration between the WP7 tools helps you to streamline the design, develop the
workflow, and test the workflow. These tools provide an end-to-end functionality
and are highly customizable.




                                                                                38
Windows Phone 7 Guide for Android Application Developers



Chapter 4: C# programming
This chapter discusses the C# features that map to the most common Java
features. This chapter includes the code snippets, which help you to work faster
with C# code. It describes important C# features that help you write safe code and
enhance productivity.
The chapter discusses the following features of C# programming:
      Managed Programming
      Class Declaration
      Strong Typing
      Class Constructors
      Properties
      Parameter Types
      Access Privileges
      Methods with multiple Parameters
      Inheritance
      Protected Access
      Instance vs. Class Level Access
      Abstract Classes
      Interfaces
      Polymorphism
      Structs
      Object Lifecycle: Creation and Deletion of Objects
      Type Checking vs. Reflection
      Exception Handling




                                                                                39
Windows Phone 7 Guide for Android Application Developers


Managed Programming
WP7 supports managed programming in C# and VB.NET.




The C# compiler (and similarly, the VB compiler) compiles the C# (or VB.NET) code
in an intermediate language (IL) byte code and metadata. The Common Language
Runtime (CLR) executes the bytecode. The C# uses metadata to manage type
safety, exception handling, and array bounds. CLR also manages memory and
performs garbage collection. In Android, the Java code is compiled in a .class file,
and the file is converted to a .dex file. The .dex file is optimized for low foot print
on memory. The .dex file is then converted to an apk file, which is executed on an
android platform.




                                                                                    40
Windows Phone 7 Guide for Android Application Developers


A Comparison between C# Features and Java Classes
Class Declaration
Like Java, C# does not separate class definition from class implementation. The
compiler derives the metadata about the classes from class implementation. As in
Java we can define multiple class definition in same file. C# also defines the
multiple classes in same file.
using System;             // In java this is similar to import
namespace FirstApplication   // scope for classes. Same like package declaration in Java
{
class Person                  // only uses class implementation
{
        private DateTime birthDate; // a private field accessible to this class
        private int ageOn(DateTime date) // a private method
        {
            TimeSpan span = date.Subtract(birthDate); //uses a .notation to invoke
            return span.Days;
        }
        public int age                // this is a property.
        {
            Get                       // just a getter; it’s a read-only property
            {
                return this.ageOn(DateTime.Now);
                 }
        }

       public Person( DateTime dob)   // instance constructor. Same like Java
        {                              // it combines allocation and initialization
            birthDate = dob;
             }
}
class Program   // Same like 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
        }
    }
}



The following example shows the public signature of the class Person that consists
of property, age, and constructor.
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 and to organize the code. You can
access classes in other namespaces by referring to a fully-qualified name. You can
refer to System.Console.WriteLine in the example above, where the console is in
the System namespace.
C# uniformly uses the “ ” notation for referring to all methods, fields, and
properties.

Strong Typing


                                                                                           41
Windows Phone 7 Guide for Android Application Developers

C# is a strongly typed language like Java. The types must be specified for variables
and input/output parameters. 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
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
You often need to decide about whether to implement a member as a property or a
method. In this case, the design pattern is identical for both Java and C#. As a
general rule, use properties when you need to access data. To take any action on
the data, use methods.
Properties helps to abstract away from directly accessing the members of a class.
This technique is similar to using accessors (getters) and modifiers (setters) in
Java. You can make the property read-only by providing the getter, write-only by
providing the setter, or read-write by providing both getter and setter.

Parameter Types
Like Java, C# uses the value parameters by default. C# does not have pointers. But
C# allows the passing of parameters by using the ref modifier. Instead of pointers,
you can use parameters with ref where you want to achieve an additional
functionality in a method. In some cases, you need to use the reference parameters
for better efficiency since they avoid data copying.


void Foo (ref int x, int y)
{
      x = 0;
      y = 0;
}
..
                                                                                    42
Windows Phone 7 Guide for Android Application Developers

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. This 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
Like Java, C# allows the access privileges on fields (for example, birthDate),
properties (for example, age) and methods (for example, ageOn). 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 response 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.

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# has introduced
the named parameters. The following example shows the comparative syntax for
Java and C#.

Java                                      C#
void addEmployee(string name, int         void addEmployee(string name, int
id, int age);                             id, int age);

 Off.addEmployee("Phil",2345, 23);        Off.addEmployee("Phil",2345, 23);
                                          Off.addEmployee(name: "Phil",
                                          age:23, id:2345);

Like Java, C# explicitly supports method overloading. C# differentiates between the
methods that have the same name by using information about the parameter
types. 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 (myClass obj, myClass before);

                                                                                     43
Windows Phone 7 Guide for Android Application Developers

The following code sample shows another example of method overloading:
using System;
namespace SecondApplication
{
    struct Point                              // In contrast Java where struct not
supported, C# structs are closer
    {                                         // classes.
        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 an 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
        protected static int counter = 0;     // Similar to protected variables in Java
        public string ID;
        protected Shape()                     //a constructor. Same name as the class
name
{
            counter++;                        // class variable being updated
        }
        public Point Origin                   // similar to Java class
variables
        {
            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                 //Similar to Java, single iinheritance
   {
       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;
       }


                                                                                        44
Windows Phone 7 Guide for Android Application Developers

         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          // 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;
         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);
                                                                                     45
Windows Phone 7 Guide for Android Application Developers

          }
          }
              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
        }
    }
}


Inheritance
Like Java, C# also 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, whereas the class Square inherits
from the class Rectangle.
class Rectangle : Shape
class Square : Rectangle
In C#, the constructor of the base class is automatically invoked when you
construct an instance of a derived class. However, a derived class can invoke a
specific constructor of the base class if needed. This you can see in the constructor
of the Square class.
public Square(double s): base(s, s) //constructor. Calls parent
constructor explicitly
Like Java, a C# derived class may not override a method by redefining it. The class
must use the keyword override in its method definition.
public override bool contains(Point p)
{
      …
}

Protected Access
Like Java, in C#, you can use protected modifier to control access to fields,
properties, and methods. 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


                                                                                     46
Windows Phone 7 Guide for Android Application Developers

Like Java, C# uses a static modifier to denote class level methods, fields, and
properties. Everything else is at an instance level. In the above code example, the
counter is a class level variable.

protected static int counter=0;

Abstract Classes
The abstract classes are classes that cannot be instantiated. Java provides a syntax
for an abstract class. The class Shape defined in the above C# code sample is an
abstract class. The abstract classes requires that both Area and the method it
contains must be overridden in any derived classes.
abstract class Shape
  {
      public abstract double Area
      {
          get;
      }
      public abstract bool contains(Point p);

Interfaces
The Java and the C# interfaces are similar. In the sample code shown below,
IThreeDShape defines an interface that is implemented by the Cube class.
interface IThreeDShape
  {
      double volume
      {
          ...
      class Cube : Shape, IThreeDShape

Polymorphism
The working of polymorphism is the same in both Java and C#. You can pass a C#
derived class as a parameter to a method that expects a base class. Similarly, you
can pass a class that implements a particular interface, as a parameter to the
method. The following sample code shows how to pass an object of the class Cube
as a parameter, where the method expects an object of the class IThreeDShape.
static void printVolume(IThreeDShape tdShape)
  {
      Console.WriteLine(“The volume is ” + tdShape.volume);
  }
      …
                                                                                  47
Windows Phone 7 Guide for Android Application Developers

  Cube c = new Cube(4.0);
  SecondProgram.printVolume(c);

Structs
C# structs are like classes. C# structs can access modifiers and have constructors,
methods, and properties. While a struct is a value, a class is a reference.
struct Point
   {
       public double x;
       public double y;




                                                                                 48
Windows Phone 7 Guide for Android Application Developers


Object Lifecycle: Creation and Deletion of Objects
The memory management in both Java and C# are similar. Both Java and C#
performs automatic memory management. Instead of allocating memory, C# allows
you to use the new operator to create objects and initialize them. When a code no
longer accesses an object, the object becomes eligible for garbage collection. The
.NET CLR garbage collector in C# periodically frees up the memory for such objects.
With C#, you don‟t have to track the free memory usage.
In rare circumstances, you may need to perform a cleanup at the time the object is
destroyed. C# allows the use of destructors, but in practice this is rare.

Type Checking vs. Reflection
Java Reflection is a versatile feature that you can find both in C# and Java. You can
use reflection to:
      Get information 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.
The following table maps the dynamic type checking in Java with its corresponding
C# reflection features.

Java Reflection         Explanation            C# Reflection

Class1 instanceOf       Is Object a subclass   type.IsSubclassOf(typeof(BaseClass))
BaseClass               or member?

object.getClass()       Is Object a member     object.getType() or typeof
                        of

search from             Does the object        type.GetMethod(MethodName)
                        implement the
Method[] methods =
                        method?
c.getMethods();

                        Does the class         type.GetMethod(MethodName)
                        respond to the
                        method?

Method.invoke(..)       Invoke a method        type.InvokeMember(…)


Exception Handling
Exception handling is similar in both C# and Java. You use a use block to handle
exceptions. You can also use either catch specific exceptions or a catch-all
statements. The syntax for exception handling is similar in Java and C#.



                                                                                   49
Windows Phone 7 Guide for Android Application Developers

try
      {
            //block of code
      }
      //Most specific:
      catch (ArgumentNullException e)
      {
            Console.WriteLine(“{0}First exception caught.”, e);
      }
      //Least specific
      catch (Exception e)
      {
            Console.WriteLine(“{0}First exception caught.”, e);
      }




                                                                  50
Windows Phone 7 Guide for Android Application Developers


A Comparison of Important Class Libraries
Strings
C# provides a comprehensive string class, which offers you all the features that you
associate with this class.

Java          C#                                   Notes
Feature

String        String greeting = “Hello WP7!”;
              Int length = greeting.Length;



Comparison    String color = “pink”;               Strings are compared using ==.
              If (color == “red”)                  They are compared
                                                   lexicographically using compare.
              System.Console.WriteLine(“Matchin
              g colors!”);
              string name = “Joe”;
              if (string.compare(name, “Jack”)
              > 0)
                System.Console.WriteLine(name +
              “ comes later”);

Concatenation System.Console.WriteLine             Strings can be concatenated
              (greeting + " You rock!")            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);




                                                                                     51
Windows Phone 7 Guide for Android Application Developers


Arrays
Arrays in C# are almost like arrays in Java.

Java Feature      C#                                       Notes

Arrays of          int[] table;                            Array size is not a part of
primitive types    table = new int[3];                     the array declaration.
such as int, float string[] names = new string[3]
                                                           Arrays are explicitly
                  {"Peter", "Paul", "Mary"};               initialized.

Multi-dim arrays Int[,] mAray;                             C# supports jagged
of primitive types Int[][] jaggedArray;                    arrays, or arrays of
                  string[][] singers = {new string[]
                                                           arrays, and they need not
                  {"Peter", "Paul", "Mary"}, new           be rectangular.
                  string[]{“Paul”,“Art”}};                 Note: Arrays of strings,
                                                           i.e. objects, work the
                                                           same way.

Mutable array of List<string> colors = new                 You can use Lists as a
objects          List<string>; //list of strings           replacement for mutable
                  Colors.Add(“Red”);                       arrays.
                  Colors.Add(“Green”);
                  Colors.Insert(1,”White”);                You may also use
                  String myColor = Colors[0]; //”Red” ArrayLists.
                  Colors[colors.IndexOf(“Red”)] =
                  “Pink”; // replace Red with pink


Dictionaries
C# provides a generic dictionary class that is similar to the HashTable 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.




                                                                                      52
Windows Phone 7 Guide for Android Application Developers


Java                 C#                                Notes

                     Dictionary<string, int> d = new   You can use Dictionary as
                     Dictionary<string, int>();        a replacement for
                     d.Add("Honda", 124);              NSMutableDictionary.
                     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);
                     }




                                                                             53
Windows Phone 7 Guide for Android Application Developers


The New features of C#
This section covers the following:
      Generics
      Operator Overloading
      Delegates
      Events
      Generics

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. For example, the following code shows how to define a generic stack:


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. The use of generics is like generics in Java.




                                                                                   54
Windows Phone 7 Guide for Android Application Developers


Operator Overloading
Operator Overloading allows you to define the implementation of user-defined
operators for user-defined classes. Consider the following example of a complex
number struct. Operator Overloading allows you to define a + operation by using 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;




                                                                               55
Windows Phone 7 Guide for Android Application Developers


Delegates
The functionality of delegates in C# is like the function pointers in C. In this design
pattern, a class delegates another class even if which 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)
        {
             Console.WriteLine("Logging to file log: {0}", s);
         }
    }
public class DelegatesTest
    {
         public delegate void StringDelegate(string s);
         public static void Main()
         {
             StringDelegate Writer, Logger;             // define twp
StringDelegate objects
         Writer = new StringDelegate(ConsoleLogger.WriteString); //
Create delegates with appropriate methods
             Logger = new StringDelegate(FileLogger.LogString);
             Writer("Warning message 1n");             // Send to
Console Writer delegate method
             Logger("Warning message 2n");             // 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

                                                                                     56
Windows Phone 7 Guide for Android Application Developers

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.

Events
Events in C# are useful in the pub-sub (publisher and subscriber) design pattern.
Events are powerful design patterns that are used for asynchronous programming.
An object can publish a set of events that a subscriber can subscribe. When a
publisher raises an event, all subscribers are notified. The publisher raises the
event, but does not know who listens to it. The events are built by using delegates.
using System;
namespace DelegateExample
{
    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();
        }
    }
}

                                                                                     57
Windows Phone 7 Guide for Android Application Developers


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:
      NDoc
      Sandcastle
      Doxygen
      Doc-O-Matic


NDoc
NDoc is a code documentation generator for Common Language Infrastructure.
NDoc uses pluggable documenters to 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


Using NDoc


To use NDocs to generate documentation, do the following:
   1. Open your Windows Phone 7 project.
   2. Select the class library for which you want to create documentation.
   3. Right-click the class library, and click Properties.




                                                                                58
Windows Phone 7 Guide for Android Application Developers




   4. In the left pane, click Build.




                                                           59
Windows Phone 7 Guide for Android Application Developers

        5. Select the XML documentation file check box.
        6. Enter the file name.

Note: NDoc uses this file for creating documentation.

Build your class library, the documentation file is saved in the Debug or Release
folder depending on your build configuration. You can see the documentation file in
the XML format.
You can use NDoc‟s help to get a fair idea of documenting your class library more
effectively.

Generating Better Documentation
To generate better documentation, follow these tips:
           Write elaborate code comments for your code. Elaborate comments make
            your documentation descriptive.
           Each Public type and the Public and Protected members of the Public types
            should have an item describing the members.
           The VS.NET C# code editor has a feature that makes it easy to create the
            basic code comments for each type and member.
            Consider the following code snippet:
public class MyClass() {
public MyClass(string s ) {}
}




Place your cursor just above the MyClass constructor, and press the '/' character
three times. Visual Studio.NET creates the skeleton of a code comment block for
that member:

public class MyClass() {
///<summary>
///
///</summary>
///<param name=”s”></param>
Public MyClass(string s) {}
    }
You can use this method to any type or member that have code comment tags.
NDoc supports a large number of documentation tags. You can use the tags to
meet your requirements.


                                                                                    60
Windows Phone 7 Guide for Android Application Developers

In a code comment block, when you press the '<' key to start a new tag, Visual
Studio.NET displays an Intellisense selector. This selector shows a list of code
comment tags. This list does not display the additional tags that NDoc supports.
You must add the additional tags manually.


Using the NDoc GUI Utility


To use the NDoc GUI Utility, do the following:
   1. Double-click NDocGui.exe, to start NDocGUI.
   2. Click Project, then click New.
   3. In the section Select and Configure Documenter, select documentation
      type from the Documentation Type list.
   4. Under Select and Configure Documenter, specify the parameters, such
      as Copyright text and Output directory.
Note: The most important settings are in the Visibility section. Here you can
configure the elements that you want to document, such as private variables,
protected variables, and Namespaces without summaries.
   5. Click Add.
   6. In the Add Assembly Filename and XML Documentation Filename
      dialog, select the required EXE or DLL.
      NDoc processes the XML documentation file based on your selection.
After building your project, find the compiled documentation for your class library in
the output directory that is specified in the output message.


NDocs vs. Javadoc

      A Javadoc tool can be run on Windows, Mac OS, Unix, and BSD. However,
       NDoc can run only on Windows.
      A Javadoc tool is for generating documents from java source files. The tool
       therefore accepts text as an input. NDoc accepts only binary files as an
       input.
      A Javadoc tool generates documents in an HTML format by default. You need
       a third-party tool called Doclet to generate an output in other formats, such
       as CHM, RTF, PDF, and postscript. NDoc can generate documents in various
       formats, such as MSDN, Linear HTML, and JavaDoc.


Summary

                                                                                   61
Windows Phone 7 Guide for Android Application Developers

In this chapter, we looked at C# programming from the perspective of a Java
developer. C# is a strongly typed, object-oriented programming language that uses
static binding. Several C# concepts are similar to the Java concepts. The knowledge
of Java and object oriented programming will help you to master C# quickly. We
also looked at NDocs, which is the API documentation tool for Windows Phone 7.


Related Resources

To go deeper into C# and Java, visit:

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

To go deeper into NDocs, visit:

      http://ndoc.sourceforge.net/

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




                                                                                62
Windows Phone 7 Guide for Android Application Developers



Chapter 5: A Comparison of
Application Life Cycles in Windows
Phone 7 and Android
The Windows Phone 7 (WP7) execution model improves user experience by cutting
down on response time and offering seamless navigation among applications. To
achieve this, WP7 prioritizes the foreground application and tombstones other open
applications. Android on the other hand, saves all the application states and
displays only the foreground application.
Android suspends an open application when a user starts another application. The
suspended application remains alive in the phone memory. WP7 activates and
deactivates applications dynamically to enable seamless navigation by limiting the
phone to run one application at a time.
The WP7 execution model provides users with a consistent navigation experience
between applications.
In Android, users open applications using the launcher screen. On the launcher
screen, all the applications are listed as icons. In WP7, users navigate forward by
launching applications from the installed Applications List or from a tile on the
Start screen.
In WP7, users can use the Back button on the phone to navigate backwards to a
page in a running application. With this Back button, users can also navigate
through a stack of previously running applications. This WP7 functionality is similar
to Android‟s backward navigation. All Android devices have the Back button on the
phone. A user can navigate to previous screens of applications until he reaches the
home screen of phone.
The Android applications consist of various components, such as Activity, Services,
ContentProvider, and Broadcast receivers. These components are not available in
WP7 except for an Activity which can be mapped to a Page in WP7.


Multitasking in Android and Windows Phone 7
Android supports multitasking and provides seamless navigation between
applications. WP7 achieves seamless navigation using application tombstoning.
Android puts applications in the background using the Service component. The
Service component runs in the background even if your application is not in
foreground until the application‟s task finishes or stopService is called.
The upcoming version of WP7 will support multitasking. The WP7 navigation model
allows natural navigation, similar to a browser‟s Back button. The last accessed


                                                                                      63
Windows Phone 7 Guide for Android Application Developers

application state is preserved as a user navigates across applications using the Back
button on the phone.


Tombstoning of Applications in Windows Phone 7
Tombstoning is a process by which WP7 deactivates an application when a user
navigates away from this application. WP7 keeps a record of the tombstoned
application and stores the latest data accessed by this application. If the user
returns to a tombstoned application, WP7 reactivates this application. The user can
access the reactivated application by using a phone‟s Back button.
Consider the following example. A user is composing a blog with WordPress. He
pressed the Start button to go to the Start screen. WP 7 deactivated the WordPress
application. The user then accessed Facebook. While in Facebook, the user pressed
the Back button. The Start screen appeared. When the user pressed the Back
button again, WordPress appeared exactly in the same way as she had viewed it
the last time.
The following table describes the user events and compares the corresponding
behavior in Android and Windows Phone 7.

User Action or Event         Android Behavior             Windows Phone 7
                                                          Behavior

An incoming phone call or    Running application is       Running application is
SMS                          moved to the background      deactivated
                             but is still in the memory

User presses the Home        Running application is       Running application is
button on the phone          moved to the background,     deactivated
                             current activity will be
                             paused but the application
                             is still in memory

User starts another          Background application is    The upcoming version of
application from the         moved to foreground with     WP7 will support
multitasking menu            the earlier saved state      multitasking

User navigates between       No navigation occurs         Deactivated or
applications using the       when Back button is          tombstoned application is
Back button on the phone     pressed when user is at      activated to the earlier
                             the home screen of the       saved state
                             phone.



Life Cycle of a Windows Phone 7 Application

                                                                                   64
Windows Phone 7 Guide for Android Application Developers

There is no similarity between the Android life-cycle stages with the WP7‟s Page
stage. Activity is the only component that can be mapped with a Page in WP7.
The following events take place during the life cycle of a WP7 application:

Launching
An application is launched when it is started by all other means except when the
user navigates to it using the Back button.
Whenever a user opens an application, WP7 creates a new instance of the
application. In Android, when an application launches a new process a new instance
of Dalvik VM is allocated to the application. The application runs within that
process. Each application runs in its own process and VM instance.
Do not store the state data when the launching event is raised. The launching event
is raised even before application is visible to the user. Storing data at this stage
may increase the startup time of the application.

Running
After launching, the application goes into the running stage. In this stage, the
application manages its own state as the user navigates through the different pages
of the application.
In the running stage, settings and the persisted data are saved. This reduces the
data that you need to save when the application‟s stage changes. However, the
decision to save data in this stage is optional. If the size of the persisted data is not
large, you need not save the data.

Closing
Your application comes across this event when the user presses the Back button on
the phone, when he is in the application‟s first page.
In the handler for this event, you can save data to an isolated storage. This action
is similar to handling the Destroyed() method in Android.
In Android, you cannot close an application after launching. Each activity in the
application can be finished but the application process remains in the memory.

Deactivating
WP7 deactivates your application in the following scenarios:
       A user opens another application
       A user locks the phone screen
       An event accesses the Launcher or Chooser APIs
       A user presses the Windows button to open the Start screen on the phone
       A user presses the Search button on the phone
In the handler for this event, you must save the transient data to the state property
and the persistent data to the isolated storage. This helps maintaining consistent
user experience after the user activates the application again.

                                                                                      65
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers
Windows Phone 7 Guide for Android Application Developers

More Related Content

What's hot

Mobile UI development on Windows Phone and what's new in S40
Mobile UI development on Windows Phone and what's new in S40Mobile UI development on Windows Phone and what's new in S40
Mobile UI development on Windows Phone and what's new in S40MobileMonday Estonia
 
Android - An Operating System
Android - An Operating SystemAndroid - An Operating System
Android - An Operating SystemSaket Khopkar
 
Mobile Application Development with Android
Mobile Application Development with AndroidMobile Application Development with Android
Mobile Application Development with AndroidIJAAS Team
 
Explaining the WinBuilder framework
Explaining the WinBuilder frameworkExplaining the WinBuilder framework
Explaining the WinBuilder frameworkNuno Brito
 
The complete srs documentation of our developed game.
The complete srs documentation of our developed game. The complete srs documentation of our developed game.
The complete srs documentation of our developed game. Isfand yar Khan
 
Android seminar-presentation
Android seminar-presentationAndroid seminar-presentation
Android seminar-presentationconnectshilpa
 
International Journal of Engineering Research and Development
International Journal of Engineering Research and DevelopmentInternational Journal of Engineering Research and Development
International Journal of Engineering Research and DevelopmentIJERD Editor
 
Seminar on android app development
Seminar on android app developmentSeminar on android app development
Seminar on android app developmentAbhishekKumar4779
 
A Review Paper on Cross Platform Mobile Application Development IDE
A Review Paper on Cross Platform Mobile Application Development IDEA Review Paper on Cross Platform Mobile Application Development IDE
A Review Paper on Cross Platform Mobile Application Development IDEIOSR Journals
 
Ii 1300-java essentials for android
Ii 1300-java essentials for androidIi 1300-java essentials for android
Ii 1300-java essentials for androidAdrian Mikeliunas
 
Porting business apps to Windows Phone
Porting business apps to Windows PhonePorting business apps to Windows Phone
Porting business apps to Windows PhoneMichele Capra
 

What's hot (17)

Mobile UI development on Windows Phone and what's new in S40
Mobile UI development on Windows Phone and what's new in S40Mobile UI development on Windows Phone and what's new in S40
Mobile UI development on Windows Phone and what's new in S40
 
Android - An Operating System
Android - An Operating SystemAndroid - An Operating System
Android - An Operating System
 
Mobile Application Development with Android
Mobile Application Development with AndroidMobile Application Development with Android
Mobile Application Development with Android
 
Android 2.1-cdd
Android 2.1-cddAndroid 2.1-cdd
Android 2.1-cdd
 
Android Presentation
Android PresentationAndroid Presentation
Android Presentation
 
Android
AndroidAndroid
Android
 
Explaining the WinBuilder framework
Explaining the WinBuilder frameworkExplaining the WinBuilder framework
Explaining the WinBuilder framework
 
Android
AndroidAndroid
Android
 
The complete srs documentation of our developed game.
The complete srs documentation of our developed game. The complete srs documentation of our developed game.
The complete srs documentation of our developed game.
 
Slideshare android
Slideshare androidSlideshare android
Slideshare android
 
Comparative Study Of Android VS Windows Phone
Comparative Study Of  Android  VS  Windows PhoneComparative Study Of  Android  VS  Windows Phone
Comparative Study Of Android VS Windows Phone
 
Android seminar-presentation
Android seminar-presentationAndroid seminar-presentation
Android seminar-presentation
 
International Journal of Engineering Research and Development
International Journal of Engineering Research and DevelopmentInternational Journal of Engineering Research and Development
International Journal of Engineering Research and Development
 
Seminar on android app development
Seminar on android app developmentSeminar on android app development
Seminar on android app development
 
A Review Paper on Cross Platform Mobile Application Development IDE
A Review Paper on Cross Platform Mobile Application Development IDEA Review Paper on Cross Platform Mobile Application Development IDE
A Review Paper on Cross Platform Mobile Application Development IDE
 
Ii 1300-java essentials for android
Ii 1300-java essentials for androidIi 1300-java essentials for android
Ii 1300-java essentials for android
 
Porting business apps to Windows Phone
Porting business apps to Windows PhonePorting business apps to Windows Phone
Porting business apps to Windows Phone
 

Similar to Windows Phone 7 Guide for Android Application Developers

Windows phone 7 launch ppt
Windows phone 7 launch pptWindows phone 7 launch ppt
Windows phone 7 launch pptaitrichtech
 
Windows phone 8 guide for android developers
Windows phone 8  guide for android developersWindows phone 8  guide for android developers
Windows phone 8 guide for android developersKhai Le
 
Which android app development tools deserve your attention this year
Which android app development tools deserve your attention this year  Which android app development tools deserve your attention this year
Which android app development tools deserve your attention this year Moon Technolabs Pvt. Ltd.
 
report A K Maurya.pdf
report A K Maurya.pdfreport A K Maurya.pdf
report A K Maurya.pdfSonu62614
 
Android Interview Questions
Android Interview QuestionsAndroid Interview Questions
Android Interview QuestionsGaurav Mehta
 
Experience The Best Android Programming Training Here | LW India
Experience The Best Android Programming Training Here | LW IndiaExperience The Best Android Programming Training Here | LW India
Experience The Best Android Programming Training Here | LW IndiaVishakhaTalmale
 
Android app Development Prepration Tips
Android app Development Prepration TipsAndroid app Development Prepration Tips
Android app Development Prepration TipsYasmeen Sheikh
 
Mobile Application Development-Lecture 03 & 04.pdf
Mobile Application Development-Lecture 03 & 04.pdfMobile Application Development-Lecture 03 & 04.pdf
Mobile Application Development-Lecture 03 & 04.pdfAbdullahMunir32
 
Native mobile app development pros, cons, alternatives, and cost optimization
Native mobile app development pros, cons, alternatives, and cost optimizationNative mobile app development pros, cons, alternatives, and cost optimization
Native mobile app development pros, cons, alternatives, and cost optimizationCynoteck Technology Solutions
 
Unit 1-android-and-its-tools-ass
Unit 1-android-and-its-tools-assUnit 1-android-and-its-tools-ass
Unit 1-android-and-its-tools-assARVIND SARDAR
 
Android AppDevelopment
Android AppDevelopmentAndroid AppDevelopment
Android AppDevelopmentAshraf Ali
 
Cross-platform App Development Company
Cross-platform App Development CompanyCross-platform App Development Company
Cross-platform App Development CompanyThe NineHertz
 
Customizing AOSP For Different Embedded Devices And Integration at Applicatio...
Customizing AOSP For Different Embedded Devices And Integration at Applicatio...Customizing AOSP For Different Embedded Devices And Integration at Applicatio...
Customizing AOSP For Different Embedded Devices And Integration at Applicatio...ijafrc
 
Best Frameworks for Android App Development in 2022.pdf
Best Frameworks for Android App Development in 2022.pdfBest Frameworks for Android App Development in 2022.pdf
Best Frameworks for Android App Development in 2022.pdfMarie Weaver
 
Android app development.pdf
Android app development.pdfAndroid app development.pdf
Android app development.pdfAbanti Aazmin
 
Top 10 Android Frameworks for Modern.pdf
Top 10 Android Frameworks for Modern.pdfTop 10 Android Frameworks for Modern.pdf
Top 10 Android Frameworks for Modern.pdfsuryamahathi1
 
Android Design Guidelines 1.1
Android Design Guidelines 1.1Android Design Guidelines 1.1
Android Design Guidelines 1.1Mutual Mobile
 

Similar to Windows Phone 7 Guide for Android Application Developers (20)

Windows phone 7 launch ppt
Windows phone 7 launch pptWindows phone 7 launch ppt
Windows phone 7 launch ppt
 
Windows phone 8 guide for android developers
Windows phone 8  guide for android developersWindows phone 8  guide for android developers
Windows phone 8 guide for android developers
 
Which android app development tools deserve your attention this year
Which android app development tools deserve your attention this year  Which android app development tools deserve your attention this year
Which android app development tools deserve your attention this year
 
report A K Maurya.pdf
report A K Maurya.pdfreport A K Maurya.pdf
report A K Maurya.pdf
 
Android Interview Questions
Android Interview QuestionsAndroid Interview Questions
Android Interview Questions
 
Android interview questions
Android interview questionsAndroid interview questions
Android interview questions
 
Experience The Best Android Programming Training Here | LW India
Experience The Best Android Programming Training Here | LW IndiaExperience The Best Android Programming Training Here | LW India
Experience The Best Android Programming Training Here | LW India
 
Android Operating System
Android Operating SystemAndroid Operating System
Android Operating System
 
Android app Development Prepration Tips
Android app Development Prepration TipsAndroid app Development Prepration Tips
Android app Development Prepration Tips
 
Mobile Application Development-Lecture 03 & 04.pdf
Mobile Application Development-Lecture 03 & 04.pdfMobile Application Development-Lecture 03 & 04.pdf
Mobile Application Development-Lecture 03 & 04.pdf
 
Native mobile app development pros, cons, alternatives, and cost optimization
Native mobile app development pros, cons, alternatives, and cost optimizationNative mobile app development pros, cons, alternatives, and cost optimization
Native mobile app development pros, cons, alternatives, and cost optimization
 
Unit 1-android-and-its-tools-ass
Unit 1-android-and-its-tools-assUnit 1-android-and-its-tools-ass
Unit 1-android-and-its-tools-ass
 
Android AppDevelopment
Android AppDevelopmentAndroid AppDevelopment
Android AppDevelopment
 
Cross-platform App Development Company
Cross-platform App Development CompanyCross-platform App Development Company
Cross-platform App Development Company
 
Android
AndroidAndroid
Android
 
Customizing AOSP For Different Embedded Devices And Integration at Applicatio...
Customizing AOSP For Different Embedded Devices And Integration at Applicatio...Customizing AOSP For Different Embedded Devices And Integration at Applicatio...
Customizing AOSP For Different Embedded Devices And Integration at Applicatio...
 
Best Frameworks for Android App Development in 2022.pdf
Best Frameworks for Android App Development in 2022.pdfBest Frameworks for Android App Development in 2022.pdf
Best Frameworks for Android App Development in 2022.pdf
 
Android app development.pdf
Android app development.pdfAndroid app development.pdf
Android app development.pdf
 
Top 10 Android Frameworks for Modern.pdf
Top 10 Android Frameworks for Modern.pdfTop 10 Android Frameworks for Modern.pdf
Top 10 Android Frameworks for Modern.pdf
 
Android Design Guidelines 1.1
Android Design Guidelines 1.1Android Design Guidelines 1.1
Android Design Guidelines 1.1
 

Recently uploaded

Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 

Recently uploaded (20)

Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 

Windows Phone 7 Guide for Android Application Developers

  • 1. Windows Phone 7 Guide for Android Application Developers Microsoft 6/6/2011 Rev 1.0
  • 2. Windows Phone 7 Guide for Android Application Developers About this Document ............................................................................ 4 Target Audience ................................................................................... 4 Conventions Used in this Document ........................................................ 4 Chapter 1: Introducing Windows Phone 7 Platform to Android Application Developers .......................................................................................... 5 The Developer Tools ........................................................................... 5 Windows Phone 7 Architecture ............................................................. 5 Comparing the Programming Stack of Windows Phone 7 with Android ...... 7 Summary ........................................................................................ 11 Related Resources ............................................................................ 11 Chapter 2: User Interface Guidelines..................................................... 12 Designing the Application Interface .................................................... 13 Application User Interface Design ....................................................... 14 Comparing Windows Phone 7 and Android Navigation ........................... 18 Windows Phone 7 Frame and Page Structure ....................................... 19 Application Templates ....................................................................... 21 Summary ........................................................................................ 21 Related Resources ............................................................................ 21 Chapter 3: The Developer and Designer Tools ........................................ 23 A Comparison of Android and Windows Phone 7 Tools .......................... 23 Development Life Cycle and Windows Phone 7 Developer Tools ............. 24 The UI Design Tools ......................................................................... 26 Building Applications ........................................................................ 33 Debugging ...................................................................................... 34 Summary ........................................................................................ 38 Chapter 4: C# programming ................................................................ 39 Managed Programming ..................................................................... 40 A Comparison between C# Features and Java Classes .......................... 41 A Comparison of Important Class Libraries .......................................... 51 The New features of C# .................................................................... 54 Comparing API Documentation Tools .................................................. 58 NDoc .............................................................................................. 58 NDocs vs. Javadoc ........................................................................... 61 Summary ........................................................................................ 61 Related Resources ............................................................................ 62 2
  • 3. Windows Phone 7 Guide for Android Application Developers Chapter 5: A Comparison of Application Life Cycles in Windows Phone 7 and Android ............................................................................................. 63 Multitasking in Android and Windows Phone 7...................................... 63 Tombstoning of Applications in Windows Phone 7 ................................. 64 Life Cycle of a Windows Phone 7 Application ........................................ 64 Role of Handlers in an Application‟s Life Cycle ...................................... 66 Comparing Life-cycle Methods ........................................................... 68 Tombstoning and Windows Phone 7 Life Cycle ..................................... 69 Summary ........................................................................................ 74 Related Resources ............................................................................ 74 Chapter 6: Storing Data and Preferences ............................................... 75 Isolated Storage in Windows Phone 7 ................................................. 75 Use Cases ....................................................................................... 78 Managing the IsolatedStorage Space .................................................. 79 Why Windows Phone 7 Does Not Use External Storage ......................... 80 Managing Content across Applications ................................................ 81 Comparing Intent API with Launchers and Choosers API ....................... 82 Summary ........................................................................................ 85 Related Resources ............................................................................ 85 Chapter 7: XML Parsing in Windows Phone 7 and Android ........................ 86 XML Parsing in Windows Phone 7 ....................................................... 86 XML Namespaces for Windows Phone 7 ............................................... 86 XML Parsing Using XMLReader ........................................................... 86 TRAVERSING XML ............................................................................ 95 Summary ........................................................................................ 99 Related Resources ............................................................................ 99 3
  • 4. Windows Phone 7 Guide for Android Application Developers About this Document If you have been developing Android applications and are interested in building your applications for Windows Phone 7, this guide is for you. The guide covers what you need to know to add Windows Phone 7 development to your skill set, while leveraging what you have already learned building Android applications. Target Audience This document is for Android application developers willing to develop applications for Windows Phone 7. Conventions Used in this Document Term Abbreviation Windows Phone 7 WP7 Application Programming API Interface Integrated Development IDE Environment 4
  • 5. Windows Phone 7 Guide for Android Application Developers Chapter 1: Introducing Windows Phone 7 Platform to Android Application Developers Ever since the release of Windows Phone 7 (WP7) platform, developers from around the globe rushed to develop applications for this platform. Now, WP7 devices are available with manufacturers all over the world. A large number of applications are already available in the WP7 marketplace. For WP7, 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 WP7 a very attractive destination for developers to build applications and games. The Developer Tools Microsoft recommends using these tools for WP7 application development. This toolset is free and can be downloaded from here. The toolset includes: An IDE (for developers): Visual Studio Express for Windows Phone  A user interface design tool (for designers): Express Blend for Windows Phone  Silverlight for Windows Phone and XNA Game Studio for Windows Phone  Windows Phone 7 emulator to test and debug applications The tools are designed to let you develop consumer applications, business applications, and games. Windows Phone 7 Architecture WP7 utilizes a layered architecture. Like Android OS, WP7 runs on multiple phones. To provide a consistent user experience and features that you can rely on, WP7 defines a minimum set of hardware specifications that all phones must meet. They include:  ARM7 CPU  A DirectX capable GPU  Camera  Multi-touch capacitive display  Standard sensors include: o A-GPS 5
  • 6. Windows Phone 7 Guide for Android Application Developers o Accelerometer o Compass o Proximity and light sensors There are three standard buttons on the phone: Back, Start, and Search. As we will see in a subsequent section, these buttons provide an easy and natural navigation model for the user. In WP7, Microsoft provides most of the device driver code. A device manufacturer has to write very little code specific to their device. This improves the consistency and quality across various devices. WP7 takes advantage of hardware acceleration through encapsulation layers, such as DirectX or XNA. WP7 applications use managed programming and run within sandboxed environments. For more details about WP7 architecture, watch the MIX‟10 presentation by Istvan Cseri, a WP7 architect. 6
  • 7. Windows Phone 7 Guide for Android Application Developers Comparing the Programming Stack of Windows Phone 7 with Android The Application Model shown above provides services, such as installation and update, for managing the application lifecycle. The UI model helps to manage application user interface. Applications are built using various WP7 frameworks. This table gives an overview of the WP7 frameworks that provide features comparable to the Android programming layers. Android Functionality Windows Phone 7 Frameworks Frameworks Application UI, Device Windows Phone 7 Phone Android Application integration (sensors, Framework, Silverlight Framework camera) controls XNA for games or Silverlight Android Application Graphics, Animation, Media media and graphics for Framework others Base services, Networking, Android Libraries Common Base Library Text, XML, storage Android runtime Windows Phone 7 (Dalvik)+ Linux kernel 7
  • 8. Windows Phone 7 Guide for Android Application Developers Android and Windows Phone 7 Stacks Side by Side This table compares the Android and WP7 Frameworks side by side. Android Frameworks Windows Phone 7 Frameworks Multi-tasking integration UI and Phone Application UI and Phone Application Java C# or VB.NET Application UI Application UI Device integration Device integration Browser Control Browser Control Notifications Notifications Peer to Peer Gamer Silverlight Two Application Types XNA Gaming Services Controls & Controls & Gestures Gestures Media Telephony Media Media Framework Media Animations Animations Animations Graphics Graphics Graphics OpenGL-ES Isolated Content File System Storage Core Libraries SQLLite Library Base Class Location Location XML XML, LINQ Networking Networking, Windows Communication Foundation Libc, Dalvik VM CLR Base Classes Android runtime + Windows Phone 7 OS Linux kernel Managed Code In Android, every application runs in its own process, with its own instance of the Dalvik virtual machine. WP7 only supports “managed code” applications using C# or VB.net; there is no native access available to the system or the phone hardware. .NET Common Language Runtime (CLR) manages the execution of such code. CLR provides garbage collection and there is no memory management to worry about or pointers to take care of. The WP7 application stack is built on the .NET compact framework 3.7. As Dalvik virtual machine is optimized for mobile devices, the .NET compact framework is optimized for resource constrained devices and is designed to be portable across various hardware platforms. 8
  • 9. Windows Phone 7 Guide for Android Application Developers Base Services WP7 Base Class Library classes roughly correspond to those provided in the Android Core Libraries.  Android core libraries include:  Media framework for audio and video codec support  SQLite for database  Opengl-ES  SGL for graphics and animation  Networking stack  Libc for embedding with Linux kernel  Dalvik VM The WP7 Base Class Library layer 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 features supporting the XML data transfer, serialization, deserialization and XML parsing.  Database support: WP7 does not have a local database, such as SQLLite. You can write SQL-like queries in C# using Language Integrated Query (LINQ) to query XML data, stored in isolated storage (see below), or in remote databases such as SQL Azure. Application UI and Device Integration You can develop WP7 applications using two libraries: Silverlight and XNA. Silverlight contains the visual components same as Android standard widgets. Generally, it is recommended that you use Silverlight for consumer or business applications and XNA for games. However, you can certainly develop great games using Silverlight animation. 9
  • 10. Windows Phone 7 Guide for Android Application Developers Android applications Windows Phone 7 counterparts UI using activity(contains Silverlight applications with pages widgets) with navigation connected by flows between them 2D or 3D games built XNA games with 2D / 3D graphics with Opengl-ES and Xbox connectivity XNA for Games For a high performance game, XNA is the right option. XNA framework, originally developed for XBOX, provides hardware accelerated 2D and 3D rendering and bitmap graphics. XNA also provides gamer services such as authentication and connectivity with XBOX Live, as well as Profiles and Leaderboards. Silverlight Controls and Media If you use Android activities and widgets, you will find a large set of Silverlight UI controls specifically designed for the OS. WP7 UI components are designed for multi-touch. Silverlight uses a declarative language called Extensible Application Markup Language (XAML) to specify user interfaces. You can use separate code- behind files, written in C# or VB.NET, to respond to events or manipulate the controls. Silverlight provides high performance audio and video with variety of CODECs. It supports both vector and bitmap graphics with hardware acceleration. As opposed to a file system, Silverlight provides sandboxed storage, called isolated Storage, to store the application-specific data. With the isolation of storage, one application cannot affect other applications that are running on the phone. Windows Phone Frameworks If you need to use HTML in your application, you can use the Internet Explorer based browser control in your application for HTML UI. Windows Phone Framework layer also provides interfaces to various sensors, such as the accelerometer or the 10
  • 11. Windows Phone 7 Guide for Android Application Developers camera. Microsoft provides a push notification service, called Microsoft Push Notification Service. In Android, multitasking is supported. In WP7, support for multitasking will be provided in the next release. In Android, you need to use third-party platforms like ADMob to publish advertisements in applications. Microsoft has made this task easier in WP7 by introducing Microsoft Advertising SDK for WP7. For more information, visit: Microsoft Advertising SDK for Windows Phone 7 Summary In this chapter we looked at the WP7 architecture and the Android and WP7 programming stacks. Now that you have a high-level idea of how the WP7 programming stack maps to the Android stack, we are now going to go one level deeper. In the next section, we will look at the user interface guidelines of WP7 applications. Related Resources To learn more about the topics covered in this blog, visit:  App Hub – Central Place for Windows Phone 7 development. Getting started, download tools and read all about Windows Phone 7 development  MIX ‟10 presentation on Windows Phone 7 Architecture by Istvan Cseri  Windows Phone 7 Development for Absolute Beginners. Video series that will help aspiring Windows Phone 7 developers get started.  App Hub Jump Start Tutorials  Introduction to WP7 programming on Codeproject.com Other Resources you may find useful:  Overview of the Windows Phone 7 Application Platform  Windows Phone 7 Team Blog  Windows Phone 7 Programming 11
  • 12. Windows Phone 7 Guide for Android Application Developers Chapter 2: User Interface Guidelines Microsoft‟s Windows Phone 7 (WP7) uses a novel user interface called Metro. WP7 sets itself apart with its clean and simple design and emphasizes on color and typography. In contrast to the application-focused design of Android, WP7 uses an information- centric design. Instead of an array of application icons, the start screen of a WP7 consists of dynamic tiles that display critical information at a glance to the user. The tiles are dynamic and they continuously display the up-to-date status of the applications. For example, they show you the next appointment on your calendar, or the number of new emails waiting for your attention. Users can personalize their phones by pinning the tiles that they care most about. WP7 introduces a new paradigm called hubs. Hubs bring related information together. There are six hubs, People, Pictures, Music + Videos, Marketplace, Office, and Games. The People hub, in the instance shown below, aggregates your address book contacts and Facebook friends. 12
  • 13. Windows Phone 7 Guide for Android Application Developers Designing the Application Interface While the design of the WP7 user interface is different from that of the Android, the core design principles are very similar. Like Android, in WP7 you need to keep in mind the compact screen, lower CPU, and limited memory while designing the applications. In WP7, users use one application at a time, with just one screen visible. Similar Application Design Goals Usability and UI design are not after thoughts, but are the primary goals behind applications on both the Android and WP7. 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 WP7 application. WP7 provides a complete set of UI controls designed for the phone. WP7 utilizes the same set of core multi-touch gestures as the 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 WP7 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: metaphors and direct manipulation with multi-touch. The need for immediate feedback and aesthetic appeal remains the same. 13
  • 14. Windows Phone 7 Guide for Android Application Developers Application User Interface Design While there are similarities in the design principles of the applications on both platforms, pay close attention to the user interface of the application for the WP7. It is best to take advantage of the unique features and strengths of WP7 platform. For the interface to provide a consistent experience across applications, applications on WP7 need to adopt the new Metro design guidelines. XML and XAML Android uses XML for mapping purposes. A part of the compilation reads the XML, performs translations, and generates Java. For example, in layout XMLs of Android, you need to set it as content view in Activity, after defining the whole UI. In WP7, XAML act as an instantiation language. XAML does not act as a mapping medium in WP7 as XML does in Android. The XML in a XAML document in WP7 contains the actual code needed for UI and needs not be transformed into code, as in case of Android. Controls and the Application Interface The WP7 development tools and SDK include a rich collection of Silverlight controls 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 WP7 Silverlight controls and corresponding Android controls. Android control Windows Phone 7 control Border Border ButtonView Button AbsoluteLayout Canvas CheckBox CheckBox GridView Grid HyperlinkButton ImageView Image ListView ListBox MediaController MediaElement 14
  • 15. Windows Phone 7 Guide for Android Application Developers Android control Windows Phone 7 control MultiScaleImage ViewGroup Panel EditText PasswordBox ProgressBar ProgressBar RadioButton, RadioButton RadioGroup ScrollView ScrollViewer SeekBar Slider LinearLayout StackPanel EditText TextBlock EditText TextBox MapView Map WebView WebBrowser Panorama Pivot TimePicker Timepicker DatePicker Datepicker ExpandableListView Gallery ImageSwitcher Spinner TableLayout TextSwitcher ViewFlipper 15
  • 16. Windows Phone 7 Guide for Android Application Developers Android control Windows Phone 7 control ZoomControl TabHost SlidingDrawer RatingBar Toggle button ToggleSwitch* * ToggleSwitch and Datepicker/Timepicker control are part of the Silverlight for Windows Phone Toolkit available on Codeplex: http://silverlight.codeplex.com/releases/view/55034 As you can see, WP7 offers controls that correspond to almost all Android controls. While the look and feel is different, they provide similar functionality. New Controls in Windows Phone 7 WP7 introduces a few novel controls that have no counterpart on the Android. Here are some of the examples:  A multi-scale image, with image data at various resolutions, is appropriate for allowing the user when zooming into a photo.  Panorama control is a multi-screen page and allows a page to span horizontally beyond the width of the phone.  The people hub is another great example. It allows a large amount of related information to be presented.  Pivot control, a novel control that is useful to manage views and display information that is logically divided in sections. 16
  • 17. Windows Phone 7 Guide for Android Application Developers Notifications Both Android and WP7 have notification services, but notifications play a key role in WP7. The 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 WP7 to show critical information. The notification service also display toast notifications that provide time sensitive information, such as an SMS. The toast notifications are shown for about 10 seconds, but the user may choose to ignore them. These are the same as Android toast notification. Android Functionality Windows Phone 7 Status bar Non-critical information that user Tile notifications notification may not respond to. That is informative to user Toast Time sensitive data that user may Toast Notifications notification not respond to Alerts Modal alerts that the user must Application respond to notifications 17
  • 18. Windows Phone 7 Guide for Android Application Developers Tool and Tab Bar vs. Application Bar WP7 features a versatile application bar. 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. If you are using action sheets in your Android application, application bar menus give you similar functionality. Android Functionality Windows Phone 7 Status bar Information about Status bar device Title bar: to show title Navigation, Title, Back button for back of application or activity Buttons for views or navigation actions Page title View and actions on Application bar Comparing Windows Phone 7 and Android Navigation WP7 application is a collection of multiple pages. Like on the Android, the user navigates through different Activities using widgets such as buttons and links. Like Android, on WP7 the Back button on the phone allows the user to navigate back between pages within an application, or across applications. It behaves much like the Back button in a browser. 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 WP7 phone, namely, Search and Home, have fixed behavior. 18
  • 19. Windows Phone 7 Guide for Android Application Developers Windows Phone 7 Frame and Page Structure Each WP7 application has a single frame, and it includes areas for:  A page where application content is rendered. This is the content where widgets or graphics are rendered.  A reserved space for the system tray and application bar. It also exposes certain properties, such as orientation to the application. System Tray and Application Bar On WP7, the system tray includes indicators for various system-level status information. The application bar includes the area for the most common application menus, which may include various data views or tasks. 19
  • 20. Windows Phone 7 Guide for Android Application Developers Page Structure of Windows Phone 7 Application The following diagram shows the structure of a typical WP7 data-bound application, which resembles 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 fast response. Splash screens are usually an image file of the entire size of the display. Usually the application starts with the home page, the main navigation page, with links for search, and other page widgets. 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, have the content of interest. For example, a list of all baseball teams. However, depending on requirement, the home page can also be the primary content page. This is a possible application usage scenario:  A user clicks one of the team links to visit the team details page (“Widget Details Page”) which can provide multiple views. The team details page may employ a pivot control or panorama to display different views such as the team summary and the list of all players (“List of Gadgets Page”) from that team  A user selects one of the baseball players and the application takes the user to the page with player statistics (“Gadget Details page”). The player statistics page uses controls such as textblocks, multi-scale images, or other multimedia using a MediaElement control  A user can also use the search widget to search and directly access the team page (“Widget Details Page”) or the player page (“Gadget Details Page”) 20
  • 21. Windows Phone 7 Guide for Android Application Developers Application Templates Eclipse does not provide the project template for Android applications. But Visual Studio provides numerous templates for WP7 application development to make your life easier. Functionality Visual Studio Template Eclipse Information drilldown Data-bound applications Not available applications Utility applications. For Windows Phone 7 utility Not available example, Bubble Level applications Games Windows Phone 7 Game Not available (XNA) applications Flexible template to design General Windows Phone 7 Not available any application applications 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. Lastly, the XNA based games application template gives you functionality like the OpenGL-ES application. Summary In this chapter we looked at the similarities between the application design goals of the Android platform and the WP7 platform. When you plan your WP7 application, you will be able to leverage your existing work on Android applications. We also looked at the application interface design to make sure you are taking advantage of the WP7 metro design that uses WP7 interface guidelines. You will find that the WP7 tools offer a large library of controls and gestures that have close counterparts on the Android. This chapter also showed you the use of innovative controls like panorama, and explore the use of live tiles to build an engaging WP7 experience. Related Resources To go deeper into the topic discussed, visit:  Windows Phone 7 User Interface Guidelines  Windows Phone 7 Developer Tools  Silverlight for Windows Phone toolkit on CodePlex  Design resources for Windows Phone 21
  • 22. Windows Phone 7 Guide for Android Application Developers Other Resources that you may find useful:  Application Page Model for Windows Phone 7  Frame and Page Navigation Overview for Windows Phone 22
  • 23. Windows Phone 7 Guide for Android Application Developers Chapter 3: The Developer and Designer Tools With the release of the Windows Phone 7 (WP7) developer tools, Microsoft brings the user-friendly, high productivity Visual Studio Development environment to WP7. As Android application developers you are familiar with Eclipse, and you can quickly migrate to WP7 developer tools and work with ease. A Comparison of Android and Windows Phone 7 Tools Visual Studio 2010 Express for Windows Phone is a full-featured Integrated Development Environment (IDE). Visual Studio 2010 facilitates designing, developing, and debugging of Windows Phone 7 applications. The other WP7 tools that help you in the development cycle of the Windows Phone application are:  Expression Blend  XNA Game Studio  Windows Phone Emulator The WP7 developer tools offer the complete functionality that is provided by the Android application developer tools. The following table gives an overview of the functionality of each of these tools. The table also indicates the equivalent tools you use for Android application development. Functionality Audience Android Windows Phone 7 tools tools Primary UI UI designers Defined in Expression Blend design: Colors, XML, any XML gradients, and tool animation  ADT UI UI design UI designers Visual Studio 2010 Express plug-in and and Expression Blend for  Third- programmer Windows Phone party tool s like DroidDraw Application Programmers Eclipse Visual Studio 2010 Express development for Windows Phone (coding) Game Programmers Eclipse XNA Game Studio development 23
  • 24. Windows Phone 7 Guide for Android Application Developers (coding) Testing / Testers Android Windows Phone Emulator in Emulation Emulator Visual Studio 2010 Express You can use the Android team structure and overall development process to build applications for Windows Phone 7. The WP7 toolset ensures that the entire team of designers, developers, and testers familiar with Android development tools will find it easy to migrate to the WP7 toolset. Development Life Cycle and Windows Phone 7 Developer Tools Expression Blend 4 and Visual Studio facilitate a close collaboration between designers and developers. Both these tools share the same file structure and source files. Expression Blend uses XAML for UI design and the XAML is consumed by Visual Studio. This system allows separation of responsibilities between the designer and the developer while allowing them to work together seamlessly. Project Management for Windows Phone 7 Like Eclipse, Visual Studio 2010 Express for WP7 is a fully-featured IDE. Visual Studio 2010 Express allows you to:  Manage the entire structure of the development project, the source, and the resource files  Configure the application codebase, known as Visual Studio Solution, as a collection of projects in a separate functional unit With Visual Studio 2010 Express, you can manage source files, share code, and manage the work among team members. Visual Studio integrates a compiler and a 24
  • 25. Windows Phone 7 Guide for Android Application Developers debugger. You can access both the compiler and the debugger either from the GUI or the command line. To create a sample application, do the following: 1. Start Visual Studio Express for WP7 from Start menu. 2. In Visual Studio Express, click File. 3. Click New Project. 4. In the New Project dialog box, select Windows Phone Application. 5. In the Name of the project text box, enter ShoppingList as the name of the project, and click OK. Visual Studio Express creates the new project. The Solution Explorer pane displays the solution that you created. This example solution has only the ShoppingList project. The project contains the sources, resources, and properties. Note: Visual Studio Express for WP7 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. You can also use Visual Studio Team System, which is designed for greater communication and collaboration among the development teams. 25
  • 26. Windows Phone 7 Guide for Android Application Developers The UI Design Tools The WP7 developer tools include:  Expression Blend  Visual Studio UI Designer WP7 uses Silverlight and a specific XML markup language for the UI specification. Visual Studio UI design tool is equivalent to the Eclipse ADT UI plug-in. As Android application developers you are familiar with Eclipse ADT UI plug-in and you will find it easy to use this tool. In our example, the main page for the ShoppingList solution, MainPage.xaml, is already open in the Visual Studio UI Designer tool for editing. To change the titles of the application and the current page, do the following: 1. Right-click the title MY APPLICATION and select Properties. 2. In the Properties window, select Text and enter SHOPPING LIST. You can also change the title of the page by entering my list in the Text property of the title. To change the title of a page, do the following: 1. Drag a Text box from the Toolbox and place it above the textblock. 2. Update the Text box‟s Text property to delete any existing entry. 26
  • 27. Windows Phone 7 Guide for Android Application Developers 3. Below Properties, click TextBox1, and enter txtItem to change the ID of the textbox to txtItem. 4. Resize the Text box by dragging its lower right corner so that its width is 300. 5. Drag a Button to the right of the TextBox. 6. Change the button‟s Content property to Add, and its ID to btnAdd. 7. Resize the button so that its width is 140. 8. Drag another TextBox and place it underneath the txtItem textbox. 9. Resize the new TextBox so that it covers the rest of the phone screen. 10.Update the ID of the new TextBox to txtList. 11.Update the Text property of the new TextBox to Nothing here yet!. Your application looks as shown below: 12.To start debugging, compile the application and launch, press F5 or click Debug The application starts the WP7 emulator, deploys, and runs the ShoppingList application. You can click Add. But the application does not respond because there is no code for the button you inserted in the previous steps. 27
  • 28. Windows Phone 7 Guide for Android Application Developers Note: You can use the context menus to add the event handlers or to set the control properties. The emulator‟s integration with Visual Studio allows for a direct manipulation of controls and makes it easy to add logic to the UI controls. Expression Blend for Windows Phone 7 Expression Blend for WP7 is a visual UI design tool that is suitable for designers. There is no exact equivalent to Expression Blend in Android development toolset. Expression Blend is like VS Design. With Expression Blend, you can:  Drag and drop UI elements to design the UI  You can layout the controls accurately up to pixels. You can easily create and use color palettes and gradients  Add special effects, such as reflections and shadows  Import Photoshop files and Android application resources to the Windows Phone application  Create fine application behavior and animations without any programming 28
  • 29. Windows Phone 7 Guide for Android Application Developers Expression Blend is for UI designers and Visual Studio Design is for programmers. Programmers can also use Visual Studio Design to integrate the application logic to the UI design. You can also use the Visual Studio UI design tool to design UI for applications. Both Expression Blend and Visual Studio Design have:  A single control set that provides accurate fidelity to their run-time visual representation. This feature allows you to easily visualize the application.  Same project structure and share the same source files for designers and developers.  Use or produce XAML, which is a Silverlight XML declarative markup language used for interface design. This feature allows a designer to work on the design using Expression Blend while the developer uses Visual Studio to design the logic behind the application. You can establish a smooth design and development workflow. 29
  • 30. Windows Phone 7 Guide for Android Application Developers Visual Studio Visual Studio has a simple to use, full-featured, and a configurable source editor. The editor tool has various features that are familiar to Eclipse users. The features of the editor include:  Flexible search  Rich editing  Format code  Auto-completion of code  Outline or hide code To add logic to the application, do the following: 1. To stop the running application, click Debug. 2. Click Stop Debugging. 3. Double click Add. The dialog displays MainPage.xaml.cs with a method btnAdd. 4. Click the MainPage class. 5. To add logic to the items that are added to the shopping list, edit the btnAdd_click method. 6. Enter the following code: string tStr = txtItem.Text;. Note: When you enter t for txtItem, Visual Studio displays the auto-completion dialog box. The Visual Studio equivalent for Eclipse auto-completion is called content assistant. 30
  • 31. Windows Phone 7 Guide for Android Application Developers 7. Enter the following code in the btnAdd_click method: if (!String.IsNullOrEmpty(tStr)) Note: 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. VS IntelliSense in Visual Studio VS IntelliSense is a feature of the IDE which uses history, code context, and .NET reflection for intelligent auto-completion. VS IntelliSense can suggest and complete variable names, parameters, classes, and method names. VS IntelliSense can also generate appropriate code where needed, as shown in the code below: To complete the event hookup, Visual Studio generates an empty stub for the event handler button1_click method. 31
  • 32. Windows Phone 7 Guide for Android Application Developers Code Snippets in Visual Studio Code Snippets in Visual Studio is equivalent to code templates in Eclipse. Code Snippets allows you to insert code fragments with a few clicks. Visual Studio contains a large number of snippets. These snippets help you to create their own snippets. You can also create an index and search for the code snippets by using the self-defined terms. To use a code snippet, do the following: 1. To start the Insert Snippet prompt, press CTRL+K CTRL+X 2. To insert a code snippet for an if statement in the code, select Visual C# followed by i The inserted snippet shows the parts of the code that you need to complete. private void btnAdd_Click(object sender, RoutedEventArgs e) { string tStr = txtItem.Text; if (!String.IsNullOrEmpty(tStr)) { if (true) { } } 3. To complete writing the code for the method, enter the required code so that the body of the method is complete as follows: string tStr = txtItem.Text; if (!String.IsNullOrEmpty(tStr)) { if (txtList.Text == “Nothin here yet”) { txtList.Text = “”; } txtList.Text += txtItem.Text + “n”; txtItem.Text = “”; } Visual Studio supports various refactoring mechanisms. You can select any piece of code and right-click the code to access the refactoring menu. 32
  • 33. Windows Phone 7 Guide for Android Application Developers Visual Studio Editor Visual Studio editor is customizable. Visual Studio editor allows you to define various keyboard shortcuts or create your own macros. Macros help you to automate repetitive actions by combining a series of commands and instructions. You can easily customize Visual Studio Editor to use shortcuts and keyboard combinations with which they are familiar. Instead of opening a separate window for each file, as in Eclipse, the default view in Visual Studio uses tabbed windows. You can change this behavior to suit your need. You can change the way in which various windows are docked within Visual Studio Shell. Building Applications Visual Studio Express for WP7 allows you to build the Visual Studio solution on demand. It allows you to separately build each project to make a part of the complete solution. Visual Studio uses an XML based, declarative build system called MSBuild. MSBuild is equivalent to Ant and Nant. You can access the builds either from the GUI or by using the command line for batch processing. MSBuild is flexible and allows you to create a specific target either as a debug build or as a release build. Windows Phone 7 Emulator The WP7 Emulator provides a virtualized environment in which you can deploy, debug, and test applications. The WP7 Emulator is designed to provide a comparative performance of an actual device and meets the peripheral specifications required for application development. To access the WP7 Emulator from Visual Studio, do any of the following:  From Deploy menu, click Deploy Solution  Press F5 in the key board, this starts the Emulator along with the debugger  Press CTRL+F5, this start only the Emulator 33
  • 34. Windows Phone 7 Guide for Android Application Developers The WP7 Emulator is like the Android Simulator. However, these differences are there:  In Android emulator you can have access to all the system application like Phone Dialer, Contacts, Mail, and Media Gallery. But the WP7 Emulator the system applications are not directly accessible to you. Though it can be accessed by the Launchers and Choosers.  Android supports various display height and width. Likewise, you can customize the Android emulator for parameters like Screen Height, Width, RAM size, and Sensors. As WP7 have specific hardware requirements, you cannot modify the WP7 Emulator for these hardware parameters. Debugging Visual Studio Express Phone 7 includes a symbolic debugger that you can use with the WP7 EMULATOR or with a remote device. Once the application loads in the debugger, you can view the variables in the application and control their execution. To work with debugger, do the following: 1. To start the debugger, press F5 2. In Textbox you previously created, enter napkins and click Add. Refer to the image below. Note: napkins is added after Nothing here yet! 3. In Visual Studio, click the light blue area to the left of the string tStr = txtItem.Text; line. Visual Studio inserts a breakpoint at that line. 34
  • 35. Windows Phone 7 Guide for Android Application Developers 4. Launch the debugger again using F5. When the application loads into the debugger, rest the mouse pointer over txtItem in the code 5. Click + in the pop-up to view the variable txtItem. Tracking Variables You can view the details of the variables such as the Type, Fields, and Properties. The dialog below shows how you can scroll up and down the Type Hierarchy to inspect the objects. You can set a watch on certain variables to keep them under observation continuously. To track variables, do the following: 1. Right-click txtList, and click Add Watch. The watch window displays the variable txtList. 2. Click + icon near txtList, to expand txtList. 35
  • 36. Windows Phone 7 Guide for Android Application Developers 3. To ensure that the control does not enter the if statement, press F10 to step through the code. if (txtList.Text == "Nothing here yet") { txtList.Text = ""; } You can observe in the Watch window that the value of txtList.Text is Nothing here yet. But it gets compared with Nothing here yet (with no exclamation point.) This is a bug in the code. Change the statement as shown below to add the exclamation point: if (txtList.Text == "Nothing here yet!") Note: While in the debugger, you can use the VS immediate mode where you can write the managed code instructions to modify or view the variables or execute code to help with debugging. 4. Update the code and re-launch the debugger by pressing F5. 5. To test the application, add items to the shopping list. 36
  • 37. Windows Phone 7 Guide for Android Application Developers A Note about Debugging You will observe that you can easily debug a WP7 application using the managed programming environment. Like Eclipse, the debugging in WP7 application is done entirely at the application level using the C# code and types. Note: The .NET framework includes two classes called Debug and Trace, which help you 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 returns true, Visual Studio does not respond. But if the statement returns false, the program enters the debugger. 37
  • 38. Windows Phone 7 Guide for Android Application Developers Summary In this chapter we looked at the Windows Phone 7 Developer Toolset. The Toolset includes the rich tools that are designed to support every step in the entire application development lifecycle. The design, development, and the testing tools are equivalent to the existing Android team roles and processes. The tight integration between the WP7 tools helps you to streamline the design, develop the workflow, and test the workflow. These tools provide an end-to-end functionality and are highly customizable. 38
  • 39. Windows Phone 7 Guide for Android Application Developers Chapter 4: C# programming This chapter discusses the C# features that map to the most common Java features. This chapter includes the code snippets, which help you to work faster with C# code. It describes important C# features that help you write safe code and enhance productivity. The chapter discusses the following features of C# programming:  Managed Programming  Class Declaration  Strong Typing  Class Constructors  Properties  Parameter Types  Access Privileges  Methods with multiple Parameters  Inheritance  Protected Access  Instance vs. Class Level Access  Abstract Classes  Interfaces  Polymorphism  Structs  Object Lifecycle: Creation and Deletion of Objects  Type Checking vs. Reflection  Exception Handling 39
  • 40. Windows Phone 7 Guide for Android Application Developers Managed Programming WP7 supports managed programming in C# and VB.NET. The C# compiler (and similarly, the VB compiler) compiles the C# (or VB.NET) code in an intermediate language (IL) byte code and metadata. The Common Language Runtime (CLR) executes the bytecode. The C# uses metadata to manage type safety, exception handling, and array bounds. CLR also manages memory and performs garbage collection. In Android, the Java code is compiled in a .class file, and the file is converted to a .dex file. The .dex file is optimized for low foot print on memory. The .dex file is then converted to an apk file, which is executed on an android platform. 40
  • 41. Windows Phone 7 Guide for Android Application Developers A Comparison between C# Features and Java Classes Class Declaration Like Java, C# does not separate class definition from class implementation. The compiler derives the metadata about the classes from class implementation. As in Java we can define multiple class definition in same file. C# also defines the multiple classes in same file. using System; // In java this is similar to import namespace FirstApplication // scope for classes. Same like package declaration in Java { class Person // only uses class implementation { private DateTime birthDate; // a private field accessible to this class private int ageOn(DateTime date) // a private method { TimeSpan span = date.Subtract(birthDate); //uses a .notation to invoke return span.Days; } public int age // this is a property. { Get // just a getter; it’s a read-only property { return this.ageOn(DateTime.Now); } } public Person( DateTime dob) // instance constructor. Same like Java { // it combines allocation and initialization birthDate = dob; } } class Program // Same like 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 } } } The following example shows the public signature of the class Person that consists of property, age, and constructor. 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 and to organize the code. You can access classes in other namespaces by referring to a fully-qualified name. You can refer to System.Console.WriteLine in the example above, where the console is in the System namespace. C# uniformly uses the “ ” notation for referring to all methods, fields, and properties. Strong Typing 41
  • 42. Windows Phone 7 Guide for Android Application Developers C# is a strongly typed language like Java. The types must be specified for variables and input/output parameters. 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 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 You often need to decide about whether to implement a member as a property or a method. In this case, the design pattern is identical for both Java and C#. As a general rule, use properties when you need to access data. To take any action on the data, use methods. Properties helps to abstract away from directly accessing the members of a class. This technique is similar to using accessors (getters) and modifiers (setters) in Java. You can make the property read-only by providing the getter, write-only by providing the setter, or read-write by providing both getter and setter. Parameter Types Like Java, C# uses the value parameters by default. C# does not have pointers. But C# allows the passing of parameters by using the ref modifier. Instead of pointers, you can use parameters with ref where you want to achieve an additional functionality in a method. In some cases, you need to use the reference parameters for better efficiency since they avoid data copying. void Foo (ref int x, int y) { x = 0; y = 0; } .. 42
  • 43. Windows Phone 7 Guide for Android Application Developers 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. This 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 Like Java, C# allows the access privileges on fields (for example, birthDate), properties (for example, age) and methods (for example, ageOn). 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 response 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. 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# has introduced the named parameters. The following example shows the comparative syntax for Java and C#. Java C# void addEmployee(string name, int void addEmployee(string name, int id, int age); id, int age); Off.addEmployee("Phil",2345, 23); Off.addEmployee("Phil",2345, 23); Off.addEmployee(name: "Phil", age:23, id:2345); Like Java, C# explicitly supports method overloading. C# differentiates between the methods that have the same name by using information about the parameter types. 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 (myClass obj, myClass before); 43
  • 44. Windows Phone 7 Guide for Android Application Developers The following code sample shows another example of method overloading: using System; namespace SecondApplication { struct Point // In contrast Java where struct not supported, C# structs are closer { // classes. 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 an 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 protected static int counter = 0; // Similar to protected variables in Java public string ID; protected Shape() //a constructor. Same name as the class name { counter++; // class variable being updated } public Point Origin // similar to Java class variables { 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 //Similar to Java, single iinheritance { 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; } 44
  • 45. Windows Phone 7 Guide for Android Application Developers 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 // 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; 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); 45
  • 46. Windows Phone 7 Guide for Android Application Developers } } 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 } } } Inheritance Like Java, C# also 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, whereas the class Square inherits from the class Rectangle. class Rectangle : Shape class Square : Rectangle In C#, the constructor of the base class is automatically invoked when you construct an instance of a derived class. However, a derived class can invoke a specific constructor of the base class if needed. This you can see in the constructor of the Square class. public Square(double s): base(s, s) //constructor. Calls parent constructor explicitly Like Java, a C# derived class may not override a method by redefining it. The class must use the keyword override in its method definition. public override bool contains(Point p) { … } Protected Access Like Java, in C#, you can use protected modifier to control access to fields, properties, and methods. 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 46
  • 47. Windows Phone 7 Guide for Android Application Developers Like Java, C# uses a static modifier to denote class level methods, fields, and properties. Everything else is at an instance level. In the above code example, the counter is a class level variable. protected static int counter=0; Abstract Classes The abstract classes are classes that cannot be instantiated. Java provides a syntax for an abstract class. The class Shape defined in the above C# code sample is an abstract class. The abstract classes requires that both Area and the method it contains must be overridden in any derived classes. abstract class Shape { public abstract double Area { get; } public abstract bool contains(Point p); Interfaces The Java and the C# interfaces are similar. In the sample code shown below, IThreeDShape defines an interface that is implemented by the Cube class. interface IThreeDShape { double volume { ... class Cube : Shape, IThreeDShape Polymorphism The working of polymorphism is the same in both Java and C#. You can pass a C# derived class as a parameter to a method that expects a base class. Similarly, you can pass a class that implements a particular interface, as a parameter to the method. The following sample code shows how to pass an object of the class Cube as a parameter, where the method expects an object of the class IThreeDShape. static void printVolume(IThreeDShape tdShape) { Console.WriteLine(“The volume is ” + tdShape.volume); } … 47
  • 48. Windows Phone 7 Guide for Android Application Developers Cube c = new Cube(4.0); SecondProgram.printVolume(c); Structs C# structs are like classes. C# structs can access modifiers and have constructors, methods, and properties. While a struct is a value, a class is a reference. struct Point { public double x; public double y; 48
  • 49. Windows Phone 7 Guide for Android Application Developers Object Lifecycle: Creation and Deletion of Objects The memory management in both Java and C# are similar. Both Java and C# performs automatic memory management. Instead of allocating memory, C# allows you to use the new operator to create objects and initialize them. When a code no longer accesses an object, the object becomes eligible for garbage collection. The .NET CLR garbage collector in C# periodically frees up the memory for such objects. With C#, you don‟t have to track the free memory usage. In rare circumstances, you may need to perform a cleanup at the time the object is destroyed. C# allows the use of destructors, but in practice this is rare. Type Checking vs. Reflection Java Reflection is a versatile feature that you can find both in C# and Java. You can use reflection to:  Get information 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. The following table maps the dynamic type checking in Java with its corresponding C# reflection features. Java Reflection Explanation C# Reflection Class1 instanceOf Is Object a subclass type.IsSubclassOf(typeof(BaseClass)) BaseClass or member? object.getClass() Is Object a member object.getType() or typeof of search from Does the object type.GetMethod(MethodName) implement the Method[] methods = method? c.getMethods(); Does the class type.GetMethod(MethodName) respond to the method? Method.invoke(..) Invoke a method type.InvokeMember(…) Exception Handling Exception handling is similar in both C# and Java. You use a use block to handle exceptions. You can also use either catch specific exceptions or a catch-all statements. The syntax for exception handling is similar in Java and C#. 49
  • 50. Windows Phone 7 Guide for Android Application Developers try { //block of code } //Most specific: catch (ArgumentNullException e) { Console.WriteLine(“{0}First exception caught.”, e); } //Least specific catch (Exception e) { Console.WriteLine(“{0}First exception caught.”, e); } 50
  • 51. Windows Phone 7 Guide for Android Application Developers A Comparison of Important Class Libraries Strings C# provides a comprehensive string class, which offers you all the features that you associate with this class. Java C# Notes Feature String String greeting = “Hello WP7!”; Int length = greeting.Length; Comparison String color = “pink”; Strings are compared using ==. If (color == “red”) They are compared lexicographically using compare. System.Console.WriteLine(“Matchin g colors!”); string name = “Joe”; if (string.compare(name, “Jack”) > 0) System.Console.WriteLine(name + “ comes later”); Concatenation System.Console.WriteLine Strings can be concatenated (greeting + " You rock!") 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); 51
  • 52. Windows Phone 7 Guide for Android Application Developers Arrays Arrays in C# are almost like arrays in Java. Java Feature C# Notes Arrays of int[] table; Array size is not a part of primitive types table = new int[3]; the array declaration. such as int, float string[] names = new string[3] Arrays are explicitly {"Peter", "Paul", "Mary"}; initialized. Multi-dim arrays Int[,] mAray; C# supports jagged of primitive types Int[][] jaggedArray; arrays, or arrays of string[][] singers = {new string[] arrays, and they need not {"Peter", "Paul", "Mary"}, new be rectangular. string[]{“Paul”,“Art”}}; Note: Arrays of strings, i.e. objects, work the same way. Mutable array of List<string> colors = new You can use Lists as a objects List<string>; //list of strings replacement for mutable Colors.Add(“Red”); arrays. Colors.Add(“Green”); Colors.Insert(1,”White”); You may also use String myColor = Colors[0]; //”Red” ArrayLists. Colors[colors.IndexOf(“Red”)] = “Pink”; // replace Red with pink Dictionaries C# provides a generic dictionary class that is similar to the HashTable 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. 52
  • 53. Windows Phone 7 Guide for Android Application Developers Java C# Notes Dictionary<string, int> d = new You can use Dictionary as Dictionary<string, int>(); a replacement for d.Add("Honda", 124); NSMutableDictionary. 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); } 53
  • 54. Windows Phone 7 Guide for Android Application Developers The New features of C# This section covers the following:  Generics  Operator Overloading  Delegates  Events  Generics 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. For example, the following code shows how to define a generic stack: 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. The use of generics is like generics in Java. 54
  • 55. Windows Phone 7 Guide for Android Application Developers Operator Overloading Operator Overloading allows you to define the implementation of user-defined operators for user-defined classes. Consider the following example of a complex number struct. Operator Overloading allows you to define a + operation by using 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; 55
  • 56. Windows Phone 7 Guide for Android Application Developers Delegates The functionality of delegates in C# is like the function pointers in C. In this design pattern, a class delegates another class even if which 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) { Console.WriteLine("Logging to file log: {0}", s); } } public class DelegatesTest { public delegate void StringDelegate(string s); public static void Main() { StringDelegate Writer, Logger; // define twp StringDelegate objects Writer = new StringDelegate(ConsoleLogger.WriteString); // Create delegates with appropriate methods Logger = new StringDelegate(FileLogger.LogString); Writer("Warning message 1n"); // Send to Console Writer delegate method Logger("Warning message 2n"); // 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 56
  • 57. Windows Phone 7 Guide for Android Application Developers 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. Events Events in C# are useful in the pub-sub (publisher and subscriber) design pattern. Events are powerful design patterns that are used for asynchronous programming. An object can publish a set of events that a subscriber can subscribe. When a publisher raises an event, all subscribers are notified. The publisher raises the event, but does not know who listens to it. The events are built by using delegates. using System; namespace DelegateExample { 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(); } } } 57
  • 58. Windows Phone 7 Guide for Android Application Developers 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:  NDoc  Sandcastle  Doxygen  Doc-O-Matic NDoc NDoc is a code documentation generator for Common Language Infrastructure. NDoc uses pluggable documenters to 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 Using NDoc To use NDocs to generate documentation, do the following: 1. Open your Windows Phone 7 project. 2. Select the class library for which you want to create documentation. 3. Right-click the class library, and click Properties. 58
  • 59. Windows Phone 7 Guide for Android Application Developers 4. In the left pane, click Build. 59
  • 60. Windows Phone 7 Guide for Android Application Developers 5. Select the XML documentation file check box. 6. Enter the file name. Note: NDoc uses this file for creating documentation. Build your class library, the documentation file is saved in the Debug or Release folder depending on your build configuration. You can see the documentation file in the XML format. You can use NDoc‟s help to get a fair idea of documenting your class library more effectively. Generating Better Documentation To generate better documentation, follow these tips:  Write elaborate code comments for your code. Elaborate comments make your documentation descriptive.  Each Public type and the Public and Protected members of the Public types should have an item describing the members.  The VS.NET C# code editor has a feature that makes it easy to create the basic code comments for each type and member. Consider the following code snippet: public class MyClass() { public MyClass(string s ) {} } Place your cursor just above the MyClass constructor, and press the '/' character three times. Visual Studio.NET creates the skeleton of a code comment block for that member: public class MyClass() { ///<summary> /// ///</summary> ///<param name=”s”></param> Public MyClass(string s) {} } You can use this method to any type or member that have code comment tags. NDoc supports a large number of documentation tags. You can use the tags to meet your requirements. 60
  • 61. Windows Phone 7 Guide for Android Application Developers In a code comment block, when you press the '<' key to start a new tag, Visual Studio.NET displays an Intellisense selector. This selector shows a list of code comment tags. This list does not display the additional tags that NDoc supports. You must add the additional tags manually. Using the NDoc GUI Utility To use the NDoc GUI Utility, do the following: 1. Double-click NDocGui.exe, to start NDocGUI. 2. Click Project, then click New. 3. In the section Select and Configure Documenter, select documentation type from the Documentation Type list. 4. Under Select and Configure Documenter, specify the parameters, such as Copyright text and Output directory. Note: The most important settings are in the Visibility section. Here you can configure the elements that you want to document, such as private variables, protected variables, and Namespaces without summaries. 5. Click Add. 6. In the Add Assembly Filename and XML Documentation Filename dialog, select the required EXE or DLL. NDoc processes the XML documentation file based on your selection. After building your project, find the compiled documentation for your class library in the output directory that is specified in the output message. NDocs vs. Javadoc  A Javadoc tool can be run on Windows, Mac OS, Unix, and BSD. However, NDoc can run only on Windows.  A Javadoc tool is for generating documents from java source files. The tool therefore accepts text as an input. NDoc accepts only binary files as an input.  A Javadoc tool generates documents in an HTML format by default. You need a third-party tool called Doclet to generate an output in other formats, such as CHM, RTF, PDF, and postscript. NDoc can generate documents in various formats, such as MSDN, Linear HTML, and JavaDoc. Summary 61
  • 62. Windows Phone 7 Guide for Android Application Developers In this chapter, we looked at C# programming from the perspective of a Java developer. C# is a strongly typed, object-oriented programming language that uses static binding. Several C# concepts are similar to the Java concepts. The knowledge of Java and object oriented programming will help you to master C# quickly. We also looked at NDocs, which is the API documentation tool for Windows Phone 7. Related Resources To go deeper into C# and Java, visit:  http://www.25hoursaday.com/CsharpVsJava.html To go deeper into NDocs, visit:  http://ndoc.sourceforge.net/  http://shfb.codeplex.com/ – Sandcastle Summary 62
  • 63. Windows Phone 7 Guide for Android Application Developers Chapter 5: A Comparison of Application Life Cycles in Windows Phone 7 and Android The Windows Phone 7 (WP7) execution model improves user experience by cutting down on response time and offering seamless navigation among applications. To achieve this, WP7 prioritizes the foreground application and tombstones other open applications. Android on the other hand, saves all the application states and displays only the foreground application. Android suspends an open application when a user starts another application. The suspended application remains alive in the phone memory. WP7 activates and deactivates applications dynamically to enable seamless navigation by limiting the phone to run one application at a time. The WP7 execution model provides users with a consistent navigation experience between applications. In Android, users open applications using the launcher screen. On the launcher screen, all the applications are listed as icons. In WP7, users navigate forward by launching applications from the installed Applications List or from a tile on the Start screen. In WP7, users can use the Back button on the phone to navigate backwards to a page in a running application. With this Back button, users can also navigate through a stack of previously running applications. This WP7 functionality is similar to Android‟s backward navigation. All Android devices have the Back button on the phone. A user can navigate to previous screens of applications until he reaches the home screen of phone. The Android applications consist of various components, such as Activity, Services, ContentProvider, and Broadcast receivers. These components are not available in WP7 except for an Activity which can be mapped to a Page in WP7. Multitasking in Android and Windows Phone 7 Android supports multitasking and provides seamless navigation between applications. WP7 achieves seamless navigation using application tombstoning. Android puts applications in the background using the Service component. The Service component runs in the background even if your application is not in foreground until the application‟s task finishes or stopService is called. The upcoming version of WP7 will support multitasking. The WP7 navigation model allows natural navigation, similar to a browser‟s Back button. The last accessed 63
  • 64. Windows Phone 7 Guide for Android Application Developers application state is preserved as a user navigates across applications using the Back button on the phone. Tombstoning of Applications in Windows Phone 7 Tombstoning is a process by which WP7 deactivates an application when a user navigates away from this application. WP7 keeps a record of the tombstoned application and stores the latest data accessed by this application. If the user returns to a tombstoned application, WP7 reactivates this application. The user can access the reactivated application by using a phone‟s Back button. Consider the following example. A user is composing a blog with WordPress. He pressed the Start button to go to the Start screen. WP 7 deactivated the WordPress application. The user then accessed Facebook. While in Facebook, the user pressed the Back button. The Start screen appeared. When the user pressed the Back button again, WordPress appeared exactly in the same way as she had viewed it the last time. The following table describes the user events and compares the corresponding behavior in Android and Windows Phone 7. User Action or Event Android Behavior Windows Phone 7 Behavior An incoming phone call or Running application is Running application is SMS moved to the background deactivated but is still in the memory User presses the Home Running application is Running application is button on the phone moved to the background, deactivated current activity will be paused but the application is still in memory User starts another Background application is The upcoming version of application from the moved to foreground with WP7 will support multitasking menu the earlier saved state multitasking User navigates between No navigation occurs Deactivated or applications using the when Back button is tombstoned application is Back button on the phone pressed when user is at activated to the earlier the home screen of the saved state phone. Life Cycle of a Windows Phone 7 Application 64
  • 65. Windows Phone 7 Guide for Android Application Developers There is no similarity between the Android life-cycle stages with the WP7‟s Page stage. Activity is the only component that can be mapped with a Page in WP7. The following events take place during the life cycle of a WP7 application: Launching An application is launched when it is started by all other means except when the user navigates to it using the Back button. Whenever a user opens an application, WP7 creates a new instance of the application. In Android, when an application launches a new process a new instance of Dalvik VM is allocated to the application. The application runs within that process. Each application runs in its own process and VM instance. Do not store the state data when the launching event is raised. The launching event is raised even before application is visible to the user. Storing data at this stage may increase the startup time of the application. Running After launching, the application goes into the running stage. In this stage, the application manages its own state as the user navigates through the different pages of the application. In the running stage, settings and the persisted data are saved. This reduces the data that you need to save when the application‟s stage changes. However, the decision to save data in this stage is optional. If the size of the persisted data is not large, you need not save the data. Closing Your application comes across this event when the user presses the Back button on the phone, when he is in the application‟s first page. In the handler for this event, you can save data to an isolated storage. This action is similar to handling the Destroyed() method in Android. In Android, you cannot close an application after launching. Each activity in the application can be finished but the application process remains in the memory. Deactivating WP7 deactivates your application in the following scenarios:  A user opens another application  A user locks the phone screen  An event accesses the Launcher or Chooser APIs  A user presses the Windows button to open the Start screen on the phone  A user presses the Search button on the phone In the handler for this event, you must save the transient data to the state property and the persistent data to the isolated storage. This helps maintaining consistent user experience after the user activates the application again. 65