Tuesday, August 27, 2013

Getting Started with Mobility, Part 7: Hybrid Development in JavaScript with Titanium

In this series of posts, we're looking at how to get started as a mobile developer. In Part 1, we provided an overview of the mobile landscape, and discussed various types of client app development (native, hybrid, mobile web) and supporting back-end services. In Parts 2-5, we examined native app development for iOS, Android, Windows Phone, and Windows 8. In Part 6, we begin examining hybrid development, starting with C# using Xamarin. And now, in Part 7, we'll look at JavaScript mobile development using Titanium.



Like Xamarin, Titanium is a hybrid solution that facilitates use of a familiar language and generates native apps. We made the point in Part 6 that any hybrid solution you're considering should be carefully examined to assess cost, performance, reliability, and risk.


Titanium: Mobile Development in JavaScript
Appcelerator Titanium is a leading hybrid mobile platform. JavaScript is arguably the most popular programming language on planet earth today--anyone who does web development has had to learn it, and the language hasn't stopped there: thanks to node.js, it is also being used server-side. It makes sense, therefore, to make mobile app development accessible to the world's large numbers of JavaScript developers. That's what Titanium does. To quote the Titanium web site, Titanium is "An open, extensible development environment for creating beautiful native apps across different mobile devices and OSs including iOS, Android, Windows and BlackBerry, as well as hybrid and HTML5. It includes an open source SDK with over 5,000 device and mobile operating system APIs, Studio, a power Eclipse-based IDE, Alloy, an MVC framework and Cloud Services for a ready-to-use mobile backend."

Titanium generates native apps that execute a JavaScript interpreter at runtime, but a very efficient one, paired with native objects in the mobile platform's runtime environment (see What Titanium Appcelerator Really is and How it Works). This is different from executing within a browser, the approach taken by PhoneGap and Icenium.

Titanium development can be fee or paid, depending on how much of Appcelerator's services you are interested in taking advantage of. From the web site: "The free version of Titanium is primarily a solution for the development of mobile apps, whereas the Appcelerator Platform supports the entire mobile lifecycle, along with commercial support, SLAs and technical training. The Appclerator Platform includes Appcelerator Studio, Appcelerator Alloy, Appcelerator Cloud, Appcelerator Test, Appcelerator Analytics, and Appcelerator Performance Management." (please review Plans and pricing and this forum thread).


The Computer You'll Develop On: Windows, Mac, or Linux
Titanium's IDE, Titanium Studio, is available in Windows, Mac, and Linux editions, giving you a lot of choice in your development machine. You'll be needing a Mac if you intend to do iOS development.


Developer Tools: Titanium Studio
The Titanium Studio IDE is based on Eclipse. A single solution can contain projects for multiple mobile targets, which according to Appcelerator leads to 60-90% code reuse.

Depending on type of computer and whether you have previously installed the SDKs for your target mobile platforms, installing and configuring Titanium may be a breeze or it may have you pulling out your hair--it can take a bit of work before you've got everything in place and the right paths and environment variables set up. The Mac setup appears to be the most streamlined in my experience. There's a Getting Started dashboard in Titanium Studio that works to help with all this.

Titanium Studio - Dashboard

Titanium Studio - on a Mac

Debugging Experience
As you would expect, at runtime you can run in a mobile platform emulator, or an actual device connected to your computer.

For iOS devices, getting your app deployed to an iPhone or iPad requires registering your app with the Apple developer center (a standard requirement) and then deploying through iTunes or XCode and syncing with your device--these are some extra steps you don't have to deal with in other mobile development environments, which some may find cumbersome.

For Android devices, things are a bit simpler: you can deploy and run right out of Titanium Studio.


Programming: JavaScript
Here's a fragment of Titanium JavaScript code (from Seven Days with Titanium).

var table1 =  Titanium.UI.createTableView({
style:Titanium.UI.iPhone.TableViewStyle.GROUPED
});

