Xamarin.Forms Projects - Johan Karlsson - E-Book

Xamarin.Forms Projects E-Book

Johan Karlsson

0,0
31,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Xamarin.Forms is a lightweight cross-platform development toolkit for building applications with a rich user interface.
In this book you'll start by building projects that explain the Xamarin.Forms ecosystem to get up and running with building cross-platform applications. We'll increase in difficulty throughout the projects, making you learn the nitty-gritty of Xamarin.Forms offerings. You'll gain insights into the architecture, how to arrange your app's design, where to begin developing, what pitfalls exist, and how to avoid them. The book contains seven real-world projects, to get you hands-on with building rich UIs and providing a truly cross-platform experience. It will also guide you on how to set up a machine for Xamarin app development. You'll build a simple to-do application that gets you going, then dive deep into building advanced apps such as messaging platform, games, and machine learning, to build a UI for an augmented reality project.
By the end of the book, you'll be confident in building cross-platforms and fitting Xamarin.Forms toolkits in your app development. You'll be able to take the practice you get from this book to build applications that comply with your requirements.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 441

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Xamarin.Forms Projects
Build seven real-world cross-platform mobile apps with C# and Xamarin.Forms
Johan Karlsson
Daniel Hindrikes
BIRMINGHAM - MUMBAI

Xamarin.Forms Projects

Copyright © 2018 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 authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.

Commissioning Editor: Pavan RamchandaniAcquisition Editor:Trusha ShriyanContent Development Editor:Pranay FereiraTechnical Editor:Aishwarya MoreCopy Editor: Safis EditingProject Coordinator: Pragati ShuklaProofreader: Safis EditingIndexer: Priyanka DhadkeGraphics: Alishon MendonsaProduction Coordinator:Shraddha Falebhai

First published: December 2018

Production reference: 1261218

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78953-750-5

www.packtpub.com

I dedicate this book to all the people I met during my years as a Xamarin developer that never believed in Xamarin. If you read this book, you will hopefully understand how great Xamarin is!
– Daniel Hindrikes
This book is dedicated to the spider in my basement that motivated me to write a book thick enough to finally kill him with.
– Johan Karlsson
mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

Packt.com

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.packt.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.packt.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.

Foreword

Xamarin.Forms was launched 6 years ago with the humble intention of being a simple tool for creating simple apps. In the years since then, the toolkit has grown considerably, becoming more capable and more complex. To my astonishment, a community sprung up around this little project, and before we knew it there were thousands of early adopters. It turns out there was a real call for bringing a XAML-style framework to mobile application development.

The journey to today has not been without mistakes. At times, things have become more complicated or less clear than they ought to have been. With the public release of version 1.0, there were many problems with the toolkit, and it took a lot of work, along with help from the community, to get most of them ironed out. I tell you this not to turn you away from using Xamarin.Forms—quite the opposite—it has had its trial by fire. I tell you this because having a guide who has seen where the traps and pitfalls are can save you time and anguish.

Johan Karlsson and Daniel Hindrikes have proven with this book that they not only understand how to use the tool we created, but they understand the vision of where we are trying to go. Their knowledge and expertise will help you to have a more complete understanding of the toolkit, as well as letting you navigate its ups and downs. This book will walk you through the most basic aspects of Xamarin.Forms through to some of the most complicated, and takes in some interesting side-streets along the way.

Jason Smith

Xamarin.Forms co-creator

Contributors

About the authors

Johan Karlsson has been working with Xamarin since the days of MonoTouch and Mono for Android, and it all started with writing a game. He is a full-stack developer, currently focusing on mobile applications using Xamarin. But he has, in the past, worked a lot with ASP.NET MVC, Visual Basic.NET, and C#. He has also created a whole bunch of databases in SQL Server over the years.Johan works at tretton37 in Sweden and has about 20 years experience in the trade of assembling ones and zeros.

I want to send a special thanks to my ex-wife, Jenny, for allowing me to pursue my coding interest by letting me fly around the world at the most inconvenient times! (Honey, I’m heading to The United States tomorrow. Please feed the cat and pick our kids up from daycare, etc.) And, of course, to my children, Ville and Lisa, for being an inspiration in life! Also, thanks to Packt and our tech reviewer, Jimmy Engström, who has nitpicked our applications, and made us sit up late at night correcting the code. (Smiles...)

Daniel Hindrikes is a developer and architect whose passion is for developing mobile apps powered by the cloud. Daniel fell in love with Xamarin in its early days, when he realized that he could use C# even for iOS and Android apps, and that he could share code with the Windows applications he was building. But Daniel started to build mobile applications long before that: he built Android applications with Java and even Java ME applications (a long, long time ago). Daniel enjoys sharing his knowledge, for example, by speaking at conferences, blogging, and recording the podcast The Code Behind. Daniel works at tretton37 in Sweden and has experience of working with both local and global customers.

