Mastering Xamarin UI Development. - Steven F. Daniel - E-Book

Mastering Xamarin UI Development. E-Book

Steven F. Daniel

0,0
34,79 €

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

Mehr erfahren.
Beschreibung

This book will provide you with the knowledge and practical skills that are required to develop real-world Xamarin and Xamarin.Forms applications. You’ll learn how to create native Android app that will interact with the device camera and photo gallery, and then create a native iOS sliding tiles game. You will learn how to implement complex UI layouts and create customizable control elements based on the platform, using XAML and C# 7 code to interact with control elements within your XAML ContentPages.

You’ll learn how to add location-based features by to your apps by creating a LocationService class and using the Xam.Plugin.Geolocator cross-platform library, that will be used to obtain the current device location. Next, you’ll learn how to work with and implement animations and visual effects within your UI using the PlatformEffects API, using C# code.

At the end of this book, you’ll learn how to integrate Microsoft Azure App Services and use the Twitter APIs within your app. You will work with the Razor Templating Engine to build a book library HTML5 solution that will use a SQLite.net library to store, update, retrieve, and delete information within a local SQLite database. Finally, you will learn how to write unit tests using the NUnit and UITest frameworks.

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

EPUB
MOBI

Seitenzahl: 508

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.



Mastering Xamarin UI Development
Second Edition
Build robust and a maintainable cross-platform mobile UI with Xamarin and C# 7
Steven F. Daniel

BIRMINGHAM - MUMBAI

Mastering Xamarin UI Development Second Edition

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 author, 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: Amarabha BanerjeeAcquisition Editor:Shweta PantContent Development Editor: Aishwarya GawankarTechnical Editor:Rutuja VazeCopy Editor: Safis EditingProject Coordinator:Sheejal ShahProofreader: Safis EditingIndexer:Pratik ShirodkarGraphics:Jason MonteiroProduction Coordinator:Arvindkumar Gupta

First published: January 2017 Second edition: August 2018

Production reference: 1310818

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

ISBN 978-1-78899-551-1

www.packtpub.com

To my favorite uncle, Benjamin Jacob Daniel: thank you for always making me smile and for inspiring me to work hard and achieve my dreams; you are a true inspiration and I couldn't have done this without your love, support, and guidance. Thank you.
As always, to Chan Ban Guan, for the continued patience, encouragement, and support, and most of all for believing in me during the writing of this book. I would like to thank my family for their continued love and support, and for always believing in me throughout the writing of this book.
This book would not have been possible without your love and understanding and I would like to thank you from the bottom of my heart.
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

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

Contributors

About the author

Steven F. Daniel is the CEO and founder of GENIESOFT STUDIOS, a software development company based in Melbourne, Victoria, that focuses primarily on developing games and business applications for the iOS, Android, and Mac OS X platforms. He is an experienced software engineer with more than 17 years' experience and is extremely passionate about making people employable by helping them use their existing skills in iOS, Android, and Xamarin to get the job done. He is a member of the SQL Server Special Interest Group (SQLSIG), CocoaHeads, and the Java Community. He was the co-founder and Chief Technology Officer (CTO) at SoftMpire Pty Ltd., a company focused primarily on developing business applications for the iOS and Android platforms.

About the reviewer

Jeremy Clough has been a programmer for 18 years, and just remembers the early days of C# when it was known as “Cool”. Since then he has developed a passion for F# and other functional programming languages, enjoying it when some of their features make it back into C#.

Senior Principal Developer at SEEK, and officially part of the furniture, Jeremy has been there long enough to have his most embarrassing code refactored out of existence.

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.

Acknowledgments

No book is the product of just the author; he just happens to be the one with his name on the cover. Several people contributed to the success of this book, and it would take more space than thanking each one individually.

First and foremost, I want to thank Chan Ban Guan for his constant guidance, support, encouragement, and understanding, throughout the whole writing process. My sincere gratitude to my Acquisition Editors, Shweta Pant and Devanshi Doshi, for giving me the opportunity to author the second edition of this book. To my Content Development Editor, Aishwarya Gawankar, for her understanding and support throughout the whole writing process.

I would also like to thank my Technical Editor, Rutuja Vaze, for her support throughout the final stages of this book. It was a pleasure to be able to work with you on this book; thanks goes to each and everyone of you for making the whole writing process such an enjoyable process. I would like to thank my technical reviewer, Jeremy Clough, for doing an awesome job of reviewing the contents and sharing his valuable feedback to make this book what it is; I am truly grateful.

Thank you also to the entire Packt Publishing team who worked on this book so diligently and tirelessly to help bring out such a high-quality final product. Finally, a big shout out to the engineers at Microsoft for creating Visual Studio for Mac and C#, the number one programming language, and the .NET platform, which helps provide developers with a rich set of tools that enables them to create fun, sophisticated applications using Xamarin and the power of Xamarin.Forms.

Finally, I would like to thank all my friends for their continued support, understanding, and encouragement during the book writing process. I am extremely grateful to have each and everyone of you as my friends, and it is a privilege to know each one of you.

Table of Contents

Title Page

Copyright and Credits

Mastering Xamarin UI Development Second Edition

Dedication

www.PacktPub.com

Why subscribe?

PacktPub.com

Contributors

About the author

About the reviewer

Packt is searching for authors like you

Acknowledgments

Preface

Who this book is for

