Microsoft Open Technologies, Inc.
8/1/2013
Rev 1.0
Windows Phone 8 Guide for Android
Application Developers
Windows Phone Guide for Android Application Developers
Table of Content
Table of Content.....................................
Windows Phone Guide for Android Application Developers
Comparison between C# and Java Features...............................
Windows Phone Guide for Android Application Developers
About this Development Guide
If you have been developing Android ap...
Windows Phone Guide for Android Application Developers
Chapter 1: An Introduction to Windows Phone Platform for Android Ap...
Windows Phone Guide for Android Application Developers
Chapter 1: An Introduction to Windows Phone Platform for Android Ap...
Windows Phone Guide for Android Application Developers
Chapter 1: An Introduction to Windows Phone Platform for Android Ap...
Windows Phone Guide for Android Application Developers
Chapter 1: An Introduction to Windows Phone Platform for Android Ap...
Windows Phone Guide for Android Application Developers
Chapter 1: An Introduction to Windows Phone Platform for Android Ap...
Windows Phone Guide for Android Application Developers
Chapter 1: An Introduction to Windows Phone Platform for Android Ap...
Windows Phone Guide for Android Application Developers
Chapter 1: An Introduction to Windows Phone Platform for Android Ap...
Windows Phone Guide for Android Application Developers
Chapter 2: User Interface Guidelines for the Windows Phone 12
Chapt...
Windows Phone Guide for Android Application Developers
Chapter 2: User Interface Guidelines for the Windows Phone 13
Desig...
Windows Phone Guide for Android Application Developers
Chapter 2: User Interface Guidelines for the Windows Phone 14
Appli...
Windows Phone Guide for Android Application Developers
Chapter 2: User Interface Guidelines for the Windows Phone 15
Andro...
Windows Phone Guide for Android Application Developers
Chapter 2: User Interface Guidelines for the Windows Phone 16
Andro...
Windows Phone Guide for Android Application Developers
Chapter 2: User Interface Guidelines for the Windows Phone 17
Notif...
Windows Phone Guide for Android Application Developers
Chapter 2: User Interface Guidelines for the Windows Phone 18
Andro...
Windows Phone Guide for Android Application Developers
Chapter 2: User Interface Guidelines for the Windows Phone 19
C: Ap...
Windows Phone Guide for Android Application Developers
Chapter 2: User Interface Guidelines for the Windows Phone 20
Windo...
Windows Phone Guide for Android Application Developers
Chapter 2: User Interface Guidelines for the Windows Phone 21
Page ...
Windows Phone Guide for Android Application Developers
Chapter 2: User Interface Guidelines for the Windows Phone 22
Visua...
Windows Phone Guide for Android Application Developers
Chapter 2: User Interface Guidelines for the Windows Phone 23
 App...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 3: An introduction to Windows Phone Developer and Designer ...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 44...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 45...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 46...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 47...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 48...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 49...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 50...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 51...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 52...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 53...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 54...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 55...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 56...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 57...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 58...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 59...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 60...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 61...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 62...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 63...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 64...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 65...
Windows Phone Guide for Android Application Developers
Chapter 4: An Introduction to C# programming for Java developers 66...
Windows Phone Guide for Android Application Developers
Chapter 5: Application Lifecycle Differences Between Windows Phone ...
Windows Phone Guide for Android Application Developers
Chapter 5: Application Lifecycle Differences Between Windows Phone ...
Windows Phone Guide for Android Application Developers
Chapter 5: Application Lifecycle Differences Between Windows Phone ...
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Windows phone 8  guide for android developers
Upcoming SlideShare
Loading in...5
×

Windows phone 8 guide for android developers

