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.

Ever since the release of Windows Phone 7 (WP7) platform, developers from aroundthe globe rushed to develop applications for this platform. Now, WP7 devices areavailable with manufacturers all over the world. A large number of applications arealready available in the WP7 marketplace.

For

WP7, Microsoft went back to the drawing board to figure out what phone usersreally want, and built a phone from the ground up. The operating system, the userexperience, and the application development platform have all been engineeredwith users in mind. The revenue opportunities in the Windows Phone marketplace,accompanied by a great set of development tools, make WP7 a very attractivedestination for developers to build applications and games.

The Developer Tools

Microsoft recommends using these tools for WP7 application development. Thistoolset is free and can be downloaded fromhere. The toolset includes:

can rely on, WP7defines a minimum set of hardware specifications that all phones must meet. Theyinclude:



ARM7 CPU



A DirectX capable GPU



Camera



Multi-touch capacitive display



Standard sensors include:

o

A-GPS

Windows Phone 7 Guide for AndroidApplicationDevelopers

6

o

Accelerometer

o

Compass

o

Proximity and light sensors

There are three standard buttons on the phone:

Back, Start, and Search. As we willsee in a subsequent section, these buttons provide an easy and natural navigationmodel for the user.

In WP7, Microsoft provides most of the device driver code. A device manufacturerhas to write very little code

specific to their device. Thisimproves the consistencyand quality across various devices. WP7 takes advantage of hardware accelerationthrough encapsulation layers, such as DirectX or XNA.

WP7 applications use managed programming and run within sandboxed

environments. For more details about WP7 architecture, watch theMIX‟10presentation

by Istvan Cseri, a WP7 architect.

Windows Phone 7 Guide for AndroidApplicationDevelopers

7

Comparing the Programming StackofWindows Phone 7with Android

The Application Model shown above provides services, such as installation andupdate, for managing the application lifecycle. The UI model helps to manageapplication user interface. Applications are built using various WP7 frameworks.

This table gives an overview of the WP7 frameworks that provide featurescomparable to the Android programming layers.

AndroidFrameworks

Functionality

Windows Phone 7

Frameworks

AndroidApplicationFramework

Application UI, Deviceintegration (sensors,camera)

Windows Phone 7

PhoneFramework, Silverlightcontrols

AndroidApplicationFramework

Graphics, Animation, Media

XNA for games or Silverlightmedia and graphics forothers

AndroidLibraries

Base services, Networking,Text, XML, storage

Common Base Library

Android runtime(Dalvik)+ Linux kernel

Windows Phone 7

Windows Phone 7 Guide for AndroidApplicationDevelopers

8

Android andWindows Phone 7

StacksSide

bySide

This table compares the Android and WP7 Frameworks side by side.

Managed Code

In Android, every application runs in its own process, with its own instance of theDalvik virtual machine. WP7 only supports “managed code” applications using C# orVB.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. CLRprovides garbage collection and there is no memory management to worry about orpointers to take care of. The WP7 application stack is built on the .NET compactframework 3.7. As Dalvik virtual machine is optimized for mobile devices, the .NETcompact framework is optimized for resource constrained devices and is designedto be portable across various hardware platforms.

Networking stacks: such as HTTP and the Windows CommunicationFoundation (WCF). WCF provides an easy interface with XML and SOAPservices across theWeb, 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 inremote 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 businessapplications and XNA for games. However, you can certainly develop great gamesusing Silverlight animation.

Windows Phone 7 Guide for AndroidApplicationDevelopers

10

Android applications

Windows Phone 7

counterparts

UI using activity(containswidgets) with navigationbetween them

Silverlight applications with pagesconnected by flows

2D or 3D games builtwithOpengl-ES

XNA games with 2D / 3D graphicsand Xbox connectivity

XNA for Games

For a high performance game, XNA is the right option. XNA framework, originallydeveloped for XBOX, provides hardware accelerated 2D and 3D rendering andbitmap graphics. XNA

also provides gamer services such as authentication andconnectivity with XBOX Live, as well asProfiles andLeaderboards.

Silverlight Controls and Media