My special thanks to my family; my wife, Anna-Karin; and our twins, Ella and Willner. They've supported me during the writing process. Also, I would like to say thanks to the fantastic team at Packt and our technical reviewer, Jimmy Engström, who has reviewed the content and helped us make it better.

About the reviewer

Jimmy Engstrom wrote his first line of code when he was 7 years old, and it has been his greatest passion. It is a passion since that day that has made him the developer he is today and that has taken him around the world, spreading his knowledge. It has given him awards such as second place in Dice's worldwide game developer competition, a place in the top ten best developers in Sweden, five Microsoft MVP awards in Windows development, not to mention Geek of the year. When he is not out spreading his knowledge, he is working as a web developer, trying out the latest tech, or reading up on the latest framework.

Jimmy also runs his own company, called Azm Dev, with his wife, where they focus on future tech such as AI, bots, and holographic computing, but also on teaching UX and presentation skills.

He is the co-host of a podcast called Coding After Work.

A big thank you to my wife, Jessica, who has been picking up my slack while reviewing this book. Love you!

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Xamarin.Forms Projects

Dedication

www.PacktPub.com

Why subscribe?

Packt.com

Foreword

Contributors

About the authors

About the reviewer

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Conventions used

Get in touch

Reviews

Introduction to Xamarin

Native applications

Xamarin and Mono

Code sharing

Using existing knowledge

Xamarin.iOS

Xamarin.Android

Xamarin.Mac

Xamarin.Forms

The architecture of Xamarin.Forms

Defining a user interface using XAML

Defining a Label control

Creating a page in XAML

Creating a page in C#

XAML or C#?

Xamarin.Forms versus traditional Xamarin

When to use Xamarin.Forms

Setting up a development machine

Setting up a Mac

Installing Xcode

Installing Visual Studio

Configuring the Android emulator

Setting up a Windows machine

Installing Xamarin for Visual Studio

Pairing Visual Studio with a Mac

Configuring an Android emulator and hardware acceleration

Configuring UWP developer mode

Summary

Building Our First Xamarin.Forms App

Technical requirements

An overview of the project

Beginning the project

Setting up the project

Creating the new project

Examining the files

DoToo

DoToo.Android

DoToo.iOS

DoToo.UWP

Updating the Xamarin.Forms packages

Removing the MainPage file

Creating a repository and a TodoItem model

Defining a to-do list item

Creating a repository and its interface

Connecting SQLite to persist data

Adding the SQLite NuGet package

Updating the TodoItem class

Creating a connection to the SQLite database

Implementing the Get, Add, and Update methods

Using MVVM – creating Views and ViewModels

Defining a ViewModel base class

Introducing PropertyChanged.Fody

Creating the MainViewModel

Creating the TodoItemViewModel

Creating the ItemViewModel

Creating the MainView

Creating the ItemView

Wiring up a dependency injection through Autofac

Adding a reference to Autofac

Creating the resolver

Creating the bootstrapper

Adding a bootstrapper on iOS

Adding a bootstrapper in Android

Adding a bootstrapper in UWP

Making the app run

Adding data bindings

Navigating from the MainView to the ItemView to add a new item

Adding new items to the list

Binding the ListView in the MainView

Creating a ValueConverter for the item status

Using the ValueConverter

Navigating to an item using a command

Marking an item as complete using a command

Creating the filter toggle function using a command

Laying out contents

Setting an application-wide background color

Laying out the MainView and ListView items

The filter button

Touching up the ListView

Summary

A Matchmaking App with a Rich UX Using Animations

Technical requirements

Project overview

Creating the matchmaking app

Creating the project

Creating the new project

Updating the Xamarin.Forms NuGet packages

Designing the MainPage file

Creating the Swiper control

Creating the control

Defining the main grid

Adding a content view for the photo

Creating the DescriptionGenerator

Creating a picture class

Binding the picture to the control

Setting the source

Controlling the loading label

Handling pan gestures

Testing the control

Creating decision zones

Extending the grid

Adding the StackLayout for liking photos

Adding the StackLayout for denying photos

Determining the screen size

Adding a clamp function

Adding code to calculate the state

Defining a method for calculating the state

Wiring up the pan state check

Adding exit logic

Checking if the image should exit

Removing the image

Updating PanCompleted

Adding events to the control

Declaring two events

Raising the events

Wiring up the Swiper control