1,345

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,345
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
62
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Windows phone 8 guide for android developers

  1. 1. Microsoft Open Technologies, Inc. 8/1/2013 Rev 1.0 Windows Phone 8 Guide for Android Application Developers
  2. 2. Windows Phone Guide for Android Application Developers Table of Content Table of Content................................................................................................................................2 About this Development Guide.................................................................................................... 4 Chapter 1: An Introduction to Windows Phone Platform for Android Application Developers ..........................................................................................................................................5 The Developer Tools...................................................................................................................................5 Windows Phone Architecture...................................................................................................................5 Comparing the Programming Stack of Windows Phone with the Android Stack......................7 Summary.......................................................................................................................................................11 Related Resources.......................................................................................................................................11 Chapter 2: User Interface Guidelines for the Windows Phone ............................................12 Designing the Application Interface......................................................................................................13 Application User Interface Design.........................................................................................................14 Comparing Windows Phone and Android Navigation....................................................................19 Windows Phone Frame and Page Structure......................................................................................20 Application Templates..............................................................................................................................21 Summary.....................................................................................................................................................22 Related Resources.....................................................................................................................................22 Chapter 3: An introduction to Windows Phone Developer and Designer Tools ........... 24 A Comparison of Android and Windows Phone Tools ..................................................................24 Visual Studio is not only a powerful IDE but it can also be extended in a variety of ways. It allows the ability to add macros, options, menus and toolbar commands, visualizers and other tools. In addition, Visual Studio supports NuGet, a package manager, to add, remove and manage libraries and tools in Visual Studio and the .NET Framework. .............................25 Windows Phone tools l............................................................................................................................26 Tool for coding..........................................................................................................................................26 Tools for designing................................................................................................................................... 27 Building Application ................................................................................................................................. 37 Debugging..................................................................................................................................................38 Summary.....................................................................................................................................................43 Chapter 4: An Introduction to C# programming for Java developers .............................44 Managed Programming..........................................................................................................................45 A
  3. 3. Windows Phone Guide for Android Application Developers Comparison between C# and Java Features.....................................................................................46 Key features compared ........................................................................................................................... 57 Summary.....................................................................................................................................................66 Related Resources.....................................................................................................................................66 Chapter 5: Application Lifecycle Differences Between Windows Phone and Android. 67 Android and Windows Phone Application Lifecycle........................................................................ 67 Programming for application States and navigation ......................................................................69 Windows Phone Application LifeCycle................................................................................................69 Comparing Life-cycle Methods............................................................................................................. 70 Windows Phone 8 Application LifeCycle and Tombstoning Example ........................................ 72 Summary..................................................................................................................................................... 77 Related Resources..................................................................................................................................... 77 Chapter 6: Storage on Windows Phone ................................................................................... 78 IsolateStorageSettings lets you save any serializable object to the settings store. .................83 Managing the IsolatedStorage Space .................................................................................................83 Sharing Data Between Applications.....................................................................................................83 Content producers....................................................................................................................................84 Summary.....................................................................................................................................................84 Related Resources.....................................................................................................................................84 Chapter 7: XML Support in Windows Phone and Android.................................................. 85 Traversing XML..........................................................................................................................................89 Summary......................................................................................................................................................91 Related Resources......................................................................................................................................91 Appendix A: Migration Sample .................................................................................................. 92 In-App Advertisements............................................................................................................................93 Appendix B: Using the API Mapping Tool .............................................................................. 101 What’s the API Mapping tool ............................................................................................................... 101 How to use the tool................................................................................................................................. 101 What's next?.............................................................................................................................................. 101
  4. 4. Windows Phone Guide for Android Application Developers About this Development Guide If you have been developing Android applications and are interested in building your applications for Windows Phone, this guide is for you. The guide covers what you need to know to add Windows Phone development to your skill set, while leveraging what you have already learned building Android applications.
  5. 5. Windows Phone Guide for Android Application Developers Chapter 1: An Introduction to Windows Phone Platform for Android Application Developers 5 Chapter 1: An Introduction to Windows Phone Platform for Android Application Developers In late 2010, Microsoft announced the release of Windows Phone 7 which was followed by the release of Windows Phone 8 in late 2012. A large number of devices running Windows Phone operating system are available from a variety of manufacturers all over the world. Over a hundred thousand apps are available on the Windows Phone Store. For Windows Phone, Microsoft went back to the drawing board to figure out what phone users really want, and built a phone from the ground up. The operating system, the user experience, and the application development platform have all been engineered with users in mind. The revenue opportunities in the Windows Phone marketplace, accompanied by a great set of development tools, make Windows Phone a very attractive platform for developers to build applications and games. The Developer Tools Microsoft has released a set of tools as part of the Windows Phone Software Development Kit (SDK) 8.0 for developing Windows Phone applications. The SDK is free and can be downloaded from here. The Windows Phone SDK 8.0 includes:  Visual Studio Express 2012 for Windows Phone, an IDE for developers  Blend for Visual Studio 2012, a User Interface design tool for designers  A Windows Phone emulator to test and debug applications The tools can help you develop consumer applications, business applications or games. While the emulator must be installed on Windows 8 pro edition on a CPU supporting Second Level Address Translation (SLAT) for running Hyper-V, you can still use the SDK to develop Windows Phone 8 apps even if your computer doesn’t support the emulator. See System requirements for Windows Phone Emulator for more information. Windows Phone Architecture Like Android OS, Windows Phone OS is designed to run on multiple phones from multiple vendors. To provide a consistent user experience and features that developers can rely on, Windows Phone defines a minimum set of hardware specifications that all phones must meet.
  6. 6. Windows Phone Guide for Android Application Developers Chapter 1: An Introduction to Windows Phone Platform for Android Application Developers 6 Minimum hardware specifications include an ARM7 CPU, a DirectX capable GPU, a camera, and a multi-touch capacitive display. Standard sensors include: an A-GPS, an accelerometer, a compass, proximity and light sensors. There are three standard physical buttons on the phone – back, start and search. As we will see in a subsequent chapter, these buttons provide an easy and natural navigation model for the user. Most of the Windows Phone 8 apps are built as managed apps using XAML with C# or VB. Windows Phone 8 games are built using Direct3D using C++. It is also possible to render 3D graphics within a XAML UI. It is also possible to build a Direct3D game using a thin XAML wrapper. For more information, see Developing apps for Windows Phone. Windows Phone 8 adopts many of the components of Windows 8, providing better compatibility between the two. Figure 1 Windows Phone 8 Programming APIs .NET API for Windows Phone Windows Phone Runtime Win32 & COM C# / VB C++ Apps with XAML Apps with XAML and Direct3D Games with Direct3D
  7. 7. Windows Phone Guide for Android Application Developers Chapter 1: An Introduction to Windows Phone Platform for Android Application Developers 7 Comparing the Programming Stack of Windows Phone with the Android Stack The Application Model shown above provides services for managing the application lifecycle such as installation and update. The UI model helps to manage the application user interface. Applications are built using various Windows Phone Application Programming Interfaces, APIs, known collectively as the Windows Phone API This table gives an overview of the Windows Phone 8 frameworks that provide features comparable to the Android programming layers. Android Frameworks Functionality Windows Phone 8 Frameworks Android Application Framework Application UI, Device integration (sensors, camera) Windows Phone API Graphics, Animation, Media Direct3D or XAML media and graphics for others Android Libraries Base services, Networking, Text, XML, storage Windows Phone API Android runtime (Dalvik)+ Linux kernel Operating System Windows Phone 8 OS
  8. 8. Windows Phone Guide for Android Application Developers Chapter 1: An Introduction to Windows Phone Platform for Android Application Developers 8 Android and Windows Phone Stacks Side by Side This table compares the Android and Windows Phone 8 Frameworks side by side. Managed Code On Android, you have been developing applications primarily using Java and some native components using C++. On Windows Phone 8 you have the option of using C# or Visual Basic (“managed code”) for XAML applications or C++ for Direct3D game development Execution of C# or Visual Basic (VB) code is managed by the .NET Common Language Runtime (CLR). . Similar to Dalvik VM on Android, CLR is the Virtual Machine (VM) on Windows Phone OS. Similar to Java, C# and VB do not require memory management; CLR handles garbage collection. Android Frameworks Windows Phone Frameworks ApplicationUIandPhone Multi-tasking Java C#,VB,orC++ Multi-tasking ApplicationUIand Phoneintegration Application UI Application UI Device integration Device integration Telephony Telephony Browser Control Browser Control Notifications Notifications Peer to Peer Gaming XAML Direct3D TwoApplicationTypes Controls & Gestures Controls & Gestures CoreWindow (PointerPressed Media Media Framework Media Media Foundation, XAudio2, WASAPI Animation Animation Direct3D Graphics Graphics Direct3D OpenGL-ES File System IsolatedStorage WindowsPhoneAPI SQLLite Location Location XML XML, LINQ Networking Networking, Windows Communication Foundation Libc, Dalvik VM CLR Base Classes Android runtime + Linux kernel Windows Phone OS
  9. 9. Windows Phone Guide for Android Application Developers Chapter 1: An Introduction to Windows Phone Platform for Android Application Developers 9 While most Windows Phone apps are written in C# or VB, you may want to use native C++ code for the following reasons: 1. Portability: This is useful if you are targeting multiple platforms you can write core login in C++. 2. Direct3D: If you want to use Direct3D esp. to develop games, you must use C++. 3. Performance: For some scenarios, you may achieve higher performance using native code. In this paper we are going to focus on managed code. Base Services Windows Phone Base Class Library classes roughly correspond to those provided in the Android Core Libraries. Android core libraries include functionality for media services such as audio and video, graphics and animation using OpenGL and SGL, SQLite for database support and networking services. It also includes LibC and interface libraries to interact with Dalvik VM and the Linux kernel. The Windows Phone Base Class Library layer includes base classes, collections, threading, text processing and IO. The base class library also includes networking stacks, such as HTTP and the Windows Communication Foundation (WCF). WCF provides an easy interface with XML and SOAP services across the web, with support for XML data transfer, serialization/deserialization and XML parsing. While Windows Phone 8 does not have a pre-installed local database such as SQLite, developers can use SQLite in their own application or use Language Integrated Query (LINQ). LINQ support SQL-like queries in C# to query data loaded in memory,stored in isolated storage (see below), or in remote databases such as SQL Azure. Application UI and Device Integration You have a choice of two different stacks in Windows Phone media applications, namely, XAML and Direct3D. XAML for Windows Phone provides controls that are similar to Android standard widgets. It is recommended that you use XAML for Windows Phone for consumer or business applications and Direct3D for games, although you can certainly also develop games using XAML animation. It is also possible to mix XAML and Direct3D to take advantage of specific features available in the two stacks.
  10. 10. Windows Phone Guide for Android Application Developers Chapter 1: An Introduction to Windows Phone Platform for Android Application Developers 10 Android applications Windows Phone counterparts UI using activity(contains widgets) with navigation between them Windows Phone Applications: XAML apps with pages connected by flows 2D or 3D games built with OpenGL-ES Direct3D games Direct3D for Games Windows Phone 8 supports Direct3D for gaming and enables hardware accelerated 3D rendering and graphics. For a high performance game, Direct3D is the right option. Controls and Media You have been using Android controls in your application, , corresponding controls and support for multi-touch are available via XAML. Extensible Application Markup Language (XAML) is a declarative language used to design UI. Windows Phone controls are specifically designed for the primary interaction with touch on a small form factor device. Developers can use separate code-behind files, written in C# or VB, to respond to events or to manipulate the controls. Windows Phone provides high performance audio and video using a variety of CODECs. It supports both vector and bitmap graphics with hardware acceleration. As opposed to a file system, Windows Phone provides sandboxed storage, called Isolated Storage, to store application-specific data. With the isolation of storage, one application cannot affect other applications that are running on the phone. Windows Phone Platform Features If you need to use HTML in your application, you can use the Internet Explorer based browser control for HTML UI. Windows Phone Framework layer also provides interfaces to various sensors, such as the accelerometer or the camera. Similar to Google Cloud Messaging Microsoft provides a push notification service, called Microsoft Push Notification Service.
  11. 11. Windows Phone Guide for Android Application Developers Chapter 1: An Introduction to Windows Phone Platform for Android Application Developers 11 Similar to multitasking in Android, Windows Phone supports multi-tasking. Windows Phone multi-tasking supports fast application switching which allows users to rapidly switch between applications. Multi-tasking also supports running scheduled tasks such as alarms and reminders, background music, GPS tracking and remote communication. If you have used ADMob API to publish advertisements in your Android application, you will find similar functionality in the Microsoft Advertising SDK for Windows Phone. Summary In this chapter we looked at the Windows Phone 8 architecture and the Android and Windows Phone 8 programming stacks. Now that you have a high-level idea of mapping between the two, we are now going to go one level deeper. In the next section, we will look at the user interface guidelines of Windows Phone 8 applications. Related Resources To learn more, visit:  Windows Phone Dev Center. Getting started, download tools and read all about Windows Phone development  Building Apps for Windows Phone 8 Jump Starts. Video series tailored for developers to build Windows Phone apps.  Windows Phone Developer Forums  Developing for Windows Phone Jumpstart Series on Channel 9  Developer Documentation  Windows Phone Code Samples Other Resources you may find useful: 1. Overview of the Windows Phone Application Platform 2. Windows Phone team blog. 3. Windows Phone Programming: Programming guide and reference documents. 4. Visual C# 5. XAML for Windows Phone
  12. 12. Windows Phone Guide for Android Application Developers Chapter 2: User Interface Guidelines for the Windows Phone 12 Chapter 2: User Interface Guidelines for the Windows Phone Microsoft’s Windows Phone uses a novel user interface that sets itself apart with its clean and simple design, emphasis on color and typography. In contrast to the application-focused design of Android, Windows Phone uses an information-centric design. Instead of an array of application icons, the start screen of a Windows Phone consists of dynamic tiles that display critical information at a glance to the user. The tiles are dynamic in the sense they continuously display the up-to-date status of the applications. For example, the Calendar app tile shows you the next appointment, the email tile shows the number of new emails waiting for your attention. Users can personalize their phones by pinning the tiles that they care most about. Windows Phone introduces a new paradigm called “hubs”. Hubs bring related information together. There are six hubs, namely, People, Pictures, Music + Videos, Marketplace, Office, and Games. The People hub, is more than an address book. It aggregates your address book contacts, as well as people and their updates from Facebook, Twitter, and LinkedIn.
  13. 13. Windows Phone Guide for Android Application Developers Chapter 2: User Interface Guidelines for the Windows Phone 13 Designing the Application Interface While Windows Phone user interface is different from that of the Android, there are similarities in the core design principles. Similar Application Design Goals Like Android, Windows Phone developers have to keep in mind the compact screen, lower CPU and limited memory while designing the applications. Users can use one application at a time, with just one screen visible. Both Android and Windows Phone are supported on variety of devices with differing screen resolutions and hardware support. Developers must keep this in mind while designing their application. For additional details on how to built multi- resolution apps, read this article. In both Android and Windows Phone, usability and UI design are not after thoughts, but are the primary goals behind. Applications need to be simple and focus on key scenarios that most users care about. Visual Elements and Direct Manipulation Like Android, visual elements and direct manipulation of objects by touch are the key characteristics of the Windows Phone application. Windows Phone provides a complete set of UI controls designed for the phone that can be manipulated using touch. The controls provide functionality similar to those on Android. It utilizes similar set of core multi-touch gestures as Android with similar semantics – these include tap, double tap, pan, flick, touch and hold, and pinch and stretch. Implications of the Similarities for the Developers For the most part, the application planning process is similar on both the platforms. While designing your Windows Phone application, you will focus on the same information that is critical to the user. Your key design principles from the Android application will get carried over: direct manipulation with multi-touch, the need for immediate feedback and aesthetic appeal, will still remain the same.
  14. 14. Windows Phone Guide for Android Application Developers Chapter 2: User Interface Guidelines for the Windows Phone 14 Application User Interface Design While there are similarities in the design principles of the applications on both platforms, pay close attention to the Windows Phone application user interface. It is best to take advantage of the unique features and strengths of the Windows Phone platform. Design Guidelines Windows Phone provides clear design guidelines, and recommends consistent UI controls, colors, typography and images. Together, they provide a consistent user experience. This can be contrasted with Android which, for a long time, did not encourage simplicity and consistency among application designs.. Unlike Android, Microsoft strongly encourages you to follow the design guidelines so that the users have a consistent user experience. XML and XAML Android UI elements such as widgets and layouts may be specified using XML or created programmatically at runtime or both. Windows Phone uses a similar mechanism. Typically, you use XAML to develop Windows Phone applications. , Extensible Application Markup Language (XAML)is an XML-based markup language used for visual representation of applications in Windows Phone. While both Android and Windows Phone use XML based languages to specify the UI elements, designing Windows Phone UI is much easier thanks to XAML support in Windows Phone design tools namely, Visual Studio and Blend. Both tools support WYSIWYG UI design and produce common XAML code. Controls and the Application Interface The Windows Phone 8 development tools and SDK include a rich collection of controls for Windows Phone that are designed specifically for usability and aesthetics. While you can create your own controls, it is best to use the standard controls wherever possible. These standard controls respond to theme changes and provide a consistent user interface. The following table shows the mapping between Android controls and corresponding Windows Phone 8 controls. Android control Windows Phone control Notes Border Border ButtonView Button
  15. 15. Windows Phone Guide for Android Application Developers Chapter 2: User Interface Guidelines for the Windows Phone 15 Android control Windows Phone control Notes AbsoluteLayout Canvas CheckBox CheckBox GridView Grid HyperlinkButton ImageView Image ListView ListBox MediaController MediaPlayerLauncher MediaPlayer MediaElement MultiScaleImage ViewGroup Panel EditText PasswordBox ProgressBar ProgressBar RadioButton, RadioGroup RadioButton, ToggleSwitch* ToggleSwitch avail on CodePlex ScrollView ScrollViewer SeekBar Slider LinearLayout StackPanel EditText TextBlock EditText TextBox MapView Map WebView WebBrowser Panorama
  16. 16. Windows Phone Guide for Android Application Developers Chapter 2: User Interface Guidelines for the Windows Phone 16 Android control Windows Phone control Notes Pivot TimePicker TimePicker* Available on Codeplex DatePicker DatePicker* Available on Codeplex ExpandableListView Spinner ListBox TableLayout Grid Layout ViewFlipper ZoomControl TabHost PivotControl RatingBar Toggle button ToggleSwitch* * ToggleSwitch and Datepicker/Timepicker control are part of the Windows Phone Toolkit available on Codeplex: As you can see, Windows Phone offers controls that correspond to many Android controls. While the look and feel is different, they provide similar functionality. New Controls in Windows Phone Windows Phone introduces a few controls that have no counterpart on Android. Here are some of the examples:  A multi-scale image control allows the user to zoom in and pan a photo.  Panorama control is a multi-screen page spanning horizontally beyond the width of the phone. It allows a large amount of related information to be presented. The People hub is a great example of this control.  The Pivot control, shown below, is useful to manage views and display information that is logically divided into sections.
  17. 17. Windows Phone Guide for Android Application Developers Chapter 2: User Interface Guidelines for the Windows Phone 17 Notifications Both Android and Windows Phone provide notification service, but notifications play a key role in Windows Phone. Windows Phone provides number of different means to show notifications to users – via status bar update, a dialog, as a toast, or live tile notifications. It is the tile notifications that make Windows Phone come alive. Windows Phone sets itself apart with live tiles that show critical information at a glance. Live tiles are used to display non- critical information without disrupting what the user is doing. If you are using status bar notifications in Android, you can use tile notification as a replacement in Windows Phone to show critical information. However, tiles have the ability to provide far more information, including photos, a message and a number. The notification service also displays toast notifications that provide time sensitive information, such as an SMS. Toast notifications are shown for about 10 seconds and the user may choose to ignore them or click to launch the app directly. These are similar to Android toast notifications. The following table shows the Windows Phone notifications that are closest to various Android notification mechanisms. While you may replace status bar notifications with Tile notifications, tile notifications provide much richer functionality. Additionally, tile notifications do not require user response.
  18. 18. Windows Phone Guide for Android Application Developers Chapter 2: User Interface Guidelines for the Windows Phone 18 Android Functionality Windows Phone Status bar notification Persistent information that requires user response. Tile notifications Toast notification Time sensitive non-persistent data that the user may not respond to. Toast Notifications ActionBar vs. Application Bar In Android, the ActionBar identifies the application and user location. It also shows actions available to the user as well as navigation such as tabs. The status bar on Android shows the device status and various notifications. While both Status bar and ActionBar are at the top of the screen, action bar may be split and may also be shown at the bottom of the screen. A: Status bar B: Action bar The status bar on Windows Phone provides functionality similar to Android status bar. On Windows Phone, Page or application menus are supported using a versatile application bar shown at the bottom of the screen on Windows Phone. The application bar can include up to 4 of the most common views or application tasks. You can also use application bar menus for additional context-sensitive tasks. Application bar does not provide navigation nor tabbed views as provided by the ActionBar. A: Status bar B: Title, Navigation
  19. 19. Windows Phone Guide for Android Application Developers Chapter 2: User Interface Guidelines for the Windows Phone 19 C: Appbar Android Functionality Windows Phone Status bar Device status and notifications Status bar Action bar Navigation, Title, Buttons for views or actions Back button for back navigation Page title ActionBar Buttons for views or actions App bar Comparing Windows Phone and Android Navigation Windows Phone apps are a collection of pages. Like Android, the user navigates through pages using controls such as buttons and links. Like Android, all Windows Phones have a Back button on them. On Windows Phone the back button behaves much like the back button in the browser allowing the user to navigate between pages of an app or even across apps. For example, consider that the user clicked a link in the email application to launch the browser. With the Back button, the user would return back to the email application. The Back button also closes menus and dialogs. As a developer, you should consider what the Back button means to your user and plan to override it appropriately. For example, you may decide to pause a game by using the Back button on the Phone. The other two hardware buttons on the Windows phone, namely, Search and Home, have fixed behaviors. The Home button takes the user to the Windows phone main page, much like Android. Unlike Android where search button provides context sensitive search, the Windows Phone search button performs a web search using Bing.
  20. 20. Windows Phone Guide for Android Application Developers Chapter 2: User Interface Guidelines for the Windows Phone 20 Windows Phone Frame and Page Structure Each Windows Phone application has a single frame. It includes areas for:  A page where application content is rendered. This is the content where controls or graphics are rendered.  A reserved space for the status bar and application bar. It also exposes certain properties, such as orientation, to the application. Status Bar and Application Bar On Windows Phone, the status bar includes indicators for a variety of system-level status information items such as connection status. The application bar includes the area for the most common application menus, which may include various data views or tasks. The application can manipulate the status bar to change its visibility, opacity or the color. The application can use it to show progress.
  21. 21. Windows Phone Guide for Android Application Developers Chapter 2: User Interface Guidelines for the Windows Phone 21 Page Structure of a Windows Phone Application The following diagram shows the structure of a typical Windows Phone data-bound application, which resembles the structure of a navigation-based Android application. When the user first starts the application, he or she is presented with a splash screen, designed to welcome the user, as well as to create the perception of a fast response. Splash screens are usually an image file of the size of the display. Usually the application starts with the home page, the main navigation page, with links for search, and other page controls. Consider an application that shows information about baseball teams and their players. The primary content page, marked as the widgets page in the above diagram, will have the content of interest, for example, a list of all baseball teams. However, depending on requirements, the home page can also be the primary content page. The user can click on one of the team links to visit the team details page (“widget details page”) which can provide multiple views. The page may employ a pivot control or a panorama to display different views such as the team summary and the list of all players (“list of gadgets”) from that team. Selecting one of the baseball players will take the user to the page with player statistics (“Gadget Details page”). Such a page may use controls such as textblocks, multi-scale images, or other multimedia using a MediaElement control.  Users may also use the search page to search and directly access the team page (“widget details”) or the player page (“gadget details”) Application Templates
  22. 22. Windows Phone Guide for Android Application Developers Chapter 2: User Interface Guidelines for the Windows Phone 22 Visual Studio Express 2012 for Windows Phone provides a variety of templates for developing Windows Phone 8 applications. Visual Studio templates create the appropriate structure of the application automatically. Functionality Android Activity Template Visual Studio Template Information drilldown applications Master/Detail Flow, Blank Activity Windows Phone Data-bound App, Pivot App, Panorama App Utility applications. For example, Bubble Level Fullscreen Activity, Blank Activity Windows Phone App Games Fullscreen Activity, Blank Activity Windows Phone Direct3D App (Visual C++) app Flexible template to design any application Blank Activity Windows Phone App You can choose the Windows Phone application template to either create an application with functionality similar to the view-based or the window-based Android application type. Summary In this chapter we looked at the similarities between the application design goals of the Android and Windows Phone 8 platforms. When you plan your Windows Phone 8 application, you will be able to leverage your existing work on Android applications. Revisit the application interface design to make sure you are taking advantage of the Windows Phone controls and Windows Phone design and interface guidelines. You will find that the Windows Phone 8 offers a large library of controls and gestures that have close counterparts on Android. This chapter also showed you the use of innovative controls like Panorama and explored the use of live tiles in building an engaging Windows Phone 8 experience. Related Resources To learn more, visit:  Windows Phone User Interface Guidelines  Windows Phone SDK ToolsWindows Phone toolkit on Codeplex Other Resources you may find useful:
  23. 23. Windows Phone Guide for Android Application Developers Chapter 2: User Interface Guidelines for the Windows Phone 23  App page model for Windows Phone  In-app navigations for Windows Phone
  24. 24. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 24 Chapter 3: An introduction to Windows Phone Developer and Designer Tools Along with the release of the Windows Phone OS , Microsoft published the user-friendly, high productivity Visual Studio Development environment for Windows Phone 8 development. Developers who have used Visual Studio will find themselves in a familiar environment. An Android application developer who is familiar with Eclipse will find it easy to quickly migrate to Windows Phone 8 developer tools and quickly become productive. A Comparison of Android and Windows Phone Tools Visual Studio Express 2012 for Windows Phone is a full-featured Integrated Development Environment (IDE). Visual Studio 2012 facilitates designing, developing, and debugging of Windows Phone applications. Other Windows Phone 8 tools that can help you in the development cycle of the Windows Phone 8 application are:  Blend for Visual Studio  Windows Phone Emulator Compared to Android developer tools, the Windows Phone 8 developer tools offer richer functionality. The following table gives an overview of the functionality of each of these tools. The table also indicates the equivalent tools that you would use for Android application development. Functionality Audience Android tools Windows Phone tools Application development (coding) Programmers Eclipse Visual Studio Express 2012 for Windows Phone Game development (coding) Programmers Eclipse Visual Studio Express 2012 for Windows Phone Testing / Emulation Testers Android Emulator Windows Phone Emulator in Visual Studio Express 2012 UI design UI designers and programmers Defined in XML(Some Visual Studio Express 2012 and Blend for Visual Studio
  25. 25. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 25 As you plan to develop applications for Windows Phone 8, you can continue to leverage the skillsets in your team. Your development team structure and overall development process can remain the same. The Windows Phone 8 toolset ensures that the entire team of designers, developers, and testers familiar with Android development tools will find it easy to migrate to the Windows Phone 8 toolset. Visual Studio is not only a powerful IDE but it can also be extended in a variety of ways. It allows the ability to add macros, options, menus and toolbar commands, visualizers and other tools. In addition, Visual Studio Primary UI design: Colors, gradients, and animation UI designers WYSIWYG support via ADT plug-in) Pixel accurate WYSIWYG layout using Blend for Visual Studio
  26. 26. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 26 supports NuGet, a package manager, to add, remove and manage libraries and tools in Visual Studio and the .NET Framework.Windows Phone tools l Windows Phone development tools facilitate a close collaboration between designers and developers through the use of Blend and Visual Studio. The UI for a Windows Phone app is created using XAML, a declarative XML-based language. Both Blend and Visual Studio can be used to edit the XAML file, allowing designers and developers to use tools targeted toward their discipline Tool for coding The file structure of a Windows Phone app Like Eclipse, Visual Studio Express 2012 for Windows Phone is a full-featured IDE. It allows you toorganize the source files s. as a collection of projects, i.e. separate functional units. The organization of the codebase into projects makes it easy to manage manage the work among team members. Visual Studio integrates a compiler and a debugger, both of which can be invoked either interactively or via the command line. In this chapter we will walk through the creation of a simple Shopping List app in order to illustrate the Windows Phone development tools and steps. Let us create a sample application 1. Start Visual Studio Express for Windows Phone from the Windows Start menu. 2. In Visual Studio Express, click File.
  27. 27. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 27 3. Click New Project. 4. In the New Project dialog expand Installed -> Templates -> Visual C# -> Windows Phone Select Windows Phone App. 5. In the Name text box, enter “ShoppingList” as the name of the project, and click OK. Visual Studio Express will prompt you select the OS you want to target. Select “Windows Phone OS 8.0” and Visual Studio will create the new project as shown below. The Solution Explorer pane displays the solution that you have created. This solution has only one project, also named ShoppingList. The project contains the sources code and other files. Note: Visual Studio Express 2012 for Windows Phone does not provide integration with source control systems. The Visual Studio Professional edition provides features such as integration with various source control systems like Subversion. Alternatively, organizations can use the Visual Studio Team System, an edition designed particularly for greater communication and collaboration among software development teams, for developing your Windows Phone application Tools for designing The Windows Phone 8 developer toolset includes two UI design tools:  Visual Studio UI Designer  Blend for Visual Studio
  28. 28. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 28 Compared to Eclipse ADT UI plugin, Visual Studio UI design tool is much simpler and richer. Android application developers migrating to Windows Phone 8 developer tools will find the task of designing an application UI much easier. The main page for our ShoppingList solution, MainPage.xaml, is already opened in the Visual Studio UI designer tool for editing (shown above). Let us change the title of the application, as well as the title of the current page. Right click on the title, “MY APPLICATION” and select Properties. In the properties window, select Text and type “SHOPPING LIST.” Similarly, change the title of the page by typing “my list” in the Text property of the title. Let us design the interface of the main page of the application. 1. Open the Toolbox window (View -> Other Windows -> Toolbox) if not already open, drag a TextBlock and drop it on the page in the designer window. Position it so that it is at the top left. Click and select the TextBlock and update its Text property to “Item:” in the Properties window.
  29. 29. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 29 2. Drag a TextBox from the toolbox and place it underneath the text block created in the previous step. 3. Update the Textbox’s Text property to delete any existing entry. 4. In the Properties window for the textbox, enter “txtItem” in the name field to set the Name of the text box to txtItem. The properties pane in the VS UI is in sync with the XAML code in the code editor window. You can set properties for controls manually in XAML or set them in the UI using properties panel. 5. Resize the text box by dragging its lower right corner so that its width is 300. 6. Drag a Button to the right of the TextBox. 7. Change the button’s Content property to “Add”, and its Name to “btnAdd”. 8. Resize the button so that its width is 140. 9. Drag another TextBox and place it underneath the txtItem textbox. 10.Resize the new TextBox so that it covers the rest of the phone screen. 11.Update the Name of the new TextBox to “txtList”. 12.Update the Text property of the new TextBox to “Nothing here yet!” At this point, your application should look something like this: 13.Click F5, or Debug and Start Debugging, to compile the application and launch it.
  30. 30. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 30 This will start the Windows Phone 8 emulator, deploy the ShoppingList application and run it. You can click on Add, but nothing will happen as we have not written any logic yet. Blend for Visual Studio Blend for Visual Studio is a full featured visual UI design tool created for designers. There is no exact counterpart to this in the Android development toolset. Similar to the Visual Studio design tool, Blend also allows drag and drop to design the UI. The tool, shown below, allows pixel accurate layout of controls. They can easily create and use color palettes and gradients, as well as special effects such as reflections and shadows. The tool can import Photoshop files, which makes it easy to bring your Android application resources to your Windows Phone application. Designers can also use the tool to define application behavior, as well as certain animations, without any programming.
  31. 31. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 31 You will need to use Visual Studio to code your application logic, but you can create the UI in VS UI or Blend. Both tools include the same control set that provides accurate fidelity to their run time visual representation, making it easy to visualize the application.
  32. 32. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 32 Editing Code Visual Studio has a simple to use, full-featured, configurable source editor. The editor has various features that are familiar to Eclipse users. These include flexible search, rich editing, code formatting, and the ability to outline/hide code. Let us now proceed to add some logic to our application. : 1. Stop the running application by clicking Debug, then click Stop Debugging. Leave the emulator running so that it doesn’t need to start up again the next time you debug. This speeds up the subsequent debug sessions. 2. Double click the “Add” button which will open MainPage.xaml.cs with a method btnAdd_click in the MainPage class. 3. To add logic for adding items to the shopping list, edit the btnAdd_click method. Enter the following code: string tStr = txtItem.Text; Unlike Android where objects must be dereferenced in Java using getViewById, in XAML, objects created in XAML are accessible in code-behind C# or VB files. The specified x:Name or Name attribute of a XAML object becomes the name of a field that is created in the underlying code when XAML is processed. This allows us to access the textbox using txtItem, its x:Name attribute. IntelliSense in Visual Studio
  33. 33. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 33 When you enter "t" for "txtItem", Visual Studio displays the auto-completion dialog box. The Visual Studio equivalent for Eclipse auto-completion content assistant is called Intellisense. 4. Enter the following code in the btnAdd_click method: if (!string.IsNullOrEmpty(tStr)) When you type "string", Visual Studio displays the auto-completion dialog box. When you type "Is", Visual Studio displays the class methods of the String class. As you see below, it provides a synopsis of the IsNullOrEmpty method. IntelliSense has a rich feature set. It uses history, code context, and .NET reflection for intelligent auto-completion. IntelliSense can suggest and complete variable names, parameters, classes, and method names. IntelliSense can also generate appropriate code where needed, as shown in the code below: To complete the event hookup, it will also generate an empty stub for the event handler, in this case, the button1_click method.
  34. 34. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 34
  35. 35. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 35 You will find the generated event handler in the C# code void button1_Click(object sender, RoutedEventArgs e) { throw new NotImplementedException(); } The default code would throw an exception if you forgot to implement necessary logic for this handler.Subsequently, we will implement the logic to handle the button click. Code Snippets in Visual Studio Visual Studio provides another very useful feature called Code Snippets, similar to code templates in Eclipse, allowing you to insert code fragments with a few clicks. Visual Studio contains a large number of snippets and developers can create their own library of snippets. They can also be indexed and searched using user defined terms. Type ctrl+k ctrl+x to bring up the Insert Snippet prompt. Select Visual C#, followed by “i” to select a code snippet for “if statement”, which will insert an if-statement in the code. The inserted snippet identifies the parts the user needs to complete: Type the remaining code, so that the body of the method is as follows: string tStr = txtItem.Text; if (!string.IsNullOrEmpty(tStr)) { if (!initialized) { txtList.Text = ""; } txtList.Text += txtItem.Text + "n"; txtItem.Text = ""; }
  36. 36. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 36 Make sure that you declare and initialize a variable called initialized as follows. public partial class MainPage : PhoneApplicationPage { bool initialized = false; Visual Studio supports various refactoring mechanisms. You can select any piece of code and right-click the code to access the refactoring menu. The Visual Studio editor is highly customizable. Developers can easily define various keyboard shortcuts or create their own macros. Macros help you to automate repetitive actions by combining a series of commands and instructions. The following table provides various functions and corresponding keyboard shortcuts in both Eclipse and Visual Studio. Tool Run Ctrl+f11 Ctrl+f5 Debug f11 f5 Toggle breakpoint Ctrl+shift+b f9 Switch editor tabs Ctrl+f6 Ctrl+f6 Source code management Comment line/block Ctrl+/ Ctrl+k Ctrl+c Uncomment line/block Ctrl+/ Ctrl+k Ctrl+u Rename Ctrl+shift+r f2 Refactor Ctrl+shift+t Ctrl+R+.. Autocompletion Ctrl+space Automatic Organize imports Ctrl+Shift+o Ctrl+. Format source code Ctrl+shift+f Ctrl+e, f Search Find Ctrl+f Ctrl+f
  37. 37. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 37 Replace Ctrl+f Ctrl+h Find next Ctrl+k f3 Find previous Ctrl+shift+k Shift+f3 Find in files Ctrl+h Ctrl+shift+f Replace in files Ctrl+h Ctrl+shift+h Navigation Goto Line Ctrl+l Ctrl+g Goto Definition Ctrl+click F12 Eclipse users can easily customize Visual Studio Editor to use shortcuts and keyboard combinations with which they are familiar. Developers can change the way various windows are laid out to suit their need. They can also change the way in which various windows are docked within the Visual Studio Shell. Building Application Similar to Eclipse, Visual Studio Express 2012 for Windows Phone allows you to build a Visual Studio solution on demand. Further, each project that is part of the solution can be built separately. Visual Studio uses an XML based, declarative build system called MSBuild which can be compared to Ant or Nant. Builds can be invoked interactively or via a command line for batch processing. This system is flexible and allows you to build a specific target either as a debug build or as a release build.
  38. 38. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 38 Tool for Testing Windows Phone 8 developer tools include an emulator that can be used effectively for testing applications. It provides features that are comparable to the Android simulator included in the developer tools. The Windows Phone 8 emulator provides a virtualized environment in which you can deploy, debug and test applications. The Windows Phone Emulator is designed to provide comparable performance to an actual device and meets the peripheral specifications required for application development. As you can see below, the emulator allows emulation of accelerometer as well as device location. It can be invoked from Visual Studio to load an application package [.xap] within the emulator. Debugging
  39. 39. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 39 Visual Studio Express 2012 for Windows Phone includes a very powerful symbolic debugger that can be used with the Windows Phone 8 emulator or with a remote device. Once the application breaks into the debugger, the developer can view the variables in the application and control the execution. Let us look at the debugger in action. Press F5 to launch the application again. Type “napkins” in the textbox and click Add Napkins is added to our list. Now add, “milk” but find that “napkins” gets removed - not something we expected. In Visual Studio, click in the light blue area to the left of the “string tStr = txtItem.Text;” line in the code window. This will insert a breakpoint at that line. Enter “milk” and click Add. When the application breaks into the debugger, use “Step over” or (f10) to enter the outer if block. Hover over initialized variable in the code as shown and Visual Studio shows its value as false something we did not expect Step through to find that the execution enters the inner if and resets txtList.Text to blank again – therein lies our bug. After adding first item to the list, we should have set the value of initialized to true.
  40. 40. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 40 Fix the bug by adding, initialized = true; in the inner if statement and restart the application. You can inspect any variable, its type, its fields and properties while debugging. For example, hover over txtList and click + to inspect various properties of txtList.
  41. 41. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 41 You can set a “watch” on certain variables to inspect them continuously. Right click txtList, followed by Add Watch. The watch window will show the variable txtList througout. In the debugger, the developer can use the Visual Studio ‘immediate mode’ where one can write managed code instructions to modify or view the variables or execute some code to help with debugging. Update the code and re-launch the application. Test it by adding couple of items to the shopping list.
  42. 42. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 42 Similar to Java applications using Eclipse with ADT, the Windows Phone 8 application debugging is done entirely at the application source code level. Overall, you will find that, with the power of Visual Studio and C#, debugging a Windows Phone 8 application is very easy whether you are running the application in the emulator or an actual device. In addition to the above debug facilities, the .NET Framework includes two specific classes, Debug and Trace, that make it easy to write run-time debug messages to the output window. C# also supports an assert statement, which is evaluated at run time. If the statement evaluates to true, nothing happens, but if the statement returns false, the program breaks into a debugger.
  43. 43. Windows Phone Guide for Android Application Developers Chapter 3: An introduction to Windows Phone Developer and Designer Tools 43 Summary In this chapter we looked at the Windows Phone Developer Toolset. The tool set includes rich tools that are designed to support every step in the entire application development lifecycle. The design, development, and testing tools are amenable to the existing Android team roles and processes. The tight integration between the Windows Phone 8 development tools helps you to streamline the design, develop the workflow, and test the workflow. These tools provide end-to-end functionality and are highly customizable, with the power to make your team quickly productive.
  44. 44. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 44 Chapter 4: An Introduction to C# programming for Java developers In the previous chapter, we looked at the user interface guidelines for Windows Phone 8 applications. We will now dive deeper into what it takes to implement a Windows Phone 8 application. In this chapter, we will look at the various C# features that map to the most common Java features. We will provide code snippets which will ease the transition into C# code. We will point to the key C# features that help you write safe code and enhance productivity.
  45. 45. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 45 Managed Programming Windows Phone 8 supports managed programming in C# or VB as well as C++. In this chapter, we will only look at C# and compare it with Java. Before we jump into the details of C#, let us briefly review the .NET programming environment. Figure 2 Managed Application Execution Flow The C# compiler (and similarly, the VB compiler) compiles the C# (or VB) code in an intermediate language (IL) byte code and metadata. The Common Language Runtime (CLR) executes the byte code. C# uses metadata to manage type safety, exception handling, and run-time validations such as checking array bounds . The CLR also manages memory and performs garbage collection. This is similar to Android where the Java code is compiled into a .dex file which is then executed by the Dalvik VM.
  46. 46. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 46 A Comparison between C# and Java Features There are many many similarities between Java and C#. They both  Are object-oriented and based on C and C++.  support single inheritance and allow classes to implement multiple interfaces.  have objects as reference types.  create instances of a class are created on the heap and do not support explicit delete.  Implement automatic garbage collection. Instances that are no longer accessible, are automatically garbage collected.  type safe languages and require type declaration for all variables. As you will see below, recently C# has started supporting implicitly typed variables where the compiler infers the type automatically.  support built-in threading and synchronization allowing developers to write concurrent programs. However, there are also many subtle and important differences between the two as we will see below. Class Declaration Like Java, C# does not separate class definition from class implementation. The compiler derives the metadata about the class from the class implementation. As in Java, we can define multiple class definitions in the same file. However, unlike Java, more than one class in a file can be public and the name of the file may be different from the public class in the file. In the example, the public signature of the class Person consists of the age property and the constructor. The rest of the class implementation is opaque. using System; // This is similar to java import except //.NET directives are for the whole namespace namespace FirstApplication // scope for classes. Similar to package in Java // Unlike C#, namespace does not force directory { class Person // Like Java, only uses class defined // implementation not declaration. { private DateTime birthDate; // a private field accessible within this class private int ageOn(DateTime date) // a private method accessible in class { TimeSpan span = date.Subtract(birthDate); //like Java uses a .notation to invoke return span.Days; //Unlike Java, C# supports properties }
  47. 47. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 47 } public int age //Unlike Java, C# supports properties. { Get // just a getter; it’s a read-only property { return this.ageOn(DateTime.Now); } } public Person( DateTime dob) // instance constructor similar to Java { birthDate = dob; } } class Program //Unlike Java, another class in the same file. { static void Main(string[] args) // main entry point into the program { Person p = new Person(new DateTime(1973,11,12)); //construct an instance System.Console.WriteLine("The age is is" + p.age.ToString()); DateTime dt = p.birthDate; //error in compilation birthDate is private } } } Instead of using the import statement in Java, C# employs a using statement to refer to the metadata of other classes. The namespace declaration that is shown at the top of the file is used to declare the scope, which avoids name conflict and organizes the code. You can access a class in another namespace by referring to its fully-qualified name. See the reference to System.Console.WriteLine in the example above, where console is in the System namespace. Strong Typing Both Java and C# are strongly typed languages. The types must be specified for variables and input/output parameters1 . The compiler enforces the types. In the section on generics, you can see how C# uses strong typing for collection classes. Strong typing works similarly for all classes. The code example below shows the strong typing for primitive types. int a = 5; int b = a + 2; //OK bool test = true; // OK int c = a + test; // Error. Operator '+' cannot mix type 'int' and 'bool'. Class Constructors 1 C# 4.0 introduced a concept of “var”, i.e. implicitly typed variables. While the developer does not declare the type of such variables, the compiler figures out the actual type variables using the right hand side expression.
  48. 48. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 48 Like Java, C# uses instance constructors to create and initialize instances. For example: p is an instance of the Person class. You can construct and initialize p with a given birthdate, in a single statement. Person p = new Person(new DateTime(1973,11,12)); Properties Unlike Java which has no class properties, C# classes can have properties. Properties provide a natural syntax for accessing members. Properties help to abstract away from directly accessing the members of a class. This technique is similar to using accessors (getters) and modifiers (setters) in Java, but is more natural to read and compact. The properties can be defined as read-only, write-only or read-write. You can make the C# property read-only by providing the getter, write-only by providing the setter, or read-write by providing both getter and setter. In the above example, “age” is implemented as a read-only property since it only exposes a getter and not a setter. You often need to decide whether to implement a member as a property or a method. As a general rule, use properties when you need to access data. To take any action on the data, use methods. Parameter Types Like Java, C# uses value parameters by default. Parameters that are passed by value cannot be modified in the method. But unlike Java, C# also allows the passing of reference parameters by using the ref modifier. You can pass parameters by ref where you want to change the value of the actual parameter. In some cases, you need to use reference parameters for better efficiency since they avoid data copying. void Foo (ref int x, int y) { x = 0; y = 0; } .. int a = 5; int b = 8; Foo (ref a, b); //a is zero and b is still 8 C# also provides the parameters with an out modifier. The out modifier represents the parameters that must be initialized by the called method before returning. This design pattern is often used to return the error in addition to the value of the function. Access Privileges
  49. 49. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 49 Like Java, C# allows access privileges for class members. Access privileges can be specified on fields (for example, birthDate), methods (for example, ageOn) and properties (for example, age). C# uses public, private, and protected as modifiers to denote the three different levels of access privileges. In the above example, the compiler gives an error on p.birthDate since that variable is private. Therefore, p.birthDate is not accessible from the Program class. Similarly, the ageOn method is also private and inaccessible from the Program class. Similar to Java, C# protected members are accessible from derived classes. Methods with Multiple Parameters Both Java and C# support methods with multiple parameters. While C# traditionally uses positional and unnamed parameters, the latest version of C# also includes named parameters. The following example shows the comparative syntax for Java and C#. Java C# void addEmployee(string name, int id, int age); Method signature void addEmployee(string name, int id, int age); Off.addEmployee("Phil",2345, 23); Positional and unmamed parameters Off.addEmployee("Phil",2345, 23); No named parameters Named parameters Off.addEmployee(name: "Phil", age:23, id:2345); Like Java, C# explicitly supports method overloading. Both Java and C# use method name and parameter types for defining method signatures and for differentiating between methods. The following code sample shows how C# differentiates between methods that have the same name. void insert (myClass obj, int index); void insert (myClass obj, myClass before); The method insert may be called with both these signatures: list.insert (myObj1, 4); list.insert ( myInstanceNew, myInstanceOld); Inheritance Like Java, C# uses a single inheritance mechanism. Inheritance is specified by listing the parent class after the class name as shown below. In this example, the class Rectangle inherits from the class Shape, and the class Square inherits from the class Rectangle. class Rectangle : Shape
  50. 50. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 50 class Square : Rectangle Similar to Java, in C#, the no parameter constructor of the base class is automatically invoked when you construct an instance of a derived class. Similarly, a derived class in C# can invoke a specific constructor of the base class if needed. You can see this in the constructor of the Square class. public Square(double s): base(s, s) //constructor. Calls parent constructor explicitly Unlike Java, a C# derived class may not override a method by just redefining it. The class must use the keyword override in its method definition to explicitly override the definition in the parent class. Override modifier is used to modify the abstract or virtual implementation of an inherited method or property. An abstract modifier is intended to denote that a class, method or property. Members marked abstract or included in an abstract class must be implemented by a derived class. A virtual member denotes that it may be overridden in a derived class. The following code sample shows inheritance and how methods can be overridden in a derived class: using System; namespace SecondApplication { struct Point // In contrast to Java C# provides structs { public double x; // struct fields can also have access modifiers public double y; public Point(double p1, double p2) //a constructor for the struct { x = p1; y = p2; } } interface IThreeDShape // an interface, like a Java interface { // defines the behavior double volume { get; // Volume is a read-only property. no setter } } abstract class Shape // this class is marked abstract, i.e. may not be instantiated. { protected Point origin; // only derived classes may access. Similar to Java protected variables protected static int counter = 0; // similar to Java class variables public string ID; protected Shape() //a constructor. Same name as the class name { counter++; // class variable being updated } public Point Origin
  51. 51. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 51 { set { origin = value; } } public abstract double Area //denotes that this property must be overridden in a derived class { get; } public abstract bool contains(Point p); // this method must also be overridden } class Rectangle : Shape // Inheritance. Similar to Java ‘extends’ { public double length; //field accessible from others public double width; public Rectangle(Point o, double l, double w) //a public constructor { ID = "Rectangle_" + counter.ToString(); origin = o; length = l; width = w; } public Rectangle(double l, double w) // one constructor using another constructor //creates a rectangle at the origin : this(new Point(0, 0), l, w) { } public override double Area // Subclass must implement abstract methods of parent class // unlike Java, overridden method must { // use override keyword get { return length * width; } } public override bool contains(Point p) { if ((origin.x < p.x && origin.x + length > p.x) || (origin.x > p.x && origin.x - length < p.x)) if ((origin.y < p.y && origin.y + length > p.y) || (origin.y > p.y && origin.y - length < p.y)) return true; return false; } } class Square : Rectangle { public double side; public Square(double s) : base(s, s) //constructor { ID = "Square_" + counter.ToString(); side = s; } } class Cube : Shape, IThreeDShape //similar to Java, class implements interface { public double side;
  52. 52. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 52 public Cube(double s) { ID = "Cube_" + counter.ToString(); side = s; } public override double Area { get { return 6 * side * side; } } public double volume { get { return side * side * side; } } public override bool contains(Point p) … } class SecondProgram { static void printVolume(IThreeDShape tdShape) { Console.WriteLine("The volume is " + tdShape.volume); } static void Main(string[] args) { Rectangle r = new Rectangle(5.0, 3.0); Cube c = new Cube(4.0); SecondProgram.printVolume(c); double a = r.Area; Console.WriteLine("The area of rectangle " + r.ID + " is " + a.ToString()); bool b = r.contains(new Point(1, 2)); Console.WriteLine("The point is in " + b.ToString()); // will print TRUE } } } Protected Access Like Java, in C#, you can use the protected modifier to limit access to fields, properties, and methods. Protected members are accessible only to derived classes. You can implement protected variables in C# by using the protected access modifier, as shown in the code sample below: protected Point origin; protected static int counter=0; Instance vs. Class Level Access
  53. 53. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 53 Like Java, C# uses a static modifier to denote class level methods, fields, and properties. Other members without static modifier are at an instance level. In the above code example, counter is a class level variable. protected static int counter=0; Abstract Classes Abstract classes in C# are similar to Java abstract classes in that they cannot be instantiated. The class Shape defined in the above C# code sample is an abstract class. It requires that both the Area property and the contains method must have an override in any derived classes. abstract class Shape { public abstract double Area { get; } public abstract bool contains(Point p); Interfaces Interfaces are similar in Java and C#. In the sample code shown below, Interface IThreeDShape is implemented by the Cube class. In both languages an Interface defines a contract consisting of method signatures, but no implementations. A class that implements an interface must implement all methods defied in the interface. interface IThreeDShape { double volume { ... class Cube : Shape, IThreeDShape Polymorphism Both Java and C# provide polymorphism via class inheritance. A class can be used as more than one type - as its own type, as a base type or as one of the interfaces it implements. You can pass a C# derived class as a parameter to a method that expects a base class. Similarly, if a method expects an interface parameter, you can pass an instance of a class that implements that interface. The following sample code shows how to pass an instance of the class Cube as a parameter, where the method expects an object of the class IThreeDShape. static void printVolume(IThreeDShape tdShape)
  54. 54. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 54 { Console.WriteLine(“The volume is ” + tdShape.volume); } … Cube c = new Cube(4.0); SecondProgram.printVolume(c); // Since Cube implements IThreeDShape interface, this is legal Structs Unlike Java, C# provides structs as first class language primitives. In C# structs are similar to classes except that they are a value-type. C# structs can use modifiers and can have constructors, methods, and properties. However, a struct does not implement inheritance. struct Point { public double x; public double y; } Object Lifecycle: Creation and Deletion of Objects Both Java and C# performs automatic memory management. Both languages use the new operator to create objects, i.e. class instances, and initialize them. However, unlike C++, neither of them provide object deletion. Objects are automatically ‘deleted’. When the code execution reaches a place where an object is outside the scope, i.e. it can no longer be accessed, the object becomes eligible for garbage collection. In C#, the garbage collection is implemented using .NET. The .NET CLR garbage collector periodically frees up the memory for the objects that are no longer accessible. Unlike C++, developers do not need to ref count objects nor free up unused objects. In rare circumstances, you may need to perform a cleanup at the time that an object is destroyed. C# allows the use of destructors, which are similar to Java finalizers, but in practice this is rare. Type Checking vs. Reflection Reflection is the ability to discover the members of a class and to invoke methods at runtime. Both Java and C# support reflection. You can use reflection to:  Get information about the type from an existing object.  Dynamically create an instance of a type.  Bind the type to an existing object, access its methods, and access its fields and properties.
  55. 55. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 55 The following table maps the dynamic type checking in Java with its corresponding C# reflection features. Java Reflection Explanation C# Reflection Constructor ct = cls.getConstructor(); Object retobj = ct.newInstance(); Create an instance Activator.CreateInstance(typeof(C If (obj instanceof MyClass) If (MyClass instnceof BaseClass) Is Object a subclass or member? type.IsSubclassOf(typeof(BaseClas object.getClass() Get class object.getType() or typeof search from Method[] methods = c.getMethods(); Does the object implement the method? type.GetMethod(MethodName) Method methlist[] = cls.getDeclaredMethods(); for (int i = 0; i < methlist.length; i++) { Method m = methlist[i]; System.out.println("name = " + m.getName()); Does the class respond to the method? type.GetMethod(MethodName) Method.invoke(..) Invoke a method type.InvokeMember(…) Exception Handling C# and Java support formal exception handling and they have many similarities. They use very similar syntax for declaring exceptions; try blocks delineate guarded regions, catch blocks handle exceptions and finally blocks release any resources. Exceptions can be caught and re-thrown. You can either catch specific exceptions or use a catch-all statement. Unlike Java, C# does not have checked exceptions. In Java, checked exceptions are declared using the “throws” keyword and that must be handled by calling code. In C#, all exceptions are unchecked and there is no counterpart to the throws declaration for the method signature. try { //block of code } //Most specific:
  56. 56. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 56 catch (ArgumentNullException e) { Console.WriteLine(“{0}First exception caught.”, e); } //Least specific catch (Exception e) { Console.WriteLine(“{0}First exception caught.”, e); }
  57. 57. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 57 Key features compared Strings C# provides a comprehensive string class, which offers you all the features that you associate with this class. Java Feature C# Notes String String greeting = “Hello WP!”; Int length = greeting.Length; Comparison String color = “pink”; If (color == “red”) System.Console.WriteLine(“Matchin g colors!”); string name = “Joe”; if (string.compare(name, “Jack”) > 0) System.Console.WriteLine(name + “ comes later”); Strings are compared using ==. They are compared lexicographically using compare. Concatenation System.Console.WriteLine (greeting + " You rock!") Strings can be concatenated with the ‘+’ operator. (This is called operator overloading.) Splitting string rainbow = "Violet, Indigo, Blue, Green, Yellow, Orange, Red"; string[] rainbowColors = rainbos.Split(','); foreach (string color in rainbowColors) System.Console.WriteLine (color);
  58. 58. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 58 Arrays Arrays in C# are almost like arrays in Java. Both support jagged arrays, i.e., arrays of arrays. In addition, C# also supports multi-dimensional arrays which are rectangular. Java Feature C# Notes Arrays of primitive types such as int, float int[] table; table = new int[3]; string[] names = new string[3] {"Peter", "Paul", "Mary"}; Array size is not a part of the array declaration. Arrays can be explicitly initialized. Multi-dim arrays of primitive types Int[,] mAray; Int[][] jaggedArray; string[][] singers = {new string[] {"Peter", "Paul", "Mary"}, new string[]{“Paul”,“Art”}}; C# supports jagged arrays, or arrays of arrays, and they need not be rectangular. Note: Arrays of strings, i.e. objects, work the same way. Mutable array of objects List<string> colors = new List<string>; //list of strings Colors.Add(“Red”); Colors.Add(“Green”); Colors.Insert(1,”White”); String myColor = Colors[0]; //”Red” Colors[colors.IndexOf(“Red”)] = “Pink”; // replace Red with pink You can use Lists as a replacement for mutable arrays. You may also use ArrayLists. Dictionaries C# provides a generic dictionary class that is similar to the HashMap functionality in Java. The generic dictionary class allows you to add, lookup, and remove objects from the dictionary. Since the dictionary class uses Generics, it also utilizes strong typing.
  59. 59. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 59 Java C# Notes HashMap Dictionary<string, int> d = new Dictionary<string, int>(); d.Add("Honda", 124); d.Add("Toyota", 95); d.Add("Ford", 135); // See if Dictionary contains string if (d.ContainsKey("Ford")) // True { int v = d["Ford"]; Console.WriteLine(v); }
  60. 60. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 60 Generics Both Java and C# support generics. Generics introduce the notion of type parameters that make it possible to design classes that are type safe, even though the actual type is deferred till the object’s instantiation. Java implements generics using erasure, i.e. type information is used only at compile time and not at runtime. This introduces certain limitations in Java generics. C#, on the other hand, implements generics using explicit support in .NET CLR. The generated intermediate language (IL) supports the notion of generics. The following code shows how to define a generic stack in C#: Stack<int> intStack = new Stack<int>(); // intStack is a stack of int intStack.Push(1); // OK intStack.Push(2); // OK int number = intStack.Pop(); // this is a type safe assignment Stack<string> strStack = new Stack<string>(); //the type of strStack is different from type of intStack strStack.Push("green"); // OK strStack.Push(23); The Stack<T> uses T as a type parameter, thus allowing you to instantiate a stack of any type. For example: Stack<int> or Stack<string>. You can use them in a type safe manner.
  61. 61. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 61 Operator Overloading Operator overloading is not supported in Java. In C#, Operator overloading allows you to define the implementation of operators for user-defined classes. Use of operators can often improve the readability of the program. Consider the following example of a complex number struct. Operator Overloading allows you to define a + operation that uses a natural syntax. public struct Complex { public int real; public int imaginary; // Declare which operator to overload (+), define how it is computed public static Complex operator +(Complex c1, Complex c2) { return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary); } … Complex c1 = new Complex(3.0, 4.0); Complex c2 = new Complex(4.0, 5.0); Complex cSum = c1 + c2;
  62. 62. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 62 Delegates There is no concept of delegates in Java. The functionality of delegates in C# is like the function pointers in C. However, unlike function pointers, C# delegates are strongly typed and as a result improve program safety and readability. In this design pattern, a class delegates another method with the same signature as the delegate even though the actual method is not known at compile time. using System; namespace DelegateExample { public class ConsoleLogger { public static void WriteString(string s) { Console.WriteLine("Writing to console log: {0}", s); } } public class FileLogger { public static void LogString(string s) { // File.WriteAllText(@"logfile.txt","Logging to file log: "+ s); } } public class DelegatesTest { public delegate void StringDelegate(string s); //Signature for the delegates. // All StringDelegates must have same signature public static void Main() { StringDelegate Writer, Logger; // define twp StringDelegate objects // Create delegates with appropriate methods Writer = new StringDelegate(ConsoleLogger.WriteString); Logger = new StringDelegate(FileLogger.LogString); Writer("Warning message 1n"); // Send to Console Writer delegate method Logger("Warning message 2n"); // Send to File Logger delegate method StringDelegate MultiLogger; // to act as the multicast delegate MultiLogger = Writer + Logger; // combine the two delegates, MultiLogger("Warning message 3"); // This should get sent to both delegates } } } In the above code example, StringDelegate is defined as a function that takes a string as a parameter and returns void. Writer, logger, and multiLogger are constructed by passing methods that have the same signature as the StringDelegate declaration. Calling Writer invokes the writeString method of ConsoleLogger to print the message to the console. Calling Logger invokes the logString method of FileLogger to log the message to the file. Delegates achieve indirection while providing type safety. Delegates may be concatenated as shown by MultiLogger, which logs the message to both loggers. Such a design pattern can only be implemented using reflection in Java. However it does not provide the type safety that delegates provide. Events
  63. 63. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 63 Both Java and C# support event handling though there are significant differences. There is no general mechanism for events in Java though specific design patterns and classes may be used for events. Events are useful in the pub-sub (publisher and subscriber) design pattern and are useful for asynchronous programming. C# events are implemented using delegates. In C#, the event is used to automatically specify that a field within a subscriber is a delegate that will be used as a callback during an event-driven situation. An object can publish an event that a subscriber can subscribe to. When the publisher raises an event, all subscribers are notified without publisher knowing who the listeners are. using System; namespace EventExample { public class ConsoleLogger { public void WriteString(string s) { Console.WriteLine("Writing to console log: {0}", s); } } public class FileLogger { public void LogString(string s) { Console.WriteLine("Logging to file log: {0}", s); } } public class DelegatesTest { public delegate void LogEventHandler(string s); // definition of the delegate. public static event LogEventHandler logEvent; // the signature of the event. public static void Main() { ConsoleLogger cl = new ConsoleLogger(); // create the first subscriber FileLogger fl = new FileLogger(); // the second subscribe logEvent += new LogEventHandler(cl.WriteString); // subscribe the event and hook up the logEvent += new LogEventHandler(fl.LogString); // event handlers logEvent("A new event"); // raise event which will invoke handlers Console.ReadLine(); } } }
  64. 64. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 64 Comparing API Documentation Tools JDK contains an API documentation generation tool called Javadoc. Javadoc automatically generates documentation from the comments that are added to the java source code file. There are a variety of document generation tools that are available for .NET, namely, NDoc, Sandcastle, Doxygen, Doc-O-Matic. . In comparison to Javadoc which produces HTML documentation, NDoc can generate documentation in several formats, including:  MSDN style HTML Help format (.chm)  Visual Studio .NET Help format (HTML Help 2)  MSDN online style web pages Unlike Java doc comments which are written in HTML, C# doc comments use XML as shown below. public class MyClass() { ///<summary> /// ///</summary> ///<param name=”s”></param> Public MyClass(string s) {} } Implicitly Typed Variables There are no implicitly typed variables in Java; all variables must be declared explicitly. However, for C# local variables can be given an inferred "type" instead of an explicit type. The “var” keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. These are still strongly typed variables but they are late bound. There is no counterpart to this in Java. // i is compiled as an int var i = 5; // a is compiled as int[] var a = new[] { 0, 1, 2 }; // londonCustomers is compiled as IEnumerable<Customer> // or perhaps IQueryable<Customer> var londonCustomers = from c in customers where c.City == "London" select c;
  65. 65. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 65 // If a query produces a sequence of anonymous types, // then use var in the foreach statement to access the properties. var upperLowerWords = from w in words select new { Upper = w.ToUpper(), Lower = w.ToLower() }; // Execute the query foreach (var ul in upperLowerWords) { Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower); } This is particularly useful for LINQ query expressions as shown above where the type of the result is based on the query. Async Programming using Async and Await In Visual Studio 2012, C# introduced async programming with compiler and runtime support, which makes it easy to write code that does asynchronous processing. Asynchronism is essential for operations that would otherwise be blocking such as accessing remote data from the web. Using asynchronous programming, activities that do not depend on remote data can continue, thereby improving response time of such operations. There is no counterpart to this in Java. Asynchronous processing in C# uses the keywords “async” and “await”. A method can call other asynchronous methods and can use await to designate a suspension point beyond which it cannot continue until the awaited asynchronous process is complete. Meanwhile, control returns to the caller of the async method. This async method can itself be waited on by methods that call it. The await operator for a method call signifies a suspension point where the calling method waits for the called asynchronous method to return the results. An async method typically returns a Task or Task<TResult> which represents an ongoing work in progress. The Task encapsulates the state of the asynchronous process, and eventually, either the final result or the exception that was raised. async Task WriteLogAsync(string filename, string message) { // Get a reference to the Local Folder Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; // Create the file in the local folder, or if it already exists, just open it Windows.Storage.StorageFile storageFile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists); Stream writeStream = await storageFile.OpenStreamForWriteAsync(); using (StreamWriter writer = new StreamWriter(writeStream)) { await writer.WriteAsync(message); } }
  66. 66. Windows Phone Guide for Android Application Developers Chapter 4: An Introduction to C# programming for Java developers 66 private async void btnAdd_Click(object sender, RoutedEventArgs e) { … Task writeLog = WriteLogAsync("logfile.txt", "btnAdd clicked"); DoLocalWork(); await writeLog; } In the above example, WriteLogAsync is an asynchronous method. It creates a file in the LocalFolder and writes to it asynchronously. Notice the await keyword before writer.WriteAsync(). On the other hand, btnAdd_Click method calls WriteToLogAsync method asynchronously and while the writing is getting completed, continues to do some local work (captured in the DoLocalWork method). Once the local work is complete, it awaits the return from WriteLogAsync method. Summary In this chapter, we looked at C# programming from the perspective of a Java developer. Java and C# have many similarities and yet have some subtle differences. The knowledge of Java and object oriented programming will help you master C# quickly. Related Resources To go deeper into C# and Java, visit:  C# and Java: Comparing Programming Languages  http://www.25hoursaday.com/CsharpVsJava.html To go deeper into NDocs, visit:  http://ndoc.sourceforge.net/  http://shfb.codeplex.com/ – Sandcastle Summary
  67. 67. Windows Phone Guide for Android Application Developers Chapter 5: Application Lifecycle Differences Between Windows Phone and Android 67 Chapter 5: Application Lifecycle Differences Between Windows Phone and Android In this chapter, we look at the application lifecycle of the Windows Phone and compare it with that of Android. We will examine the various application states needed to support the navigation model, and what the developer needs to do to support those application states and the transitions between them. Android and Windows Phone Application Lifecycle Both Windows Phone 8 and Android have a limit of one application running in the foreground. They both support multitasking which allows other applications to run in the background. They both provide an illusion that applications are always running and allow application to be restarted “instantaneously.” Android Application Lifecycle When the user clicks the “home” button or launches another application, instead of terminating the running application, Android moves the foreground activity to the background. The background application remains alive in the phone memory and continues to execute. It can do what it needs to even though it does not have focus. For example, if it has a thread running in the background to download data, it can continue to do so.If the user returns to that activity, the activity is resumed or restarted. However, if there is memory pressure, Android destroys the activity and subsequently the activity must be restarted. In addition, Android applications may include a service, a component that performs long running operations such as background music or data transfer. A service does not present user interface. A service may also be terminated in low memory situations. Windows Phone Application Lifecycle Windows Phone too supports multitasking and provides very similar features as Android. It supports fast application switching and background processing. When the user presses the start button while using an application, that application is deactivated and moved to background and kept intact in memory, in a state referred to as dormant. When the user navigates using the back button on the phone, this application is reactivated. Since the application was in memory, the reactivation is instantaneous. As the user invokes other apps, the Windows Phone OS reclaims memory by terminating dormant apps. Consider that the user is composing a blog post, using the WordPress application, and then hits the start button to reach the Start screen, at which time the WordPress application is made dormant in which the application state is preserved in memory. The user then opens
  68. 68. Windows Phone Guide for Android Application Developers Chapter 5: Application Lifecycle Differences Between Windows Phone and Android 68 up the Facebook application. At this time, the Facebook application is launched. The user can hit the back button while in the Facebook application, to first reach the Windows Phone Start screen, and hit the back button again to go back to the WordPress application. The WordPress application would open with the compose screen, exactly how and where the user left it. The back button on Windows Phone behaves like browser back button. It not only allows the user to move through application pages but also through apps. In addition to using back button, user can switch to another application in a number of ways. This includes fast switching to a dormant app by long pressing the back button, launching another app from the start button, or clicking on a toast or tile. The following table describes the user events and compares the corresponding behavior in Android and Windows Phone. User Action or Event Android Behavior Windows Phone Behavior An incoming phone call or SMS that user answers Running application is moved to the background, current activity is paused but the application is still in memory Running application is deactivated and made dormant User presses the Home button on the phone Running application is moved to the background but application is still in memory and attached to window manager. Any background thread such as downloading data will continue to run. Running application is deactivated and made dormant User starts another application from the multitasking menu Backround app is moved to foreground, If the activity was destroyed, it must be recreated and previous state restored. Running application is deactivated and made dormant. Background application is moved to foreground and reactivated in its original state. User navigates between applications Backround app is moved to foreground, If the activity was Dormant application is made active again with its state intact. If the app was
  69. 69. Windows Phone Guide for Android Application Developers Chapter 5: Application Lifecycle Differences Between Windows Phone and Android 69 using the Back button on the phone destroyed, it must be recreated and previous state restored.. tombstoned it is activated and the app needs to recreate its state User launches application by clicking on a toast Running application is moved to the background, current activity is paused but the application is still in memory. Running application is deactivated and then put into dormant state Programming for application States and navigation As the application makes state transitions in response to various actions or events, Android makes callbacks on the application. In response, the application has to save appropriate state or load it depending on the event. Similarly, Windows Phone OS raises different events in response to which the app has to save or load app state. Android support for multitasking In order to support Android multitasking, Android application developers have certain responsibilities. When the application is moved to the background, they need to save the application state, which must then restored if the activity is recreated. If the activity is resumed or restarted, the state is intact and there is no need to recreate the state. In particular, the application moving to background will receive a callback, onPause(), at which time the application should commit unsaved changes to persistent state and reduce any CPU intensive tasks such as animations. This processing should be quick since another activity is not started till onPause of the previous activity completes. When the activity is no longer visible to the user, onStop() is called at which time, the activity should stop all UI operations. When the system destroys the activity to reclaim memory, onDestroy() is called. When activity is created for the first time, the activity should restore previously frozen state. When the activity becomes visible to the user, system called onStart() method whereas when it comes to foreground, the system calls onResume(). Windows Phone Application LifeCycle Windows Phone Application State Transition Diagram The following state diagram shows the various states and explains what the developer should do in response to various events.

×