If you use Android activities and widgets, you will find a large set of Silverlight UIcontrols specifically designed for the OS. WP7 UI components are designed formulti-touch. Silverlight uses a declarative language called Extensible ApplicationMarkup Language (XAML) to specify user interfaces. You can use separate code-behind files, written in C# orVB.NET, to respond to events or manipulate thecontrols.

Silverlight provides high performance audio and video with variety of CODECs. Itsupports both vector and bitmap graphics with hardware acceleration. As opposedto a file system, Silverlight provides sandboxed storage, called isolated Storage, tostore the application-specific data. With the isolation of storage, one applicationcannot 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 Explorerbased browser control in your application for HTML UI. Windows Phone Frameworklayer also provides interfaces to various sensors, such as the accelerometer or theWindows Phone 7 Guide for AndroidApplicationDevelopers

In Android, multitasking is supported. In WP7, support for multitasking will beprovided in the next release. In

Android, you need to use third-party platforms likeADMob to publish advertisements in applications. Microsoft has made this taskeasier 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 WP7programming stacks. Now that you have a high-level idea of how the WP7programming stack maps to the Android stack, we are now going togo one leveldeeper. In the next section, we will look at the user interface guidelines of WP7applications.

uses a novel user interface called Metro. WP7sets itself apart with its clean and simple design and emphasizes on color andtypography.

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 WP7consists ofdynamic 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 theapplications. For example, they show you the next appointment on your calendar,or the number of new emails waiting for your attention. Users can personalize theirphones by pinning the tiles that they care most about.

WP7 introduces a new paradigm called hubs.Hubs bring related informationtogether. There are six hubs, People, Pictures, Music + Videos, Marketplace, Office,and Games. ThePeople hub, in the instance

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 thatis critical to the user. Your key design principles from the Android application willget carried over:

metaphors and direct manipulation with multi-touch. The need forimmediate feedback and aesthetic appeal remains the same.

Windows Phone 7 Guide for AndroidApplicationDevelopers

14

Application User Interface Design

While there are similarities in the design principles of the applications on bothplatforms, pay close attention to the user interface of the application for the WP7. Itis best to take advantage of the unique features and strengths of WP7 platform.

For the interface to provide a consistent experience across applications, applicationson WP7 need to adopt the newMetro design guidelines.

XML andXAML

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 mappingmedium in WP7 as XML does in Android. The XML in aXAML

document in WP7contains the actual code needed for UI and needs not be transformed into code, asin case of Android.

Controls andthe Application Interface

TheWP7 development tools and SDK

include a rich collection of Silverlight controlsthat are designed specifically for usability and aesthetics. While you can create yourown controls, it is best to use the standard controls wherever possible. Thesestandard controls respond to theme changes and provide a consistent userinterface.

The following table shows the mapping between WP7 Silverlight controls andcorresponding 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

Windows Phone 7 Guide for AndroidApplicationDevelopers

15

Android control

Windows Phone 7

control

MultiScaleImage

ViewGroup

Panel

EditText

PasswordBox

ProgressBar

ProgressBar

RadioButton,RadioGroup

RadioButton

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

Windows Phone 7 Guide for AndroidApplicationDevelopers

16

Android control

Windows Phone 7

control

ZoomControl

TabHost

SlidingDrawer

RatingBar

Toggle button

ToggleSwitch*

* ToggleSwitch and Datepicker/Timepicker control are part of the Silverlight forWindows 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. Hereare some of the examples:



A multi-scale image, with image data at various resolutions, is appropriatefor allowing the user when zooming into a photo.



Panorama control is a multi-screen page and allows a page to spanhorizontally beyond the width of the phone.



The people hub is another great example. It allows a large amount of relatedinformation to be presented.



Pivot control, a novel control that is useful to manage views and displayinformation that is logically divided in sections.

Windows Phone 7 Guide for AndroidApplicationDevelopers

17

Notifications

Both Android and WP7 have notification services, but notifications play a key role inWP7. The tiles are used to display non-critical information without disrupting whatthe user is doing. If you are using status bar notifications in Android, you can usetile notification as a replacement in WP7 to show critical information.