What this book covers

To get the most out of this book

Downloading the example code

Download the color images

Conventions used

Get in touch

Reviews

Setting Up Visual Studio for Mac

Downloading and installing Visual Studio for Mac

Installing Visual Studio for Mac and Xamarin

Exploring the Microsoft Visual Studio for Mac IDE

Configuring and including additional .NET Runtimes

Defining your Android and iOS SDK locations

Understanding the Xamarin mobile platform

Benefits of developing apps using the Xamarin mobile platform

Developing native apps using the Xamarin approach

Developing apps using the Xamarin.Forms approach

Creating a Xamarin project for both iOS and Android

Creating the user interface for our Planetary app using XAML

Displaying a list of planet names using C#

Launching the Planetary app using the iOS simulator

Using and setting Breakpoints in your code

Setting a Breakpoint in your Planetary App solution

Using the Breakpoints Pad to view Breakpoints that have been set

Creating conditional Breakpoints to perform an action

Using the Visual Studio for Mac built-in debugger

Overview of the Visual Studio for Mac debugger

Using the debugger to step through your code

Using the Immediate window to print code variable contents

Summary

Building a PhotoLibrary App Using Android

Creating a native Android app using Visual Studio for Mac

Adding the Xamarin Media Plugin NuGet package to our solution

Creating the user interface for our PhotoLibrary app using XML

Updating the Strings XML file to include our UI control values

Creating the Styles XML file for our Photo Library app

Creating and implementing the PhotoLibrary Activity class

Updating the MainActivity class to call the PhotoLibrary Activity

Implementing Material Design in the PhotoLibrary app

Creating custom themes for the PhotoLibrary application

Creating custom styles for the Photo Library application UI controls

Applying the custom theme to the PhotoLibrary application

Setting up camera and photo album permissions

Interacting with the device camera and photo album

Launching the Photo Library app using the Android emulator

Summary

Building a SlidingTiles Game Using Xamarin.iOS

Creating a native iOS app using Visual Studio for Mac

Creating the SlidingTiles user interface using Storyboards

Adding a label to our ViewController in the Storyboard

Adding a View to our View Controller in the Storyboard

Adding a reset button to our View Controller in the Storyboard

Adding the Shuffle Button to our View Controller in the Storyboard

Adding the GameTile image to our SlidingTiles game

Implementing the game logic for our SlidingTiles Game

Creating and implementing the GameTile Interface class

Creating and implementing the GameTile class

Updating the ViewController class to implement our class methods

Creating and implementing the CreateGameBoard method

Creating and implementing the ResetGame_Clicked method

Randomly shuffling our Game Tiles on the Game Board

Implementing the StartNewGame Instance method

Handling touch events in the Game Board user interface

Working with and applying animations to your app

Creating and implementing animations for the SlidingTiles game

Launching the SlidingTiles game using the iOS simulator

Summary

Creating the TrackMyWalks Native App

Creating the TrackMyWalks project solution

Updating the NuGet packages within our solution

Creating and implementing our data model

Creating the WalksMainPage interface using XAML

Implementing the WalksMainPage code using C#

Creating the WalkEntryPage interface using XAML

Implementing the WalkEntryPage code using C#

Creating the WalkTrailInfoPage interface using XAML

Implementing the WalkTrailInfoPage code using C#

Integrating and implementing maps within your app

Creating the WalkDistancePage interface using XAML

Implementing the WalkDistancePage code using C#

Updating the TrackMyWalks.iOS AppDelegate

Updating the TrackMyWalks.Android MainActivity

Creating the SplashPage interface using XAML

Implementing the SplashPage code using C#

Updating the App.xaml class to target various platforms

Launching TrackMyWalks using the iOS simulator

Summary

MVVM and Data Binding

Understanding the MVVM architectural pattern

Creating and implementing the BaseViewModel

Creating the WalksMainPageViewModel using C#

Updating the WalksMainPage user interface using XAML

Updating the WalksMainPage code-behind using C#

Creating the WalkEntryPageViewModel using C#

Updating the WalkEntryPage user interface using XAML

Updating the WalkEntryPage code-behind using C#

Creating the WalkTrailInfoPageViewModel using C#

Updating the WalkTrailInfoPage user interface using XAML

Updating the WalkTrailInfoPage code-behind using C#

Creating the WalkDistancePageViewModel using C#

Updating the WalkDistancePage user interface using XAML

Updating the WalkDistancePage code-behind using C#

Launching the TrackMyWalks app using the iOS simulator

Summary

Navigating Within the Mvvm Model

Understanding the Xamarin.Forms Navigation API

Differences between the Navigation and ViewModel approaches

Creating and implementing the NavigationService interface

Creating and implementing the NavigationService class

Updating the BaseViewModel to use the navigation service

Updating the WalksMainPageViewModel using C#

Updating the WalksMainPage code-behind using C#

Updating the WalkEntryPageViewModel using C#

Updating the WalkEntryPage code-behind using C#

Updating the WalkTrailInfoPageViewModel using C#

Updating the WalkTrailInfoPage code-behind using C#

Updating the WalkDistancePageViewModel using C#

Updating the WalkDistancePage code-behind using C#

Updating the SplashPage code-behind using C#

Updating the App.xaml class to use the navigation service

Summary

Adding Location-based Features Within Your App

Creating and using platform-specific services within your app