Adding images

Adding initial photos

Making the call from the constructor

Adding count labels

Subscribing to events

Adding methods to update the GUI and respond to events

Wiring up events

Summary

Building a Location Tracking App Using GPS and Maps

Technical requirements

Project overview

Getting started

Building the MeTracker app

Creating a repository to save the location of the users

Creating a model for the location data

Creating the repository

Xamarin.Essentials

Installing the NuGet package

Configuring Xamarin.Essentials on Android

Creating a service for location tracking

Setting up the app logic

Creating a view with a map

Creating a ViewModel

Creating a resolver

Creating the bootstrapper

Creating the iOS bootstrapper

Creating the Android bootstrapper

Setting the MainPage

Background location tracking on iOS

Enabling location updates in the background

Getting permissions to use the location of the user

Subscribing to location updates

Background location tracking with Android

Adding the required permissions to use the location of the user

Creating a background job

Scheduling a background job

Subscribing to location updates

Creating a heat map

Adding a GetAll method to the LocationRepository

Preparing the data for visualization

Creating custom renderers

Creating a custom control for the map

Creating a custom renderer to extend the map in the iOS app

Creating a custom renderer to extend the map in the Android app

Refreshing the map when resuming the app

Summary

Building a Weather App for Multiple Form Factors

Technical requirements

Project overview

Getting started

Building the weather app

Creating models for the weather data

Adding the weather API models manually

Adding the app-specific models

Adding the ForecastItem model

Adding the Forecast model

Creating a service for fetching the weather data

Configuring the applications to use location services

Configuring the iOS app to use location services

Configuring the Android app to use location services

Configuring the UWP app to use location services

Creating the ViewModel class

Getting the weather data

Grouping the weather data

Creating a Resolver

Creating a bootstrapper

Creating a RepeaterView based on a FlexLayout

Creating the view for tablets and desktop computers

Using RepeaterView

Adding a toolbar item to refresh the weather data

Adding a loading indicator

Setting a background image

Creating the view for phones

Using a grouped ListView

Adding pull to refresh functionality

Navigating to different views based on the form factor

Handling states with VisualStateManager

Creating a behavior to set state changes

Summary

Setting up a Backend for a Chat App Using Azure Services

Technical requirements

Azure serverless services

Azure SignalR Service

Azure functions

Azure blob storage

Azure Cognitive Services

Project overview

Building the serverless backend

Creating a SignalR service

Creating a storage account

Creating a Cognitive Service

Creating functions

Creating the Azure service for functions

Creating a function to return the connection information for the SignalR service

Creating a message library

Creating a storage helper

Creating a function for sending messages

Using the Computer Vision API to scan for adult content

Creating a scheduled job to clear photos from storage

Deploying the functions to Azure

Summary

Building a Real-Time Chat Application

Technical requirements

Project overview

Getting started

Building the chat app

Creating the chat service

Initializing the app

Creating a resolver

Creating a Bootstrapper

Creating a base ViewModel

Creating the Mainview

Creating MainViewModel

Creating the MainView

Replacing the MainPage

Editing the XAML

Fixing the code behind the view

Setting the main view

Creating the ChatView

Creating the ChatViewModel

Creating the class

Adding the text property

Receiving messages

Creating the LocalSimpleTextMessage class

Sending text messages

Installing the Acr.UserDialogs plugin

Installing the Media plugin

Sending photos

Creating the ChatView

Creating Base64ToImageConverter

Creating the skeleton ChatView

Adding ResourceDictionary

Adding ListView

Adding templates

Creating a template selector

Adding the buttons and entry control

Fixing the code behind

Styling

Styling with CSS

Applying the style sheet

Handling life cycle events

Summary

Creating an Augmented-Reality Game

Technical requirements

Essential theory

An overview of the project

Beginning the project

Creating the project

Updating the Xamarin.Forms NuGet packages

Setting the Android target to 8.1

Adding the camera permission to Android

Adding Camera Usage Description for iOS

Defining the user interface

Creating the ARView control

Modifying the MainPage

Adding Urhosharp

Installing the UrhoSharp NuGet package for iOS

Installing the UrhoSharp.ARCore Nuget Package for Android

Adding the Android life cycle events

Defining the PlaneNode

Adding custom renderers for the ARView control

For iOS

For Android

Creating the game

Adding the shared partial Game class

CreateSubPlane

UpdateSubPlane

FindNodeByPlaneId

Adding platform-specific partial classes

Adding the iOS-specific partial class

Adding the Android-specific partial class

Writing the ARKit-specific code

Defining the ARKitComponent

Writing handlers for adding and updating anchors