The notification service also display toast notifications that provide time sensitiveinformation, such as an SMS. The toast notifications are shown for about 10seconds, but the user may choose to ignore them. These are the same as Androidtoast notification.

Android

Functionality

Windows Phone7

Status barnotification

Non-critical information that usermay not respond to. That isinformative to user

Tile notifications

Toastnotification

Time sensitive data that user maynot respond to

Toast Notifications

Alerts

Modal alerts that the user mustrespond to

Applicationnotifications

Windows Phone 7 Guide for AndroidApplicationDevelopers

18

Tool and TabBar vs.ApplicationBar

WP7

features a versatileapplication bar. The application bar can include up to 4 ofthe most common views or application tasks. You can also use application barmenus for additional context-sensitive tasks. If you are using action sheetsin yourAndroid application, application bar menus give yousimilar functionality.

Android

Functionality

Windows Phone 7

Status bar

Information aboutdevice

Status bar

Title bar: to show titleof application or activity

Navigation, Title,Buttons for views oractions

Back button for backnavigation

Page title

View and actions onApplication bar

ComparingWindows Phone 7

and Android Navigation

WP7 application is a collection of multiple pages. Like on the Android, the usernavigates through different Activities using widgets such as buttons and links.

Like

Android,onWP7 theBack

button

on the phone

allows the user to navigateback between pages within an application, or across applications. It behaves muchlike theBack

button in a browser. TheBack

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

button means to your user andplan to override it appropriately. For example, you may decide to pause a gamebyusing theBack

button

on the Phone.

The other two hardware buttons on the WP7 phone, namely, Search and Home,have fixed behavior.

Windows Phone 7 Guide for AndroidApplicationDevelopers

19

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 wherewidgets or graphics are rendered.



A reserved space for the system tray and application bar. It also exposescertain properties, such as orientation to the application.

System Tray and Application Bar

On WP7, the system tray includes indicators

for various system-level statusinformation. The application bar includes the area for the most common applicationmenus, which may include various data views or tasks.

Windows Phone 7 Guide for AndroidApplicationDevelopers

20

Page Structure ofWindows Phone 7

Application

The following diagram shows thestructure 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 splashscreen, designed to welcome the user, as well as to create the perception of fastresponse. 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, withlinks for search, and other page widgets. Consider an application thatshowsinformation about baseball teams and their players. The primary content page,marked as the widgets page in the above diagram, have the content of interest.

Forexample,

a list of all baseball teams. However, depending on requirement, thehome page can also be the primary content page.

This is a possibleapplicationusage scenario:



A user clicks one of the team links to visit the team details page (“WidgetDetailsPage”) which can provide multiple views. The team details page mayemploy a pivot control or panorama to display different views such as theteam summary and the list of all players (“List ofGadgets

Page”) from thatteam



A user selects one of the baseball players

and the applicationtakes the userto the page with player statistics (“Gadget Details page”). The playerstatistics page uses controls such as textblocks, multi-scale images, or othermultimedia using a MediaElement control



A user can also use the search widget to search and directly access the teampage (“Widget Details

Page”)or the player page (“GadgetDetails

Page”)

Windows Phone 7 Guide for AndroidApplicationDevelopers

21

Application Templates

Eclipse does not provide the project template for Android applications. But

You can choose the Windows Phone application template to either create anapplication with functionality similar to the view-based or the window-basedAndroid application type. Lastly, the XNA based games application template givesyou functionalitylike

the OpenGL-ES application.

Summary

In this chapter we looked at the similarities between the application design goals ofthe 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 takingadvantage of the WP7 metro design that uses WP7 interface guidelines. You willfind that the WP7 tools offer a large library of controls and gestures that have closecounterparts on the Android.

This chapter also showed you theuse of innovative controls like panorama, andexplore the use of live tiles to build an engaging WP7 experience.

are familiar with Eclipse, and youcan quicklymigrate to WP7 developer tools and work with ease.

A Comparison of Android andWindows Phone 7

Tools

Visual Studio 2010 Express for WindowsPhone is a full-featured IntegratedDevelopment Environment (IDE). Visual Studio 2010 facilitates designing,developing, and debugging of Windows Phone 7 applications. The other WP7 toolsthat 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 theAndroid application developer tools. The following table gives an overview of thefunctionality of each of these tools. The table also indicates the equivalent tools youuse for Android application development.