Adding the plugin geolocator NuGet package to our solution

Creating and implementing the ILocationService interface

Creating and implementing the LocationService class

Updating the WalkEntryPageViewModel using C#

Updating the WalkDistancePageViewModel using C#

Creating the CustomMapOverlay class using C#

Updating the WalkDistancePage user interface using XAML

Updating the WalkDistancePage code-behind using C#

Creating and implementing the CustomMapRenderer (iOS)

Creating and implementing the CustomMapRenderer (Android)

Enabling background location updates and permissions

Launching the TrackMyWalks app using the iOS simulator

Summary

Customizing the User Interface

Customizing the DataTemplate in the WalksMainPage

Applying padding and margins to XAML layouts

Updating the WalksMainPage user interface using XAML

Updating the WalkEntryPage user interface using XAML

Updating the WalkTrailInfoPage user interface using XAML

Creating and implementing Styles in your App

Creating and implementing Global Styles using XAML

Updating our WalksMainPage to use the Device Style

Updating our WalkTrailInfoPage to use Explicit and Global Styles

Updating our WalksEntryPage to use our Implicit Style

Creating and using PlatformEffects in your app

Creating and Implementing the ButtonShadowEffect (iOS)

Creating and implementing the LabelShadowEffect (iOS)

Creating and implementing the ButtonShadowEffect (Android)

Creating and implementing the LabelShadowEffect (Android)

Implementing the ButtonShadowEffect RoutingEffect class

Implementing the LabelShadowEffect RoutingEffect class

Updating the WalksMainPage to use the LabelShadowEffect

Updating the WalkTrailInfoPage to use the LabelShadowEffect

Updating the WalkTrailInfoPage to use the ButtonShadowEffect

Creating and implementing ValueConverters in your app

Updating the BaseViewModel class to include additional properties

Updating the WalksMainPageViewModel to use our property

Updating the WalksMainPage to use our ImageConverter class

Updating the WalkEntryPage to use our ImageConverter class

Updating the WalkTrailInfoPage to use our ImageConverter class

Launching the TrackMyWalks app using the iOS simulator

Summary

Working with Animations in Xamarin.Forms

Creating and using Simple Animations in Xamarin.Forms

Updating the WalkEntryPage to use Simple Animations

Updating the WalkTrailInfoPage to use Simple Animations

Creating and using Easing Functions in Xamarin.Forms

Updating the WalkTrailInfoPage to use Easing Functions

Creating and implementing your own Custom Animations

Updating our WalkTrailInfoPage to use Custom Animations

Updating our WalksMainPage to use Custom Animations

Creating and implementing Entrance Animations

Updating the WalkTrailInfoPage to use Entrance Animations

Updating our WalksMainPage to use Entrance Animations

Updating our WalkEntryPage to use Entrance Animations

Launching the TrackMyWalks app using the iOS simulator

Summary

Working with the Razor Templating Engine

Understanding the Razor templating engine

Building a BookLibrary app using the Razor templating engine

Adding the SQLite-net NuGet package to our solution

Creating and implementing the BookLibrary data model

Creating and implementing the BookDatabase interface

Creating and implementing the BookDatabase class

Creating and implementing the BookLibraryListing page

Creating and implementing the BookLibraryAddEdit page

Updating the Book Library cascading style sheet (CSS)

Updating the WebViewController class using C#

Launching the BookLibrary app using the iOS simulator

Summary

Incorporating Microsoft Azure App Services

Understanding the Microsoft Azure App services platform

Setting up and configuring Microsoft Azure App services

Adding the Newtonsoft.Json NuGet package to our solution

Updating the WalkDataModel for our TrackMyWalks app

Creating and implementing the RestWebService interface

Creating and implementing the RestWebService class

Updating the BaseViewModel class to include our RestWebService

Updating the WalksMainPage code-behind using C#

Updating the WalksMainPageViewModel using C#

Updating the WalkEntryPage user interface using XAML

Updating the WalkEntryPageViewModel using C#

Launching the TrackMyWalks app using the iOS simulator

Summary

Making Our App Social Using the Twitter API

Creating and registering the TrackMyWalks app with the Twitter Developer Portal

Adding the Xamarin.Auth NuGet Package to our solution

Creating and implementing the TwitterAuthDetails class

Creating and implementing the TwitterWebService interface

Creating and implementing the TwitterWebService class

Creating and implementing the TwitterSignInPageViewModel using C#

Creating and implementing the user interface for the TwitterSignInPage

Creating and implementing the TwitterSignInPageRenderer (iOS)

Updating the WalksMainPage code-behind using C#

Updating the WalkDistancePage user unterface using XAML

Registering the TwitterSignInPage within the App.xaml class

Launching the TrackMyWalks app using the iOS simulator

Summary

Unit Testing Your Xamarin.Forms Apps

Creating the Unit Testing project within the TrackMyWalks solution

Adding the Moq NuGet package to the TrackMyWalks.UnitTests project

Adding the TrackMyWalks project to the TrackMyWalks.UnitTests project

Creating and implementing the WalksMainPageViewModelTest class

Creating and implementing the WalksEntryPageViewModelTest class

Running unit tests within the Visual Studio for Mac IDE

Creating a UITest project within the TrackMyWalks solution

Understanding the most commonly used Xamarin.UITest testing methods

Creating and implementing the CreateNewTrailDetails class for iOS

