Wp8 Guide For Android Devs
Wp8 Guide For Android Devs
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
Windows Phone Guide for Android Application Developers
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.
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.
C# / VB C++
Android runtime
Operating System Windows Phone 8 OS
(Dalvik)+ Linux kernel
Multi-tasking Multi-tasking
Application UI and Phone
Java
Application UI and
Phone integration
Application UI Application UI
Device integration Device integration
Telephony Telephony
Browser Control Browser Control
Notifications Notifications
Peer to Peer Gaming
XAML
Foundation,
XAudio2, WASAPI
Animation Animation Direct3D
Graphics Graphics Direct3D
OpenGL-ES
File System IsolatedStorage
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.
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.
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.
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
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.
Border Border
ButtonView Button
AbsoluteLayout Canvas
CheckBox CheckBox
GridView Grid
HyperlinkButton
ImageView Image
ListView ListBox
MediaController MediaPlayerLauncher
MediaPlayer MediaElement
MultiScaleImage
ViewGroup Panel
EditText PasswordBox
ProgressBar ProgressBar
ScrollView ScrollViewer
SeekBar Slider
LinearLayout StackPanel
EditText TextBlock
EditText TextBox
MapView Map
WebView WebBrowser
Panorama
Pivot
ExpandableListView
ListBox
Spinner
Grid Layout
TableLayout
ViewFlipper
ZoomControl
PivotControl
TabHost
RatingBar
* 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.
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.
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
C: Appbar
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
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.
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
WYSIWYG support
Primary UI UI designers Pixel accurate WYSIWYG
via ADT plug-in)
design: Colors, layout using Blend for Visual
gradients, and Studio
animation
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.
their discipline
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
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.
2. Drag a TextBox from the toolbox and place it underneath the text block created in the
previous step.
3. Update the Textboxs 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 buttons 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.
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.
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.
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 doesnt 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.
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.
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.
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.
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 = "";
}
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
Debug f11 f5
Rename Ctrl+shift+r f2
Search
Navigation
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.
Debugging
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
}
public int age //Unlike Java, C# supports properties.
{
Get // just a getter; its 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.
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.
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
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.
Java C#
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
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
{
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
}
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);
}
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;
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.
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)
{
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;
}
The following table maps the dynamic type checking in Java with its corresponding C#
reflection features.
Create an instance
Constructor ct = cls.getConstructor(); Activator.CreateInstance(typeof(C
Object retobj = ct.newInstance();
Is Object a subclass or
If (obj instanceof MyClass) type.IsSubclassOf(typeof(BaseClas
If (MyClass instnceof BaseClass)
member?
Get class
object.getClass() object.getType() or typeof
Invoke a method
Method.invoke(..) 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:
catch (ArgumentNullException e)
{
Console.WriteLine({0}First exception caught., e);
}
//Least specific
catch (Exception e)
{
Console.WriteLine({0}First exception caught., e);
}
Strings
C# provides a comprehensive string class, which offers you all the features that you associate
with this class.
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.
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.
Java C# Notes
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 objects 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#:
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.
Delegates
There is no concept of delegates in Java. The functionality of delegates in C# is like the
function pointers in C. However, unlike function pointers, C# delegates are strongly typed
and as a result improve program safety and readability.
In this design pattern, a class delegates another method with the same signature as the
delegate even though the actual method is not known at compile time.
using System;
namespace DelegateExample
{
public class ConsoleLogger
{
public static void WriteString(string s)
{
Console.WriteLine("Writing to console log: {0}", s);
}
}
public class FileLogger
{
public static void LogString(string s)
{
// File.WriteAllText(@"logfile.txt","Logging to file log: "+ s);
}
}
public class DelegatesTest
{
public delegate void StringDelegate(string s); //Signature for the delegates.
// All StringDelegates must have same signature
public static void Main()
{
StringDelegate Writer, Logger; // define twp StringDelegate objects
// Create delegates with appropriate methods
Writer = new StringDelegate(ConsoleLogger.WriteString);
Logger = new StringDelegate(FileLogger.LogString);
Writer("Warning message 1\n"); // Send to Console Writer delegate method
Logger("Warning message 2\n"); // Send to File Logger delegate method
StringDelegate MultiLogger; // to act as the multicast delegate
MultiLogger = Writer + Logger; // combine the two delegates,
MultiLogger("Warning message 3"); // This should get sent to both delegates
}
}
}
In the above code example, StringDelegate is defined as a function that takes a string as a
parameter and returns void. Writer, logger, and multiLogger are constructed by passing
methods that have the same signature as the StringDelegate declaration.
Calling Writer invokes the writeString method of ConsoleLogger to print the message to the
console. Calling Logger invokes the logString method of FileLogger to log the message to
the file. Delegates achieve indirection while providing type safety. Delegates may be
concatenated as shown by MultiLogger, which logs the message to both loggers.
Such a design pattern can only be implemented using reflection in Java. However it does not
provide the type safety that delegates provide.
Events
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
Unlike Java doc comments which are written in HTML, C# doc comments use XML as shown
below.
// 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);
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
http://www.25hoursaday.com/CsharpVsJava.html
http://ndoc.sourceforge.net/
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.
See App activation and deactivation for Windows Phone for details of application states and
transitions.
onCreate() Application_Launching
onStart(),
onResume() NavigatedTo
onPause(),onSaveInstanceSta NavigatedFrom
te
onStop(), Application_Deactivated
onSaveInstanceState
onRestart() Application_Activated
onDestroy() Application_Closing
In Android, you can use the onCreate() method to initialize the activity, to setup or recreate
the activity state. In Windows Phone 8, application initialization is performed in response to
application_launching event. Windows Phone application should also load any persistent
state, state that should be preserved between instances of the application, at that time.
In Android, if a user launches a new application, the application in the foreground receives
onPause and onStop callbacks. You need to commit the application data to the persistent
storage or database as part of onPause (or during onSaveInstanceState). In Windows Phone
8, if a user launches a new application, the current foreground application is deactivated. At
the time of deactivation, the application receives the Application_Deactivated event and you
need to save the applications state in its event handler. You have 10 seconds to complete the
processing.
When application is resume, Android makes onRestart and onResume callback methods. If
the activity was in background, there is no need to restore state, . However, if the activity was
destroyed, persistent state must be restored. In Windows Phone 8, when a user starts a
dormant or tombstoned application, the Application_activated event is raised. If the
application is reactivated from a dormant state as indicated by
IsApplicationInstancePreserved property, the application need not do anything. Otherwise,
you should restore the application state from the State object where the state is saved during
deactivation.
In Android, when one Activity replaces another, the current Activity receives the onPause and
onStop callbacks. This behavior is similar to the Page to Page navigation in Windows Phone
8. While moving from one page to another, the current page receives the NavigatedFrom()
event and the new page receives the NavigatedTo() event.
To save the shopping list, we first serialize the list and then save it to the file.
public static void SaveShoppingList(ShoppingListInfo shoppingListInfo, string fileName)
{
//Get the isolatedStore for this application
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
// create a new file
using (IsolatedStorageFileStream fs = isf.CreateFile(fileName))
{
//and serialize data and save it
XmlSerializer xmlSer = new XmlSerializer(typeof(ShoppingListInfo));
xmlSer.Serialize(fs, shoppingListInfo);
}
}
}
In order to save transient state, Windows Phone 8 provides another class called
PhoneApplicationService.State. We will see the use of this object below.
Application Launching
When the application is launched from the Start screen, the application received the
Application_Launching event. This is equivalent to the activity onCreate, onStart and
onResume methods being called.
To improve the application startup time, application should do as little work as possible and it
should avoid loading application state from isolated storage or from remote servers.
In our application, we do no work and leave it to the appropriate page.
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
Application Activation
When the user uses back button to navigate into the application, the application receives the
Application_Activated event. Like the Launching event, doing resource intensive
work in response to this event will delay the app from resuming. Just like
Application_Launching, do as little work as possible.
Application Deactivation
Let us examine what happens when the user navigates forward from the application.e.g. by
hitting the start button while running the application. When the user hits the home button
on Android the onResume of the activity is called. On Windows Phone 8, the application will
receive the Application_Deactivated event. The application would be made
dormant and moreover, it may also be tombstoned. As a result, we save the application
persistent state both in the application state dictionary as well as in isolateStorage. If this
application is reactivated, we will restore either from the state dictionary or from the
isolatedStorage.
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
// If there is data in the application member variable...
if (ApplicationDataObject != null)
{
// Store it in the State dictionary.
PhoneApplicationService.Current.State["ApplicationDataObject"] =
ApplicationDataObject;
Application Closing
This event is raised when the user uses the back button to navigate backward past the first
page, after which the app is terminated. The user must re-launch the application to use it. As
a result, you should save any persistent data but not the transient data.
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
if (ApplicationDataObject != null)
{
// Also store it in isolated storage, so that we can restore the shopping list
SaveShoppingList(ApplicationDataObject, "myDataFile.txt");
}
}
Page Operations
In addition to the above application events, each page needs to override certain methods to
implement Fast Application Switching.
OnNavigatedFrom
OnNavigatedFrom method is called whenever the user navigates away from the page, i.e.
forward or back. In our method implementation, we determine if the user navigated forward,
we save the transient state of the page. This transient state is stored in the application state
dictionary. And we save the rest of the page state in the applications data object which will
be saved to isolatedStorage if the user leaves the application. The transient state is used if the
navigates back to the same page using back button.
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
if (e.NavigationMode !=
System.Windows.Navigation.NavigationMode.Back)
{
PhoneApplicationService.Current.State["ShoppingListItem"] = txtItem.Text;
}
(Application.Current as ShoppingList.App).ApplicationDataObject.ItemsList =
shoppingItems;
}
OnNavigatedTo
OnNavigatedTo method is called whenever the user navigates to a page. In this method, we
check _isNewPageInstance to see if this is a new instance of the page or if the user is
navigating to a page that is already in memory. If it is a new page, and we have restored
application state, we load the page UI from the application state. Otherwise, we load the
page by using a method called GetDataAsync. This method loads the application state
asynchronously so that the page is responsive to user as we load it.
Once we have loaded the persistent state of the page, we load the transient data if any data
is stored in the application state. If any transient state is available in the state dictionary, we
load it and populate the page controls.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// If _isNewPageInstance is true, the page constructor has been called, so
// state may need to be restored.
if (_isNewPageInstance)
{
// If the application member variable is not empty,
// set the page's data object from the application member variable.
if ((Application.Current as ShoppingList.App).ApplicationDataObject != null)
{
UpdateApplicationDataUI();
}
else
{
// Otherwise, call the method that loads data.
(Application.Current as ShoppingList.App).GetDataAsync();
}
}
if (PhoneApplicationService.Current.State.ContainsKey("ShoppingListItem"))
{
// If it exists, assign the data to the application member variable.
txtItem.Text = PhoneApplicationService.Current.State["ShoppingListItem"] as
string;
}
// Set _isNewPageInstance to false. If the user navigates back to this page
// and it has remained in memory, this value will continue to be false.
_isNewPageInstance = false;
}
Summary
In this chapter we had a look at the different states of application life cycle in Android and
Windows Phone. We also compared methods for saving application state data in Android
and Windows Phone.
Related Resources
To learn more about the execution model for Windows Phone, visit:
Launching, resuming, and multitasking for Windows Phone
Implementing the Model-View-ViewModel pattern in a Windows Phone app
App structure and navigation models for Windows Phone
App manifest file for Windows Phone
Asynchronous Programming For Windows Phone 8
Quickstart: Working with settings in Windows Phone
Windows phone uses IsolatedStorage to store data supported by the above abstractions. We
will look at each of the Windows Phone features in detail below.
2
While no database is preinstalled on Windows Phone, app developers can use bundle and use SQLite as part
of their app.
The following table compares the Data Storage Methods in Windows Phone and Android:
Storage Store application data in local Store the application data in the
folder phones internal storage
3
Installation folder is a read-only folder.
In both operating systems, the application developer has to manage the data that gets
stored during application installation or reinstallation. The developer has to modify and
migrate data if the application is updated; the OS does not manage data for the application.
Both operating systems delete the application files and folders in the private store when the
application is uninstalled.
The following table shows how various file operations are accomplished on the two
platforms.
StorageFolder.CreateFileAsync
Create File or open Context.openFileInput,
StorageFolder.OpenStreamForReadAsync
Context.openFileOutput
File StorageFolder.OpenStreamForWriteAsync
StreamWriter.Write
File IO FileOutputStream.write
StreamReader.Read
FileInputStream.read
StorageFolder.CreateFolderAsync
Get or Create Context.getDir
StorageFolder.GetFolderAsync
Directory
Using files from local folder is similar to using regular files. The only difference is that you
have to first access application specific local folder. Here is an example of how you can use
local folder to write to files. In the first line, we retrieve local folder for the calling application.
We create a file in that storage and use a StreamWriter to write to the file. This may be
compared to opening a private file in Android using MODE_PRIVATE mode. Note that most
file and folder operations are asynchronous. The methods ReadFile and WriteToFile are also
marked using async keyword. These methods return a Task which represents an async
operation.
The following code snippet that shows how to read data from files in local folder. The
structure of this code is similar to the above code.
private async Task ReadFile()
{
// Get the local folder.
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
if (local != null)
{
// Get the DataFolder folder.
var dataFolder = await local.GetFolderAsync("DataFolder");
// Read the data.
using (StreamReader streamReader = new StreamReader(await
dataFolder.OpenStreamForReadAsync("logfile.txt")))
{
string text = streamReader.ReadToEnd();
}
}
}
Application Settings
Most applications need to store and use application settings, options, and user data, such as
user language preference, or last used time stamp.
In Android, you can store application settings and data by using the SharedPreferences class.
The SharedPreferences class stores the key value pair of primitive data types. On Windows
Phone 8, you can save such data using the IsolatedStorageSettings class. This is the most
convenient way to store the data. The application can store its settings by using the following
code:
IsolatedStorageSettings.ApplicationSettings.Add(some_property, value);
IsolatedStorageSettings.ApplicationSettings.Save();
The value object is serialized to disk when you call the Save() method. You can read the data
back by using the following code:
List<string> mydata =
(List<string>)IsolatedStorageSettings.ApplicationSettings["some_property"];
IsolateStorageSettings lets you save any serializable object to the settings store.
Content producers
Windows Phone applications cannot directly access information from other information
stores, such as the contacts list or data managed by other applications.
Windows Phone 8 uses a mechanism called Launchers and Choosers which allow one
application to invoke other applications to access data managed by the phone or by other
applications, such as contacts and photos. This avoids the risk of unsafe data access and data
corruption.
Choosers
A Chooser is similar to a launcher except that a Chooser returns data back to the calling
application.
For example, consider that in your app you want the user to select a photo from the photo
gallery. Instead of allowing your app to access photo gallery, Windows Phone allows your
app to invoke the built-in PhotoChooserTask and select a photo. Then the Chooser returns
that photo to your app. .
Summary
In this chapter we compared data storage and access mechanisms for Windows Phone and
Android. We also looked at the file and folder storage APIs in Windows Phone and Android
as well as for application settings. We looked at launchers and choosers from Windows
Phone 8 which allow one app to invoke another without allowing direct data sharing among
apps.
Related Resources
To learn more, visit:
Launchers and Choosers for Windows Phone
String xmlString =
@"<?xml version='1.0'?>
<!-- This is a sample XML document -->
<Items>
<Item >test with a child element <more/> stuff</Item>
</Items>";
// Create an XmlReader
// Uses StringReader which reads from string
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
// XmlWriterSettings specifis options on XmlWriter, i.e. Indent = true
XmlWriterSettings ws = new XmlWriterSettings();
ws.Indent = true;
}
}
As you can see above, handling XML in Windows Phone has many similarities with XMLPullPa
rser in Android.
String xmlString1 =
@"<Items>
<Item>Beer</Item>
<Item>Chips</Item>
<Item>Salsa</Item>
<Item>Cheesecake</Item>
</Items>";
We use the following LINQ query to all children of Items node to extract those that start
with C.
from el in srcTree.Element("Items").Elements()
where ((string)el).StartsWith("C")
select el
You can compare this functionality with the DOMParser in Android where you can build an
XML document from bottom-up. You create the document and add XML elements to the
document.
Functional Construction
LINQ to XML supports functional construction to construct XML using a single statement.
Functional construction uses the XElement and XAttribute constructors to build an XML tree.
For example, consider the following XML Data:
<contacts>
<contact>
<name>Patrick Hines</name>
<phone type="home">206-555-0144</phone>
<phone type="work">425-555-0145</phone>
<address>
<street1>123 Main St</street1>
<city>Mercer Island</city>
<state>WA</state>
<postal>68042</postal>
</address>
<netWorth>10</netWorth>
</contact>
<contact>
<name>Gretchen Rivas</name>
</contact>
</contacts>
The following example constructs an XML tree by using LINQ to XML functional construction:
XElement contacts =
new XElement("Contacts",
new XElement("Contact",
new XElement("Name", "Patrick Hines"),
new XElement("Phone", "206-555-0144",
new XAttribute("Type", "Home")),
new XElement("phone", "425-555-0145",
new XAttribute("Type", "Work")),
new XElement("Address",
new XElement("Street1", "123 Main St"),
new XElement("City", "Mercer Island"),
new XElement("State", "WA"),
new XElement("Postal", "68042")
)
)
);
Traversing XML
This section demonstrates the use of LINQ to XML for navigating an XML tree.
XDocument contacts = XDocument.Load("contacts.xml");
That is all it takes to load XML in a Windows Phone 8 application. Once loaded, you can
query the XML document to not only parse it, but select appropriate nodes from it.
Let us see what it takes to query the above XML document and look for all contacts in the
document. We can search for the descendants of the top element that are of type contact.
The trailing select c is used to select the entire node with contact tag.
We can add filters to the query using a "where" clause on the attribute state. Here we select
all contact where state is WA.
var query1 = from c in contacts.Descendants("contact")
where c.Element("address").Element("state").Value == "WA"
select c;
But, if you do not want the entire node, you can select only certain attributes. For example, in
this example, we create new nodes with just name and networth elements.
var query2 = from c in contacts.Descendants("contact")
where c.Element("address").Element("state").Value == "WA"
select new
{
Name = c.Attribute("name").Value,
Networth = c.Attribute("netWorth").Value
};
from c in contacts.Elements("contact")
where (string) c.Element("address").Element("state") == "WA"
orderby (string) c.Element("name")
select (string) c.Element("name");
In the following example, contacts that have a networth that is greater than the average
networth are retrieved.
from c in contacts.Elements("contact"),
average = contacts.Elements("contact").
Average(x => (int) x.Element("netWorth"))
where (int) c.Element("netWorth") > average
select c;
Summary
In this chapter we compared XML processing technologies available on Android and
Windows Phone. Windows Phone OS provides two different mechanisms: XMLReader, a fast
forward only XML parser, and LINQ to XML, a powerful query mechanism to query XML
documents.
Related Resources
To learn more about XML data, visit:
http://msdn.microsoft.com/en-us/library/2bcctyt8.aspx
To learn more about LINQ to XML for Windows Phone, visit:
http://msdn.microsoft.com/en-
us/library/windowsphone/develop/system.xml.linq(v=vs.105).aspx
To learn more about processing XML data with LINQ to XML:
http://msdn.microsoft.com/en-us/library/bb387098.aspx
The content within is intended to aid you in the process of migrating your Android
applications over to Windows Phone by providing a look at the differences and similarities of
each platform. Through analysis, you'll see how to implement the same functionality on
Windows Phone as you have within your Android application.
In-App Advertisements
Introduction
Advertising in smartphone applications is a proven way to generate revenue from your paid,
trial, and free applications. Each phone platform has frameworks available for presenting ads
with little effort on the developers part. For Android phones, developers can use AdMobTM,
a platform from Google.
You can use Microsoft Advertising platform and SDK for showing ads in your Windows
Phone application. This allows Microsoft AdCenter as well as various other ad networks to bid
for the right show ads in your applications. . In this chapter, we are going to look at the use
of Microsoft Advertising SDK.
In Windows Phone ads can be text- or image-based. Ads are rotated automatically by the
AdControl. The rate at which the ads rotate is controlled by the setting on the AdControl. A
subtle animation helps make those rotations visible but not too jarring while the main part of
the application is being used. A simple vertical motion in the ad content happens as new ad
text appears from the top and the old ad text fades towards the bottom of the control.
Windows Phone uses the AdControl control to present the ads, but the only options that you
have over visuals is to set the BorderBrush property (there are other visual properties that
you may see for this control, but they are inherited from the Control class and will have no
effect). Note that this could be specified in code, but is more commonly specified in the
XAML:
<UI:AdControl Height="80" Width="480" BorderBrush="Blue" />
It is recommended that the ad control be positioned at the top or bottom of the Windows
Phone screen. Place the AdControl outside any scroll viewer otherwise, the ad will scroll on
and off the page. Similarly, ads placed inside Panorama or Pivot control will scroll out of view.
If you want the ad to remain visible, place the AdControl outside these controls.
While AdControl allows sizes of 350x50 and 480x80, the recommended size is 480x80 with
matching ad unit selected in Microsoft pubCenter. If the ad unit in pubCenter is smaller than
the size of AdControl, the ad will be centered in the available space. In fact, if you use any
other size for AdControl, ads may not display in your application. When testing or
debugging your app, you should set the ApplicationId and AdUnitId properties to the test
values so that a test ad is displayed.
This is analogus to including AdView control in the activitys XML layout file.
You must include following capabilities to serve ads in your Windows Phone 8 app:
<Capabilities>
<Capability Name="ID_CAP_IDENTITY_USER" />
<Capability Name="ID_CAP_MEDIALIB_PHOTO" />
<Capability Name="ID_CAP_NETWORKING" />
<Capability Name="ID_CAP_PHONEDIALER" />
<Capability Name="ID_CAP_WEBBROWSERCOMPONENT" />
</Capabilities>
Failure to set these capabilities will result in no ads being served in your app.
Now, run your app in the emulator to see the Ad Control in action. Your app shows a test ad
from Microsoft Advertising as shown below.
Before you receive real ads on your app, you must register the app with pubCenter and
acquire an ApplicationId for the app. You must also register an Ad Unit. However, you can
test the app without registering them. When the AdControl was added to the page, it was
initialized with two attributes, namely, ApplicationId and AdUnitId.
ApplicationId="test_client" AdUnitId="Image480_80"
These values are used only for test purposes. ApplicationId must be test_client as shown
below and AdUnitId Image480_80 for a 480x80 size image.
Follow Getting started instructions listed in Microsoft pubCenter to Create an account and
register the application.
To display the ads, you need to create mobile application ad unit which defines the size and
categories of ads that appear in the Windows Phone app. Select the target categories
appropriate for your app.
Once you have registered your app and ad units (targeted ad content), enter the values of
ApplicationId and AdUnitIId in the AdControl control in your app.
<UI:AdControl ApplicationId="f807XXXXX-bXXd-4XX1-bXX5-37fcXXXX5e6" AdUnitId="123456"
HorizontalAlignment="Left" Height="80" Margin="0,527,0,0" VerticalAlignment="Top"
Width="480"/>
With this change, you can deploy your application to a device and get real advertisements to
show up in your application.
Ad Targeting
Similar to AdMob ad filters that allow the publisher to set categories, and filters, pubCenter
ad units allow you to create customizable targeted ad categories as well as filters consisting
of URLs and keywords. The targeting categories may include Travel and Automtive. You can
select up to three categories per ad unit. Also, like URL exclusions in Like AdMob filters, you
can exclude URLs to certain web sites, for example, your competitors site. For best results,
you will want to create an ad unit that targets the users of your app.
An advantage of ad units is that multiple similar apps can (though dont need to) share the
same ad unit to simplify management.You can also specify ID_CAP_LOCATION capability to
enable location based targeting that can improve quality and relevance of ads shown to your
users. You may specify latitude, logitude, postal code and country or region for better
location-based targeting. This is similar to Android AdView which allows you to specify
latitude, longitude.
Refresh Interval
AdControl includes a property IsAutoRefreshEnabled that creates a background timer to
refresh ads automatically. This property is set to true by default. The default refresh interval
of ads is sixty seconds for the Microsoft AdControl. For iOS, the refresh interval is a server
setting in your iAd account.
To increase the number of advertisements, and potential revenue from ads, you may want to
decrease the refresh interval. In AdControl, turn of auto refresh by setting
IsAutoRefreshEnabled to false and refresh the ad by calling Refresh() on the AdControl.
Location-Based Personalization
The Microsoft Advertising platform allows you to personalize ads based on the users current
location via postal code, latitude/longitude, or country name. Note that performing location-
based customization requires extra steps to actually determine the location. You also need
to notify the user that you are doing this, with the ability to opt-out, and you will need to add
the ID_CAP_LOCATION capability to the manifest file.
Summary
You can easily monetize your Windows Phone applications by using the Microsoft
Advertising controls. Just create your pubCenter account, register your application, register
an ad unit, and embed the AdControl. For more information about Microsoft AdCenterTM
you are encouraged to read the link article Monetize your Windows Phone Apps at
http://advertising.microsoft.com/mobile-apps.
What's next?
Of course, this is a work in progress, coverage will expand and more APIs will be mapped
soon. So, please consider using the mapping tool in your porting efforts, and provide
feedback on the dedicated forum, where you can also suggest new mapping APIs to include:
http://WP7mapping.uservoice.com
Revision History
Rev 1.0:
Creation
This document is provided as-is. Information and views expressed in this document,
including URL and other Internet Web site references, may change without notice. This
document does not provide you with any legal rights to any intellectual property in any
Microsoft product. You may copy and use this document for your internal, reference
purposes. You may modify this document for your internal, reference purposes.
Distributed under Creative Commons Attribution-Noncommercial-No Derivative Works 3.0