Functionality

Audience

Androidtools

Windows Phone 7

tools

Primary UIdesign: Colors,gradients, andanimation

UI designers

Defined inXML, any XMLtool

Expression Blend

UI design

UI designersandprogrammers



ADT UIplug-in



Third-party toollikeDroidDraw

Visual Studio 2010 Express

and Expression Blend

forWindows Phone

Applicationdevelopment(coding)

Programmers

Eclipse

Visual Studio 2010 Express

for Windows Phone

GamedevelopmentProgrammers

Eclipse

XNA Game Studio

Windows Phone 7 Guide for AndroidApplicationDevelopers

24

You can use the Android team structure and overall development process to buildapplications for Windows Phone 7. The WP7 toolset ensures that the entire team ofdesigners, developers, and testers familiar with Android development tools will findit easy to migrate to the WP7 toolset.

Development LifeCycle andWindows Phone 7

DeveloperTools

Expression Blend 4 and Visual Studio facilitate a close collaboration betweendesigners and developers.

Both these tools share the same file structure and source files. Expression Blenduses XAML for UI design and the XAML is consumed by Visual Studio. This systemallows separation of responsibilities between the designer and the developer whileallowing them to work together seamlessly.

familiar withEclipse ADT UI plug-inand youwill findit easy to use this tool. In our example, the main page for the ShoppingListsolution, MainPage.xaml, is already open in the Visual Studio UI Designer tool forediting.

To change the titles of the application and the current page, do the following:

1.

Right-click the title MY APPLICATION and selectProperties.

2.

In theProperties

window, selectText

and enter SHOPPING LIST.

You can also change the title of the page by entering my list in theText

property ofthe title.

To change the title of a page, dothe following:

1.

Drag a Text box from theToolboxand place it above the textblock.

2.

Update the Text box‟sText

property to delete any existing entry.

Windows Phone 7 Guide for AndroidApplicationDevelopers

27

3.

BelowProperties, clickTextBox1, and entertxtItem

to change the ID ofthe textbox totxtItem.

4.

Resize

the Text box by dragging its lower right corner so that its width is300.

5.

Drag aButton

to the right of theTextBox.

6.

Change the button‟sContentproperty toAdd, and itsID

tobtnAdd.

7.

Resize the button so that its width is 140.

8.

Drag anotherTextBox

and place it underneath thetxtItem

textbox.

9.

Resize the newTextBox

so that it covers the rest of the phone screen.

10.Update theID

of the new TextBox totxtList.

11.Update theTextproperty of the new TextBox toNothing here yet!.

Your application looks as shown below:

12.To start debugging, compile the application and launch,

pressF5

or clickDebug

The application starts the WP7 emulator,deploys,

and runs

the ShoppingListapplication. You can clickAdd.But the application does not respondbecause

thereis nocode for the button you inserted in the previous steps.

Windows Phone 7 Guide for AndroidApplicationDevelopers

28

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

Expression Blend forWindows 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 islike

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 createand use color palettes and gradients

Create fine application behavior and animations without any programming

Windows Phone 7 Guide for AndroidApplicationDevelopers

29

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 tothe UI design. You can also use the Visual Studio UI design tool to design UI forapplications.

Both Expression Blend and Visual Studio Design have:



A single control set that

provides accurate fidelity to their run-time visualrepresentation. This feature allows you to easily visualize the application.



Same project structure and share the same source files for designers anddevelopers.



Use or produce XAML, which is a Silverlight XML declarative markuplanguage used for interface design. This feature allows a designer to work onthe design using Expression Blend while the developer uses Visual Studio todesign the logic behind the application. You can establish a smooth designand development workflow.

Windows Phone 7 Guide for AndroidApplicationDevelopers

30

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 featuresof 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, clickDebug.

2.

ClickStop Debugging.

3.

Double clickAdd. The dialog displaysMainPage.xaml.cs

with a methodbtnAdd.

4.

Click theMainPage

class.

5.