var section1 = Titanium.UI.createTableViewSection();
section1.headerTitle = "Hello";
var row1 = Titanium.UI.createTableViewRow({title:"Hello 1"});
var row2 = Titanium.UI.createTableViewRow({title:"Hello 2"});
section1.add(row1);
section1.add(row2);

var section2 = Titanium.UI.createTableViewSection();
section2.headerTitle = "Hello2";
var row3 = Titanium.UI.createTableViewRow({title:"Hello 3"});
var row4 = Titanium.UI.createTableViewRow({title:"Hello 4"});
section2.add(row3);
section2.add(row4);

table1.setData([section1,section2]);


Here's how this code renders on iOS and Android:

 

Here's another code example from the same blog series that shows playing video:

var videoURL = 'http://movies.apple.com/media/us/ipad/2010/tours/apple-ipad-video-us-20100127_r848-9cie.mov';

var activeMovie = Titanium.Media.createVideoPlayer({
url: videoURL,
width:300,
height:200,
top:50,
left:50,
backgroundColor:'#0f0'
});

view.add(activeMovie);
activeMovie.play();



Capabilities
Titanium allows you good access to mobile platform APIs. Your code can interact with device sensors like the camera, GPS, and accelerometer; and get to resources like Photos, Contacts, and Maps.

Titanium KitchenSink Sample showing Map Access on iOS
 

Online Resources
The Appcelerator Developer Center includes downloads. documentation, training, and community forums.

Key resources:
Quick Start Guide
Training Resources
Sample Code


Appcelerator Cloud Services
Appcelerator offers Appcelerator Cloud Services, which provide Mobile Backend as a Service (MBaaS) functionality. Services provided include push notification, status updates, photo storage, and social integration.



Tutorials
Appcelerator provides both free training resources as well as paid training classes. Titanium also has a certified developer program.


Creating Your First Titanium Apps

This initial tutorial gets you oriented with Titanium and shows how to import sample projects; and also how to create a custom project.

 
 KitchenSink Sample running on Android and iOS

 
Tutorial App running on Android and iOS


Building Native Mobile App with Titanium

This series of tutorials follows the Titanium Certified App Developer (TCAD) course, an introductory training course. They are fairly sparse, not providing a lot of detail.

1a. Native Android Development
1b. Native iPhone Development

These labs guide you through creating, building, and running a simple "Hello, World" app using native Android and iOS tools.

2. Cross-Platform Mobile Development in Titanium

This lab has you begin creation of a cross-platform mobile app called TiBountyHunter, which enables bounty hunters to track a list of fugitives on their mobile device.

Lab 2 - TiBountyHunter

3. UI Fundamentals

This lab has you create the user interface for TiBountyHunter, including table views and windows. populated with dummy data.

Lab 3 - TiBountyHunter with UI and Dummy Data

4. Working with Local Data

This lab uses data from a local SQL database to populate the app's fugitive list.

Lab 4 - TiBountyHunter with data from local SQL Database

5. Working with Remote Data

This lab enhances the TiBountyHunter app to retrieve a list of fugitives from a remote web service.

Lab 5 - TiBountyHunter - with data retrieved from a Web Service

6. Working with Media and the File System

In this lab, you use the camera to add an image to your fugitive and save the image to the file system.

Lab 6 - Camera Support
 

7. Using Location Services

In this lab, you add geolocation support to TiBountyHunter, storing the coordinates of where a fugitive is captured and providing an option to plot location on a map.

Lab 7 - Location Services

8. Appcelerator Cloud Services

In this lab, you integrate Appcelerator Cloud Services so users can boast about their captured bounties.

Lab 8 - Integrated with Cloud Services

9. Integrating Web Content

In this lab, you integrate web content into a partial RSS reader.

Lab 9 - RSS reader

10. Deploy and Distribute

In this lab, you deploy an app for testing on a physical device and follow steps for publishing to the Android Market and iTunes App Store.


