Mastering Cross-Platform Development with Xamarin

Total Page:16

File Type:pdf, Size:1020Kb

Mastering Cross-Platform Development with Xamarin [ 1 ] Mastering Cross-Platform Development with Xamarin Master the skills required to steer cross-platform applications from drawing board to app store(s) using Xamarin Can Bilgin BIRMINGHAM - MUMBAI Mastering Cross-Platform Development with Xamarin Copyright © 2016 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: March 2016 Production reference: 1280316 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78528-568-4 www.packtpub.com Credits Author Project Coordinator Can Bilgin Nidhi Joshi Reviewers Proofreader Engin Polat Safis Editing Lance McCarthy Toni Petrina Indexer Hemangini Bari Commissioning Editor Veena Pagare Graphics Kirk D'Penha Acquisition Editors Vinay Argekar Production Coordinator Shantanu N. Zagade Meeta Rajani Cover Work Content Development Editor Shantanu N. Zagade Siddhesh Salvi Technical Editors Pramod Kumavat Siddhi Rane Copy Editor Roshni Banerjee About the Authors Can Bilgin currently works for Authority Partners Inc. as a program architect. He has been working in the software industry, primarily with Microsoft technologies, for over a decade and has been recognized as a Microsoft Most Valuable Professional (MVP) for his technical contributions. In this period, he played key roles in projects for high profile clients using technologies such as BizTalk, SharePoint, Dynamics CRM, Xamarin, WCF, and other web technologies. His main passion lies in mobile and IoT development using the modern toolset available for developers. He tries to share his experience on his blog (http://canbilgin.wordpress.com), social media (@can_bilgin), and through speaking engagements at both local and international conferences and community events in the Balkans region. This book is dedicated to three girls who shaped my life and still are doing so: my best friend and beloved wife, Sanja Grebovic Bilgin, our little daughter, Dilara Bilgin, and my loving mother, Turkan Bilgin. About the Reviewers Engin Polat has been involved in many large and medium-scale projects on .NET technologies as a developer, architect, and consultant, and has won many awards since 1999. Since 2008, he has been giving training to many large enterprises in Turkey about Windows development, web development, distributed application development, software architecture, mobile development, cloud development, and so on. Apart from this, he organizes seminars and events in many universities in Turkey about .NET technologies, Windows platform development, cloud development, web development, game development, and so on. He shares his experiences on his personal blog (http://www.enginpolat.com). He has MCP, MCAD, MCSD, MCDBA, and MCT certifications. In 2012, he was recognized as a Windows Platform Development MVP (Most Valuable Professional) by Microsoft. Between 2013 and 2015, he was recognized as a Nokia Developer Champion; very few people in the world are given this award. In 2015, he was recognized as the Regional Director by Microsoft. I'd like to thank my dear wife, Yeliz, and my beautiful daughter, Melis Ada, for all the support they gave me while I was working on this book project. Lance McCarthy, Microsoft MVP, is a community leader with an acute expertise for all things, such as .NET and C#, especially on the XAML stack, including WPF, Silverlight, Windows Phone, and Windows Store apps. He is very helpful online and guides and answers questions from Microsoft developers on Twitter as @lancewmccarthy. In his free time, he writes his blog at http://WinPlatform. wordpress.com, which focuses on Windows Universal apps. He organizes and hosts events in the Boston area, such as user group nights, mini-code camps, and full hackathons. During the day, he is a senior technical support engineer at Telerik where he supports developers with their Classic Windows, Universal Windows Platform, Web and Mobile application development (Xamarin, Android native, and iOS native). He is also a technical consultant for the Windows Developer social media team where he helps respond to development questions via the official@WindowsDev Twitter account. Previously, he worked for Nokia/Microsoft as a developer ambassador where he sought out and engaged developers through outreach programs and provided them with technical support and resources to make them successful on the Windows Phone and Windows 8 platforms. He was also an assistant professor at Harvard University for a short time where he helped students build, market, and publish successful Windows Phone apps. At Boston University, he was a guest professor for the Cloud computing course and would teach one class a semester. He has also appeared on podcasts, such as the Windows Developer Show, has been a technical editor for publications and books, has won several app building contests and hackathons (including the first place in the Microsoft Build 2013 hackathon), and is a published developer with over a million downloads in the Windows Store. I'd like to thank my wife Amy for her undying patience while I did "more work after I got home from work" and to Can Bilgin for the opportunity to review this. www.PacktPub.com eBooks, discount offers, and more 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. TM https://www2.packtpub.com/books/subscription/packtlib Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books. Why subscribe? • Fully searchable across every book published by Packt • Copy and paste, print, and bookmark content • On demand and accessible via a web browser Table of Contents Preface ix Chapter 1: Developing with Xamarin 1 Cross-platform projects with Xamarin 1 Xamarin as a platform 2 Xamarin as a product 3 Target platforms 3 Xamarin on Android 4 Xamarin on iOS 5 Windows Runtime apps 6 Setting up the development environment 6 Choosing the right development OS 7 Xamarin Studio setup and configuration 8 Visual Studio setup and configuration 10 Emulator options 13 Emulators for Android 13 iOS emulation 15 A typical Xamarin solution structure 15 Portable class libraries 16 Shared projects 18 Xamarin.Forms 20 NuGet packages 21 Components 23 Quality in cross-development 23 Reusability 23 Abstraction 23 Loose-coupling 24 Nativity 24 Summary 24 [ i ] Table of Contents Chapter 2: Memory Management 27 Application Component lifecycle 27 Activity lifecycle (Android) 27 Active/Running 28 Paused 28 Backgrounded 28 Stopped 29 Restarted 29 Application lifecycle (iOS) 29 Garbage collection 31 GC on Xamarin projects 32 SGen garbage collector 32 Boehm garbage collector (iOS only) 32 Platform-specific concepts 33 Object reference types 33 Automatic Reference Counting (ARC) 33 Troubleshooting and diagnosis 34 Xamarin Profiler 34 Allocations instrument 35 Time Profiler 35 Device Monitor (Android only) 35 Instruments (iOS only) 37 Monotouch Profiler (iOS only) 38 Patterns and best practices 39 Disposable objects 39 The lapsed listener problem 40 Weak references 45 Cross-domain objects 47 Cyclic references (cycles) 49 Summary 52 Chapter 3: Asynchronous Programming 53 Multithreading on Xamarin 53 Single thread model 54 Task-based Asynchronous Pattern 55 Concurrency model on iOS 56 Asynchronous methods 56 Continuation 57 Cancellation 57 Progress 59 Task batches 60 Parallel execution 62 [ ii ] Table of Contents Patterns and best practices 64 Async pattern conversions 65 Multi-threading with tasks 67 Exception handling 74 Initialization pattern 77 Semaphores 80 Background tasks 82 Background tasks on iOS 83 Services (Android only) 84 Summary 86 Chapter 4: Local Data Management 87 Data in mobile applications 87 State 88 App data 88 Local files 89 External data 89 Application data 89 Installation directory 90 Android 90 iOS 92 Local storage 93 Android 93 iOS 96 Temporary storage 98 Local filesystem 99 SQLite 101 Patterns and best practices 104 Application preferences 104 File picker 106 Backup/Roaming 110 Android and Backup API 110 iOS and ubiquitous storage 114 Summary 120 Chapter 5: Networking 121 Connected apps 121 Web services 122 Transport 123 Messaging 123 SOAP/XML services 124 RESTful services 129 [ iii ] Table of Contents OData and OAuth 133 OData 133 OAuth
Recommended publications
  • Interview Questions ASP.NET
    Interview Questions ASP.NET 1. Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process. inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension),the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe. 2. What’s the difference between Response.Write() andResponse.Output.Write()? The latter one allows you to write formattedoutput. 3. What methods are fired during the page load? Init() - when the pageis instantiated, Load() - when the page is loaded into server memory,PreRender() - the brief moment before the page is displayed to the user asHTML, Unload() - when page finishes loading. 4. Where does the Web page belong in the .NET Framework class hierarchy? System.Web.UI.Page 5. Where do you store the information about the user’s locale? System.Web.UI.Page.Culture 6. What’s the difference between Codebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"? CodeBehind is relevant to Visual Studio.NET only. 7. What’s a bubbled event? When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents. 8. Suppose you want a certain ASP.NET function executed on MouseOver overa certain button. Where do you add an event handler? It’s the Attributesproperty, the Add function inside that property.
    [Show full text]
  • A Hands-On Guide with Real-World Examples — Vaskaran Sarcar Foreword by Priya Shimanthoor
    Design Patterns in C# A Hands-on Guide with Real-World Examples — Vaskaran Sarcar Foreword by Priya Shimanthoor www.EBooksWorld.ir Design Patterns in C# A Hands-on Guide with Real-World Examples Vaskaran Sarcar Foreword by Priya Shimanthoor www.EBooksWorld.ir Design Patterns in C# Vaskaran Sarcar Whitefield, Bangalore, Karnataka, India ISBN-13 (pbk): 978-1-4842-3639-0 ISBN-13 (electronic): 978-1-4842-3640-6 https://doi.org/10.1007/978-1-4842-3640-6 Library of Congress Control Number: 2018946636 Copyright © 2018 by Vaskaran Sarcar This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the author nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made.
    [Show full text]
  • Dot Net Interview Questions
    Dear Friends, Hi I am satish marwat, this documents contains all the important questions that usually asked during the .NET interview, I had downloaded all the material from the Internet from various websites and collected to form a single film, u will find few repeated questions also, all the material are from the various websites, so I had just bind it into a single file. So for any mistake I am not responsible, this is just for the view purpose. My view was only to collect a material to a single file. Please, if u find any mistake in this file, please contact me to my email address [email protected], so that I can able to correct it. ALL THE BEST Thanks Satish J Satish Marwat Dot Net Web Resources [email protected] 1 Page .NET FRAME WORK Introduction 1.1 What is .NET? .NET is a general-purpose software development platform, similar to Java. At its core is a virtual machine that turns intermediate language (IL) into machine code. High-level language compilers for C#, VB.NET and C++ are provided to turn source code into IL. C# is a new programming language, very similar to Java. An extensive class library is included, featuring all the functionality one might expect from a contempory development platform - windows GUI development (Windows Form s), database access (ADO.NET), web development (ASP.NET), web services, XML etc. 1.2 When was .NET announced? Bill Gates delivered a keynote at Forum 2000, held June 22, 2000, outlining the .NET 'vision'. The July 2000 PDC had a number of sessions on .NET technology, and delegates were given CDs containing a pre-release version of the .NET framework/SDK and Visual Studio.NET.
    [Show full text]
  • لینک دانلود کتاب Node.Js High Performance.Pdf
    Node.js High Performance Take your application to the next level of high performance using the extensive capabilities of Node.js Diogo Resende BIRMINGHAM - MUMBAI Node.js High Performance Copyright © 2015 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: August 2015 Production reference: 1120815 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78528-614-8 www.packtpub.com Credits Author Copy Editor Diogo Resende Vikrant Phadkay Reviewers Project Coordinator Abhishek Dey Judie Jose Glenn Geenen Stefan Lapers Proofreader Safis Editing Aravind V.S Indexer Commissioning Editor Rekha Nair Ashwin Nair Production Coordinator Acquisition Editor Manu Joseph Sonali Vernekar Cover Work Content Development Editor Manu Joseph Rashmi Suvarna Technical Editor Utkarsha S.
    [Show full text]
  • Advanced Design and Implementation of Virtual Machines
    Advanced Design and Implementation of Virtual Machines Advanced Design and Implementation of Virtual Machines Xiao-Feng Li CRC Press Taylor & Francis Group 6000 Broken Sound Parkway NW, Suite 300 Boca Raton, FL 33487-2742 © 2017 by Taylor & Francis Group, LLC CRC Press is an imprint of Taylor & Francis Group, an Informa business No claim to original U.S. Government works Printed on acid-free paper Version Date: 20160714 International Standard Book Number-13: 978-1-4665-8260-6 (Hardback) This book contains information obtained from authentic and highly regarded sources. Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot assume responsibility for the valid- ity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright holders of all material reproduced in this publication and apologize to copyright holders if permission to publish in this form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may rectify in any future reprint. Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or uti- lized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopy- ing, microfilming, and recording, or in any information storage or retrieval system, without written permission from the publishers. For permission to photocopy or use material electronically from this work, please access www.copyright.com (http:// www.copyright.com/) or contact the Copyright Clearance Center, Inc.
    [Show full text]
  • Automating Resource Management in Java
    The CLOSER: Automating Resource Management in Java Isil Dillig Thomas Dillig Eran Yahav Satish Chandra Computer Science Department IBM T.J. Watson Research Center, USA Stanford University feyahav, [email protected] fisil, [email protected] Abstract 1 class BufferPrinter { While automatic garbage collection has relieved programmers from 2 private Buffer buf; manual memory management in Java-like languages, managing re- 3 private BufferListener listener; sources remains a considerable burden and a source of performance 4 private Socket socket; problems. In this paper, we present a novel technique for automatic 5 resource management based on static approximation of resource 6 public BufferPrinter(Buffer buf) { 7 this.buf = buf; lifetimes. Our source-to-source transformation tool, CLOSER, au- 8 this.listener = new BufferListener(this); tomatically transforms program code to guarantee that resources 9 buf.addListener(listener); are properly disposed and handles arbitrary resource usage pat- 10 } terns. CLOSER generates code for directly disposing any resource 11 whose lifetime can be statically determined; when this is not pos- 12 public void setSocket(Socket s) { sible, CLOSER inserts conditional disposal code based on interest- 13 if (socket!=null) socket.close(); reference counts that identify when the resource can be safely dis- 14 this.socket = s; posed. The programmer is only required to identify which types 15 if (!socket.isConnected()) should be treated as resources, and what method to invoke to dis- 16 socket.connect(...); 17 } pose each such resource. We have successfully applied CLOSER on a moderate-sized graphics application that requires complex rea- 18 19 // Invoked by listener when buf is full.
    [Show full text]
  • Software Design Pattern 1 Software Design Pattern
    Software design pattern 1 Software design pattern In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code. Rather, it is a description or template for how to solve a problem that can be used in many different situations. Design patterns are formalized best practices that the programmer can use to solve common problems when designing an application or system. Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved. Patterns that imply mutable state may be unsuited for functional programming languages, some patterns can be rendered unnecessary in languages that have built-in support for solving the problem they are trying to solve, and object-oriented patterns are not necessarily suitable for non-object-oriented languages. Design patterns may be viewed as a structured approach to computer programming intermediate between the levels of a programming paradigm and a concrete algorithm. History Patterns originated as an architectural concept by Christopher Alexander as early as 1966 (c.f. "The Pattern of Streets," JOURNAL OF THE AIP, September, 1966, Vol. 32, No. 3, pp. 273-278). In 1987, Kent Beck and Ward Cunningham began experimenting with the idea of applying patterns to programming – specifically pattern languages – and presented their results at the OOPSLA conference that year. In the following years, Beck, Cunningham and others followed up on this work.
    [Show full text]
  • Node.Js High Performance
    www.allitebooks.com Node.js High Performance Take your application to the next level of high performance using the extensive capabilities of Node.js Diogo Resende BIRMINGHAM - MUMBAI www.allitebooks.com Node.js High Performance Copyright © 2015 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: August 2015 Production reference: 1120815 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78528-614-8 www.packtpub.com www.allitebooks.com Credits Author Copy Editor Diogo Resende Vikrant Phadkay Reviewers Project Coordinator Abhishek Dey Judie Jose Glenn Geenen Stefan Lapers Proofreader Safis Editing Aravind V.S Indexer Commissioning Editor Rekha Nair Ashwin Nair Production Coordinator Acquisition Editor Manu Joseph Sonali Vernekar Cover Work Content Development Editor Manu Joseph Rashmi Suvarna Technical Editor Utkarsha S.
    [Show full text]
  • Client-Side Web Application Memory Management
    RIKU NIEMINEN CLIENT-SIDE WEB APPLICATION MEMORY MANAGEMENT Master of Science thesis Examiner: Prof. Tommi Mikkonen Examiner and topic approved by the Faculty Council of the Faculty of Computing and Electrical Engineering on 9th December 2015 II ABSTRACT RIKU NIEMINEN: Client-Side Web Application Memory Management Tampere University of Technology Master of Science thesis, 55 pages December 2015 Master’s Degree Programme in Computer Technology Major: Software Engineering Examiner: Prof. Tommi Mikkonen Keywords: Client-Side Web Application, Memory Management, Single Page Application, SPA, JavaScript, Diagnostics Today web browsers are used more and more as application runtime environment in addition to their use and origins as document viewers. At the same time web application’s architecture is undergoing changes. For instance functionality is be- ing moved from the backend into the client, following the so-called Thick client architecture. Currently it is quite easy to create client side web applications that do not manage their memory allocations. There has not been large focus in client side application’s memory usage for various reasons. However, currently client side web applications are widely being built and some of these applications are expected to be run for ex- tended periods. Longevity of the application requires application’s succesful memory management. From the performance point of view it is also beneficial that the appli- cation manages its memory succesfully. The client-side behaviour of the application is developed with JavaScript, which has automatically managed memory allocations. However, like all abstractions, automatically managed memory is a leaky abstraction to an undecidable problem. In this thesis we aim at finding out what it takes to create client side applications that succesfully manage their memory allocations.
    [Show full text]