To add logic to the items that are added to the shopping list, edit thebtnAdd_click

method.

6.

Enter the following code: string tStr = txtItem.Text;.

Note: When you enter t for txtItem, Visual Studio displays the auto-completiondialog box. The Visual Studio equivalent for Eclipse auto-completion is calledcontent assistant.

VS IntelliSense is a feature of the IDE which uses history, code context, and .NETreflection for intelligent auto-completion. VS IntelliSense can suggest and completevariable names, parameters, classes, and method names. VS IntelliSense can alsogenerate appropriate code where needed, as shown in thecode

below:

To complete the event hookup, Visual Studio generates an empty stub for the eventhandlerbutton1_click

method.

Windows Phone 7 Guide for AndroidApplicationDevelopers

32

Code Snippets in Visual Studio

Code Snippets in Visual Studio is equivalent to code templates in Eclipse. CodeSnippets allows you to insert code fragments with a few clicks. Visual Studiocontains a large number of snippets. These snippets helpyou

to create their ownsnippets. You can also create an index and search for thecode snippets by usingthe self-defined terms.

To use a code snippet, do the following:

1.

To start theInsert Snippet

prompt, pressCTRL+K

CTRL+X

2.

To insert a code snippet for an if statement in the code, selectVisual C#

followed by

i

The inserted snippet shows the parts of the code thatyou 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 sothat 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 ofcode and right-click the code to access the refactoring menu.

Windows Phone 7 Guide for AndroidApplicationDevelopers

33

Visual StudioEditor

Visual Studio editor is customizable. Visual Studio editor allows you to definevarious keyboard shortcuts or create your own macros. Macros help you toautomate repetitive actions by combining a series of commands and instructions.You

can easily customize Visual StudioEditor to use shortcuts and keyboardcombinations with which they are familiar.

Instead of opening a separate window for each file, as in Eclipse, the default view inVisual 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 StudioShell.

Building Applications

Visual Studio Express for WP7 allows you to build the Visual

Studio solution ondemand. It allows you to separately build each project to make a part of thecomplete solution.

is equivalent to Ant and Nant. You can access the builds either from the GUI or byusing the command line for batch processing. MSBuild is flexible and allows you tocreate a specific target either as a debug build or as a release build.

Windows Phone 7Emulator

TheWP7 Emulatorprovides a virtualized environment in which you can deploy,debug, and test applications. TheWP7 Emulatoris designed to provide acomparative performance of an actual device and meets the peripheralspecifications required for application development.

To access the WP7 Emulator

fromVisual Studio,doany of the following:



FromDeploy

menu, clickDeploy Solution



PressF5

in the key board, this starts

the Emulator

along with the debugger



PressCTRL+F5,

this

start only the Emulator

Windows Phone 7 Guide for AndroidApplicationDevelopers

34

TheWP7 Emulator

islike

the AndroidSimulator.However,

these differences arethere:



InAndroid emulator you can have access to all the system applicationlike

Phone Dialer, Contacts, Mail,andMedia Gallery. But theWP7 Emulator

thesystem

applications

are not directly accessible toyou. Though it can beaccessed bythe Launchers andChoosers.

Visual Studio Express Phone 7 includes a symbolic debugger that you can use withtheWP7 EMULATORor with a remote device. Once the application loads in thedebugger, you can view the variables in the application and control their execution.

To work with debugger, do the following:

1.

Tostart

the debugger, pressF5

2.

InTextbox

you previously created, enternapkins

and clickAdd. Refer tothe 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.

Windows Phone 7 Guide for AndroidApplicationDevelopers

35

4.

Launch the debugger again usingF5.When the application loads into thedebugger, rest the mousepointer overtxtItem

in the code

5.

Click+

in the pop-up to view the variabletxtItem.

Tracking Variables

You can view the details of the variables

such as theType,Fields, andProperties.Thedialog

below shows how you canscroll

up and down theTypeHierarchy toinspect the objects.

You can set a watch on certain variables to keep them under observationcontinuously.

To track variables, do the following:

1.

Right-clicktxtList, and clickAdd Watch.

The watch window displays the variabletxtList.

2.

Click+ iconnear txtList,