Contrasting Xamarin and Titanium
It's hard not to draw parallels between Titanium and Xamarin because they have many similarities. Like Xamarin, Titanium is all about using a familiar language--JavaScript in this case--to do your mobile development. Like Xamarin, Titanium generates native applications and gives your code access to the APIs of your target mobile platforms. Both host an execution layer in their native apps (the Google V8 JavaScript engine for Titanium, Mono/.NET for Xamarin). Titanium has been around a few years longer than Xamarin.

Although they fill the same need and have similarities, it's important to evaluate them individually. If you've decided on a hybrid approach and are torn between the two, take the time to get familiar with each of them and you'll likely find reasons to favor one over the other.


Summary: Titanium Hybrid Mobile Development in JavaScript
Titanium puts mobile development in easy reach of JavaScript developers, the world's largest programmer community. While it's still necessary to learn the APIs and conventions of each mobile platform, taking Objective C and Java out of the equation is nevertheless a major boost. And, being able to use a common language for your iOS and Android projects makes a good deal of code re-use possible.

Next: Getting Started with Mobility, Part 8: Hybrid Development in HTML5 with Icenium



Friday, August 23, 2013

Getting Started with Mobility, Part 6: Hybrid Development in C# with Xamarin

In this series of posts, we're looking at how to get started as a mobile developer. In Part 1, we provided an overview of the mobile landscape, and discussed various types of client app development (native, hybrid, mobile web) and supporting back-end services. In Parts 2-5, we examined native app development for iOS, Android, Windows Phone, and Windows 8. Here in Part 6, we'll begin examining hybrid development approaches--starting with Xamarin.

Hybrid Frameworks: Assess the Risks
Hybrid mobile frameworks are a mixed bag: they may make all the difference in getting developers up to speed and productive; but they can also bring consequences. Before adopting any hybrid framework, you should get the answers to some key questions:
  • Does the hybrid framework have a runtime layer or execute in a browser, or does it compile to native code?
  • Does it support all of the mobile platforms you need to target?
  • Does it restrict access to some of the features you need?
  • Does it increase overhead or compromise performance?
  • What is its cost? Is it a one-time cost, or a subscription?
  • What are the limitations imposed by the license terms?
  • What risks come with having a third-party dependency?
  • Is it well-established and trustworthy, or is it new and unproven?
  • Does the producer have a good track record of good relations with mobile platform vendors, and are they able to stay in sync with mobile platform updates in a timely manner?
  • Is good support available, including community forums?

Above all, don't make the mistake of thinking all hybrid solutions are similar. They vary greatly in their approach, mechanics, performance, and reliability.

Xamarin: Mobile Development in C#
Xamarin is a third-party product that allows you to develop for iOS and Android in C# and .NET--very familiar territory to Microsoft developers. How is this magic accomplished? From the Xamarin web site: "Write your app in C# and call any native platform APIs directly from C#. The Xamarin compiler bundles the .NET runtime and outputs a native ARM executable, packaged as an iOS or Android app.". In short, Microsoft developers can develop native apps for iOS and Android while working in a familiar language, C#.


Xamarin is the most expensive of the various mobile development approaches we're considering in this series: the Business Edition developer license costs $1,000 per target platform, per developer, per year (there are also Starter, Indie and Enterprise editions available). It may well be worth the cost, depending on what programming language your developers are familiar with.

The Computer You'll Develop on: A PC or a Mac
Xamarin development for iOS requires a Mac; Android development can be done from a PC or a Mac.

Developer Tools: Xamarin Studio
Xamarin provides an IDE, Xamarin Studio, in both Mac OS X and Windows editions. It's also possible to use Xamarin with Visual Studio.

Xamarin Studio requires and makes use of the Software Development Kits for the mobile platform(s) you are targeting--automatically downloading them during installation if it needs to.

For Android development, you can work self-contained in Xamarin Studio: there's a screen editor, allowing you to see what your layout XML looks like visually. For iOS development, on the other hand, you have to use both Xamarin Studio and Apple's XCode side-by-side, so that you can use Interface Builder.

Xamarin Studio
 