Updating the WalksMainPage code-behind using C#

Adding the Xamarin.Test Cloud.Agent NuGet package

Running UITests within the Visual Studio for Mac IDE

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Xamarin is the most powerful cross-platform mobile development framework. If you are interested in creating stunning user interfaces for the iOS and Android mobile platforms using the power of Xamarin and Xamarin.Forms, then this is your ticket.

This book will provide you with the knowledge and practical skills that are required to develop real-world Xamarin and Xamarin.Forms applications. You'll learn how to create native Android app that will interact with the device camera and photo gallery, and then create a native iOS sliding tiles game. Moving on, you will learn how to implement complex user interface layouts and create customisable control elements based on the platform, usingXAMLand C# 7 code to interact with control elements within your XAML ContentPages.

You'll be introduced to the Model-View-ViewModel (MVVM) architecture pattern, and you'll learn how to implement this within your application by creating a NavigationService class that will be used to navigate between your Views and ViewModels. You will also learn how to implement data binding to connect your XAML pages to your ViewModels.

We will then discuss how you can add location-based features by to your apps by creating a LocationService class and using the Xam.Plugin.Geolocator cross-platform library, which will be used to obtain the current device location, and you will learn how to properly perform location updates, whether the application's state is in the foreground or background, by registering the app as a background-necessary application.

We discuss more advanced topics such as how to integrate Microsoft Azure App Services and use the Twitter APIs to incorporate social networking features to obtain information about a Twitter user, as well as posting walk information to the user's Twitter feed.

Moving on, you will learn how to use third-party libraries, such as the Razor Templating Engine, which allows you to create your own HTML5 templates, within the Visual Studio for Mac environment to build a book library HTML5 solution that will use a SQLite.net library to store, update, retrieve, and delete information within a local SQLite database. You'll also implement key data binding techniques that will make your user interfaces dynamic and create personalised animations and visual effects within your user interfaces using custom renderers and the PlatformEffects API to customise and change the appearance of control elements.

At the end of this book, you'll learn how to create and run unit tests using the xUnit and UITest testing frameworks within the Visual Studio for Mac IDE. You'll learn how to write unit tests for your ViewModels that will essentially test the business logic to validate that everything is working correctly, before moving on to test the user interface portion using automated UI testing.

In this book, I have tried my best to keep the code simple and easy to understand by providing a step-by-step approach, with lots of screenshots at each step to make it easier to follow. You will soon be mastering the technology behind the Xamarin and Xamarin.Forms platforms, as well as obtaining the skills required to create your own applications for the Xamarin and Xamarin.Forms platforms.

Feel free to contact me at [email protected] with any queries, or just drop me an email to say a friendly hello.

Who this book is for

This book is intended for readers who have experience of the C# 6.0 programming language and are interested in learning how to create stunning native and cross-platform user interfaces for the iOS and Android platforms using the Xamarin and Xamarin.Forms frameworks with C# 7. It is assumed that you are familiar with object-oriented programming (OOP) techniques and have experience of developing C# applications using Visual Studio.

What this book covers

Chapter 1, Setting Up Visual Studio for Mac, focuses on how to download and install Visual Studio Community 2017 for Mac, as well as the Xamarin components for both the iOS and Android platforms. You'll explore some of the features contained within the Visual Studio for Mac IDE, and then gain an understanding of the Xamarin mobile platform. You'll learn how to create your very first Xamarin.Forms cross-platform application and create the user interface using XAML and the underlying C# code. We we also cover how to set and define conditional breakpoints within your code, as well as how to use the built-in debugging tools to debug your application.

Chapter 2, Building a Photo Library App Using Android, focuses on how to develop native Android app usingVisual Studio for Mac,Xamarin.AndroidandC#. You'll learn how to use and work with theVisual Designerto construct the user interface for ourPhotoLibraryapp using XML and implementMaterial Designwithin your apps, as well as creating your own custom themes and then apply theming to your app. You'll learn how to provide the necessary permissions to theAndroidManifest.xmlso that we can interact with the device camera and photo album, before launching the app within the Android emulator.

Chapter 3, Building a SlidingTiles Game Using Xamarin.iOS, focuses on how to develop a nativeiOSapp usingVisual Studio for Mac, Xamarin.iOS, andC#. You'll learn how to use and work withStoryboardsto construct the user interface for ourSlidingTilesgame by dragging a number ofLabels,Views, andButtonsthat will make up our game. You'll create a GameTile interfaceand classthat will be used to create each of the tiles for our game, and then implement the remaining logic within theViewControllerclass to build the game board and create each of our game tiles using the images from an array.

You'll also create an instance method that will randomly shuffle each of our game tiles within our game board using theRandomclass, and work with theUITouchclass to handle touch events to determine when a game tile has been tapped within the game boardsUIView, and work withCoreAnimationso that you can apply simple animations to your UIViews by usingView Transitionswithin an animation block, before deploying and launching the app within theiOS Simulator.

Chapter 4, Creating the TrackMyWalks Native App, will focus on how to develop a cross-platform app usingXamarin.FormsandC#, by creating each of the Content Pages that will form the user interface for our app using XAML, as well as creating aC#class that will act as the data-model for our application.