to expand txtList.

Windows Phone 7 Guide for AndroidApplicationDevelopers

36

3.

To ensure that the control does not enter the if statement, press F10 to stepthrough the code.

if

(txtList.Text == "Nothing here yet")

{

txtList.Text = "";

}

Youcan observe in theWatch

window that the value of txtList.Text isNothing hereyet.

But it gets compared withNothing here yet

(with no exclamation point.) This isa 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 canwrite the managed code instructions to modify or view the variables or executecode to help with debugging.

4.

Update the code and re-launch the debugger by pressingF5.

5.

To test the application, add items to theshopping list.

Windows Phone 7 Guide for AndroidApplicationDevelopers

37

A Note about Debugging

You will observe that you can easily debug a WP7 application using the managedprogramming environment.Like

Eclipse, the debugging in WP7 application is doneentirely at the application level using the C# code and types.

Note: The .NET framework includes two classes called Debug and Trace, which helpyou to write run-time debug messages to the output window. C# also supports anassert statement, which is evaluated at run time. If the statement returns true,Visual Studio does not respond. But if the statement returns false, the programenters the debugger.

Windows Phone 7 Guide for AndroidApplicationDevelopers

38

Summary

In this chapter we looked atthe Windows Phone 7 Developer Toolset. The Toolset

includes the rich tools that are designed to support every step in the entireapplication development lifecycle. The design, development, and the testing toolsare equivalent to the existing Android team roles and processes. The tightintegration between the WP7 tools helps

you to streamline the design, develop theworkflow, and test the workflow. These tools provide an end-to-end functionalityand are highly customizable.

Windows Phone 7 Guide for AndroidApplicationDevelopers

39

Chapter 4: C# programming

This chapter discusses the C# features that map to the most common Javafeatures. This chapter includes the code snippets, which help you to work fasterwith C# code. It describes important C# features that help you write safe code andenhance 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

Windows Phone 7 Guide for AndroidApplicationDevelopers

40

Managed Programming

WP7 supportsmanaged programming

in C# and VB.NET.

The C# compiler (and similarly, the VB compiler) compiles the C# (or VB.NET) codein an intermediate language (IL) byte code and metadata. The Common LanguageRuntime (CLR) executes the bytecode. The C# uses metadata to manage typesafety, exception handling, and array bounds. CLR also manages memory andperforms 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 printon memory. The .dex

file is then converted to anapk

file, which is executed on anandroid platform.

Windows Phone 7 Guide for AndroidApplicationDevelopers

41

A Comparison between C# Features and Java Classes

Class Declaration

Like Java, C# does not separate class definition from class implementation. Thecompiler derives the metadata about the classes from class implementation. As inJava we can define multiple

class definition in same file.

C# also defines themultiple classes in same file.

using System; // In java this is similar to import

namespace FirstApplication // scope for classes. Same like package declaration in Java

{

classPerson

// only uses class implementation

{

privateDateTime

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;

}

}

classProgram

//Same like Java, another class in the same file.