SetPositionAndRotation

UpdateOrAddPlaneNode

OnAddAnchor

OnUpdateAnchors

Writing a handler for removing anchors

OnRemoveAnchors

Initializing ARKit

Writing ARCore-specific code

Defining the ARCoreComponent

SetPositionAndRotation

Writing a handler for ARFrame updates

Initializing ARCore

OnConfigRequested

InitializeAR

Writing the game

Adding a camera

Configuring a renderer

Adding lights

Implementing the game startup

Adding boxes

AddBox()

OnUpdate()

Making boxes rotate

Creating the rotate component

Assigning the Rotator component

Adding box hit-test

Adding a death animation

DetermineHit()

OnTouchBegin()

Wiring up input

Updating statistics

Defining a statistics class

Sending updates via MessagingCenter

Wiring up events

Updating the GUI

Subscribing to the updates in the MainForm

Summary

Hot Dog or Not Hot Dog Using Machine Learning

Technical requirements

Machine learning

Azure Cognitive Services – Custom Vision

CoreML

TensorFlow

Project overview

Getting started

Building the Hot Dog or Not Hot Dog application using machine learning

Training a model

Tagging images

Training a model

Exporting a model

Building the app

Classifying images with machine learning

Using CoreML for image classification

Using TensorFlow for image classification

Creating a base ViewModel

Initializing the app

Creating a Resolver

Creating a Bootstrapper

Creating the iOS bootstrapper

Creating the Android bootstrapper

Building the first view

Building the ViewModel

Building the view

Building the result view

Building the ViewModel

Building the view

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Xamarin.Forms Projects is a hands-on book in which you get to create seven applications from the ground up. You will gain the fundamental skills you need in order to set up your environment, and we will explain what Xamarin is before we transition into Xamarin.Forms to really take advantage of truly native cross-platform code.

After reading this book, you will have a real-life understanding of what it takes to create an app that you can build on and that stands the test of time.

We will cover, among other things, animations, augmented reality, consuming REST interfaces, real-time chat using SignalR, and location tracking using a device's GPS. There is also room for machine learning and the must-have to-do list.

Happy coding!

Who this book is for

This book is for developers who know their way around C# and Visual Studio. You don't have to be a professional programmer, but you should have basic knowledge of object-oriented programming using .NET and C#. The typical reader would be someone who wants to explore how you can use Xamarin, and specifically Xamarin.Forms, to create applications using .NET and C#.

No knowledge of Xamarin is required ahead of time, but it would be a great help if you've worked in traditional Xamarin and want to take the step toward Xamarin.Forms.

What this book covers

Chapter 1, Introduction to Xamarin, explains the basic concepts of Xamarin and Xamarin.Forms. It helps you understand the building blocks of how to create a true cross-platform app. It's the only theoretical chapter of the book and it will help you get started and set up your development environment.

Chapter 2, Building Our First Xamarin.Forms App, guides you through the concepts of Model-View-ViewModel and explains how to use Inversion of Control to simplify the creation of Views and ViewModels. We will create a to-do app that supports navigation, filtering, and the adding of to-do items to a list, and will also render a user interface that takes advantage of the powerful data-binding mechanisms in Xamarin.Forms.

Chapter 3, A Matchmaking App with a Rich UX Using Animations, lets you dive deeper into how to define a richer user interface with animations and content placement. It also covers the concept of custom controls to encapsulate the user interface into components that are self-contained.

Chapter 4, Building a Location-Tracking App Using GPS and Maps, taps into using geolocation data from the device's GPS and how to plot this data on a layer on a map. It also explains how to use background services to keep tracking the location over a long period of time to create a heat map of where you spend your time.

Chapter 5, Building a Weather App for Multiple Form Factors, is all about consuming a third-party REST interface and displaying the data in a user-friendly way. We will hook up to a weather service to get the forecast for the current location you are in and display the results in a list.

Chapter 6, Setting up a Backend for a Chat App Using Azure Services, is the first of a two-part chapter in which we'll set up as a chat app. This chapter explains how to use Azure Services to create a backend that exposes functionality through SignalR to set up a real-time communication channel between apps.

Chapter 7, Building a Real-Time Chat Application, follows on from the previous chapter and covers the frontend of the app, in this case, a Xamarin.Forms app that connects to the backend that relays messages between users. The chapter focuses on setting up SignalR on the client side and explains how to create a service model that abstracts this communication through messages and events.

Chapter 8, Creating an Augmented Reality Game, ties the two different AR APIs into a single UrhoSharp solution. Android uses ARCore to handle augmented reality, and iOS uses ARKit to do the same. We will drop down into platform-specific APIs through custom renderers and expose the result as a common API for the Xamarin.Forms app to consume.