Chapter 5, MVVM and Data Binding, teaches you the concepts behind theMVVM architectural pattern, as well as how to implement theMVVMarchitectural pattern within theTrackMyWalksapplication. You'll learn how to create aBaseViewModelbase class that everyViewModelwill inherit from, as well as creating the associatedC#class files for each of ourViewModelsthat willdata-bindto each of the properties defined within ourXAMLPages.

The associated properties that we define within theViewModelfor theContentPagewill be used to represent the information that will be displayed within the user interface for our application. You'll also learn how to addContextActionsto your (XAML) content pages, and how to implement the code action events within your code, so that you can respond to those actions.

Chapter 6, Navigating Within the MVVM Model, shows you how you can leverage what you already know about theMVVM architectural design pattern to learn how to navigate between each of theViewModelswithin ourTrackMyWalksapplication. You'll learn how to create aNavigationService class and update ourBaseViewModelbase class that will include a reference to ourNavigationServiceclass that each of ourViewModelswill utilize. You will then proceed to update each of theViewModelsas well as each of theXAMLpages to allow navigation between these pages to happen.

Chapter 7, Adding Location-Based Features within Your App, shows how you can incorporateplatform-specificfeatures within your application, which is dependent on the mobile platform that is being run. You will then learn how to incorporate the Xam.Plugin.Geolocator NuGetpackage that you will use in order to create aLocationService class so that you can obtain currentGPScoordinates and handle location updates in the background on the device.

You'll update both theWalkEntryPageViewModelandWalkDistancePageViewModelto allow location-based features to happen and create aCustomMapOverlayclass that will be used to display a nativeMapcontrol, based on the platform. You'll learn how to perform location updates in the background so that you can update the native mapcontrol automatically, whenever new location coordinates are obtained.

Chapter 8,Customizing the User Interface, shows how you can use and customizeDataTemplatesto lay out your Views beautifully and neatly within your user interfaces by modifying your ContentPages. You'll learn how to create and implement various styles within each of your XAML pages, prior to getting accustomed to working with thePlatformEffectsAPI to customize the appearance, as well as applying styling to native control elements for each platform. You'll learn how to set up your margins and apply padding, as well as how to create and implement ValueConvertersandImageConverters.

Chapter 9, Working with Animations in Xamarin.Forms, shows you how to work with the Animation class that comes part of the Xamarin.Forms platform, so that you can apply really cool animations and transition effects to your user interfaces and control elements, by implementing Simple Animations, Easing Functions, and Entrance Animations using C# code.

Chapter 10, Working with the Razor Templating Engine, focuses on how you can use the Razor Templating Engine to create a Book library mobile application using the power of Razor templates. You'll learn how to create a BookItem data-model within your application, as well as how to incorporate the SQLite-net NuGet package within your application, that you will use to create a BookDatabase class, that will include various methods to communicate with a SQLite database to Create, Update, Retrieve, and Delete book items. Finally, you will learn how to create the necessary Razor Template Pages, that will use our BookItem data model to display book information.

Chapter 11, Incorporating Microsoft Azure App Services, focuses on showing you how you can use the Microsoft Azure App Services Platform to create your cloud-based databases. You will learn how to set up and configure a Microsoft Azure App Service, as well as configuring the SQL Server database and the WalkEntries table for our app. You'll incorporate the Newtonsoft.Json NuGet package, as well as modify the WalkDataModel data model. You will then create a RestWebservice class, which will include a number of class instance methods that will be used to communicate with our TrackMyWalks SQL Server database, so you can perform CRUD operations to Create, Update, Retrieve, and Delete walk entries.

Chapter 12, Making Our App Social – Using the Twitter API, focuses on showing you how to create and register our TrackMyWalks app within the Twitter Portal, byapplying for a Twitter developer account. You'll incorporate the Xamarin.Auth NuGet package within our solution and create a TwitterService class that we can use to communicate with the Twitter APIs using RESTful web service calls. You will then create a TwitterSignInPage and the associated TwitterSignInPageViewModel and TwitterSignInPageRenderer class, so users can sign into your app using their Twitter credentials.

Finally, you'll update the WalksMainPage code-behind to call our TwitterSignInPage to check to see if the user has signed in, as well as making changes to our WalkDistancePage XAML and code-behind so that we can utilize our TwitterService class to display profile information, as well as posting information about the trail to the user's Twitter feed.

Chapter 13, Unit Testing Your Xamarin.Forms Apps, focuses on showing you how to create and run each of your unit tests using the xUnit and Xamarin.UITest frameworks. You will also learn how to write unit tests for our ViewModels that will essentially test the business logic to validate that everything is working correctly, after which, we will move on to learning how to use the UITest framework to perform testing on the TrackMyWalks user interfaces, using automated testing.

To get the most out of this book

The minimum requirement for this book is an Intel-based Macintosh computer running macOS High Sierra 10.13. We will be using Visual Studio Community 2017, which is the Integrated Development Environment (IDE) used for creating Xamarin and Xamarin.Forms applications using C# 7, as well as Xcode 9.4.1 to compile our iOS app and run it within the simulator.

Almost all the projects that you create with the help of this book will work and run on the iOS simulator. However, some projects will require an actual iOS or Android device to work correctly. You can download the latest versions of Visual Studio Community 2017 and Xcode from here:

Visual Studio Community 2017 for Mac:

http://xamarin.com/download

Xcode 9.4.1:

https://itunes.apple.com/au/app/xcode/id497799835?mt=12

Downloading the example code

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:

Log in or register to our website using your e-mail address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