{

static void Main(string[] args) // main entry point into the program

{

Person

p = newPerson(newDateTime(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 consistsof property, age, and constructor.

Instead of using theimport

statement in Java, C# employs ausing

statement torefer to the metadata of other classes. The namespace declaration that is shown atthe top of the file is used to declare thescope and to organize the code. You canaccess classes in other namespaces by referring to a fully-qualified name. You canrefer to System.Console.WriteLine in the example above, where the console is inthe System namespace.

Like Java, C# uses instance constructors to create and initialize instances. Forexample: p is an instance of the Person class. You can construct and initialize pwith a given birthdate, in a single statement.

Person

p =new

Person(newDateTime(1973,11,12));

Properties

You

often need to decide about whether to implement a member as a property or amethod. In this case, the design pattern is identical for both Java and C#. As ageneral rule, use properties when you need to access data. To take any action onthe 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) inJava. You can make the property read-only by providing the getter, write-only byproviding 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. ButC# 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 additionalfunctionality in a method. In some cases, you need to use the reference parametersfor better efficiency since they avoid data copying.

void

Foo

(ref

int x, int y)

{

x =0;

y = 0;

}

..

Windows Phone 7 Guide for AndroidApplicationDevelopers

43

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 representsthe parameters that must be initialized by the called method before returning. Thisdesign pattern is often used to return the error in addition to the value of thefunction.

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 accessprivileges.

In the above example, the compiler gives an error response onp.birthDate sincethat variable is private. Therefore p.birthDate is not accessible from the Programclass. Similarly, the ageOn method is also private and inaccessible from theProgram class.

Methods withMultiple Parameters

Both Java and C# support methods with multiple parameters. While C# traditionallyuses positional and unnamed parameters, the latest version of C# has introducedthe named parameters. The following example shows the comparative syntax forJava and C#.

Java

C#

void addEmployee(string name, intid, int age);

void addEmployee(string name, intid, 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 themethods that have the same name by using information about the parametertypes. The following code sample shows how C# differentiates between methodsthat 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);

Windows Phone 7 Guide for AndroidApplicationDevelopers

44

The following code sample shows another example of method overloading:

Like Java, C# also uses a single inheritance mechanism. Inheritance is specified bylisting the parent class after the class name as shown below. In this example, theclass Rectangle inherits from the class Shape, whereas the class Square inheritsfrom the class Rectangle.

class

Rectangle : Shape

class

Square : Rectangle

In C#, the constructor of the base class is automatically invoked when youconstruct an instance of a derived class. However, a derived class can invoke aspecific constructor of the base class if needed. This you can see in the constructorof the Square class.

public

Square(double

s):base(s, s)//constructor. Calls parentconstructor explicitly

Like Java, a C# derived class may not override a method by redefining it. The classmust 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 theprotected access modifier, as shown in the code sample below:

The abstract classes are classes that cannot be instantiated. Java provides asyntaxfor an abstract class. The class Shape defined in the above C# code sample is anabstract class. The abstract classes requires that both Area and the method itcontains must be overridden in any derived classes.

abstract classShape

{

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.

interfaceIThreeDShape

{

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, youcan pass a

class that implements a particular interface, as a parameter to themethod. The following sample code shows how to pass an object of the class Cubeas a parameter, where the method expects an object of the class IThreeDShape.

static voidprintVolume(IThreeDShape

tdShape)

{

Console.WriteLine(“The volume is ”

+ tdShape.volume);

}

…

Windows Phone 7 Guide for AndroidApplicationDevelopers

48

Cubec =

new

Cube(4.0);

SecondProgram.printVolume(c);

Structs

C# structs arelike

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;

Windows Phone 7 Guide for AndroidApplicationDevelopers

49

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# allowsyou to use the new operator to create objects and initialize them. When a code nolonger 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 isdestroyed. 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 canuse 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 fieldsand properties.

The following table maps the dynamic type checking in Java with its correspondingC# reflection features.

Java Reflection

Explanation

C# Reflection

Class1 instanceOfBaseClass

Is Object a subclassor member?

type.IsSubclassOf(typeof(BaseClass))

object.getClass()

Is Object a memberof

object.getType() or typeof

search from

Method[] methods =c.getMethods();

Does the objectimplement themethod?

type.GetMethod(MethodName)

Does the

classrespond to themethod?

type.GetMethod(MethodName)

Method.invoke(..)

Invoke a method

type.InvokeMember(…)

Exception Handling

Exception handling is similar in both C# and Java. You use a use block to handleexceptions. You can also use either catchspecific exceptions or a catch-allstatements. The syntax for exception handling is similar in Java and C#.

Windows Phone 7 Guide for AndroidApplicationDevelopers

50

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);

}

Windows Phone 7 Guide for AndroidApplicationDevelopers

51

A Comparison of Important Class Libraries

Strings

C# provides a comprehensive string class, which offers you all the features that youassociate with this class.

JavaFeature

C#

Notes

String

String greeting = “Hello WP7!”;

Int length = greeting.Length;

Comparison

String color = “pink”;

If (color == “red”)

System.Console.WriteLine(“Matching colors!”);

string name = “Joe”;

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

System.Console.WriteLine(name +“ comes later”);

Strings are compared using ==.They are comparedlexicographically usingcompare.