O'Reilly logo

Mobile Development with C# by Greg Shackles

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 1. Surveying the Landscape

The last decade has been nothing short of a whirlwind in the mobile space. Phones have been transformed from simple conveniences to indispensable extensions of everyday life. With high-resolution displays, GPS, cameras capable of both still photography and recording high-definition videos, full-featured web browsers, rich native applications, touchscreens, and a constant connection to the Internet, the phone has evolved into a powerful mobile computer. The evolution has gone so far that the actual telephone functionality has essentially become secondary to the rest of the features. Today’s mobile phone is now more than the sum of its parts. It is your connection to the world.

The Players

As with any fast-moving market, there are many players with skin in the mobile game at any given time. This book, however, is going to be focused on three of the bigger names right now:

iOS

It can be argued that Apple is responsible for being the catalyst in bringing about the modern smartphone generation. Back in early 2007, Apple announced the iPhone, which marked the company’s first foray into building their own mobile phone. The product included many features, such as a touchscreen and a focus on a polished user experience, that would quickly become standard in smartphones across the board. In many ways, the iPhone remains the gold standard for smartphones today, even as the market continues to evolve and innovate. Apple’s mobile operating system, iOS, is also found on its tablet offering, the iPad, as well as the iPod, Apple’s portable music player. Since the company produces both the devices and operating system, it maintains a high level of control over its ecosystem.

Android