Click on

Code Download

.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for Windows

Zipeg / iZip / UnRarX for Mac

7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-Xamarin-UI-Development-Second-Edition. We also have other code bundles from our rich catalog of books and videos available at https://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/MasteringXamarinUIDevelopmentSecondEdition_ColorImages.pdf.

Conventions used

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Before we can proceed, we need to create our PlanetaryApp project."

A block of code is set as follows:

// // GameTile.cs // Creates each of our tile images for our Tile Slider Game. // // Created by Steven F. Daniel on 24/04/2018. // Copyright © 2018 GENIESOFT STUDIOS. All rights reserved. // using UIKit; using SlidingTiles.Interfaces; using CoreGraphics; using System; namespace SlidingTiles.Classes {

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

<?xml version="1.0" encoding="UTF-8"?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:maps="clr-namespace:Xamarin.Forms.Maps;assembly=Xamarin.Forms.Maps" x:Class="TrackMyWalks.Views.WalkDistancePage"> <ContentPage.Content> <ScrollView Padding="2,0,2,2"> <StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"> <maps:Map x:Name="customMap" IsShowingUser="true" MapType="Street" /> <Button x:Name="EndThisTrail" Text="End this Trail" TextColor="White" BackgroundColor="#008080" Clicked="EndThisTrailButton_Clicked" Margin="20" /></StackLayout></ScrollView> </ContentPage.Content> </ContentPage>

Any command-line input or output is written as follows:

Last login: Fri Aug 24 16:40:41 on console

stevens-mbp:~ stevendaniel$ curl https://trackmywalk.azurewebsites.net/tables/WalkEntries --header

"ZUMO-API-VERSION:2.0.0

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Alternatively, you can specify it for the Android platform by selecting the Android node in the SDK Locations section."

Warnings or important notes appear in a box like this.
Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please 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.packtpub.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 packtpub.com.

Setting Up Visual Studio for Mac

Since Xamarin made its appearance several years ago, developers have been delighted with being able to create native mobile applications that can target different OS platforms, as well as having the option of developing apps using either the C# or F# programming languages, enabling developers to distribute their app ideas to either the iOS, Android, or Windows platforms.

As you progress through this book, you'll learn how to apply best practices and design principles when developing cross-platform mobile applications using the Xamarin.Forms platform, to allow developers to build cross-platform user interface layouts that can be shared across the Android, iOS, and Windows mobile platforms.

Since each of these apps can be written using a single programming language, it makes sense to write a single codebase that would compile and build into separate apps for each of these different platforms.

This chapter will begin by showing you how to download and install the Visual Studio for Mac IDE, as well as the Xamarin components for both the iOS and Android platforms. You'll explore some of the features contained in the Visual Studio for Mac IDE and then gain an understanding of the Xamarin mobile platform.

You'll learn how to create your very first cross-platform Xamarin.Forms application for both the iOS and Android platforms, create the user interface using XAML, and create some C# code that will communicate with the XAML code.

To end this chapter, you'll learn how to set Breakpoints and define conditional Breakpoints in your code to pause execution, before moving on to learning how to use the built-in debugging tools to debug your application and launch it in the iOS simulator.

This chapter will cover the following points:

Downloading and installing the Visual Studio for Mac IDE and the Xamarin Platform SDKs

Exploring the Visual Studio for Mac IDE

Understanding the Xamarin mobile platform

Creating a new

Xamarin.Forms

project for both iOS and Android

Setting Breakpoints and defining conditional Breakpoints in your code

Using the Visual Studio for Mac built-in debugger

Downloading and installing Visual Studio for Mac

In this section, we will take a look at how to download and install Microsoft Visual Studio for Mac as well as the Xamarin Platform SDKs for both the iOS and Android platforms.

Installing Visual Studio for Mac and Xamarin

Before we can begin developing applications for the Xamarin platform, we will need to download Visual Studio for Mac. Simply follow these steps:

Open your browser and type in

https://www.visualstudio.com/

.

Next, hover your mouse cursor over the

Download for Mac

button and click on the

Community 2017 for Mac

menu option to proceed:

Downloading Visual Studio Community 2017 for Mac

Next, once the Visual Studio for Mac installer has been downloaded, double-click on it to display

Visual Studio for Mac – Installation.

Then, click on the

Continue

button to proceed to the next step in the wizard, which can be seen in the following screenshot:

Visual Studio for Mac - Installation

Next, ensure that the checkboxes for

Android

,

iOS

, and

macOS

, as well as

.NET Core

, have been selected under the

Platforms

group and ensure that the checkbox for

Xamarin Workbooks & Inspector

has been selected under the

Tools

group, which can be seen in the following screenshot:

Choosing Visual Studio for Mac Platform Components

Next, click on the

Install and Update

button to proceed to the next step in the wizard and begin installing the Visual Studio for Mac IDE along with the Xamarin platform SDK and tools, which can be seen in the following screenshot:

Visual Studio for Mac Downloading Components

Finally,

Visual Studio for Mac - installation

will proceed to download and begin installing the Microsoft Visual Studio for Mac IDE, as well as downloading the components for the platforms that you have selected.

Now that you have installed the Microsoft Visual Studio for Mac IDE and the Xamarin Platform SDK, as well as the tools for both the iOS and Android platforms, our next step is to explore some of the features of the Visual Studio for Mac IDE, which we will be covering in the next section.