Programming: C#
In Xamarin you program in C#, the favorite language of Microsoft.NET developers. Here's an example of Xamarin C# code for iOS (compare to Objective C):
 
var context = CIContext.FromOptions (new CIContextOptions () {
    UseSoftwareRenderer = true
});
var ciImage = new CIImage (cgImage);
var hueAdjustFilter = new CIHueAdjust {
    InputAngle = 3.0f * Math.PI,
    Image = ciImage,
};

var colorControlsFilter = new CIColorControls {
    InputSaturation = 1.3f,
    InputBrightness = 0.3f,
    Image = hueAdjustFilter.OutputImage
};

ciImage = colorControlsFilter.OutputImage;
context.CreateImage (ciImage, ciImage.Extent);

And, here's an example of Xamarin C# code for Android (normally programmed in Java):

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace Android1
{
    [Activity (Label = "Android1", MainLauncher = true)]
    public class MainActivity : Activity
    {
        int count = 1;

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button> (Resource.Id.myButton);
           
            button.Click += delegate {
                button.Text = string.Format ("{0} clicks!", count++);
            };
        }
    }
}


Debugging Experience
The debugging experience with Xamarin is similar to that of native iOS and Android development: you can run in the mobile platform's emulator, or on an actual device connected to your computer by USB cable. You're using the same emulators you would use in native development, so they are just as good (or bad, or slow).

In getting Xamarin on my PC to work on actual Android devices, I did need to install a Universal Android Debug Bridge driver.

Android Emulator Selection Dialog
 
Android Emulator

Capabilities
Xamarin doesn't get in the way of using device features. For example, your code can access the Accelerometer and the GPS and the Camera; and can access Contacts and Photos.


AccelerometerPlay Sample
 
CameraAppDemo Sample

Online Resources
The Xamarin web site has a good developer center, whose resources include documentation, guides, recipes, samples, videos, and forums.

Xamarin Developer Center

Key online resources:
Getting Started
Introduction to Mobile Development
Building Cross-Platform Applications
Hello, Android
Hello, iPhone
Android APIs
iOS APIs
Recipes
Sample Code
Videos
Forums

Components Store
Xamarin has a components store; the components offer a broad range of functionality, from charting to syncing with DropBox. Some of the components are free.

Components Gallery

Tutorials
There are a number of good tutorials to be found in the Getting Started area of the Xamarin Developer Center.

1a. Android: Installing Xamarin.Android
1b. iOS: Installing Xamarin.iOS

This tutorial walks you through installation of Xamarin for Android or iOS, and has both Windows PC and Mac editions.

Installing Xamarin on a Mac 

2a. Android: Hello, Android
2b iOS: Hello, iPhone

This tutorial explains how to build a Hello, World application for Android or iOS. It takes you through creating a new project, defining a simple interface and writing simple action code, building the solution, and running it on an emulator.

Creating a New Project in Xamarin Studio

Defining iPhone User Interface in XCode Interface Builder

Hello, iPhone running in iOS Simulator
 
3a. Android: Multi-Screen Applications
3b. iOS: Multi-Screen Applications

This tutorial shows how to create a multi-screen app, with data from the first view passed to the second when a button is pressed.

Android Multi-Screen App Tutorial Running in Emulator



iOS Multi-Screen App Tutorial Running in Emulator

Summary: Xamarin Hybrid Mobile Development in C#
Xamarin puts mobile development in easy reach of Microsoft developers. While it's still necessary to learn the APIs and conventions of each mobile platform, taking Objective C and Java out of the equation is nevertheless a major boost. And, being able to use a common language for your iOS and Android projects makes a good deal of code re-use possible.

Next: Getting Started with Mobility, Part 7: Hybrid Development in JavaScript with Titanium

Wednesday, August 21, 2013

Getting Started with Mobility, Part 5: Native Windows 8

In this series, we're introducing mobile development by looking at a variety of platforms. In Part 1, we provided an overview of the mobile landscape, and in Parts 2, 3, and 4 we examined native development for iOS, Android, and Windows Phone. Here in Part 5, we'll introduce you to native development Windows 8.

