cross platform native mobile app development for ios, android and windows using the power of c#
DESCRIPTION
Session presented at vsug BelgiumTRANSCRIPT
Cross Platform Native Mobile App Development for iOS, Android and
Windows Using the Power of C#
Marcel de VriesTechnology Manager @marcelv
AgendaIntroduction to Xamarin& MobileCreating your first iOS appCreating your first Android appCode Sharing TipsSummary
Building mobile apps
Building apps for the Mobile SpaceUser Experience Developer
productivity
Which platforms?
Application Lifecycle
Management
Distribution: Public or private
Corporate?Security &
privacy
Application types
Application types
Native look & feel -- -- ++Camera Access -- +- ++GPS ++ ++ ++
Secure service communication JSON/REST JSON/REST JSON/SOAP
Access to calendar -- -- ++Twitter integration +- +- +Distribution ++ AppStore presence AppStore presence
3 types
App Logic
Vendor tools “Magic Box” Hybrid
XCodeObjective-C
WP7 Silverlight
C#
Android SDKJava
Appcelerator TitaniumJavaScript > Native
PhoneGapHTML5 / CSS / JS
Adobe AIRActionScript
AntennaRapid Scripting
Language
Service2MediaLua C#
XamarinXamarin.iOS
WP8/win8 Xaml + C#
XamarinXamarin.Android
RhodesRuby + HTML
Sybase Unwired“4GL” code gen
Shared languageKony
Javascript Lua
Xamarin HistoryOver a Decade of Enterprise Production Use
2000
Ximian Founded
2001
MonoLaunches
2003
Ximian Acquired by Novell
2009
First iOS product (now Xamarin.iOS) launches
2011
Xamarin Founded
First Release of Xamarin.Android
2012
First release of Xamarin.Mac
LaunchPartnerProgram
2013
Xamarin 2.0
Component Store
Xamarin TestCloud
Evolve 2013
Microsoft Partnership
Reach 200,000Developer
Mark
450,000 Developers
100+ Partners100+ Components
Anything you can do in Objective-C or Java can be done in C# and Visual Studio with Xamarin.
Xamarin.iOS does full Ahead Of Time (AOT) compilation to produce an ARM binary suitable for Apple’s App Store.
Native Performance
Xamarin.Android takes advantage of Just In Time (JIT) compilation on the Android device.
Accelerate Development with Code Sharing Code sharing statistics from production Xamarin app: real-time circuit
simulator and editor used to design analog and digital circuits
Completely Up-to-Date with Device OS releases
Always up-to-date with the latest APIs from Apple and Google.
Track record of offering same-day support: iOS 5, iOS 6, iOS 6.1 and
iOS 7.
✔
iOS
3rd party app
AppDelegate
UIKit
Tap app icon
main()
UIApplicationMain()
Quit foreground msg
Background
Event loop
FinishedLaunching
HandleEvent
OnResignActivation
DidEnterBackgroundWillTerminate
Save stateSave data
Free resources
Pause tasksThrottle down
frame rates
OnActivatedRestart tasksReload stateRefresh UI
App model
View
Controller
Model
NavigationController
Model manipulation
UIView
UIViewController
Outlets Actions
UITableView & Navigation
UITableView & Navigation
UITableViewController
UITableViewDataSource
UITableViewDelegate
UITableViewSource
Data + table cells
Events
DemoiOS app basics
Android
Android
Mobile OS made by googleTargets: Tablets and mobile phones
Mono for AndroidArchitectural picture of Mono for Android
Linux Kernel
Mono (.NET Runtime) Dalvik (Java Runtime)
.NET APIs Android Bindings
Android.* Java.*MCW
ACW
App model - Activity lifecycleActivity
Launched
onCreate()
onStart()
onResume()
onPause()
onStop()
onDestroy()
onRestart()
Activity shut down
Activity running
User navigates to the activity
Apps with higher priority need
memory
User returns to the activity
User navigates to the activity
Another activity comes into the foreground
App process killed
The activity is no longer visible
The activity is finishing or being destroyed by the system
Initialize layout here
Save state here
Restore state here
Building apps on android
Activity Activity
View View
Intent
IntentBroadcast Receiver
Service
Content Provider
Intent
Intent
Intent
Intent
Inte
nt
DemoAndroid app basics
The promise…
Reusable34%
Shared Logic17%
Android10%
iOS8%
Win-dows Phone10%
Services21%
Shared84%
Specific16%
Per App
DataSerialization
Caching
SecurityAuthN/AuthZEncryption
Data Self Destruction
UtilitiesAnalyticsLogging
Device services
Platform Agnostic API
Application Business Logic
Platform UI
Design Patterns for Reuse
Glue together the application layers
Design Patterns for Reuse
Basics
Services
ModelController
Etc.
GPS
Storage
Motion sensors
View
Model ImplementationWe implement the Model as a SingletonModel Implements INotifyPropertyChangedEasy to enlist subscribers
Facilitate automatic databinding in XAMLModel contains rich features such as filtering and advanced selections
Easy to share logic
Model Implementationpublic class MainModel : INotifyPropertyChanged{ private static MainModel _model; private static object _lockHandle = new object(); // Facilitates Windows Phone app resume public void RestoreState(MainModel state) { _model = state; }
public static MainModel Current { get { if (_model == null) { _model = new MainModel(); } return _model; } }
public IEnumerable<Event> ActualEvents { get { // E.g. Complex linq stuff } }}
// Model Usage:var foo = MainModel.Current.ActualEvents;
Check your water level
Reusable Business Logic
Device SpecificXAML /
ValueConverter
Model PropertyValue
Transformation
Controller implementation
Controller is a singleton as well• Maintains a reference to the service proxy• Singleton helps to prevent threading issues with proxy initialization
on iOS device
Expose public methods to provide business logic
Handle service calls and threading in the controller as much as possible
• Now much easier with async/await
public class ISKEController{ private static ISKEController _instance; private ISKEDomainServicesoap _proxy;
public static ISKEController Current { get { if (_instance == null) { _instance = new ISKEController(); } return _instance; } }
private void GetActualEvents (Action<object> OnSuccess, Action<Exception> OnFail) { // do some logic, or service call // use actions to report result or trigger UI action }}
Controller implementation
Callback pattern
Shared Controller
UIViewController
XAML View Activity
Web Services
S F S F S F
ModelGetActualEvents
(Action<object> OnSuccess, Action<Exception> OnFail)
PropertyChanged(“Events”);
public void OnFailed(Exception e){ // Do something with error}
public void OnSuccess(object data){ // Do something with data // Notify user}
DemoAction<T>
What about accessing device capabilities?
Platform agnostic API for capabilities• If you squint, device capabilities look the same
across platformsiOS
MonoTouch.CoreLocationMonoTouch.CoreMotionMonoTouch.AVFoundationMonoTouch.AddressBookMonoTouch.EventKit…
Android: Android.Hardware.SensorAndroid.LocationAndroid.BluetoothAndroid.Nfc…
Windows Phone: Microsoft.Devices.Sensors.GyroscopeMicrosoft.Devices.Sensors.AccelerometerMicrosoft.Devices.Sensors.CompassMicrosoft.Devices.Sensors.Motion…
Use device abstractions!Xamarin.Mobile or Roll Your
Own
Partial classes & methods
Partial classes 101
• Span a class implementation over multiple files
• Useful for partly generated code• ...or separating shared implementation and
device specific implementation
partial class A{ // Half of the implementation}
partial class A{ // The other half}
A.cs
A.extra.cs
Partial methods 101
• Put implementation details in a partial method and put shared logic around it
partial class A{ // Declare the method here partial void DoSomethingEx(); public void DoSomething() { // Some shared logic DoSomethingEx(); }}
partial class A{ // Provide the implementation here partial void DoSomethingEx() { // Do something iOS specific }}
Can be used from shared logic
Leaves room for specific
implementation
Always private and returns void
A.cs
A.iOS.cs
Device Abstraction Patterns
DemoDevice Abstractions
SummaryXamarin provides Native Cross platform capabilities– Best of all worlds
Use the power of C#– BCL, LINQ, ASYNC, etc
Keep abstractions as simple as possible– Avoid IOC, Big frameworks– Remember your on a mobile device, each cycle counts!