Chapter 9, Hot Dog or Not Hot Dog Using Machine Learning, covers the creation of an app that uses machine learning to identify whether an image contains a hot dog or not.

To get the most out of this book

We recommend that you read the first chapter to make sure that you are up to speed with the basic concepts of Xamarin in general. After that, you could pretty much pick any chapter you like to learn more about. Each chapter is standalone but the chapters are ordered by complexity; the further you are into the book, the more complex the app is.

The apps are adapted for real-world use but some parts are left out, such as proper error handling and analytics, since they are out of the scope of the book. You should, however, get a good grasp of the building blocks of how to create an app.

Having said that, it does help if you have been a C# and .NET developer for a while, since many of the concepts are not really app-specific but are good practice in general, such as Model-View-ViewModel and Inversion of Control.

But, most of all, it's a book you can use to kick-start your Xamarin.Forms development learning curve by focusing on what chapters interest you the most.

Download the example code files

The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Xamarin.Forms-Projects. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781789537505_ColorImages.pdf.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

Introduction to Xamarin

This chapter is all about getting to know what Xamarin is and what to expect from it. It is the only chapter that is a pure theory chapter; all the others will cover hands-on projects. You're not expected to write any code at this point, but instead, simply read through the chapter to develop a high-level understanding of what Xamarin is and how Xamarin.Forms are related to Xamarin.

We will start by defining what a native application is and what .NET as a technology brings to the table. After that, we will look at how Xamarin.Forms fit into the bigger picture and

learn when it is appropriate to use traditional Xamarin and Xamarin.Forms. We often use the term traditional Xamarin to describe applications that don't use Xamarin.Forms, even though Xamarin.Forms applications are bootstrapped through a traditional Xamarin application.

In this chapter, we will be covering the following topics:

Native applicationsXamarin and MonoXamarin.FormsSetting up a development machine

Let's get started!

Native applications

The term native applicationmeans differentthingsto differentpeople.For some people, it is an application thatisdeveloped using the tools specified by the creator of the platform, such as an application developed for iOS with Objective-C or Swift, an Android app developed with Java or Kotlin, or a Windows app developed with .NET. Other people use the term native application to refer to applications that are compiled to machine code that is native. In this book, we will define a native application as one that has a native user interface, performance, and API access. The following list explains these three concepts in greater detail:

Native user interface

:Applications built with Xamarin use the standard controls for each platform. This means, for example, that an iOS app built with Xamarin will look and behave as an iOS user would expect, and an Android app built with Xamarin will look and behave as an Android user would expect.

Native performance

:

Applications

built with Xamarin are compiled for native performance and could use platform-specific hardware acceleration.

Native API access:

Native API access means that applications built with Xamarin could use everything that the target platforms and devices offer to developers.

Xamarin and Mono

Xamarin is a developer platform that is used for developing native applications for iOS (Xamarin.iOS), Android (Xamarin.Android), andmacOS (Xamarin.Mac). It is technically a binding layer on top of these platforms. Binding to platform APIs enables .NET developers to use C# (and F#) to develop native applications with the full capacity of each platform. The C# APIs we use when we develop applications with Xamarin are more or less identical to the platform APIs, but they are .NETified. For example, APIs are often customized to follow .NET naming conventions, and Android set and get methods are often replaced by properties. The reason for this is that APIs should be easier to use for .NET developers.