Windows 8: Microsoft's Platform for Tablets and PCs
Windows 8 is Microsoft's operating system for tablets that can also run on PCs. While Windows 8 is distinct from Windows Phone, as part of Microsoft's efforts to unify their products and services there are a number of similarities in terms of design principles and development skills.

Windows 8 apps are officially known as Windows Store Apps. Windows Store Apps can run on traditional Intel architecture machines (standard PCs, or the Surface Pro tablet) on Windows 8, Windows 8 Pro, or Windows 8 Enterprise; or, on ARM devices running Windows RT (such as the Surface RT tablet). On the former, you are able to run traditional Windows 7 apps as well as Windows Store apps; on the latter, only Windows Store apps.
Microsoft Surface Tablet

Windows 8 features a bold new look. The User Interface for Windows 8 was originally called Metro, but after objections from a company in Europe, Microsoft changed the name to Modern UI.

Windows 8 Start Screen
 
Windows 8 Weather App

The Computer You'll Develop on: A Windows PC or Surface Pro Tablet
Windows 8 development is done on a PC, or a compatible tablet like the Surface Pro. If you happen to use a Mac, you'll need to run a Windows VM in order to do Windows 8 development.

Developer Tools: Visual Studio and the Windows 8 SDK
For development, you'll need Visual Studio and the Windows 8 SDK. Although Visual Studio is a commercial product, there is a Visual Studio Express edition for Windows 8 available.

As we covered in Part 4, Visual Studio is a mature IDE familiar to anyone who develops for Microsoft's mobile, web, desktop, server, or cloud platforms.

Visual Studio IDE

Programming: WinJS, C#/XAML, or C++/XAML
For Windows Store app development, developers can choose from 3 lanes:
  • WinJS: HTML5, CSS, and JavaScript
  • C#/XAML: XAML screen markup and C# code-behind
  • C++/XAML: XAML screen markup and C++ code-behind
 
Windows 8 Platform
 
The choice of languages makes Windows 8 development very approachable to a broad number of developers. I'll give some attention to WinJS and C#/XAML here in this post, as they are the most frequently used.

It's important to note that all three of the approaches are first-class citizens and are all considered "native"--even when using HTML5/CSS/JavaScript. That's because all Windows Store Apps intrinsically leverage Internet Explorer--it's part of the platform and application model.

Programming in WinJS
Web developers will like being able to leverage HTML5, CSS, and JavaScript--including many of their preferred open source JavaScript libraries and frameworks. There are a few differences from standard web development however:
  • You don't have to worry about cross-domain "same origin" policy: a Windows Store app can reach out and access Internet URLs from anywhere. This is different from a web app, where you are restricted to your web server's originating domain.
  • Your code references need to be local. Including JavaScript or CSS from an online source is disallowed, so you'll need to copy those files locally into your project.
  • You can count on Internet Explorer being the browser, so you don't have to be concerned about supporting multiple browsers and testing whether specific browser features are available.
Here's what a view (page) looks like in WinJS:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>HelloWorld</title>

    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.2.0.Preview/css/ui-dark.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.2.0.Preview/js/base.js"></script>
    <script src="//Microsoft.WinJS.2.0.Preview/js/ui.js"></script>

    <!-- HelloWorld references -->
    <link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>
</head>
<body>
    <h1>Hello, world!</h1>
    <p>What's your name?</p>
    <input id="nameInput" type="text" />
    <button id="helloButton">Say "Hello"</button>
    <div id="greetingOutput"></div>

</body>
</html>


And here's some code-behind JavaScript for that page:

// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/p/?linkid=232509
(function () {
    "use strict";

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll());

            // Retrieve the button and register our event handler.
            var helloButton = document.getElementById("helloButton");
            helloButton.addEventListener("click", buttonClickHandler, false);
        }
    };

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // args.setPromise().
    };

    function buttonClickHandler(eventInfo) {

        var userName = document.getElementById("nameInput").value;
        var greetingString = "Hello, " + userName + "!";
        document.getElementById("greetingOutput").innerText = greetingString;
    }

    app.start();
})();