Exploring the Microsoft Visual Studio for Mac IDE

In this section, we'll take some time and explore the Visual Studio for Mac IDE and learn how to configure its visual appearance, how to set font styles, and how to go about configuring and including additional .NET runtime versions. Lastly, you'll learn how to define the Android and iOS SDK locations.

To begin exploring the Visual Studio for Mac IDE, simply follow these steps:

From the

Visual Studio Community

menu, choose the

Preferences…

menu option, or alternatively press the

command

+

,

key combination that can be seen in the following screenshot:

Visual Studio Community for Mac IDE

Once you have clicked

on the

Preferences...

button, you will be presented with the following screen:

Visual Studio Community for Mac - Preferences

As you can see in the preceding screenshot, you have the ability to configure environment settings, such as Visual Style, Fonts, .NET Runtimes, SDK Locations, and Tasks, as well as your Google Play Accounts and Apple Developer Accounts.

Configuring and including additional .NET Runtimes

The Visual Studio for Mac IDE Preferences pane provides you with the ability to configure and include additional .NET Runtimes that you would like to compile your application against.

The default runtime that has been set will contain the word (Default) at the end, which signifies that this is the default .NET Runtime that will be used for building and running applications when none has been specified. Refer to the following screenshot:

Visual Studio Community for Mac - .NET Runtimes

From this screen, you have the ability to add new or remove existing.NET Runtimesthat you would like to test your applications with, by using theAddorRemovebuttons. In the next section, we will look at how to define your Android and iOS SDK locations.

Defining your Android and iOS SDK locations

The Visual Studio for Mac IDE Preferences pane allows you to define both your Android and iOS SDK locations that you can compile your application against:

When configuring the

SDK Locations

for the iOS platform, this will initially default to the current location where the

Xcode.app

application is located. This is typically found in the

Applications

folder and will contain the latest iOS platform SDK that has been installed for your version of Xcode:

Visual Studio Community for Mac - Apple SDK Location

In order to specify a different location for where

Xcode.app

is located, click on the

Browse…

button, which can be seen in the preceding screenshot. Alternatively, you can specify it for the Android platform by selecting the

Android

node in the

SDK Locations

section.

In this section, you can specify the

Android SDK Location

and

Android NDK Location

, as well as the

Java SDK (JDK) Location

:

Visual Studio Community for Mac - Android SDK Locations

You can also install additional SDK

Platforms

and

Tools

for the Android platform that you would like to build your application against, or remove those platforms and system images that you no longer wish to target; this can be seen in the following screenshot:

Visual Studio Community for Mac - Choosing Android Platforms

Now that you have explored some of the features contained in the Visual Studio for Mac IDE, our next step is to take a look at, and understand a bit more about, the Xamarin mobile platform, which we will be covering in the next section.

Understanding the Xamarin mobile platform

The Xamarin platform is essentially a framework that enables developers to develop cross-platform mobile applications, using either the C# or F# programming languages, as well as a runtime that runs on the Android, iOS, and Windows platforms, giving you an app that looks, feels, and behaves completely native.

In this section, we will gain an understanding of what the Xamarin mobile platform isand the benefits of using Xamarin to develop your iOS, Android, and Windows apps.

Benefits of developing apps using the Xamarin mobile platform

When you use the Xamarin platform to build your mobile apps, you'll have access to all of the features available in the native SDK and you can even use your existing APIs, so that these can be shared across each of the different mobile platforms for iOS, Android, and Windows.

That said, anything you can do in Objective-C, Swift, or Java can be done in C# or F#, with Xamarin and Visual Studio for Mac.

Developing native apps using the Xamarin approach

When considering developing native iOS, Android, or Windows apps, most developers would either choose to use Objective-C, Swift, or Java. However, there are more ways to build performant and user-friendly mobile apps and Xamarin is one of them. Let's take a look at the benefits of developing native apps using Xamarin.

The Xamarin platform uses a single programming language, C# or F#, which can be used to create apps for the iOS, Android, and Windows platforms, as well as providing you with the flexibility of writing C# code so that you can design your user interfaces specifically for each platform.

The C# programming language is a mature language that is strongly typed to prevent code from producing unexpected behavior. Since C# is one of the .NET framework languages, it can be used with a number of useful .NET features, such as Lambdas, LINQ, and asynchronous programming. The C# source code that you write is then compiled into a native app for each platform.

Technically speaking, Xamarin uses C# and native libraries wrapped in the .NET layer for cross-platform app development. Such applications are often compared to native ones for both iOS and Android mobile development platforms in terms of performance and user experience:

Developing native apps using the Xamarin approach

As you can see from the preceding screenshot, this shows each platform for the Xamarin.iOS, Xamarin.Android, and Windows platforms, each containing their own platform-specific UI code layer and a common Shared C# Backend containing the business logic, which can be shared across all platforms.

Developing apps using the Xamarin.Forms approach

Developing iOS, Android, or Windows apps using the Xamarin.Forms approach is very different from developing apps using the native approach. Let's take a look at the benefits of developing apps using the Xamarin.Forms approach.

The Xamarin.Forms approach allows you to build your user interfaces, which can then be shared across each of the different mobile development platforms using 100% percent shared C# or F# code.

Using the Xamarin.Forms approach means that your applications will have access to over 40 user interface controls and layouts, which are then mapped to each of the native controls specific to the platform at runtime:

Developing apps using the Xamarin.Forms approach

As you can see from the preceding screenshot, each platform for the Xamarin.iOS, Xamarin.Android, and Windows platforms shares common user interface code, which will be rendered differently on each platform, as well as a common Shared C# Backend containing the business logic that can be shared across all platforms.

Now that you have a good understanding of developing Xamarin apps using the native approach versus developing apps using the Xamarin.Forms approach, we can start to build our first app, which we will be covering in the next section.

Creating the user interface for our Planetary app using XAML

In this section, we will begin defining the user interface for our MainPage using XAML. This page will be used to display a list of planet names, as well as information relating to the distance the planet is from the sun. There are a number of ways you can go about presenting this information, but for the purpose of this app, we will be using a ListView to present this information.

Let's start by creating the user interface for our MainPage by performing the following steps:

Open the

MainPage.xaml

file, which is located as part of the

PlanetaryApp

group, ensure that it is displayed in the code editor, and enter the following code snippet:

<?xml version="1.0" encoding="utf-8"?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemsas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:PlanetaryApp" x:Class="PlanetaryApp.MainPage"> <ListView x:Name="planetsListView" RowHeight="80" HasUnevenRows="True"> <ListView.ItemTemplate> <DataTemplate> <TextCell Text="{Binding Name}" TextColor="Black" Detail="{Binding Distance}" DetailColor="Red" /> </DataTemplate> </ListView.ItemTemplate> </ListView> </ContentPage>

Let's take a look at what we covered in the preceding code snippet:

We started by defining a

ListView

and specified the

RowHeight

to be used for each of the rows that will be allocated and displayed, as well as providing our

ListView

control with a name,

planetsListView

.

Next, we defined the

ItemTemplate

property of our

ListView

control, which will be used to display the data items, and then defined a

DataTemplate

that will be used to handle displaying data from a collection of objects in our

ListView

.

Finally, we used the

TextCell

control and then set the

Text

property to bind to our

name

property, and we set the

Detail

property to bind our

distance

property, then set the

Textcolor

and

DetailColor

properties of our

TextCell

control.

Launching the Planetary app using the iOS simulator

In this section, we will take a look at how to compile and run our PlanetaryApp. You have the option of choosing to run your application using an actual device, or choosing from a list of simulators available for an iOS device.

Let's begin by performing the following steps:

Ensure that you have chosen the

PlanetaryApp.iOS

project from the drop-down menu.

Next, choose your preferred device from the list of available iOS simulators.

Then, select the

Run|Start Without Debugging

menu option, as shown in the following screenshot:

Launching the PlanetaryApp within the iOS Simulator

Alternatively, you can also build and run the

PlanetaryApp

by pressing

command + Enter

.

When the compilation is complete, the iOS simulator will appear automatically and the PlanetaryApp application will be displayed, as shown in the following screenshot:

PlanetaryApp running within the iOS Simulator

As you can see from the preceding screenshot, this currently displays a list of static planetary entries that are displayed in our ListView control contained in our XAML. Congratulations, you have successfully built your first Xamarin.Forms application, as well as the user interface using XAML for the PlanetaryAppContentPage used by our app!

Using and setting Breakpoints in your code

In this section, we will learn how we can use the Visual Studio for Mac IDE to set Breakpoints in our PlanetaryApp solution. We'll learn how to create conditional Breakpoints that can be used to perform a specific action.

Next, we will learn how we can utilize the Breakpoints Pad to view all Breakpoints that have been set in a solution. Finally, we will learn how we can use the Visual Studio for Mac debugger to step through our code and display the contents of variables in the Immediate window.

Setting a Breakpoint in your Planetary App solution

Breakpoints are a good way for you to pause execution at a particular point in the code contained in your project solution, so that you can debug your code or check the contents of a variable.

To set a breakpoint, simply follow the steps outlined here:

Locate

MainPage.xaml.cs

in the .NET Standard (Shared Library)and ensure that the

MainPage.xaml.cs

file is displayed in the code editor window

To set a Breakpoint, simply click to the left of the line number at the place in your code that you need to troubleshoot, as you can see in the following screenshot:

Setting a Breakpoint within the PlanetaryApp solution

As you can see from the preceding screenshot, whenever you set a breakpoint in your code, you will notice that the line will turn red, but this can be overridden in the Visual Studio for Mac Preferences pane.

Using the Breakpoints Pad to view Breakpoints that have been set

Whenever you set Breakpoints in your code, rather than navigating through each of your individual code files in your project solution, you can quickly see all of these in one place by viewing them using the Breakpoints Pad.

To view all of the Breakpoints that have been set in your project, follow the steps outlined here:

Ensure that the

MainPage.xaml.cs

file is displayed in the code editor window and choose the

View|Debug Pads|Breakpoints

menu option:

Enable viewing of Breakpoints within your solution

You will then see all

Breakpoints

that have been set in your

PlanetaryApp

project solution, including the ones that have been set in your subprojects, as can be seen in the following screenshot:

Displays all Breakpoints within your solution

As you can see in the preceding screenshot, you will see all Breakpoints that have been set in your .NET Standard (Shared Library) project, and even the ones that have been set in your PlanetaryApp.iOS, PlanetaryApp.Android and PlanetaryApp.UWP subproject solutions.

Creating conditional Breakpoints to perform an action