Mono (https://www.mono-project.com) is an open source implementation of the Microsoft .NET framework, which is based on the European Computer Manufacturers Association (ECMA) standards for C# and the common language runtime (CLR). Mono was created to bring the .NET framework to platforms other than Windows. It is part of the .NET foundation (http://www.dotnetfoundation.org), an independent organization that supports open development and collaboration involving the .NET ecosystem.

With the combination of Xamarin platforms and Mono, we will be able to use both all platform-specific APIs and all platform-independent parts of .NET, including, for example, namespaces, systems, System.Linq, System.IO, System.Net, and System.Threading.Tasks.

There are several reasons to use Xamarin for mobile application development, as we will see in the following sections.

Code sharing

If there is one common programming language for multiple mobile platforms, and even server platforms, then we can share a lot of code between our target platforms, as illustrated in the following diagram. All code that isn't related to the target platform can be shared with other .NET platforms. Code that is typically shared in this way includes business logic, network calls, and data models:

There is also a large community based around the .NET platforms and a wide range of third-party libraries and components that can be downloaded from NuGet (https://nuget.org) and used across the .NET platforms.

Code sharing across platforms will lead to shorter development times. It will also lead to applications of a higher quality because we only need to write the code for business logic once. There will be a lower risk of bugs, and we will also be able to guarantee that a calculation will return the same result, no matter what platform our users are using.

Using existing knowledge

For .NET developers who want to start building native mobile applications, it is easier to just learn the APIs for the new platforms than it is to learn programming languages and APIs for both old and new platforms.

Similarly, organizations that want to build native mobile applications could use their existing developers with their knowledge of .NET to develop applications. Because there are more .NET developers than Objective-C and Swift developers, it would be easier to find new developers for mobile application development projects.

Xamarin.iOS

Xamarin.iOSis used for building applications for iOS with .NET, and contains the bindings to theiOS APIs mentioned previously.Xamarin.iOS uses ahead of time (AOT) compiling to compile the C# code to Advanced RISC Machines (ARM) assembly language. The Mono runtime runs along with the Objective-C runtime. Code that uses .NET namespaces, such as System.LinqorSystem.Net, will be executed by the Mono runtime, while code that uses iOS-specific namespaces will be executed by the Objective-C runtime. Both the Mono runtime and the Objective-C runtime will run on top of theUnix-likekernel,X is Not Unix (XNU) (https://en.wikipedia.org/wiki/XNU), which is developed by Apple. The following diagram shows an overview of the iOS architecture:

Xamarin.Android

Xamarin.Android is used to build applications for Android with .NET, and contains the bindings to the Android APIs. The Mono runtime and the Android runtime run side by side on top of a Linux kernel. Xamarin.Android applications could either be just-in-time (JIT)-compiled or AOT-compiled, but to AOT-compile them, you need to use Visual Studio Enterprise.

Communication between the Mono runtime and the Android runtime occurs via a Java Native Interface (JNI) bridge. There are two types of JNI bridges: manage callable wrapper (MCW) and Android callable wrapper (ACW). An MCW is used when the code needs to run in the Android runtime (ART) and an ACW is used when ART needs to run code in the Mono runtime, as shown in the following diagram:

Xamarin.Mac

Xamarin.Macis for building applications for macOS with .NET, and contains the bindings to the macOS APIs.Xamarin.Machas the same architecture asXamarin.iOS—the only difference is thatXamarin.Macapplications are JIT compiled, unlikeXamarin.iOSapps, which are AOT-compiled. This is shown in the following diagram:

Xamarin.Forms

Xamarin.Formsis a UI framework that is built on top of Xamarin (for iOS and Android) and the Universal Windows Platform (UWP). Xamarin.Forms enables developers to create a UI for iOS, Android, and UWP with one shared code base, as illustrated in the following diagram. If we are building an application with Xamarin.Forms, we can use XAML, C#, or a combination of both to create the UI:

The architecture of Xamarin.Forms

Xamarin.Formsis more or less just an abstract layer on top of each platform.Xamarin.Formshas a shared layer, which is used by all platforms, as well as a platform-specific layer.The platform-specific layercontainsrenderers. A renderer is a class that maps a Xamarin.Forms control into a platform-specific native control. Each Xamarin.Forms control has a platform-specific renderer.

The following diagram illustrates howan entry control inXamarin.Formsis rendered to aUITextField control from the UIKit namespace when the shared Xamarin.Forms code is used in an iOS app. The same code in Android renders an EditText control from the Android.Widget namespace:

Defining a user interface using XAML

The most common way to declare your user interface in Xamarin.Forms is by defining it in a XAML document. It is also possible to create the GUI in C#, since XAML is really only a markup language for instantiating objects. You could, in theory, use XAML to create any type of object, as long as it has a parameterless constructor. A XAML document is an Extensible Markup Language (XML) document with a specific schema.

Creating a page in XAML

A single control is no good unless it has a container that hosts it. Let's see what an entire page would look like. A fully valid ContentPage defined in XAML is an XML document. This means that we must start with an XML declaration. After that, we must have one, and only one, root node, as shown in the following code:

<

?

xml

version

"

1.0

"

encoding

"

UTF-8

"

?>

<

ContentPage

xmlns

"

http://xamarin.com/schemas/2014/forms

"

xmlns

:

x

"

http://schemas.microsoft.com/winfx/2009/xaml

"

x

:

Class

"

MyApp.MainPage

"

> <StackLayout> <Label Text="Hello world!" /> </StackLayout></ContentPage>

In the preceding example, we have defined a ContentPage that translates into a single view on each platform. In order to make it valid XAML, you must specify a default namespace (xmlns="http://xamarin.com/schemas/2014/forms") and then add the x namespace (xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml").

The default namespace lets you create objects without prefixing them, like the StackLayout object. The x namespace lets you access properties such as the x:Class, which tells the XAML parser which class to instantiate to control the page when the ContentPage object is being created.

A ContentPage can have only one child. In this case, it's a StackLayout control. Unless you specify otherwise, the default layout orientation is vertical. A StackLayout can, therefore, have multiple children. Later on, we will touch on more advanced layout controls, such as the Grid and the FlexLayout control.

In this specific example, we are going to create a Label control as the first child of the StackLayout.

XAML or C#?

Generally, using XAML will give you a much better overview, since the page is a hierarchical structure of objects and XAML is a very nice way of defining that structure. In code, the structure gets flipped around since you must define the innermost object first, making it harder to read the structure of your page. This was shown in an earlier examplein this chapter. Having said that, it is generally a matter of preference as to how you decide to define the GUI. This book will use XAML rather than C# in the projects to come.

Xamarin.Forms versus traditional Xamarin

While this book is about Xamarin.Forms, we will highlight the difference between using traditional Xamarin and Xamarin.Forms. Traditional Xamarin is used when developing applications that use iOS and Android SDK without any means of abstraction. For example, we can create an iOS app that defines its user interface in a storyboard or in the code directly. This code will not be reusable for other platforms, such as Android. Applications built using this approach can still share non-platform-specific code by simply referencing a .NET standard library. This relationship is shown in the following diagram:

Xamarin.Forms, on the other hand, is an abstraction of the GUI, which allows us to define user interfaces in a platform-agnostic way. It still builds on top of Xamarin.iOS, Xamarin.Android, and all other supported platforms. The Xamarin.Forms application can be created as a .NET standard library or as a shared code project, where the source files are linked as copies and built within the same project as the platform you are currently building for. This relationship is shown in the following diagram:

Having said that, Xamarin.Forms cannot exist without traditional Xamarin, since it's bootstrapped through an application for each platform. This gives you the ability to extend Xamarin.Forms on each platform using custom renderers and platform-specific code that can be exposed to your shared code base through interfaces. We'll look at these concepts in detaillater in this chapter.

When to use Xamarin.Forms

We can use Xamarin.Forms in most cases and for most types of applications. If we need to use controls that not are available in Xamarin.Forms, we can always use the platform-specific APIs. There are, however, cases where Xamarin.Forms is not useful. The most common situation in which we might want to avoid using Xamarin.Forms is if we are building an app that we want to look very different across our target platforms.

Setting up a development machine

To develop an app for multiple platforms imposes higher demands on our development machine. One reason for this is that we often want to run one or multiple simulators or emulators on our development machine. Different platforms also have different requirements with regard to what is needed to begin development. Regardless of whether we are using Mac or Windows, Visual Studio will be our IDE. There are several versions of Visual Studio, including the free community edition. Go to https://visualstudio.microsoft.com/ to compare the available versions of Visual Studio. The following list is a summary of what we need to begin development for each platform:

iOS

:To develop an app for iOS, we need a Mac. This could either be the machine that we are developing on or a machine on our network, if we are using one. The reason that we need to connect to a Mac is that we need Xcode for compiling and debugging an app. Xcode also provides the iOS simulator.

Android

:Android apps can be developed on either macOS or Windows. Everything you need, including SDKs and simulators, are installed with Visual Studio.

UWP

:UWP apps can only be developed in Visual Studio on a Windows machine.

Setting up a Mac

There are two main tools that are required to develop applications for iOS and Android with Xamarin on a Mac. These are Visual Studio for Mac (if we are onlydeveloping Android applications, this is the only tool we need) and Xcode. In the following sections, we will take a look at how to set up a Mac for app development.

Installing Xcode

Before we install Visual Studio, we need to download and install Xcode. Xcode is the official development IDE from Apple and contains all the tools they provide for iOS development, including SDKs for iOS, macOS, tvOS, and watchOS.

We can download Xcode from the Apple developer portal (https://developer.apple.com) or from Apple App Store. I recommend that you download it from App Store because this will always provide you with the latest stable version. The only reason to download Xcode from the developer portal is if we want to use a prerelease version of Xcode, to develop for a prerelease of iOS, for example.

After the first installation, and after each update of Xcode, it is important to open it. Xcode often needs to install additional components after an installation or an update. You also need to open Xcode to accept the license agreement with Apple.

Installing Visual Studio

To install Visual Studio, we first need to download it from https://visualstudio.microsoft.com.

When we start the Visual Studio installer via the file we downloaded, it will start to check what we already have installed on our machine. When the check has finished, we will be able to select which platforms and tools we would like to install. Note that Xamarin Inspector requires a Visual Studio Enterprise license.

Once we have selected the platforms that we want to install, Visual Studio will download and install everything that we need to get started with app development using Xamarin, as shown in the following screenshot:

Configuring the Android emulator

Visual Studio will use the Android emulators provided by Google. If we would like the emulator to be fast, then we need to ensure that it is hardware-accelerated. To hardware-accelerate the Android emulator, we need to install the Intel Hardware Accelerated Execution Manager (HAXM), which can be downloaded from https://software.intel.com/en-us/articles/intel-hardware-accelerated-execution-manager-intel-haxm.

The next step is to create an Android Emulator. First, we need to ensure that the Android emulator and the Android OS images are installed. To do this, go through the following steps:

Go to the

Tools

tab to install the

Android Emulator

:

We also need to install one or multiple images to use with the emulator. We can install multiple images if, for example, we want to run our application on different versions of Android. We will select emulators with

Google Play

(as shown in the following screenshot) so that we can use Google Play services in our app, even when we are running it in an emulator. This is required if, for example, we want to use Google Maps in our app:

Then, to create and configure an emulator, go to the

Android Device Manager

from the

Tools

tab in Visual Studio. From the

Android Device Manager

, we can start an emulator if we have already created one, or we can create new emulators, as shown in the following screenshot:

If we click the

New Device

button, we can create a new emulator with the specifications that we need. The easiest way to create a new emulator here is to select a base device that matches our needs. These base devices will be preconfigured, and that is often enough. However, it is also possible to edit the properties of the device so that we can get an emulator that matches our specific needs.

Because we will not run the emulator on a device with an ARM processor, we have to select either an x86 processor or an x64 processor, as shown in the following screenshot. If we try to use an ARM processor, the emulator will be very slow:

Setting up a Windows machine

We can either use a virtual or a physical Windows machine for development with Xamarin. We can, for example, run a virtual Windows machine on our Mac. The only tool we need for app development on our Windows machine is Visual Studio.

Installing Xamarin for Visual Studio

If we already have Visual Studio installed, we must first open Visual Studio Installer; otherwise, we need to go to https://visualstudio.microsoft.com to download the installation files.

Before the installation starts, we need to select which workloads we want to install.

If we want to develop apps for Windows, we need to select the Universal Windows Platform development workload, as shown in the following screenshot:

For Xamarin development, we need to install Mobile development with .NET. If you want to use Hyper-V for hardware acceleration, we can deselect the checkbox for Intel HAXM in the detailed description of the Mobile development with .NET workload on the left-hand side, as shown in the following screenshot. When we deselect Intel HAXM, the Android emulator will also be deselected, but we can install it later:

When we first start Visual Studio, we will be asked whether we want to sign in. It is not necessary for us to sign in unless we want to use Visual Studio Professional or Enterprise, in which case we have to sign in so that our license can be verified.

Pairing Visual Studio with a Mac

If we want to run, debug, and compile our iOS app, then we need to connect it to a Mac. We can set up the Mac manually, as described earlier in this chapter, or we can use Automatic Mac Provisioning. This will install Mono and Xamarin.iOS on the Mac that we are connecting to. It will not install the Visual Studio IDE, but this isn't necessary if you just want to use it as a build machine. We do, however, need to install Xcode manually.

To be able to connect to the Mac—either to a manually-installed Mac or using Automatic Mac Provisioning—the Mac needs to be accessible via our network and we need to enable Remote Login on the Mac. To do this, go to Settings | Sharing and select the checkbox for Remote Login. To the left of the window, we can select which users are allowed to connect with Remote Login, as shown in the following screenshot:

To connect to the Mac from Visual Studio, use the Pair to Mac button in the toolbar (as shown in the following screenshot), or, in the top menu, select Tools | iOS and finally Pair to Mac:

A dialog will appear showing all the Macs that can be found on the network. If the Mac doesn't appear in the list of available Macs, we can use the Add Mac button in the bottom left corner to enter an IP address, as shown in the following screenshot:

If everything that you require is installed on the Mac, then Visual Studio will connect and we can start building and debugging our iOS app. If Mono is missing on the Mac, a warning will appear. This warning will also give us the option to install it, as shown in the following screenshot:

Configuring an Android emulator and hardware acceleration

If we want a fast Android emulator that works smoothly, we need to enable hardware acceleration. This can be done using either Intel HAXM or Hyper-V. The disadvantage of Intel HAXM is that it can't be used on machines with an Advanced Micro Devices (AMD) processor; you have to have a machine with an Intel processor. We can't use IntelHAXM in parallel with Hyper-V.