One of the things you'll notice from the above code is that you need to pay attention to application state. Like most mobile platforms, your apps can be suspended by the operating system and you'll need to ensure you save state and restore state appropriately.

Programming in C# and XAML
Silverlight, WPF, and Windows Phone developers will like being able to leverage familiar XAML and C#. Indeed, if you're developing for both Windows 8 and Windows Phone using C#/XAML makes a lot of sense as you'll be able to share some of your markup and code assets.

Here's an example of XAML screen markup for a Windows Store app:

<Page
    x:Name="pageRoot"
    x:Class="HelloWorld.MainPage"
    DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:HelloWorld"
    xmlns:common="using:HelloWorld.Common"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Page.Resources>
        <common:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
        <!-- TODO: Delete this line if the key AppName is declared in App.xaml -->
        <x:String x:Key="AppName">My Application</x:String>
    </Page.Resources>

    <!--
        This grid acts as a root panel for the page that defines two rows:
        * Row 0 contains the back button and page title
        * Row 1 contains the rest of the page layout
    -->
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.ChildrenTransitions>
            <TransitionCollection>
                <EntranceThemeTransition/>
            </TransitionCollection>
        </Grid.ChildrenTransitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="140"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!-- Back button and page title -->
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="120"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <AppBarButton x:Name="backButton" Icon="Back" Height="95" Margin="10,46,10,0"
                          Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageRoot}"
                          Visibility="{Binding IsEnabled, Converter={StaticResource BooleanToVisibilityConverter}, RelativeSource={RelativeSource Mode=Self}}"
                          AutomationProperties.Name="Back"
                          AutomationProperties.AutomationId="BackButton"
                          AutomationProperties.ItemType="Navigation Button"/>
            <TextBlock x:Name="pageTitle" Text="{StaticResource AppName}" Style="{StaticResource HeaderTextBlockStyle}" Grid.Column="1"
                       IsHitTestVisible="false" TextWrapping="NoWrap" VerticalAlignment="Bottom" Margin="0,0,30,40"/>
        </Grid>
    </Grid>
</Page>


And, here's an example of C# code to go with the XAML markup:

using HelloWorld.Common;
using System;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237
namespace HelloWorld
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class MainPage : Page
    {

        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();

        /// <summary>
        /// This can be changed to a strongly typed view model.
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        /// <summary>
        /// NavigationHelper is used on each page to aid in navigation and
        /// process lifetime management
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }


        public MainPage()
        {
            this.InitializeComponent();
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
            this.navigationHelper.SaveState += navigationHelper_SaveState;
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
        }

        #region NavigationHelper registration
        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        ///
        /// Page specific logic should be placed in event handlers for the 
        /// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
        /// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method
        /// in addition to page state preserved during an earlier session.

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedFrom(e);
        }

        #endregion
    }
}


Online Resources
Like most mobile platforms, Microsoft provides a comprehensive developer center for Windows Store Apps. It includes design guidance, developer resources, training, code and tool downloads, community forums, and store management.

Windows Store Apps Developer Center

You'll want to check out these resources:
Get Started with Windows Store Apps
The Basics
App Architecture
Design Principles
How to Develop Windows Store Apps
API Reference
Sample Code
Community Forums

Tutorials
Microsoft provides a lot of online tutorial content, as well as periodic developer events in regional areas around the world. You might also consider Pluralsight video training courses, which have a lot of Windows 8 content.

1a. WinJS: Create your first Windows Store app using JavaScript

This tutorial walks you through creating a simple Hello, World app using HTML and JavaScript. The tutorial walks you through creating Hello World, then managing app lifecycle and state; working with page control objects and navigation; working with layout and orientation; and adding file picker functionality to select a photo.

Part 1 of Tutorial
 
Part 5 of Tutorial
 
1b. C#/XAML: Create your first Windows Store app using C#