Since Google purchased it in 2005 and began releasing versions in 2008, Android has taken the smartphone market by storm. Just a few years and numerous versions after its initial release, as of February 2012, Android accounts for just over 50% of the US smartphone market, a number that continues to climb every month (http://www.comscore.com/Press_Events/Press_Releases/2012/4/comScore_Reports_February_2012_U.S._Mobile_Subscriber_Market_Share). Most of Android is open source and licensed in a way that gives hardware vendors a lot of flexibility, so the ecosystem of Android phones is very diverse. Because of that flexibility, many vendors make significant changes to the versions of Android that ship on their devices, so very few devices are actually running a stock version of the operating system. With the release of Honeycomb, Android has also started to stake its claim in the tablet market as well. Additionally, Android can be found in Google’s television platform, Google TV, as well devices such as Barnes & Noble’s Nook Color and Amazon’s Kindle Fire, which bring the richness of tablets to the world of e-readers. Ice Cream Sandwich, the version of Android following Honeycomb, aims to help bridge the growing divide between Android smartphones and tablets.

Windows Phone

In 2010, Microsoft released Windows Phone 7, which marked a long-overdue shift away from its legacy Windows Mobile platform that had long since stagnated. The user interface in Windows Phone 7, dubbed Metro, is decidedly unlike the approach taken by both iOS and Android. A strong emphasis is placed on simplicity, typography, and expansive interfaces that aim to provide a sense of depth and a natural user experience. Device vendors are given a small amount of freedom in designing their devices, but Microsoft maintains a strict set of requirements they have to meet in order to ensure stability and quality, as well as avoid some of the fragmentation problems seen in the Android realm. While the platform is still in the very early stages of its life, Microsoft seems dedicated to pushing the platform forward to try and gain back some of the market share the company has lost over the years. In late 2011, Microsoft shipped the Windows Phone 7.5 update, codenamed Mango, which started to bring in many features missing from the first releases, such as local databases and camera access.

Write Once, Run Anywhere

iOS, Android, and Windows Phone, despite the fact that they are all mobile platforms, have very distinct ways of doing things and their own required languages in which to do them. iOS applications are written in Objective-C, while Android makes use of Java. Windows Phone leverages the .NET Framework, where the primary languages are C# and Visual Basic .NET. You can also use C and C++ on iOS and Android, but they are not currently supported on Windows Phone (see Table 1-1). As developers, we dread the idea of having to repeat all of our work three times in three different programming languages. Aside from the upfront overhead of doing the work three times, bug fixes found later on will also likely have to be fixed three times. For any non-trivial application, the technical debt can add up quickly, so the natural response is to seek out some sort of cross-platform solution to minimize the cost of building and maintaining applications for these devices.

Table 1-1. Native platform languages
 

iOS

Android

Windows Phone

C / C++

XX 

Objective-C

X

  

Java

 

X

 

C#

  

X

Visual Basic .NET

  

X

The promise of a “write once, run anywhere” solution is nothing new in the development world. It tends to come around whenever there’s a need to publish applications on multiple platforms, whether on the desktop or on mobile devices. The mantra was originally coined by Sun when it was pushing for Java to be the unifying language for all platforms and devices. The concept is certainly not unique to Java, though, nor was that the first time such a solution was proposed.

It has a natural appeal to us as developers. Who wouldn’t want a silver bullet like that at our disposal? We could write everything once, get it just the way we want it, and then instantly be able to target users on all platforms. Unfortunately, things that seem too good to be true often are; there’s a reason why Java, over a decade and a half into its life, has yet to become the common language for developing cross-platform desktop applications. I think Nat Friedman, CEO of Xamarin, put it best in an interview he did on the .NET Rocks! podcast:

“‘Write once, run anywhere perfectly’ is a unicorn.”

Now, let me take a step back for just a moment to provide some clarification here. I don’t intend for anything in this chapter, or this book for that matter, to be taken as a slight against frameworks that decided to take this approach to solving the problem. The silver bullet trap works in both directions. No matter the context, there is never a solution so perfect that it solves all problems. Instead, what I will outline in this book is meant to demonstrate only one approach to solving things. It’s another set of tools for your developer tool belt.

Having said that, let’s take a moment to think about who stands to benefit the most from the “write once, run anywhere” method. You could make the argument that the user benefits from you being quicker to market or supporting his platform, and though there is some legitimacy to that, I would tend to disagree. Instead, when all is said and done, it is we, the developers, who really benefit by cutting down the amount of time it takes to write and publish our applications. However, this reduced development time often involves making concessions that sacrifice user experience. Each platform has its own hardware configurations, with varying screen sizes, resolutions, and buttons. Each has its own set of user interaction metaphors and guidelines for how an application should look and behave. In order for your application to look and feel native, it should act like the other applications on that platform.

Writing to the lowest common denominator can end up making your application feel foreign to all of them. Applications on Windows Phone are designed to look and behave differently than those on iOS, and that is something that should be embraced rather than glossed over or abstracted away. The experience you present to your users should be the primary concern when designing your application’s interface. Ultimately, that is what will set your application apart from others who take shortcuts along the way.

By now, you’re probably thinking to yourself, “So if I’m not writing in the platform’s native language, and I’m not leveraging one of these cross-platform frameworks, how do you expect me to write my applications?”

An Alternative Approach

What I am going to propose is an alternative approach where you can leverage the power of the .NET Framework, along with the powerful C# language, across all three platforms. While this may sound similar to “write once, run anywhere,” the key difference is that C# and the Base Class Libraries are used as a universal language and library where the device-specific and user interface-specific elements are not abstracted, but are instead exposed to developers. This means that developers build native applications using three different user interface programming models, one for each platform, while using C# across the board.

As mentioned earlier, .NET is exposed natively on Windows Phone, so there’s no friction there. However, we know that on both iOS and Android it is not, so how can we make this work? To help bridge this gap, a company named Xamarin has created two products, MonoTouch and Mono for Android. We will explore these products in more depth in later chapters, but the elevator pitch is that they allow for writing native applications in C# (see Table 1-2), providing bindings to the platform’s native libraries and toolkits so that you’re targeting the same classes you would in Objective-C for iOS or Java for Android. Because you’re working against the platform’s native user interface toolkits, you don’t need to worry about how to make your application look and feel native to the platform, since it already is.

Table 1-2. Native platform languages with Mono tools
 

iOS

Android

Windows Phone

C / C++

X

X

 

Objective-C

X

  

Java

 

X

 

C#

X

X

X

Visual Basic .NET

  

X

Note

Apple is known for being strict about what gets into the App Store, so you might be wondering whether it will only accept applications written natively in Objective-C. There are actually thousands of MonoTouch applications in the store. In fact, iCircuit, a MonoTouch application, was shipped with their demo iPad 2 units that were sent out to stores.

As the names imply, MonoTouch and Mono for Android expose .NET on iOS and Android by leveraging Mono, an open-source, cross-platform implementation of the Common Language Infrastructure (CLI), an ISO standard that describes the virtual execution environment that is used by C#. Despite the fact that they are commercial products, both offer free evaluation versions that do not expire, and allow you to deploy to the iOS simulator or the Android emulator. There is no risk in taking them out for a spin. In the next chapter, we will explore how to get started with these tools, and build your first application along the way.

Note

Apple and Google release new versions regularly, so you might be wondering what that means for you if you’re using MonoTouch or Mono for Android. Generally, there is no waiting period here, as both products track the beta programs for iOS and Android. For example, MonoTouch typically releases the bindings for a new operating system within 24 hours of the official Apple release. In addition to the quick release cycle, Xamarin offers first-class support for its products, providing prompt responses through mailing lists and IRC, and maintaining thorough, user-friendly documentation. Even outside of Xamarin, the Mono community in general is very active and helpful as well. You can find information about the company and products at http://www.xamarin.com/.

If you’re already a .NET developer, you can immediately hit the ground running, still having the familiar namespaces and classes in the Base Class Library at your disposal. Since the Mono Framework is being used to run your code, you don’t need to worry about whether Objective-C or Java implements a particular C# feature you want to use. That means you get things like generics, LINQ to Objects, LINQ to XML, events, lambda expressions, reflection, garbage collection, thread pooling, and asynchronous programming features. Taking things even further, you can often leverage many existing third-party .NET libraries in your applications as well. You can turn your focus towards solving the business problem at hand instead of learning and fighting yet another set of new languages.

As great as this is, the bigger win with this approach is the ability to share a large percentage of your core application code across all platforms. The key to making the most out of this is to structure your applications in such a way that you extract your core business logic into a separate layer, independent of any particular user interface, and reference that across platforms. By doing so, each application essentially becomes a native user interface layer on top of that shared layer, so you get all the benefits of a native user experience without having to rewrite the application’s main functionality every time (see Table 1-3). In Chapter 3, we will explore some techniques available to help keep as much code as possible in this shared layer and maximize code reuse across platforms.

Table 1-3. Application layers
 

iOS

Android

Windows Phone

Runtime

Mono

Mono

.NET

Business logic

C#

C#

C#

User interface

MonoTouch

Mono for Android

Silverlight

The classes and methods exposed by a framework make up what is referred to as its profile. The .NET profile exposed by both MonoTouch and Mono for Android is based on the Mono Mobile profile. The mobile profile is a version of the .NET 4.0 API that has some of the desktop and server features removed for the sake of running on small embedded devices, such as the System.Configuration namespace. This profile is very similar to the core of Silverlight, which is also a subset of the full .NET profile for the same reasons. Since Windows Phone is also based on Silverlight, there is a large amount of overlap between all three of these profiles, meaning that non-user interface code you write for one platform is very likely to be compatible with the other two.

Note

Technically, the Windows Phone platform supports developing applications using both the Silverlight and XNA frameworks. Since XNA is more suited for game development, this book will focus on building applications with Silverlight. By definition, games define their own user interfaces, so not all of the problems outlined earlier with regards to providing a quality cross-platform user experience will necessarily apply when developing games.

The MonoGame project provides an XNA 2D implementation that runs on both MonoTouch and Mono for Android. This is a third-party community project that is continuously evolving. More information about the MonoGame project can be found at http://github.com/mono/MonoGame.

In later chapters, we’ll explore various patterns and techniques to help maximize the amount of functionality that can go into the shared layer. After walking through the process of creating a simple application for iOS, Android, and Windows Phone, we’ll go through many of the common tasks you’ll want to perform in your applications, such as consuming data from the Internet, persisting data to the filesystem or a database, and accessing the device’s location information and mapping capabilities. As we go through these topics, we’ll discuss how you can achieve some code reusability there as well.

It’s also worth noting that since .NET is being used across the board, reusing code in this shared layer isn’t just limited to mobile applications, or even just Silverlight-based applications. Since the Silverlight profile is essentially a subset of the full .NET Framework, in addition to Silverlight for the web or desktop, the same code can be applied to applications written in ASP.NET, WPF, Windows Forms, or even a Windows 8 Metro application. Using Mono, you can also take your code onto Linux or even the Mac using MonoMac, which takes a similar approach to MonoTouch and Mono for Android. In the end, your code can follow you anywhere the .NET Framework goes. That’s pretty powerful.

Summary

In this chapter, we looked at some of the big names in the smartphone world and evaluated some of the options available to us as developers for building applications on these devices. We then explored how to target all three platforms using the .NET Framework, as well as the benefits this method brings with it. By using this approach, you can develop fully native applications across each platform without having to abstract away the user interface, while still being able to reuse the bulk of your code across them all. In the next chapter, we will walk through setting up your development environment and building your first application on all three platforms.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required