39,59 €
A recipe-based practical guide to get you up and running with Xamarin cross-platform development
This book is for mobile developers. You must have some basic experience of C# programming, but no previous experience with Xamarin is required. If you are just starting with C# and want to use Xamarin todevelop cross-platform apps effectively and efficiently, then this book is the right choice for you.
You can create native mobile applications using the Xamarin Forms platform for the three major platforms iOS, Android, and Windows Phone. The advantage of this is sharing as much code as you can, such as the UI, business logic, data models, SQLite data access, HTTP data access, and file storage across the three major platforms.
This book provide recipes on how to create an architecture that will be maintainable, extendable, use Xamarin Forms plugins to boost productivity, customize your views per platforms, and use platform-specific implementations at runtime.
We start with a simple creation of a Xamarin Forms solution with the three major platforms. We will then jump to XAML recipes and you will learn how to create a tabbed application page, and customize the style and behavior of views for each platform. Moving on, you will acquire more advanced knowledge and techniques while implementing views and pages for each platform and also calling native UI screens such as the native camera page.
Further on, we demonstrate the power of architecting a cross-platform solution and how to share code between platforms, create abstractions, and inject platform-specific implementations. Next, you will utilize and access hardware features that vary from platform to platform with cross-platform techniques. We'll then show you the power of databinding offered by Xamarin Forms and how you can create bindable models and use them in XAML. You will learn how to handle user interactions with the device and take actions in particular events.
With all the work done and your application ready, you will master the steps of getting the app ready and publishing it in the app store.
This book will serve as a quick reference with a unique recipe-based approach that will engage you like never before as you create real-world cross-platform apps on your own.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 301
Veröffentlichungsjahr: 2016
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: March 2016
Production reference: 1210316
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-053-7
www.packtpub.com
Author
George Taskos
Reviewer
Stan Okunevic
Commissioning Editor
Amarabha Banerjee
Acquisition Editor
Reshma Raman
Content Development Editor
Samantha Gonsalves
Technical Editor
Nirant Carvalho
Copy Editors
Dipti Mankame
Jonathan Todd
Project Coordinator
Sanchita Mandal
Proofreader
Safis Editing
Indexer
Priya Sane
Graphics
Kirk D'Penha
Production Coordinator
Shantanu N. Zagade
Cover Work
Shantanu N. Zagade
George Taskos is a senior software engineer. He has been creating applications professionally since 2005, and he started coding at the age of 8. George has worked as a consultant for the past 10 years in the enterprise and consumer domains.
George is a Microsoft Certified Solutions Developer since 2009 and Xamarin Certified Mobile Developer. Throughout his career, he has created multitier interoperable applications with various technologies, including Windows Forms, WPF, ASP.NET MVC, SOAP, and REST web services, focusing on native iOS/Android and Xamarin Cross Platform Mobile applications for the past 5 years.
As a professional, he worked with small and large enterprises in Greece, Cyprus, South Africa, UK, and USA where he is currently based in New York City.
George is a passionate engineer involved in the start-up community by contributing his free time. He was a member of the BugSense mobile analytics team that was acquired by a NASDAQ big data analytics corporation in 2013.
Currently, he is working with Verisk Analytics, a NASDAQ 100 company, leading the engineering of Xamarin iOS/Android platforms and working in general software architecture of products.
I would like to thank my wife, Natalya Taskos, for putting up with my all night sessions in the writing of the book and trying to find the next best practice and technology to create the amazing software.
Stan Okunevic is a speaker, entrepreneur, and a true lover of All Things Mobile. Having dropped out of university to start a career in software consultancy, he entered the world of Xamarin by accident—having stumbled upon mentions of MonoTouch while looking for something new to learn— and has not looked back since. Having worked with a wide array of clients ranging from small, stealth-mode start-ups to Fortune 50 companies, he has gained invaluable insight into what it takes to build a product and run a team.
Nowadays, he spends most of his time expanding his technology consultancy, building various products of his own whenever an opportunity arises, studying for an MSc degree in Cyber Security and updating his personal blog at Nowadays, he spends most of his time expanding his technology consultancy, building various products of his own whenever an opportunity arises, studying for an MSc degree in Cyber Security and updating his personal blog at daytimehacker.com.
I'd like to thank each and every one of my clients to trust me and my team, as well as everyone I have worked with in the early stages of my career to provide invaluable advice. Special thanks to Paul F. Johnson for the review recommendation that reviewing the book has been of immense pleasure.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
There is no better time for advancing your toolbox with cross-platform mobile development using Xamarin.Forms. Xamarin has over 1,300,000 registered developers and 15,000 clients, it is now the standard in enterprise mobility, and the demand for cross-platform Xamarin mobile developers is very high. The idea behind Xamarin.Forms is that you're no longer only able to share your business logic but the UI code across iOS, Android and Windows Phone. With Xamarin, you can open your favorite IDE, Visual Studio, or use Xamarin Studio, to create cross-platform applications using C# while still generating and deploying a 100% native platform application.
If you know C#, you know how to create native cross-platform, and this book will just make it easier for you.
You will learn everything available to combine your application and build RAD mobile applications. Even if there is a requirement to work on the native application layers, you will find step-by-step recipes that provide you with the knowledge and understanding of how to accomplish your goal.
Work with the UI in XAML or in code, and learn how every control and page is mapped to each equivalent native UI component. Create custom views, call platform APIs, and explore all the cross-platform types of pages, layouts and controls. Create your own cross-platform plugin, and deploy it to NuGet for other developers or commercial purposes.
At the core of the book, the focus is on cross-platform architecture: how to efficiently share code between all platforms, use the built-in dependency service locator, and configure your solution to use a third-party dependency injection using aspect-oriented programming.
Using a cross-platform UI framework doesn't mean that your UI should be coupled to the rest of your code; in this book, the MVVM architecture is demonstrated by injecting the ViewModel in the XAML and using data binding to sync your data between UI controls and models, keeping clean the separation of concerns.
What is programming? Art? Are we the crafts people? No. We process data, that's what we do from the backend to the frontend and vice versa, fetching, transforming, accepting input changes and persisting back to a storage. Data access is the most important layer in an application and there are recipes to cook the repository pattern for local and remote data with many tips, tricks, and best practices for performance and efficiency.
These sequences of data are often presented in a list control. Continuing from this, the book covers the practices needed to create and customize a Xamarin.Forms ListView, adding grouping, jump list, and custom cells.
No modern application is built today without unit testing; in addition, you will find recipes that will help you understand and leverage acceptance UI testing locally and uploading them in Xamarin Test Cloud testing in thousands of physical devices.
Towards the end, we will focus on monitoring an application using Xamarin Insights and preparing and packaging each native platform to upload to the corresponding marketplaces.
Chapter 1, One Ring to Rule Them All, shows you how to work with Xamarin Forms, how to get started with a simple project, understand the structure, and make use of available controls. Starting out the first chapter with creating a cross-platform solution using Xamarin Studio and Visual Studio, create your first first page, use Xamarin's out-of-the-box common platform APIs, and learn how to access the native platform page renderers.
Chapter 2, Declare Once, Visualize Everywhere, shows you how to use the Xamarin Forms XAML declarative language to create cross-platform UI. This chapter introduces you to how to create a tabbed application and add UI behaviors and triggers; the main focus is user interface development and providing knowledge in view renderers.
Chapter 3, Native Platform-Specific Views and Behavior, teaches you how to create different page layouts and custom controls per platform. Cross-platform development has all the benefits of sharing code across all three platforms, though there are many scenarios in which you need to access the native platform layer. This chapter will give you all the recipes to create custom platform views, add platform-specific gestures, and access the camera platform APIs.
Chapter 4, Different Cars, Same Engine, shows you how to apply cross-platform architecture, patterns, and practices. Leverage the power of Xamarin.Forms with six sections with all the ins and outs of best practices for sharing code between platform. Use the built-in dependency locator to resolve implementation classes and publish messages to components. Design an MVVM solution, add a third-party DI container for Aspect Oriented Programming and localize your applications for any languages.
Chapter 5, Dude, Where's my Data?, shows you how to create a cross-platform data access component fetching data from a local SQLite database and a REST web service. Separation of concerns in a cross-platform solution is critical, learn how to create efficient web and local database repositories. Leverage the native platform performant HTTP SDKs adding and configuring a NuGet package.
Chapter 6, One for All and All for One, shows you how to use Xamarin plugins to access native platform capabilities like the camera, GPS, and showing local notifications. The Xamarin community is very generous, there are plugins for Xamarin almost for anything you might want or learn how to do it adding your own implementation, and then share it with giving back or maybe as a commercial library. Learn how to create your own cross-platform plugins and how to use plugins for photos, GPS and local notifications.
Chapter 7, Bind to the Data, shows you how to leverage the built-in Xamarin Forms data-binding mechanism. Databinding is not a concept that every native platform is providing out of the box, and if you can't actually use data-binding the MVVM architecture doesn't sound such a great idea. Xamarin.Forms provides an out of the box mechanism to bind your data in code or declarative XAML.
Chapter 8, A List to View, teaches you how to bind collections to ListView, customize its appearance with custom cells and apply grouping.
Chapter 9, Gestures and Animations, shows you how to add cross-platform animations shared between iOS, Android, and Windows Phone and handle user gestures in XAML and in native platform renderers.
Chapter 10, Test Your Applications, You Must, shows you how to create unit tests for your portable shared code, and platform-specific unit tests. Create UI acceptance tests and run them locally or in Xamarin Test Cloud. Learn how to use Calabash and REPL.
Chapter 11, Three, Two, One – Launch and Monitor, shows you how to add real-time monitoring to get detailed error reports. Prepare and package your applications for submission in iOS, Android, and Windows Phone stores.
All examples will work with the Free Trial evaluation or Xamarin Starter licenses. Xamarin Starter is installed by default with Visual Studio 2015 and works with VS 2012, 2013, and 2015 (including Community editions).
This book is for mobile developers. You must have some basic experience of C# programming, but no previous experience with Xamarin is required. If you are just starting with C# and want to use Xamarin to develop cross-platform apps effectively and efficiently, then this book is the right choice for you.
In this book, you will find several headings that appear frequently (Getting ready, How to do it…, How it works…, There's more…, and See also).
To give clear instructions on how to complete a recipe, we use these sections as follows:
This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
In this chapter, we will cover the following recipes:
Xamarin.Forms is a cross-platform UI framework where the idea is no longer to share only your models, business logic, and data access layers similar to a traditional Xamarin solution but also the user interface (UI) across iOS, Android, and Windows Phone. With Xamarin.Forms, you can easily and quickly create great data-driven and utility applications or prototypes.
To accomplish this, Xamarin uses the super-modern C# language, the power of the .NET Base Class Libraries (BCL), these are C# bindings to the native APIs, and two great IDEs, Xamarin Studio and Microsoft Visual Studio. You can't, however, create iOS applications if you don't have a Mac connected to the network and acting as a server to build and deploy your application with the help of the Xamarin Build Host.
This book will provide you with real-world recipes and step-by-step development of the most common practices that you need to create professional cross-platform applications. You will learn how to create one UI across all platforms, customize the layout and views, and inject implementation per platform with a focus on patterns and best practices.
In this chapter, we will dive into the details of creating a cross-platform solution, adding a login screen, storing values for each platform, and using the Xamarin.Auth component to allow your users to log in with Facebook and Google providers. Neat! Exactly what you need to create a real-world application.
Getting started with apps for Xamarin.Forms is very easy. The installer sets everything up, the IDE creates the project, and you're up and running in minutes! Lean!
Before we can start creating cross-platform apps, we need to get our tools in place using a single installer from Xamarin:
Once the install is finished, you will have a working installation of Xamarin Studio, the IDE designed for cross-platform development:
Creating a Xamarin.Forms solution is easy using the default templates in Xamarin Studio or Visual Studio. Depending on the IDE, you will get three (Xamarin Studio in Windows), four (Xamarin Studio in Mac), and four (Visual Studio) projects. Of course, you can open the solution in the desired IDE and add the projects missing while moving forward with development. In this section, we will create a Xamarin.Forms blank application in Xamarin Studio for Mac and then add the Windows Phone project in Visual Studio.
In Xamarin Studio, choose File | New | Solution, and in the Cross-platform section, App category, you will see two options: Blank Xamarin.Forms App and Single View App, as shown in the following screenshot:
Choose Blank Xamarin.Forms App and click the Next button. You get to a screen with the options App Name, the name of your applications, and Identifier, which will be used as your package name for Android and the bundle identifier for iOS and the platforms you want to target.
The last option is if you want to use a Portable Class Library or a Shared Library as shown in the following screenshot. Shared Library will create a project that uses conditional compilation directives and it will be built in your main binary. With a Portable Class Library, on the other hand, you get to choose a profile you want to target and also distribute it via NuGet or the Xamarin Component Store. In this book, we only focus on the option of a Portable Class Library and its corresponding patterns and practices.
Click the Next button. Enter the project name, which will be used to create the names for each platform-specific project with the convention [ProjectName].[Platform] and a solution name as shown in the following screenshot. You can choose where to save the solution and if you want to use Git version control.
Click Create. Notice that we have a solution with four projects. You will learn later in Chapter 10, Test Your Applications, You Must how to create tests for our solution. This project is created only if we create the solution with Xamarin Studio.
With no hesitation, choose your iPhone simulator and click the play button. You will see the simulator starting and a simple app running with the message Welcome to Xamarin Forms!. Congratulations, you can do the same for Android by right-clicking in the project and Set As Startup Project. For Android projects, you can use either Google's emulators or the Xamarin Android Player, https://xamarin.com/android-player, which personally I find more efficient and faster. Click the play button and enjoy the same message in your favorite emulator.
Sweet! Three clicks and we have an application running in iOS and Android! Now, before we examine the project structure, let's jump into Visual Studio and add the Windows Phone project.
Voila! Another platform is added but it's missing some parts to work with our Xamarin.Forms solution. We need to add the required packages/libraries and make a small modification to the application starting point code.
Right-click in References of the Windows Phone project we just created and choose Manage NuGet Packages.Search for the Xamarin.Forms package and hit Install to add it to the Windows Phone project.We also need to reference the PCL library. Right-click to References | Add Reference, and in the section Solution you will find the PCL with the Project Name. Check the box and hit OK.We're almost done. We just need some code changes to the XAML MainPage to convert it to an Xamarin.Forms application.
Select the MainPage.xaml file and modify the root tag from PhoneApplicationPage to FormsApplicationPage as shown in the following screenshot:You might need to bring the namespace in XAML. If you use any fancy tool like ReSharper you already took care of it; if not, add the following line to your project root tag that we just modified. Again, check the final result in the preceding screenshot.Congratulations! You have created a solution with three platform-specific projects (iOS, Android, and Windows Phone) and a core class library (PCL). Remember, the Windows Phone project will only be active when the solution is opened in Visual Studio.
So, we still have the beauty of native applications but we get to share the UI code as well! Sweet!
See in the following screenshot the Xamarin.Forms platform architecture that reflects what we just created:
Our three platform-specific projects are at the top architecture layer, the shared C# user interface code below, and the Shared C# App Logic at the bottom.
Xamarin.Forms allows you to describe the UI once using a shared set of controls while still rendering a native UI. This is happening with the help of the native platforms' renderers; there is one for each supported control for every platform. So, when we add a Label control, the platform renderer will transform it to a UILabel for iOS, a TextView for Android, and a TextBlock for Windows Phone.
In the core Portable Class Library project, expand References | From Packages. Referenced are the libraries Xamarin.Forms.Core and Xamarin.Forms.Xaml; the first one contains all the core logic of Xamarin.Forms and the second is specific to the XAML code, which we will discuss in detail in Chapter 2, Declare Once, Visualize Everywhere.
Go to a platform-specific project now; let's see Android first. Expand References | From Packages, and we have again Xamarin.Forms.Core and Xamarin.Forms.Xaml, but also Xamarin.Forms.Platform.Android. This is the platform-specific library where all the Android renderers live and its responsibility is to take the UI abstractions and translate to a platform-specific UI.
The same applies to our iOS project with the platform-specific library having the name Xamarin.Forms.Platform.iOS.
In the references of the platform-specific projects you can see our core PCL reference too; it couldn't work without our base code, right?
That is all great! But how do these platform-specific projects connect to the Xamarin.Forms application? For that we have to look in the code behind every platform application entry point.
Start from the Windows Phone project. We modified our MainPage.xaml.cs code behind, and now it is not a Windows Phone Page type but Xamarin.Forms.Platform.WinPhone.FormsApplicationPage. The important calls is in the constructor, Forms.Init, and the LoadApplication methods. In the latter we pass a Xamarin.Forms.Appplication instance located in our PCL. Open the FormsCookbook.cs file in the PCL project. Here is our Xamarin.Forms entry point, with some UI code in the constructor. In the next section, we discuss and change this code.
For the iOS project, you will find the related method calls in the AppDelegate.cs, FinishedLaunching method implementation. The difference is that the AppDelegate class inherits from Xamarin.Forms.Platform.iOS.FormsApplicationDelegate.
And finally, in the Android project, the MainActivity.cs file is our MainLauncher activity and inherits from Xamarin.Forms.Platform.Android.FormsApplicationActivity. It initializes the platform specifics and loads the Xamarin.Forms application class in the OnCreate method implementation. Notice the difference in the Forms.Init method: it requires two parameters: an Activity and Bundle instances.