This tutorial is similar to the Hello World app described above, but uses C# and XAML for development. This edition of the tutorial also includes creating a blog reader.

Part 4 of Tutorial

Part 5 of Tutorial

2a. WinJS: Developing Windows Store Apps with HTML5 Jumpstart

Microsoft Virtual Academy provides a video series on getting started with Windows Store app development in HTML5/JavaScript. Topics covered include:
  • Designing a Windows Store App
  • Developing Windows Store Apps
  • Working with Contracts
  • UI and Controls
  • Programming User Interactions
  • Data Access

2b. C#/XAML: Essentials of Developing Windows Store Apps using C# Jump Start

Microsoft Virtual Academy also provides a video series on getting started with Windows Store app development in C#/XAML. Topics covered include:
  • Overview of the Windows 8 Platform and Windows Store Apps
  • Creating User Interfaces using XAML
  • Presenting Data and Implementing Layout using Windows 8 Built-in Controls
  • Handling Files in Windows Store Apps and Process Lifecycle Management
  • Working with Resources, Styles, and Templates
  • Designing and Implementing Navigation in a Windows Store App
  • Implementing Windows 8 Contracts, Tiles and User Notifications
  • Local data and Planning for Windows Store App Deployment
  • Recommended Resources and Next Steps for Essentials of Development

Summary: Native Windows 8 Development
Windows 8 is a bit of a category-buster: it's Microsoft's chosen platform for tablets as well for PCs. Windows Store apps need to be designed to work well in a touch-centric environment, but should also support mouse and keyboard well. They need to support a variety of form factors. The three first-class language paths make Windows 8 app development accessible to web developers, C#/.NET developers, and C++ developers.

Next: Getting Started with Mobility, Part 6: Hybrid Development in C# with Xamarin

Getting Started with Mobility, Part 4: Native Windows Phone

In this series, we're introducing mobile development by looking at a variety of platforms. In Part 1, we provided an overview of the mobile landscape, and in Parts 2 and 3 we examined native iOS and Android development. Here in Part 4, we'll introduce you to native development for Windows Phone.

Windows Phone, Microsoft's Smartphone Platform
Windows Phone isn't the dominant player in the mobile market, but it's still worth developing for, especially if you're looking to have good coverage across mobile platforms. Windows Phone devices are a favorite of many businesspeople who rely on its mail and calendar functionality. When Microsoft replaced the former Windows Mobile with the new design of Windows Phone, it was a huge improvement; and the latest update, Windows Phone 8, improves things even more. Some of the key factors emphasized in Windows Phone include ease of access (pinning anything important to you to the start screen), hubs for content important to you such as people, games, and music; cloud sharing and backup via SkyDrive; and deluxe cameras and photo sharing.

Microsoft is busy transforming itself into a devices and services company, and one of the outpourings of that is convergence across their products and services. You'll find increasing similarities between design and development for Windows Phone, Windows 8 on tablets and PCs, and XBox, with Cloud-based services providing a unifying layer that allows users to comfortably move among multiple devices seamlessly.

Like Google, Microsoft works with multiple manufacturers and carriers, giving customers a lot of choice in Windows Phone devices.

Windows Phone: A Variety of Devices and Carriers

The Computer You'll Develop on: A Windows PC
Windows Phone development is done a PC. If you happen to use a Mac, you'll need to run a Windows VM in order to do Windows Phone development.

Developer Tools: Visual Studio and the Windows Phone SDK
For development, you'll need Visual Studio and the Windows Phone SDK. Although Visual Studio is a commercial product, there is a Visual Studio Express edition for Windows Phone available which is free.

Visual Studio is a mature development environment, familiar to anyone who writes code for the Microsoft mobile, web, desktop, server, or cloud platforms. For Windows Phone 8 development, Visual Studio 2012 provides a good spectrum of project templates for everything from media streaming apps to games.

Visual Studio IDE

Another tool you'll want to consider is Microsoft Expression Blend. Blend will help you develop your user interface with professional tooling rather than having to code your XAML markup directly.

