Windows Phone 7 Guide for Android Application Developers
Upcoming SlideShare
Loading in...5
×
 

Windows Phone 7 Guide for Android Application Developers

on

  • 1,750 views

If you have been developing Android applications and are interested in building your applications for Windows Phone 7, this guide is for you. ...

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.

Statistics

Views

Total Views
1,750
Views on SlideShare
1,749
Embed Views
1

Actions

Likes
0
Downloads
39
Comments
1

1 Embed 1

http://www.slideshare.net 1

Accessibility

Upload Details

Uploaded via as Adobe PDF

Usage Rights

CC Attribution-ShareAlike LicenseCC Attribution-ShareAlike License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Windows Phone 7 Guide for Android Application Developers Windows Phone 7 Guide for Android Application Developers Document Transcript

  • Windows Phone 7Guide for AndroidApplicationDevelopers Microsoft 6/6/2011 Rev 1.0
  • Windows Phone 7 Guide for Android Application DevelopersAbout this Document ............................................................................ 4Target Audience ................................................................................... 4Conventions Used in this Document ........................................................ 4Chapter 1: Introducing Windows Phone 7 Platform to Android ApplicationDevelopers .......................................................................................... 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 ............................................................................ 11Chapter 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 ............................................................................ 21Chapter 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 ........................................................................................ 38Chapter 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 DevelopersChapter 5: A Comparison of Application Life Cycles in Windows Phone 7 andAndroid ............................................................................................. 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 ............................................................................ 74Chapter 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 ............................................................................ 85Chapter 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 DevelopersAbout this DocumentIf you have been developing Android applications and are interested in buildingyour applications for Windows Phone 7, this guide is for you.The guide covers what you need to know to add Windows Phone 7 development toyour skill set, while leveraging what you have already learned building Androidapplications.Target AudienceThis document is for Android application developers willing to develop applicationsfor Windows Phone 7.Conventions Used in this DocumentTerm AbbreviationWindows Phone 7 WP7Application Programming APIInterfaceIntegrated Development IDEEnvironment 4
  • Windows Phone 7 Guide for Android Application DevelopersChapter 1: Introducing WindowsPhone 7 Platform to AndroidApplication DevelopersEver 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 ToolsMicrosoft recommends using these tools for WP7 application development. Thistoolset 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 applicationsThe tools are designed to let you develop consumer applications, businessapplications, and games.Windows Phone 7 ArchitectureWP7 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, 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 5
  • Windows Phone 7 Guide for Android Application Developers o Accelerometer o Compass o Proximity and light sensorsThere 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. This improves 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 sandboxedenvironments. For more details about WP7 architecture, watch the MIX‟10presentation by Istvan Cseri, a WP7 architect. 6
  • Windows Phone 7 Guide for Android Application DevelopersComparing the Programming Stack of Windows Phone 7with AndroidThe 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.Android Functionality Windows Phone 7Frameworks Frameworks Application UI, Device Windows Phone 7 PhoneAndroid Application integration (sensors, Framework, SilverlightFramework camera) controls XNA for games or SilverlightAndroid Application Graphics, Animation, Media media and graphics forFramework others Base services, Networking,Android Libraries Common Base Library Text, XML, storageAndroid runtime Windows Phone 7(Dalvik)+ Linux kernel 7
  • Windows Phone 7 Guide for Android Application DevelopersAndroid and Windows Phone 7 Stacks Side by SideThis 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 kernelManaged CodeIn 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. 8
  • Windows Phone 7 Guide for Android Application DevelopersBase ServicesWP7 Base Class Library classes roughly correspond to those provided in the AndroidCore 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 VMThe 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 IntegrationYou 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. 9
  • Windows Phone 7 Guide for Android Application DevelopersAndroid applications Windows Phone 7 counterpartsUI using activity(contains Silverlight applications with pageswidgets) with navigation connected by flowsbetween them2D or 3D games built XNA games with 2D / 3D graphicswith Opengl-ES and Xbox connectivityXNA for GamesFor 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 as Profiles and Leaderboards.Silverlight Controls and MediaIf 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# or VB.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 FrameworksIf 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 the 10
  • Windows Phone 7 Guide for Android Application Developerscamera. Microsoft provides a push notification service, called Microsoft PushNotification Service.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 7SummaryIn 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 to go one leveldeeper. In the next section, we will look at the user interface guidelines of WP7applications.Related ResourcesTo 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.comOther 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 DevelopersChapter 2: User Interface GuidelinesMicrosoft‟s Windows Phone 7 (WP7) 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 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 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. The People hub, in the instance shown below, aggregates your addressbook contacts and Facebook friends. 12
  • Windows Phone 7 Guide for Android Application DevelopersDesigning the Application InterfaceWhile the design of the WP7 user interface is different from that of the Android, thecore design principles are very similar. Like Android, in WP7 you need to keep inmind the compact screen, lower CPU, and limited memory while designing theapplications. In WP7, users use one application at a time, with just one screenvisible.Similar Application Design GoalsUsability and UI design are not after thoughts, but are the primary goals behindapplications on both the Android and WP7. Applications need to be simple and focuson key scenarios that most users care about.Visual Elements and Direct ManipulationLike Android, visual elements and direct manipulation of objects by touch are thekey characteristics of the WP7 application. WP7 provides a complete set of UIcontrols designed for the phone.WP7 utilizes the same set of core multi-touch gestures as the Android with similarsemantics, these include: tap, double tap, pan, flick, touch and hold, and pinch andstretch.Implications of the Similarities for the DevelopersFor 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. 13
  • Windows Phone 7 Guide for Android Application DevelopersApplication User Interface DesignWhile 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 new Metro design guidelines.XML and XAMLAndroid 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 a XAML document in WP7contains the actual code needed for UI and needs not be transformed into code, asin case of Android.Controls and the Application InterfaceThe WP7 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 controlBorder BorderButtonView ButtonAbsoluteLayout CanvasCheckBox CheckBoxGridView Grid HyperlinkButtonImageView ImageListView ListBoxMediaController MediaElement 14
  • Windows Phone 7 Guide for Android Application DevelopersAndroid control Windows Phone 7 control MultiScaleImageViewGroup PanelEditText PasswordBoxProgressBar ProgressBarRadioButton, RadioButtonRadioGroupScrollView ScrollViewerSeekBar SliderLinearLayout StackPanelEditText TextBlockEditText TextBoxMapView MapWebView WebBrowser Panorama PivotTimePicker TimepickerDatePicker DatepickerExpandableListViewGalleryImageSwitcherSpinnerTableLayoutTextSwitcherViewFlipper 15
  • Windows Phone 7 Guide for Android Application DevelopersAndroid control Windows Phone 7 controlZoomControlTabHostSlidingDrawerRatingBarToggle button ToggleSwitch** ToggleSwitch and Datepicker/Timepicker control are part of the Silverlight forWindows Phone Toolkit available on Codeplex:http://silverlight.codeplex.com/releases/view/55034As 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 7WP7 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 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 DevelopersNotificationsBoth 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 Phone 7Status bar Non-critical information that user Tile notificationsnotification may not respond to. That is informative to userToast Time sensitive data that user may Toast Notificationsnotification not respond toAlerts Modal alerts that the user must Application respond to notifications 17
  • Windows Phone 7 Guide for Android Application DevelopersTool and Tab Bar vs. Application BarWP7 features a versatile application 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 sheets in yourAndroid application, application bar menus give you similar functionality.Android Functionality Windows Phone 7Status bar Information about Status bar deviceTitle bar: to show title Navigation, Title, Back button for backof application or activity Buttons for views or navigation actions Page title View and actions on Application barComparing Windows Phone 7 and Android NavigationWP7 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, on WP7 the Back button on the phone allows the user to navigateback between pages within an application, or across applications. It behaves muchlike 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 andplan to override it appropriately. For example, you may decide to pause a game byusing 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 DevelopersWindows Phone 7 Frame and Page StructureEach 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 BarOn 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. 19
  • Windows Phone 7 Guide for Android Application DevelopersPage Structure of Windows Phone 7 ApplicationThe 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 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 that showsinformation 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 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 DevelopersApplication TemplatesEclipse does not provide the project template for Android applications. But VisualStudio provides numerous templates for WP7 application development to makeyour life easier.Functionality Visual Studio Template EclipseInformation drilldown Data-bound applications Not availableapplicationsUtility applications. For Windows Phone 7 utility Not availableexample, Bubble Level applicationsGames Windows Phone 7 Game Not available (XNA) applicationsFlexible template to design General Windows Phone 7 Not availableany application applicationsYou 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 functionality like the OpenGL-ES application.SummaryIn 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 the use of innovative controls like panorama, andexplore the use of live tiles to build an engaging WP7 experience.Related ResourcesTo 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 DevelopersOther 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 DevelopersChapter 3: The Developer andDesigner ToolsWith the release of the Windows Phone 7 (WP7) developer tools, Microsoft bringsthe user-friendly, high productivity Visual Studio Development environment to WP7.As Android application developers you are familiar with Eclipse, and you can quicklymigrate to WP7 developer tools and work with ease.A Comparison of Android and Windows Phone 7 ToolsVisual Studio 2010 Express for Windows Phone 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 EmulatorThe 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 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 ExpressYou 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 Life Cycle and Windows Phone 7 DeveloperToolsExpression 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.Project Management for Windows Phone 7Like Eclipse, Visual Studio 2010 Express for WP7 is a fully-featured IDE. VisualStudio 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 unitWith Visual Studio 2010 Express, you can manage source files, share code, andmanage the work among team members. Visual Studio integrates a compiler and a 24
  • Windows Phone 7 Guide for Android Application Developersdebugger. You can access both the compiler and the debugger either from the GUIor 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 examplesolution has only the ShoppingList project. The project contains the sources,resources, and properties.Note: Visual Studio Express for WP7 does not provide integration with sourcecontrol systems. The Visual Studio Professional edition provides features such asintegration with various source control systems like Subversion. You can also useVisual Studio Team System, which is designed for greater communication andcollaboration among the development teams. 25
  • Windows Phone 7 Guide for Android Application DevelopersThe UI Design ToolsThe WP7 developer tools include:  Expression Blend  Visual Studio UI DesignerWP7 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 Androidapplication developers you are familiar with Eclipse ADT UI plug-in and you will 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 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 ofthe 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 DebugThe application starts the WP7 emulator, deploys, and runs the ShoppingListapplication. You can click Add. But the application does not respond because thereis no code for the button you inserted in the previous steps. 27
  • Windows Phone 7 Guide for Android Application DevelopersNote: 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 makes it easy to add logic to the UI controls.Expression Blend for Windows Phone 7Expression 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 DevelopersExpression 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 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 DevelopersVisual StudioVisual 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 codeTo 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-completiondialog box. The Visual Studio equivalent for Eclipse auto-completion is calledcontent 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 StudioVS 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 the code below:To complete the event hookup, Visual Studio generates an empty stub for the eventhandler button1_click method. 31
  • Windows Phone 7 Guide for Android Application DevelopersCode Snippets in Visual StudioCode 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 help you to create their ownsnippets. You can also create an index and search for the code snippets by usingthe 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 iThe 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 ofcode and right-click the code to access the refactoring menu. 32
  • Windows Phone 7 Guide for Android Application DevelopersVisual Studio EditorVisual 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 Studio Editor 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 ApplicationsVisual 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.Visual Studio uses an XML based, declarative build system called MSBuild. MSBuildis 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 7 EmulatorThe WP7 Emulator provides a virtualized environment in which you can deploy,debug, and test applications. The WP7 Emulator is designed to provide acomparative performance of an actual device and meets the peripheralspecifications 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 DevelopersThe WP7 Emulator is like the Android Simulator. However, these differences arethere:  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.DebuggingVisual Studio Express Phone 7 includes a symbolic debugger that you can use withthe WP7 EMULATOR or 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. 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 VariablesYou 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 toinspect the objects.You can set a watch on certain variables to keep them under observationcontinuously.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 hereyet. But it gets compared with Nothing 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 pressing F5. 5. To test the application, add items to the shopping list. 36
  • Windows Phone 7 Guide for Android Application DevelopersA Note about DebuggingYou 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. 37
  • Windows Phone 7 Guide for Android Application DevelopersSummaryIn this chapter we looked at the Windows Phone 7 Developer Toolset. The Toolsetincludes 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. 38
  • Windows Phone 7 Guide for Android Application DevelopersChapter 4: C# programmingThis 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 39
  • Windows Phone 7 Guide for Android Application DevelopersManaged ProgrammingWP7 supports managed 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 an apk file, which is executed on anandroid platform. 40
  • Windows Phone 7 Guide for Android Application DevelopersA Comparison between C# Features and Java ClassesClass DeclarationLike 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 importnamespace 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 consistsof property, age, and constructor.Instead of using the import statement in Java, C# employs a using statement torefer to the metadata of other classes. The namespace declaration that is shown atthe top of the file is used to declare the scope 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.C# uniformly uses the “ ” notation for referring to all methods, fields, andproperties.Strong Typing 41
  • Windows Phone 7 Guide for Android Application DevelopersC# is a strongly typed language like Java. The types must be specified for variablesand input/output parameters. The compiler enforces the types. In the section ongenerics, you can see how C# uses strong typing for collection classes.Strong typing works similarly for all classes. The code example below shows thestrong typing for primitive types.int a = 5;int b = a + 2; //OKbool test = true; // OKint c = a + test; // Error. Operator + cannot mix type int andbool.Class ConstructorsLike 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(new DateTime(1973,11,12));PropertiesYou 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 TypesLike 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;}.. 42
  • Windows Phone 7 Guide for Android Application Developersint a = 5;int b = 8;Foo (ref a, b);//a is zero and b is still 8C# 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 PrivilegesLike 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 on p.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 with Multiple ParametersBoth 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, int void addEmployee(string name, intid, 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 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); 43
  • Windows Phone 7 Guide for Android Application DevelopersThe following code sample shows another example of method overloading:using System;namespace SecondApplication{ struct Point // In contrast Java where struct notsupported, C# structs are closer { // classes. public double x; // struct fields can also have accessmodifiers 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. nosetter } } abstract class Shape // this class is marked abstract, i.e. maynot 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 classname{ counter++; // class variable being updated } public Point Origin // similar to Java classvariables { set { origin = value; } } public abstract double Area //denotes that this property must beoverridden { // in a derived class get; } public abstract bool contains(Point p); // this method must also beoverridden } 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 anotherconstructor //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 implementsinterface { 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 printTRUE } }}InheritanceLike 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 : Shapeclass Square : RectangleIn 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 explicitlyLike 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 AccessLike 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:protected Point origin; protected static int counter=0;Instance vs. Class Level Access 46
  • Windows Phone 7 Guide for Android Application DevelopersLike Java, C# uses a static modifier to denote class level methods, fields, andproperties. Everything else is at an instance level. In the above code example, thecounter is a class level variable.protected static int counter=0;Abstract ClassesThe abstract classes are classes that cannot be instantiated. Java provides a syntaxfor 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 class Shape { public abstract double Area { get; } public abstract bool contains(Point p);InterfacesThe 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, IThreeDShapePolymorphismThe 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 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);StructsC# 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 DevelopersObject Lifecycle: Creation and Deletion of ObjectsThe 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. ReflectionJava 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 fields and properties.The following table maps the dynamic type checking in Java with its correspondingC# reflection features.Java Reflection Explanation C# ReflectionClass1 instanceOf Is Object a subclass type.IsSubclassOf(typeof(BaseClass))BaseClass or member?object.getClass() Is Object a member object.getType() or typeof ofsearch from Does the object type.GetMethod(MethodName) implement theMethod[] methods = method?c.getMethods(); Does the class type.GetMethod(MethodName) respond to the method?Method.invoke(..) Invoke a method type.InvokeMember(…)Exception HandlingException handling is similar in both C# and Java. You use a use block to handleexceptions. You can also use either catch specific exceptions or a catch-allstatements. The syntax for exception handling is similar in Java and C#. 49
  • Windows Phone 7 Guide for Android Application Developerstry { //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 DevelopersA Comparison of Important Class LibrariesStringsC# provides a comprehensive string class, which offers you all the features that youassociate with this class.Java C# NotesFeatureString 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 DevelopersArraysArrays in C# are almost like arrays in Java.Java Feature C# NotesArrays of int[] table; Array size is not a part ofprimitive 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 jaggedof 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 aobjects 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 pinkDictionariesC# provides a generic dictionary class that is similar to the HashTable functionalityin Java. The generic dictionary class allows you to add, lookup, and remove objectsfrom the dictionary. Since the dictionary class uses Generics, it also utilizes strongtyping. 52
  • Windows Phone 7 Guide for Android Application DevelopersJava 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 DevelopersThe New features of C#This section covers the following:  Generics  Operator Overloading  Delegates  Events  GenericsGenericsGenerics introduce the notion of type parameters that make it possible to designclasses that are type safe, even though the actual type is deferred till the object‟sinstantiation. For example, the following code shows how to define a generic stack:Stack<int> intStack = new Stack<int>(); // intStack is a stackof intintStack.Push(1); // OKintStack.Push(2); // OKint number = intStack.Pop(); // this is a type safeassignmentStack<string> strStack = new Stack<string>(); //the type of strStackis different from type of intStackstrStack.Push("green"); // OKstrStack.Push(23);The Stack<T> uses T as a type parameter, thus allowing you to instantiate a stackof any type. For example: Stack<int> or Stack<string>. You can use them in atype safe manner. The use of generics is like generics in Java. 54
  • Windows Phone 7 Guide for Android Application DevelopersOperator OverloadingOperator Overloading allows you to define the implementation of user-definedoperators for user-defined classes. Consider the following example of a complexnumber struct. Operator Overloading allows you to define a + operation by using anatural syntax.public struct Complex { public int real; public int imaginary; // Declare which operator to overload (+), define how it iscomputed 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 DevelopersDelegatesThe functionality of delegates in C# is like the function pointers in C. In this designpattern, 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 twpStringDelegate objects Writer = new StringDelegate(ConsoleLogger.WriteString); //Create delegates with appropriate methods Logger = new StringDelegate(FileLogger.LogString); Writer("Warning message 1n"); // Send toConsole Writer delegate method Logger("Warning message 2n"); // Send to FileLogger delegate method StringDelegate MultiLogger; // to act as the multicast delegate MultiLogger = Writer + Logger; // combine thetwo delegates, MultiLogger("Warning message 3"); // This shouldget sent to both delegates } }}In the above code example, StringDelegate is defined as a function that takes astring as a parameter and returns void. Writer, logger, and multiLogger areconstructed by passing methods that have the same signature as theStringDelegate declaration.Calling Writer invokes the writeString method of ConsoleLogger to print themessage to the console. Calling Logger invokes the logString method of FileLogger 56
  • Windows Phone 7 Guide for Android Application Developersto log the message to the file. Delegates achieve indirection while providing typesafety. Delegates may be concatenated as shown by MultiLogger, which logs themessage to both loggers.EventsEvents 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 apublisher raises an event, all subscribers are notified. The publisher raises theevent, 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 DevelopersComparing API Documentation ToolsJDK contains an API documentation generation tool called Javadoc. Javadocautomatically generates documentation from the comments that are added to thejava source code file.There are a variety of document generation tools that are available for .NET:  NDoc  Sandcastle  Doxygen  Doc-O-MaticNDocNDoc 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 pagesUsing NDocTo 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 Releasefolder depending on your build configuration. You can see the documentation file inthe XML format.You can use NDoc‟s help to get a fair idea of documenting your class library moreeffectively.Generating Better DocumentationTo 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 / characterthree times. Visual Studio.NET creates the skeleton of a code comment block forthat 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 tomeet your requirements. 60
  • Windows Phone 7 Guide for Android Application DevelopersIn a code comment block, when you press the < key to start a new tag, VisualStudio.NET displays an Intellisense selector. This selector shows a list of codecomment tags. This list does not display the additional tags that NDoc supports.You must add the additional tags manually.Using the NDoc GUI UtilityTo 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 canconfigure 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 inthe 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 DevelopersIn this chapter, we looked at C# programming from the perspective of a Javadeveloper. C# is a strongly typed, object-oriented programming language that usesstatic binding. Several C# concepts are similar to the Java concepts. The knowledgeof Java and object oriented programming will help you to master C# quickly. Wealso looked at NDocs, which is the API documentation tool for Windows Phone 7.Related ResourcesTo go deeper into C# and Java, visit:  http://www.25hoursaday.com/CsharpVsJava.htmlTo go deeper into NDocs, visit:  http://ndoc.sourceforge.net/  http://shfb.codeplex.com/ – Sandcastle Summary 62
  • Windows Phone 7 Guide for Android Application DevelopersChapter 5: A Comparison ofApplication Life Cycles in WindowsPhone 7 and AndroidThe Windows Phone 7 (WP7) execution model improves user experience by cuttingdown on response time and offering seamless navigation among applications. Toachieve this, WP7 prioritizes the foreground application and tombstones other openapplications. Android on the other hand, saves all the application states anddisplays only the foreground application.Android suspends an open application when a user starts another application. Thesuspended application remains alive in the phone memory. WP7 activates anddeactivates applications dynamically to enable seamless navigation by limiting thephone to run one application at a time.The WP7 execution model provides users with a consistent navigation experiencebetween applications.In Android, users open applications using the launcher screen. On the launcherscreen, all the applications are listed as icons. In WP7, users navigate forward bylaunching applications from the installed Applications List or from a tile on theStart screen.In WP7, users can use the Back button on the phone to navigate backwards to apage in a running application. With this Back button, users can also navigatethrough a stack of previously running applications. This WP7 functionality is similarto Android‟s backward navigation. All Android devices have the Back button on thephone. A user can navigate to previous screens of applications until he reaches thehome screen of phone.The Android applications consist of various components, such as Activity, Services,ContentProvider, and Broadcast receivers. These components are not available inWP7 except for an Activity which can be mapped to a Page in WP7.Multitasking in Android and Windows Phone 7Android supports multitasking and provides seamless navigation betweenapplications. WP7 achieves seamless navigation using application tombstoning.Android puts applications in the background using the Service component. TheService component runs in the background even if your application is not inforeground until the application‟s task finishes or stopService is called.The upcoming version of WP7 will support multitasking. The WP7 navigation modelallows natural navigation, similar to a browser‟s Back button. The last accessed 63
  • Windows Phone 7 Guide for Android Application Developersapplication state is preserved as a user navigates across applications using the Backbutton on the phone.Tombstoning of Applications in Windows Phone 7Tombstoning is a process by which WP7 deactivates an application when a usernavigates away from this application. WP7 keeps a record of the tombstonedapplication and stores the latest data accessed by this application. If the userreturns to a tombstoned application, WP7 reactivates this application. The user canaccess the reactivated application by using a phone‟s Back button.Consider the following example. A user is composing a blog with WordPress. Hepressed the Start button to go to the Start screen. WP 7 deactivated the WordPressapplication. The user then accessed Facebook. While in Facebook, the user pressedthe Back button. The Start screen appeared. When the user pressed the Backbutton again, WordPress appeared exactly in the same way as she had viewed itthe last time.The following table describes the user events and compares the correspondingbehavior in Android and Windows Phone 7.User Action or Event Android Behavior Windows Phone 7 BehaviorAn incoming phone call or Running application is Running application isSMS moved to the background deactivated but is still in the memoryUser presses the Home Running application is Running application isbutton on the phone moved to the background, deactivated current activity will be paused but the application is still in memoryUser starts another Background application is The upcoming version ofapplication from the moved to foreground with WP7 will supportmultitasking menu the earlier saved state multitaskingUser navigates between No navigation occurs Deactivated orapplications using the when Back button is tombstoned application isBack 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 DevelopersThere is no similarity between the Android life-cycle stages with the WP7‟s Pagestage. 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:LaunchingAn application is launched when it is started by all other means except when theuser navigates to it using the Back button.Whenever a user opens an application, WP7 creates a new instance of theapplication. In Android, when an application launches a new process a new instanceof Dalvik VM is allocated to the application. The application runs within thatprocess. Each application runs in its own process and VM instance.Do not store the state data when the launching event is raised. The launching eventis raised even before application is visible to the user. Storing data at this stagemay increase the startup time of the application.RunningAfter launching, the application goes into the running stage. In this stage, theapplication manages its own state as the user navigates through the different pagesof the application.In the running stage, settings and the persisted data are saved. This reduces thedata that you need to save when the application‟s stage changes. However, thedecision to save data in this stage is optional. If the size of the persisted data is notlarge, you need not save the data.ClosingYour application comes across this event when the user presses the Back button onthe 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 actionis similar to handling the Destroyed() method in Android.In Android, you cannot close an application after launching. Each activity in theapplication can be finished but the application process remains in the memory.DeactivatingWP7 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 phoneIn the handler for this event, you must save the transient data to the state propertyand the persistent data to the isolated storage. This helps maintaining consistentuser experience after the user activates the application again. 65
  • Windows Phone 7 Guide for Android Application DevelopersAndroid suspends a current application‟s activity when a new application comes tothe foreground.ActivatingWP7 raises this event:  If a user returns to a deactivated application using the Back button on the phone  If a user returns to a tombstoned application, which was deactivated by Launcher or ChooserThis event is similar to resuming an Activity in Android. However, WP7 creates anew instance of the application when a user starts the application from:  A phone‟s Applications List  An application‟s tile on the Start screen  A toast notificationIn the handler for this event, you restore all the transient data of the application.The transient data restores the application to the state before the application wasdeactivated.You must avoid accessing the isolated storage or network resources in this eventhandler. When you access an isolated storage or network resources, anapplications launch time may increase.Role of Handlers in an Application‟s Life CycleIn WP7, your applications transition between the active and inactive states. You canimplement handlers for an application‟s life-cycle events to save and restoreapplication states.A WP7 application‟s life cycle offers users consistency while working withapplications. The users feel that the application is running in the background whenit is not visible to him.In Android, you save application state when an activity is paused. You can use themethod onSaveInstanceState to access the event, and use the methodonRestoreInstanceState to restore the event to previous state. 66
  • Windows Phone 7 Guide for Android Application DevelopersFigure: Windows Phone 7 Application Life Cycle 67
  • Windows Phone 7 Guide for Android Application DevelopersComparing Life-cycle MethodsAs mentioned in the earlier sections, a Page in WP7 is similar to an Activity inAndroid. We can compare the Android lifecycle method with WP7‟s state-changeevents and Page methods. Windows Windows Phone 7 Windows Phone 7 Android Phone 7 Application Events Page Methods Methods Stage Launching Application_Launching InitializeComponent() onCreate() Running onStart(), onResume() Deactivated Application_Deactivated NavigatedFrom onStop(), onPause() Activation Application_Activated NavigatedTo onResume() Closing Event Application_Closing onDestroy()In Android, you can use the onCreate() method to initialize the variables, such asthe view components, the database connection, and a GPS provider. In WP7, youcan use the InitializeComponent() method in the constructor of the Page class toinitialize variables. You also need to get the application_launching event to definethe global variables in InitializeComponent() method.In Android, if a user launches a new application, the current application activitycalls the onPause and onStop methods. In this scenario, you can commit theapplication data to the database. But in WP7, if a user launches a new application,the current application is deactivated. At the time of deactivation, WP7 calls theApplication_Deactivated function. You need to save the application‟s state-data inthe Application_Deactivated function.In Android, a user can see the running application on a phone by keeping the Homebutton on the phone pressed for some time. The user can also resume a runningapplication from the running applications list. In this scenario, Android calls theapplication activities on the Start and onResume lifecycle methods. With thesemethods, you can restore the data from a previous state. In WP7, when a userstarts a tombstoned application, the Application_activated function is called. Youcan restore the data from the previous state of the application to this function.In Android, when one Activity replaces another, the current Activity calls theonPause and onStop methods. This behavior is similar to the Page to Pagenavigation in WP7. In WP7, While moving from one page to another, the currentpage raises the NavigatedFrom() event and the new page raises the NavigatedTo()event. 68
  • Windows Phone 7 Guide for Android Application DevelopersTombstoning and Windows Phone 7 Life CycleConsider a simple example that illustrates the WP7 application life cycle stagetransitions and tombstoning. Here is a single page example application calledShopping List. In this application, the user can add items to a shopping list. Whenthe user leaves the application, the shopping list is saved automatically.Saving the Application State DataIn Android, you can save application state data in a number of different ways. Forexample, using SharedPreferences, using files in the internal storage/externalstorage, or using SQLLite.To save the persistent state data of an application on WP7 you can useIsolatedStorage. IsolatedStorage is a safe storage space that is accessible only tothat application to which the space is allocated. One application cannot affectanother application‟s data. To save the stage data, you need to get theIsolatedStore for the application. After that, create a file in IsolatedStorage, to savethe persistent state. In our example of the Shopping List application, you canserialize the list and save it to the file.public static void SaveShoppingList(ShoppingListInfo shoppingListInfo, stringfileName){ //Get the isolatedStore for this application using (IsolatedStorageFile isf =IsolatedStorageFile.GetUserStoreForApplication()) { // create a new file using (IsolatedStorageFileStream fs = isf.CreateFile(fileName)) { //and serialize data and save it XmlSerializer xmlSer = newXmlSerializer(typeof(ShoppingListInfo)); xmlSer.Serialize(fs, shoppingListInfo); } }}WP7 provides another class called PhoneApplicationService.State to save thetransient stage data.Terminating Applications 69
  • Windows Phone 7 Guide for Android Application DevelopersWhen the user uses the back button to leave an open application, WP7 terminatesthe application. Depending on the nature of your application, you may need to savecertain data when WP7 terminate your application.In the example of the Shopping List application, you can save the application datawithout confirmation from the user. This ensures that the shopping list is intact,when the user get opens the application next time. In this example, you are notsaving any item that the user is typing in the Item text box. You can use thehelper method to save the shopping list. Your application can perform such cleanupand state saving operations in response to the Application_Closing event instead ofOnBackKeyPress.protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgse){ base.OnBackKeyPress(e); //do not save what is in the item, i.e. it is transient txtItem.Text = ""; //preserve data in persistent store Utils.SaveShoppingList((App.Current.RootVisual asPhoneApplicationFrame).DataContext as ShoppingListInfo, "ShoppingListInfo.dat"); }}Application LaunchingWhen the user starts an application from the Start screen, the application receivesthe Application_Launching event.During launch, you can examine whether any persistent data is available. In theShopping List application, if you find the persistent data, load the data in the txtListtext box to launch the shopping list. You can first get the IsolatedStore for theapplication. Using the IsolatedStore, check if the ShoppingListInfo.dat file exists. Ifthe DAT file is available, you can de-serialize the existing data and reload theShoppingListInfo.You can make the fields in Shopping List application databound using the last line inthis code snippet. Now, if you run the application, you find that the shopping list ispreserved when the application is closed and presented when you launch theapplication again. // Code to execute when the application is launching (eg, from Start) // This code will not execute when the application is reactivated private void Application_Launching(object sender, LaunchingEventArgs e) { //Trace the event for debug purposes Utils.Trace("Application Launching"); //Create new data object variable ShoppingListInfo shoppingListInfo = null; 70
  • Windows Phone 7 Guide for Android Application Developers //Try to load previously saved data from IsolatedStorage using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { //Check if file exits if (isf.FileExists("ShoppingListInfo.dat")) { using (IsolatedStorageFileStream fs = isf.OpenFile("ShoppingListInfo.dat",System.IO.FileMode.Open)) { //Read the file contents and try to deserialize it back to data object XmlSerializer ser = new XmlSerializer(typeof(ShoppingListInfo)); object obj = ser.Deserialize(fs); //If successfully deserialized, initialize data object variable with it if (null != obj && obj is ShoppingListInfo) shoppingListInfo = obj as ShoppingListInfo; else shoppingListInfo = new ShoppingListInfo(); } } else //If previous data not found, create new instance shoppingListInfo = new ShoppingListInfo(); } //Set data variable (either recovered or new) as a DataContext for all the pages ofthe application RootFrame.DataContext = shoppingListInfo; }Deactivating ApplicationsThis event occurs when a user press the Start button while running an application.Android suspends the current application‟s activity whenever a new applicationcomes to foreground. In WP7, the application receives the Application_Deactivatedevent. 71
  • Windows Phone 7 Guide for Android Application DevelopersIn response to this event, you can save the entire application state. In the exampleof the Shopping List application, you need to save the shopping list as well as thetext entered in the Item text box.You can save the transient application state by using thePhoneApplicationService.State object.// Code to execute when the application is deactivated (sent to background) // This code will not execute when the application is closing private void Application_Deactivated(object sender,DeactivatedEventArgs e) { //Trace the event for debug purposes Utils.Trace("Application Deactivated"); //Add current data object to Application statePhoneApplicationService.Current.State.Add("UnsavedShoppingListInfo",RootFrame.DataContext as ShoppingListInfo); }Activating ApplicationsIf a user returns to a deactivated application using the Back button on the phone,WP7 raises the Application_Activated event.In response to this event, you can load the data from thePhoneApplicationService.State object. If you find the necessary data for launchingthe application, you can populate the UI elements using that data. If you do notfind any saved data, keep the UI fields blank.To test the Shopping List application for this code snippet, press the Home buttonto leave the application and navigate back to the application using the Back button.You will find that both the shopping item in the text box and the shopping list arepreserved.// Code to execute when the application is activated (brought to foreground) // This code will not execute when the application is first launched private void Application_Activated(object sender, ActivatedEventArgs e) { //Trace the event for debug purposes Utils.Trace("Application Activated"); //Create new data object variable ShoppingListInfo shoppingListInfo = null; //Try to locate previous data in transient state of theapplication if(PhoneApplicationService.Current.State.ContainsKey("UnsavedShoppingListInfo")) { 72
  • Windows Phone 7 Guide for Android Application Developers //If found, initialize the data variable and remove in fromapplications state shoppingListInfo =PhoneApplicationService.Current.State["UnsavedShoppingListInfo"] asShoppingListInfo;PhoneApplicationService.Current.State.Remove("UnsavedShoppingListInfo"); } //If found set it as a DataContext for all the pages of theapplication //An application is not guaranteed to be activated after it hasbeen tombstoned, //thus if not found create new data object if (null != shoppingListInfo) RootFrame.DataContext = shoppingListInfo; else RootFrame.DataContext = new ShoppingListInfo(); } 73
  • Windows Phone 7 Guide for Android Application DevelopersSummaryIn this chapter we had a look at the different stages of application life cycle inAndroid and Windows Phone 7. We also compared methods for saving applicationstate data in Android and Windows Phone 7.Related ResourcesTo know more about the execution model for Windows Phone 7, visit:  Execution Model Overview for Windows Phone  Execution Model Best Practices for Windows Phone  How to: Preserve and Restore Page State for Windows Phone  How to: Preserve and Restore Application State for Windows Phone  Android Application Life-cycle Diagram 74
  • Windows Phone 7 Guide for Android Application DevelopersChapter 6: Storing Data andPreferencesWindows Phone 7 (WP7) features a very comprehensive system of managing datafor your application and across all applications on the phone. This section comparesthe data handling features of WP7 and Android.Isolated Storage in Windows Phone 7With WP7, you can store data in the device file system of your application. Thistype of data storage is called IsolatedStorage.The following diagram shows the folder structure for a storage application: 75
  • Windows Phone 7 Guide for Android Application DevelopersComparing the Data Storage Methods in Windows Phone 7 and AndroidStorage Windows Phone 7 AndroidMethodsStorage You can store the application You can store the application data in IsolatedStorage data in the phone‟s internal storage, which is private to your application Windows Phone 7‟s isolated InternalStorage enables storage model allows the applications to create and managed applications to maintain local data. create and maintain the local database.Security Windows Phone 7 does not Neither the user nor other allow the application to make applications can access the the file system calls outside data stored in the internal the isolated storage area or storage. The internal storage outside of the operating area is private to the system area. This design gives respective application. a sandbox effect to the application. The advantage of this design is that the application cannot access the data storage area of other applications.Security Windows Phone 7 restricts all Android prevents unauthorized Input and Output (I/O) data access by restricting I/O operations to isolated storage operations of internal storage and prevents the I/O to the same application. operations from accessing the However, you have an option operating system files. This to make this data public by Windows Phone 7 feature writing data to external prevents unauthorized access storage. and data corruption.Installation When you update an Android does not delete the application after it is available application data after in the market, Windows Phone uninstalling or reinstalling. 7 does not modify the isolated While updating the applications storage folder. You need to that are already in the market, ensure that the data is you need to ensure that the migrated or transformed data is updated to maintain appropriately to work with the compatibility with the updated new version of the application version of the application. 76
  • Windows Phone 7 Guide for Android Application DevelopersUninstallation When an application is Android deletes only the uninstalled, Windows Phone 7 internal storage of an deletes the uninstalled, application when the Windows Phone 7 deletes the application is uninstalled. data root, the isolated storage folder, and all the data within the store.Memory Space Windows Phone 7 does not The internal storage limit of an restrict applications from Android application is using the memory space. dependent on the availability Adequate memory is provided of memory. Your application to each application depending must use the memory on the requirement. carefully.Settings Windows Phone 7 allows you Android allows you to store an to store the settings for the application‟s settings in the application in the SharedPreference memory IsolatedStorageSettings area. space. You can store the You can store key and value primitive data types in pairs of data in this memory key/value pairs. space.To know more about the comparison between the data storage methods, visit:  IsolatedStorage for Windows Phone  Windows Phone 7 Series Developer General FAQ 77
  • Windows Phone 7 Guide for Android Application DevelopersUse CasesStoring the Configuration Settings and DataMany applications need to store application settings and data, such as user name,password, and language preference, and last login time stamp. The nature of suchdata depends on the nature of the application.In Android, you can store such application settings and data by using theSharedPreferences class. The SharedPreferences class stores the key value pair ofprimitive data types. In WP7, you can save this data by using theIsolatedStorageSettings.ApplicationSettings property.IsolatedStorage stores objects by using theIsolatedStorageSettings.ApplicationSettings property. This is the most convenientway to store simple data. You just need to add your data to the Settings store byusing the following code:IsolatedStorageSettings.ApplicationSettings.Add(“some_property”, value);IsolatedStorageSettings.ApplicationSettings.Save();The value object is serialized automatically to a disk when you call the Save()method. You can read back data by using the following code:List<string> mydata =(List<string>)IsolatedStorageSettings.ApplicationSettings["some_property"];Serializing Objects to XMLYou may need to serialize an entire object to the file system to save the state ofobject or to save the memory. In Java, you can serialize objects by usingObjectOutputStream. In WP7, you can serialize objects by using the StreamWriterclass.You can store objects as XML by using the following code. This code serializes a listof strings to the xml format and saves this format in IsolatedStorage: 78
  • Windows Phone 7 Guide for Android Application Developersusing(IsolatedStorageFile storage =IsolatedStorageFile.GetUserStoreForApplication()){ using(IsolatedStorageFileStream fs = storage.CreateFile(“myfile.wp”)){ using(StreamWriter writer = new StreamWriter(fs)){ XmlSerializer serializer = new XmlSerializer(typeof(List<string>)); serializer.Serialize(writer, myStringList); } }}After storing the data in the XML format, you can use LINQ to XML to utilize thedata later. You can use this method to store any structured data on a disk.Note: For details about LINQ to XML, see Chapter 8.To read back the file, use the following code:using(IsolatedStorageFile storage =IsolatedStorageFile.GetUserStoreForApplication()){ using(IsolatedStorageFileStream fs = storage.OpenFile(“myfile.wp”,FileMode.Open)){ XDocument doc = XDocument.Load(fs); XmlSerializer serializer = new XmlSerializer(typeof(List<string>)); List<string> myData =(List<string>)serializer.Deserialize(doc.CreateReader()); }}Managing the IsolatedStorage SpaceThe Windows Phone 7 applications do not have an imposed quota size because therequirements for each application‟s scenario are different. Also, limiting the disksize on a per application basis can increase the response time and dilute userexperience. Therefore, ensure that your application stores only the necessary datafor a subsequent launching of the application.The storage space in mobile phones is limited. Windows Phone 7 displays anotification to the user when only 10% of the storage-space remains. The userneeds to delete the existing data to create the necessary storage space. From auser‟s point of view, this is not a favorable option.The Best Practices for Managing the IsolatedStorage SpaceThe following best practices help you to efficiently manage the data storage-spacein Windows Phone 7:Temporary data and filesIf your application stores any temporary data in IsolatedStorage, delete thetemporary data if the data is no longer required. For example, delete the earlierversion of the data when the updated version is available. You can implementperiodic deletion of data by creating a temporary cache folder for the data and byclearing the cache from time to time. 79
  • Windows Phone 7 Guide for Android Application DevelopersUser generated dataThe user generated data can be in the form of photos from the camera, or notesand documents.  If your application allows a user to create data, offer the user the delete option. For example, users should be able to take photos and delete those that they do not want.  Increase the performance of an application by reducing the application‟s footprint. You can use techniques, such as: o Synchronizing or archiving data to the cloud o Keeping only the relevant dataApplication DataExamples of application data include:  A list of stores or shops that are managed by a shopping list application  Words in a dictionaryNote: If your application takes data from the cloud and stores it locally, recycle thedata based on your priorities.Why Windows Phone 7 Does Not Use External StorageYou can save files to a shared external storage in an Android compatible device.The shared external storage can also include the internal non-removable storage.Android allows you to access and modify the files that are saved to the externalstorage by connecting to a computer. In this type of connection, the files might getdeleted or corrupted if the connection gets disconnected during the data transfer.You cannot make the file system calls outside the WP7 application‟s own externalspace. This provides the application with a safe-sandbox, and prevents the otherapplications from inadvertently affecting the applications data.Library Recommendation for Supporting SQLite in Windows Phone7Android features SQLite version 3.4.0. Android also provides the API for managingthe SQLite database. This API provides the methods to create, delete, run SQLcommands, and perform the other common database management tasks. AnAndroid application can create a database to store and manage the structured dataon phone. The application can also share the same database with other applicationsby using a ContentProvider.WP7 does not feature SQLite. You can use a third-party library to get thatfunctionality in WP7.To know more about incorporating SQLite in WP7, visit:  http://sqlitewindowsphone.codeplex.com/  http://wp7sqlite.codeplex.com/ 80
  • Windows Phone 7 Guide for Android Application DevelopersManaging Content across ApplicationsIn Android, ContentProviders store and retrieve data and make the data accessibleto all applications. In Android, you can share data only through ContentProviders.However, Android does not provide a common data storage area that all Androidapplications can access.Android provides you two ways to make the application data public by usingContentProviders:  You can create your own ContentProvider. This is the ContentProvider subclass.  You can add the data to an existing provider. For this, you need a ContentProvider that controls similar data and the permission to write to it.To know more about ContentProviders, visit:http://developer.android.com/guide/topics/providers/content-providers.htmlThe WP7 execution model isolates every application in its own sandbox for bothrunning the application and for storing data. Applications cannot access informationfrom the common information stores, such as the contacts list. Applications alsocannot directly invoke other applications, such as the phone or messagingapplications. To enable applications to perform these common tasks, WP7 offers aset of APIs called Launchers and Choosers. They allow applications to indirectlyaccess the various features of a phone.Launchers and ChoosersThe Launcher and Chooser APIs call the distinct built-in applications that replacethe currently running application.Android has functionality similar to Launchers and Choosers. In Android, you usethe Intent filter and the Intent API to launch any built-in or installed applications toreturn the data you need or to perform a task.To know more about the Intent filters, visit:  http://developer.android.com/guide/topics/intents/intents-filters.htmlLaunchersA Launcher is an API that starts built-in applications in WP7. Your application cancomplete the tasks through these built-in applications for which no data is returnedback to your application. Let‟s take the example of PhoneCallTask. Your applicationcan provide the PhoneCallTask Launcher with a phone number and display a nameto access the phone. When the phone displays the built-in application, the user canchoose whether to initiate the call by using the supplied parameters. When the usercloses the built-in application, your application is activated again. But the built-inapplication does not return any data that result from the user‟s actions. 81
  • Windows Phone 7 Guide for Android Application DevelopersChoosersA Chooser is an API that launches the built-in applications in WP7. Your applicationcan complete various tasks by using these built-in applications for which yourapplication needs data in return.For example, consider the PhotoChooserTask. Your application can use thePhotoChooserTask Chooser to show the built-in Photo Chooser application. The usercan either select a photo or close the Photo Chooser. Now, WP7 activates yourapplication and supplies the result of the Chooser. The result indicates whether theuser completes the task. If the user completes the task, the result includes an I/Ostream that contains the image data of the photo.After the Photo Chooser application is launched, the user can press the Start buttonon the phone and select another application. In this case, WP7 does not reactivateyour application and does not return the results generated by Chooser. Yourapplication should handle this ambiguity properly.Comparing Intent API with Launchers and Choosers APIThis table compares the Intent API of Android with Launchers and Choosers APIs ofWP7. This section compares the mechanism of handling cross application data andperforming tasks based on data I/O in WP7 and Android platforms.Function Android Windows Phone 7Camera Intent intent = new CameraCaptureTask Intent("android.media.action. IMAGE_CAPTURE"); startActivityForResult(intent, cameraCaptureTask = new 0); CameraCaptureTask(); cameraCaptureTask.Completed += new EventHandler<PhotoResult> (cameraCaptureTask_Complete d); cameraCaptureTask.Show();Email Intent emailIntent = new EmailAddressChooserTask,chooser and Intent(android.content.Intent.ACT EmailComposeTask, ION_SEND);composer EmailResult, SaveEmailAddressTask emailIntent .setType("plain/text"); EmailComposeTask emailIntent emailComposeTask = new .putExtra(android.content.Intent. EmailComposeTask(); EXTRA_EMAIL, new String[]{"webmaster@website.com"} emailComposeTask.To = 82
  • Windows Phone 7 Guide for Android Application DevelopersFunction Android Windows Phone 7 ); "user@example.com"; emailIntent emailComposeTask.Body = .putExtra(android.content.Intent. "Email message body"; EXTRA_SUBJECT, mySubject); emailComposeTask.Cc = emailIntent "user2@example.com"; .putExtra(android.content.Intent. emailComposeTask.Subject = EXTRA_TEXT, myBodyText); "Email subject"; startActivity(emailintent); emailComposeTask.Show();Market Intent market_intent = new Intent MarketplaceHubTask, MarketplaceDetailTask, (Intent.ACTION_VIEW, MarketplaceReviewTask, Uri.parse("market://search? q=pname:com.google.somepackage") MarketplaceSearchTask ) startActivity(market_intet); MarketplaceSearchTask marketplaceSearchTask = new MarketplaceSearchTask(); marketplaceSearchTask. SearchTerms = "accelerometer xna"; marketplaceSearchTask.Show( );Media player Intent i = new MediaPlayerLauncher Intent(Intent.ACTION_VIEW); Uri u = Uri.parse(xpath); i.setData(u); MediaPlayerLauncher startActivity(i); mediaPlayerLauncher = new MediaPlayerLauncher(); mediaPlayerLauncher.Media = new Uri("MyVideo.wmv", UriKind.Relative); mediaPlayerLauncher.Location = MediaLocationType.Data; mediaPlayerLauncher.Controls = MediaPlaybackControls.Pause | MediaPlaybackControls.Stop; mediaPlayerLauncher.Show();Phone call String url = "tel:3334444"; PhoneCallTask Intent call_intent = new Intent 83
  • Windows Phone 7 Guide for Android Application DevelopersFunction Android Windows Phone 7 (Intent.ACTION_CALL, Uri.parse(url)); PhoneCallTask phoneCallTask startActivity(call_intent); = new PhoneCallTask(); phoneCallTask.PhoneNumber = number; phoneCallTask.DisplayName = name; phoneCallTask.Show();Address book In Android you can access PhoneNumberChooserTask, anything that is stored in the PhoneNumberResult, address book. For example, name, SavePhoneNumberTask address, and number. phoneNumberChooserTask = new Intent intent = new PhoneNumberChooserTask(); Intent(Intent.ACTION_PICK, People.CONTENT_URI); phoneNumberChooser Task.Completed += new startActivityForResult(intent, EventHandler<PhoneNumberResu 1); lt> (phoneNumberChooserTask_Comp leted); phoneNumberChooserTask .show();Photo Intent i = new PhotoChooserTask,chooser Intent(Intent.ACTION_GET_CONTENT) PhotoResult ; i.setType("image/*"); photoChooserTask = new PhotoChooserTask(); startActivityForResult(i,4); photoChooserTask.Completed += new EventHandler<PhotoResult> (photoChooserTask_Completed) ; photoChooserTask.Show();Web search Intent search = new SearchTask Intent(Intent.ACTION_WEB_SEARCH); search.putExtra(SearchManager.QUE Task searchTask = new 84
  • Windows Phone 7 Guide for Android Application DevelopersFunction Android Windows Phone 7 RY, "android"); SearchTask(); searchTask.SearchQuery = startActivity(search); txtInput.Text; searchTask.Show();}SMS Intent sendIntent = new SmsComposeTask Intent(Intent.ACTION_VIEW); sendIntent.putExtra("sms_body", SmsMessage SMSComposer = new "The SMS text"); SmsMessage("123456789","This sendIntent.setType("vnd.android- is a sample sms"); dir/mms-sms"); MessagingApplication. DisplayComposeForm(SMSCompos startActivity(sendIntent); er);Web browser Intent myIntent = new WebBrowserTaskchooser Intent(Intent.VIEW_ACTION, Uri.parse("http://www.google.com" )); WebBrowserTask wb= new WebBrowserTask(); startActivity(i); wb.URL = "http://www.google.com"; wb.Show();SummaryIn this chapter we compared data storage guidelines for Windows Phone 7 andAndroid. We also looked at the storage APIs in Windows Phone 7 and Android.Related ResourcesTo learn more about the topics covered in this blog, visit:  Launchers and Choosers Overview for Windows Phone  Launchers and Choosers 85
  • Windows Phone 7 Guide for Android Application DevelopersChapter 7: XML Parsing in WindowsPhone 7 and AndroidThis chapter discusses the XML parsing methods in Windows Phone 7 (WP7) andcompares them with the parsing methods in Android.XML Parsing in Windows Phone 7In WP7, you can parse XML in two ways:  Using XMLReader  Using LINQ to XMLSAXParser and DOMParser are not available in WP7. However, the XMLReader andLINQ to XML parsers function in the same way as these Android parsers.XMLReader is a fast, forward-only, and a non-caching parser. In Android, you usethe SAXParser API when you want a fast parser and want to minimize the memoryfootprint of your application. XMLReader is very similar to SAXParser.LINQ to XML is an in-memory XML programming interface that enables you to editXML documents. LINQ to XML is similar to DOMParser that you use in Java. DOMparser loads the entire XML document to memory and allows you to use the DOMAPIs to retrieve the data that you want.You can use XMLReader to read very large XML documents. Loading largedocuments to an in-memory tree uses a lot of memory and slows downperformance. You can use LINQ to XML for parsing smaller XML documents.XML Namespaces for Windows Phone 7In WP7, the following namespaces are available for XML processing:  System.xml: Provides a standards-based support for processing XML  System.xml.Schema: Contains the XML classes that provide a standards- based support for XML Schema Definition (XSD)  System.xml.Linq: Contains the classes for LINQ to XML  System.xml.Serialization: Contains the classes that are used to serialize objects in XML documents or streamsXML Parsing Using XMLReaderXMLReader provides a forward-only and read-only access to a stream of XML data.XMLReader is similar to SAXParser. SAXParser parse XML node by node and 86
  • Windows Phone 7 Guide for Android Application Developerstraverse a tree view from top to bottom. Here is a sample code that queries theXML data stream to determine the current node type. This sample code usesXMLWriter to generate output the XMLReader content.StringBuilder output = new StringBuilder();String xmlString = @"<?xml version=1.0?> <!-- This is a sample XML document --> <Items> <Item>test with a child element <more/> stuff</Item> </Items>";// Create an XmlReader , this is similar to creating SAXParser instance fromSAXParserFactory in Androidusing (XmlReader reader = XmlReader.Create(new StringReader(xmlString))){ XmlWriterSettings ws = new XmlWriterSettings(); ws.Indent = true; using (XmlWriter writer = XmlWriter.Create(output, ws)) { // Parse the file and display each of the node. In Android, followingiteration is done in handler implementation while using SAXParser while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: // This is similar to startElement() methodof handler in Android writer.WriteStartElement(reader.Name); break; case XmlNodeType.Text: writer.WriteString(reader.Value); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: writer.WriteProcessingInstruction(reader.Name, reader.Value); break; case XmlNodeType.Comment: writer.WriteComment(reader.Value); break; case XmlNodeType.EndElement: // This is similar to endElement()method of handler in Android writer.WriteFullEndElement(); break; } } }} 87
  • Windows Phone 7 Guide for Android Application DevelopersSaxParser and XMLReaderThis table shows a comparison of SAXParser and XMLReader:SaxParser XMLReaderXML data is parsed node by node XML data is parsed node by nodeXML data is not stored in the memory XML data is not stored in the memorynode nodeParsing occurs in the read-only node and Parsing occurs in the read-only node andthe nodes cannot be inserted or deleted the nodes cannot be inserted or deletedDo a top to bottom traversal Do a forward-only traversalXML Parsing using LINQ to XMLLINQ to XML provides a versatile in-memory XML programming API. With LINQ toXML in WP7, you can perform all the operations that you come across while readingand manipulating XML data. LINQ to XML helps you to:  Load the XML data into phone memory in a variety of ways, such as from a file or from XMLReader  Create an XML tree from scratch  Insert the new XML elements into an in-memory XML tree  Delete XML elements from an in-memory XML tree  Save XML to outputs, such as a file or XmlWriterLINQ to XML is similar to DOMParser. However, unlike DOM, LINQ to XML providesa new object-model that is less resource consuming and is easier to work with.In WP7, an application‟s memory-usage, including the UI components and images,cannot exceed 90 MB of the applications memory. Since XML parsing is resourceconsuming, you need to consider your applications memory-usage while using theLINQ to XML API. As parsing XML can be resource consuming, use memory carefullywhile using the LINQ to XML API.Note: A device whose memory exceeds 256 MB is exempted from the memory-usage restriction. You need to include the UI components, images and any othercontent that are in memory, within that 90MB limit.LINQ to XML Class Hierarchy 88
  • Windows Phone 7 Guide for Android Application Developers  Although XElement is at a lower level in the class hierarchy, it is the fundamental class in LINQ to XML. XML trees are made up of XElements. XAttributes are name or value pairs that are associated with an XElement. XDocuments are created only in certain scenarios, such as to hold a DTD or a top level XML processing instruction (XProcessingInstruction). All the other XNodes can be the leaf nodes under an XElement or Xdocument, if they exist at the root level.  XAttribute and XNode are derived from the common base class XObject. XAttributes are not XNodes because the XML attributes are really the name- value pairs that are associated with an XML element and not with nodes in the XML tree. This behavior of XAttribute is in contrast with W3C DOM.  XText and XCData are available in the present version of LINQ to XML. However, it is best to think of them as a semi-hidden implementation except when exposing text nodes is necessary. You can retrieve the value of the text within an element or attribute as a simple value, such as a string.  XContainer is the only XNode that can have child elements. The child elements can be an XDocument or XElement. The only XNode that can have children is an XContainer. The child elements are either an XDocument or XElement. An XDocument can contain an XElement (the root element), an XDeclaration, an XDocumentType, or an XProcessingInstruction. An XElement can contain another XElement, an XComment, an XProcessingInstruction, or text. You can parse the text that is contained in an XElement in a variety of formats. However, you need to represent the text as an XML tree.Like the Document Class in Android, the XDocument Class in WP7 represents an in-memory XML document. See the sample code below. This sample code creates adocument, and then adds a comment and an element to the document. The samplecode also creates another document using the results of a query. The XElementclass, used in the sample code, is similar to Element class in Android. 89
  • Windows Phone 7 Guide for Android Application DevelopersStringBuilder output = new StringBuilder();XDocument srcTree = new XDocument( new XComment("This is a comment"), new XElement("Root", new XElement("Child1", "data1"), new XElement("Child2", "data2"), new XElement("Child3", "data3"), new XElement("Child2", "data4"), new XElement("Info5", "info5"), new XElement("Info6", "info6"), new XElement("Info7", "info7"), new XElement("Info8", "info8") ));XDocument doc = new XDocument( new XComment("This is a comment"), new XElement("Root", from el in srcTree.Element("Root").Elements() where ((string)el).StartsWith("data") select el )); // In Android to parse the XML tags using DOM, equivalent code isroot.getElementsByTagName(ITEM);output.Append(doc + Environment.NewLine);OutputTextBlock.Text = output.ToString();With DOMParser in Android, you write a series of statements to create an XMLdocument. In WP7, the coding constructs offer you flexibility and help in creating awell-structured code more easily.In Android, you use DOMParser to build an XML tree from the bottom-up. WithDOMParser, you create a document and elements, and then add the elements tothe document. In addition to supporting this approach for constructing an XML tree,LINQ to XML also supports functional construction. Functional construction uses theXElement and XAttribute constructors to build an XML tree. For example, considerthe following XML Data: 90
  • Windows Phone 7 Guide for Android Application Developers<contacts><contact> <name>Patrick Hines</name> <phone type="home">206-555-0144</phone> <phone type="work">425-555-0145</phone> <address> <street1>123 Main St</street1> <city>Mercer Island</city> <state>WA</state> <postal>68042</postal> </address> <netWorth>10</netWorth> </contact> <contact> <name>Gretchen Rivas</name> <phone type="mobile">206-555-0163</phone> <address> <street1>123 Main St</street1> <city>Mercer Island</city> <state>WA</state> <postal>68042</postal> </address> <netWorth>11</netWorth> </contact> <contact> <name>Scott MacDonald</name> <phone type="home">925-555-0134</phone> <phone type="mobile">425-555-0177</phone> <address> <street1>345 Stewart St</street1> <city>Chatsworth</city> <state>CA</state> <postal>91746</postal> </address> <netWorth>500000</netWorth> </contact></contacts>The following example constructs an XML tree by using LINQ to XML functionalconstruction:XElement contacts = new XElement("Contacts", new XElement("Contact", new XElement("Name", "Patrick Hines"), new XElement("Phone", "206-555-0144", new XAttribute("Type", "Home")), new XElement("phone", "425-555-0145", new XAttribute("Type", "Work")), new XElement("Address", new XElement("Street1", "123 Main St"), 91
  • Windows Phone 7 Guide for Android Application Developers new XElement("City", "Mercer Island"), new XElement("State", "WA"), new XElement("Postal", "68042") ) ) );After you indent the code, the XElement constructors resemble the structure of theunderlying XML. The XElement constructor enables functional construction thattakes a params object. This is an example code snippet:public XElement(XName name, params object[] contents)The Contents parameter is flexible and supports an object that is a child of anXElement. The parameters can be:  A string that is added as the text content. This is the recommended way to add a string as the value of an element. The LINQ to XML implementation creates the internal XText node.  An XText, which can have either a string or a CData value added as child content. This parameter is useful for CData values since using a string is easy for ordinary string values.  An XElement that is added as a child element  An XAttribute that is added as an attribute  An XProcessingInstruction or XComment, which is added as child content  An IEnumerable, which is enumerated and these rules are applied recursively  Anything to which the ToString() method is called and the result is added as the text content.  A Null parameter, which is ignored.In this example below, a string Patrick Hines is passed in the name XElementconstructor.<contacts> <contact> <name>Patrick Hines</name> <phone type="home">206-555-0144</phone> <phone type="work">425-555-0145</phone> <address> <street1>123 Main St</street1> <city>Mercer Island</city> <state>WA</state> <postal>68042</postal> </address> <netWorth>10</netWorth> </contact> <contact> <name>Gretchen Rivas</name> <phone type="mobile">206-555-0163</phone> <address> 92
  • Windows Phone 7 Guide for Android Application Developers <street1>123 Main St</street1> <city>Mercer Island</city> <state>WA</state> <postal>68042</postal> </address> <netWorth>11</netWorth> </contact> <contact> <name>Scott MacDonald</name> <phone type="home">925-555-0134</phone> <phone type="mobile">425-555-0177</phone> <address> <street1>345 Stewart St</street1> <city>Chatsworth</city> <state>CA</state> <postal>91746</postal> </address> <netWorth>500000</netWorth> </contact></contacts>Now, see the following scenario:  This string Patrick Hines can also be a variable. For example, new XElement ("name", custName)  This string Patrick Hines can also be a different type besides a string. For example, a new XElement("quantity", 55). This data is the result of the following function call:{... XElement qty = new XElement("quantity", GetQuantity());...}public int GetQuantity() { return 55; }  This string can also be an IEnumerable<XElement>. A common scenario is to use a query within a constructor to create the inner XML. The following code snippet reads contacts from an array of Person objects in a new XML element Contacts.class Person { public string Name; public string[] PhoneNumbers; } var persons = new[] { new Person { Name = "Patrick Hines", 93
  • Windows Phone 7 Guide for Android Application Developers PhoneNumbers = new[] { "206-555-0144", "425-555-0145" } }, new Person { Name = "Gretchen Rivas", PhoneNumbers = new[] { "206-555-0163" } }}; XElement contacts = new XElement("contacts", from p in persons select new XElement("contact", new XElement("name", p.Name), from ph in p.PhoneNumbers select new XElement("phone", ph) ) );The output of the code snippet is as follows:<contacts> <contact> <name>Patrick Hines</name> <phone>206-555-0144</phone> <phone>425-555-0145</phone> </contact> <contact> <name>Gretchen Rivas</name> <phone>206-555-0163</phone> </contact></contacts>Notice how the repeating phone element is generated by queries that return anIEnumerable for:  The inner body of the XML  The repeating Contact element  Each contactYou can use the functional construction to design your output document. You caneither create the subtree of XML items inline, or call out to functions to do the work. 94
  • Windows Phone 7 Guide for Android Application DevelopersTRAVERSING XMLThis section discusses the traditional approaches for navigating through an XMLtree. When XML is available in the in-memory, you usually have to navigate to therequired XML elements. Language-Integrated Query provides powerful options forperforming this task.Getting the Children of an XML ElementLINQ to XML offers ways to access the child elements of an XElement. To access allthe child elements of an XElement or XDocument, you can use the Nodes() method.This returns the IEnumerable<object> because you cannot have text along with theother LINQ to XML types. For example, you need to load the following XML in anXElement called contact:<contact> Met in 2005. <name>Patrick Hines</name> <phone>206-555-0144</phone> <phone>425-555-0145</phone> <!--Avoid whenever possible--></contact>Using the Nodes() methods, you can access all the child elements and generate theoutput by using this code fragment:foreach (c in contact.Nodes()) {//Output the results}This is the output:Met in 2005.<name>Patrick Hines</name><phone>206-555-0144</phone><phone>425-555-0145</phone>For a more specific output, query for the content nodes of an XElement of aparticular type. For example, consider accessing the XElement child elements onlyfor contact XElement. In this case, you can specify a parameterized type:foreach (c in contact.Nodes().OfType<XElement>()) 95
  • Windows Phone 7 Guide for Android Application DevelopersIn the output, you will view only the child element:<name>Patrick Hines</name><phone>206-555-0144</phone><phone>425-555-0145</phone>To get all of the child elements of Contact, use this code:foreach (x in contact.Elements())In the output, you will view only the XElement children:<name>Patrick Hines</name><phone>206-555-0144</phone><phone>425-555-0145</phone>To get all the XElements with a specific name, use the Elements(XName) overloadthat uses an XName as a parameter. For example, to view only the phoneXElements, use the following code:foreach (x in contact.Elements("phone"))In the output, you will view the entire phone XElements:<phone>206-555-0144</phone><phone>425-555-0145</phone>Querying XML using LINQ to XMLThis section describes how to use Language-Integrated Query with XML. The use ofLanguage-Integrated Query in LINQ to XML distinguishes LINQ to XML from otherin-memory XML programming APIs.Language-Integrated Query provides a consistent query experience across thedifferent data models. Language-Integrated Query also provides the ability to mixand match data models within a single query. Here are a few examples of usingLanguage-Integrated Query across data models.Standard query operators form a complete query language for IEnumerable<T>.The standard query operators show up as extension methods on any object that 96
  • Windows Phone 7 Guide for Android Application Developersimplements IEnumerable<T>. You can use Standard query operators like any othermethod.This approach of calling query methods directly is called Explicit Dot Notation. Apartfrom the query operators, there are query expressions for five common queryoperators:  Where  Select  SelectMany  OrderBy  GroupByThe LINQ to XML integration with Language-Integrated Query is apparent in threeways:  Leveraging Standard query operators  Using XML Query extensions  Using XML TransformationLeveraging Standard query operators is common with any Language-IntegratedQuery enabled data access technology and contributes to a consistent queryexperience. Using XML Query extensions and Transformation, provide XML-specificquery and transform features.Using Query Expressions with XMLThis section shows a few examples of using the query expressions with LINQ toXML. Consider the following XML:<contacts> <contact> <name>Patrick Hines</name> <phone type="home">206-555-0144</phone> <phone type="work">425-555-0145</phone> <address> <street1>123 Main St</street1> <city>Mercer Island</city> <state>WA</state> <postal>68042</postal> </address> <netWorth>10</netWorth> </contact> <contact> <name>Gretchen Rivas</name> <phone type="mobile">206-555-0163</phone> <address> <street1>123 Main St</street1> <city>Mercer Island</city> <state>WA</state> <postal>68042</postal> </address> <netWorth>11</netWorth> </contact> <contact> <name>Scott MacDonald</name> 97
  • Windows Phone 7 Guide for Android Application Developers <phone type="home">925-555-0134</phone> <phone type="mobile">425-555-0177</phone> <address> <street1>345 Stewart St</street1> <city>Chatsworth</city> <state>CA</state> <postal>91746</postal> </address> <netWorth>500000</netWorth> </contact></contacts>The following query retrieves all contacts from location Washington and sorts thecontacts by name. The data is returned as string and is displayed in theIEnumerable<string> format.from c in contacts.Elements("contact")where (string) c.Element("address").Element("state") == "WA"orderby (string) c.Element("name")select (string) c.Element("name");This query retrieves all the contacts from Washington that have an area code 206.The result of this query is IEnumerable<XElement>.from c in contacts.Elements("contact"), ph in c.Elements("phone")where (string) c.Element("address").Element("state") == "WA" && ph.Value.StartsWith("206")orderby (string) c.Element("name")select c;In the following example, contacts that have a networth that is greater than theaverage networth are retrieved.from c in contacts.Elements("contact"), average = contacts.Elements("contact"). Average(x => (int) x.Element("netWorth"))where (int) c.Element("netWorth") > averageselect c; 98
  • Windows Phone 7 Guide for Android Application DevelopersSummaryIn this chapter we looked at XML parsing in Windows Phone 7. We also comparedXML parsing in Android and Windows Phone 7.Related Resources  To know more about XML Data and Silverlight, visit: http://msdn.microsoft.com/en-us/library/cc188996(v=vs.95).aspx  To know more about LINQ to XML for Windows Phone 7, visit: http://msdn.microsoft.com/en-us/library/system.xml.linq(v=VS.95).aspx  To know more about processing XML Data with LINQ to XML (Silverlight): http://msdn.microsoft.com/en-us/library/cc189074(v=VS.95).aspx 99