Microsoft Expression Blend

Programming: XAML and C#
Typically, you'll do your Windows Phone development in Microsoft's C# language and express your screens in a markup language named XAML. It is also possible to write some or all of your app in C++, which you might choose to do for performance reasons for certain kinds of apps. You can also leverage Microsoft's XNA Game Studio and Direct3D graphics engines for your Windows Phone apps.

Here's what a Windows Phone screen definition looks like in XAML:

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
  <TextBox x:Name="URL" Margin="10,10,85,0" Text=http://www.xbox.com
           VerticalAlignment="Top"/>
  <Button x:Name="Go" Content="Go" HorizontalAlignment="Right"
          Margin="346,10,0,0" VerticalAlignment="Top"/>
  <phone:WebBrowser x:Name="MiniBrowser" Margin="10,82,0,0"/>
</Grid&gt
;

You'll write code in C#. Here's an example of C# that goes with the above XAML screen:

using System;
...
using Microsoft.Phone.Shell;
using MiniBrowser.Resources;
namespace MiniBrowser
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        } 


        private void Go_Click(object sender, RoutedEventArgs e)
        {
            string site = URL.Text; MiniBrowser.Navigate(

                new Uri(site, UriKind.Absolute));
        }
    }
}

C# is a popular and effective language to develop in. Like Java it features garbage collection so you won't have to work with pointers or be overly concerned about memory management.

Testing Your Apps: The Windows Phone Emulator
The Windows Phone SDK provides an emulator for Windows Phone. You can test your apps on the emulator or an actual Windows Phone device as you prefer.

Selecting Emulator or Device in Visual Studio


Windows Phone Emulator

Online Resources
Like most mobile platforms, Microsoft provides a comprehensive developer center, found at developer.windowsphone.com. Here you'll find design guidance, developer resources, training, community forums, and store management. You'll want to begin with Getting started with developing for Windows Phone.

Here are some key online resources you'll want to get familiar with:
Design Principles
Development
Publishing your App
Community
Sample Code

Tutorials
Windows Phone tutorials are available in a number of places. In addition to free and paid materials available from Microsoft, along with occasional developer events in your area, you may also want to consider third-party materials such as Pluralsight video training courses.

1. How to create your first app for Windows Phone

This first tutorial shows you how to develop a simple initial app, a Mini Browser. You'll design a simple screen in XAML and implement C# code to go with it.
Mini Browser App

After this initial tutorial, most of the learning materials available to you are in the form of video tutorials. You may find it useful to also get familiar with some of the sample code projects available.

2. Building Apps for Windows Phone 8 Jump Start

Microsoft Virtual Academy provides a video series on getting started with Windows Phone 8 development. Topics covered include:

• Introducing Windows Phone 8 Development
• Designing Windows Phone 8 Apps
• Building Windows Phone 8 Apps
• Files and Storage on Windows Phone 8
• Windows Phone 8 Application Lifecycle
• Background Agents
• Tiles and Lock Screen Notifications
• Push Notifications
• Using Phone Resources in Windows Phone 8
• App to App Communication in Windows Phone 8
• Network Communication in Windows Phone 8
• Proximity Sensors in Windows Phone 8
• Speech Input in Windows Phone 8
• Maps and Location in Windows Phone 8
• Wallet Support
• In-App Purchasing
• The Windows Phone Store
• Enterprise App Architecture
• Windows 8 Cross-Platform Development
• Mobile Web

3. Windows Phone Design Bootcamp

These videos will acquaint you with the philosophies of Windows Phone Design Language and the design process.

4. Microsoft Learning Courses and Exams

Microsoft Learning offers paid online courses on Windows Phone and certification exams to demonstrate your expertise.

Summary: Native Windows Phone Development
It's easy to get started with Windows Phone development, especially if you have previously done any work with Microsoft .NET, C#, Silverlight, or Windows Presentation Foundation--you'll be in familiar territory.

Next: Getting Started with Mobility, Part 5: Native Windows 8