38,39 €
This third edition of .NET MAUI Projects explores the features of .NET MAUI, a lightweight multi-platform development toolkit for building apps with a rich user interface. Updated to cover the latest features of .NET MAUI, including CollectionView and Shell, this book delves into concepts such as machine learning and cloud services.
Starting with an overview of .NET Core and how it works, this book shares tips for choosing the right development environment for planning multi-platform apps. You'll then build your first .NET MAUI app and advance to learning how to use Shell to implement app architecture. Progressing in complexity, the projects guide you through creating apps, ranging from a location tracker and weather map to machine learning and multiplayer games. Further, the book will take you through modern mobile development frameworks such as SQLite, .NET Core, and ML.NET, empowering you to customize your apps for Windows, macOS, Android, and iOS platforms for native-like performance. Engaging examples are woven throughout the book so you can grasp essential concepts by writing code rather than extensive theory.
By the end of this book, you'll be ready to develop your own native apps using .NET MAUI and associated technologies such as .NET Core, Visual Studio 2022, and C#.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 638
Veröffentlichungsjahr: 2024
.NET MAUI Projects
Build multi-platform desktop and mobile apps from scratch using C# and Visual Studio 2022
Michael Cummings Daniel Hindrikes Johan Karlsson
Copyright © 2024 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.
Group Product Manager: Rohit Rajkumar
Publishing Product Manager: Kaustubh Manglurkar
Book Project Manager: Aishwarya Mohan
Senior Editor: Rakhi Patel
Technical Editor: K Bimala Singha
Copy Editor: Safis Editing
Proofreader: Safis Editing
Indexer: Pratik Shirodkar
Production Designer: Joshua Misquitta
DevRel Marketing Coordinators: Namita Velgekar and Nivedita Pandey
First published: December 2018
Second edition: June 2020
Third edition: February 2024
Production reference: 2080224
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK
ISBN 978-1-83763-491-0
www.packtpub.com
I dedicate this book to my rock, my confidant, and my partner for life, Rita. Your unwavering support and love have been my guiding light through thick and thin. This book is dedicated to you with all my heart.
– Michael Cummings
I dedicate this book to all the people I met during my years as a Xamarin developer who 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 it with.
– Johan Karlsson
I’d never actually made a mobile app before, but that didn’t stop me from standing in line, a little starstruck, to get my hands on a preview edition of a Xamarin.Forms book –signed by the author! Microsoft Build 2015 was an amazing conference, but nothing topped the Xamarin afterparty, and getting to meet one of my favorite technical writers was unbelievable. I walked away from the party with an armful of little stuffed monkeys and my personally inscribed book.
I had no idea at the time that I’d be frantically reading that book a few months later to prepare for my interview with the Xamarin.Forms team. I had no idea at the time that I’d spend the next eight and a half years with them – first, building the framework, taking it from 1.5 to 5.0, and expanding from mobile to desktop, too; then, leading and growing the team; and finally, helping to architect the next evolution of cross-platform development with .NET MAUI, .NET for iOS, and .NET for Android.
The mobile and desktop development world changes quickly, and any framework must be ready to bend, shift, and grow along with its underlying platforms. .NET MAUI is meant to be as flexible as the palm trees that sway with island winds. With that goal comes a formidable challenge – how do we build a framework that will stay constant enough for developers to rely on, yet continue to be relevant with the modern landscape?
We use the word “evolution” a lot when we talk about .NET MAUI because that’s the most apt term for what it is. Each new version looks familiar – the fundamentals are all there – but if you dig a little deeper, you’ll see the new capabilities, boosted performance, and updated expectations that make each version unique. If we did our jobs right, each version will deliver more delight than the last.
I’ve had the pleasure of working with Michael for several years, and when I learned that he would be writing this book, I wasn’t surprised at all. Michael is a natural teacher, and he understands that .NET MAUI (and, of course, .NET for Android and .NET for iOS) is a sensible choice for the simplest of apps as well as more complex and intricate apps. This book walks you through the journey of your basic first app and onward to the real-world scenarios that you’re likely to incorporate in your next project.
And even though you can be sure that .NET MAUI, .NET for Android, and .NET for iOS will continue to evolve and that some of the code you find in this book will look a bit different a few years from now, you can also be sure that the concepts and the fundamentals you learn in this book will be valuable for a long time to come. Have some fun with this book, and keep coding!
Samantha Houts
Principal Group Engineering Manager – .NET MAUI/.NET for Android/.NET for iOS
Michael Cummings is a senior development engineer at Microsoft. He currently works on the Visual Studio tooling for building WPF, Xamarin.Forms, and .NET MAUI apps. He has experience as a developer and architect with a focus on app development, design, deployment, and the business process as it relates to technology. Michael has dabbled in graphics and game programming since the days of the TI99-4/A. He contributes to open source projects, including AXIOM, a .NET 3D rendering engine, and Planeshift, a 3D Massive Multiplayer Online Role-Playing Game (MMORPG). Michael lives in Lexington, MA, with his wife and their dog. When not working with technology, he enjoys watching movies, trying out new recipes, and the occasional game of full-contact racquetball.
I want to give a special thank you to my faithful companion, Smidgeon, who was always on point to be the needed distraction. You are missed.
Thank you to all the members of the teams I work with at Microsoft, for your patience and knowledge.
Additionally, thank you to the incredible team at Packt and the reviewers for this edition of the book, Pietro Libro and Robby Gunawan Sutanto; your comments and suggestions were invaluable.
Daniel Hindrikes is a developer and architect with a passion for developing mobile apps powered by the cloud. Daniel fell in love with Xamarin in the early days of Xamarin when he realized that he could use C# even for iOS and Android apps and that he could share code with the Windows apps he was also building. But Daniel started to build mobile apps long before that, working on Android apps with Java and even Java ME apps (a long, long time ago).
Daniel enjoys sharing his knowledge and can be found speaking at conferences, blogging, or recording the podcast The Code Behind. Daniel works at tretton37 in Sweden and has experience working with both local and global customers.
I want to say a special thanks to my family, my wife, Anna-Karin, and our twins, Ella and Willner, all of whom have supported me during the writing process.
I also would like to say thanks to the fantastic team at Packt and our technical reviewers, who helped us write this book and make us look better than we really are.
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 has in the past worked a lot with ASP.NET MVC, Visual Basic .NET (not proud), and C# in general. Also, he’s created a whole bunch of databases in SQL Server over the years.
Johan works at tretton37 in Sweden and has about 20 years of experience in the trade of assembling ones and zeros.
I want to send a special thanks to my partner in life, Elin. Thanks for being there during this special period of time including (but not limited to) moving together, living through a pandemic, writing a book, and selling a house. And, of course, to my children, Ville and Lisa, for being an inspiration in life!
Also, thanks to Packt and our tech reviewers, who nitpicked our applications apart, making us spend late nights correcting our code.
Pietro Libro is a seasoned technology enthusiast with over two decades of experience in software development. He has honed his practical problem-solving skills through engagements in public administration, finance, and the automation industries. Simultaneously pursuing university education and professional work, Pietro attained a second-level degree, enriching his practical knowledge. Demonstrating a commitment to continuous learning, he holds numerous certifications and actively imparts his expertise as a technical speaker. His areas of expertise span a diverse range of technologies, with a particular emphasis on software and cloud architecture. Born in Italy, Pietro moved to Switzerland in 2013 and currently works as a Cloud Solution Architect. He resides in Zürich with his wife, Eleonora, and daughter, Giulia.
Robby Gunawan is a proficient full stack C# developer specializing in Windows Forms applications. He has been actively involved in writing commercial software since 2007, contributing his skills to several companies in Indonesia. His journey began with Basic during high school, followed by VB6 in university, and subsequently transitioning to VB.NET. In his professional career, he has adeptly embraced C#. Leveraging his C# background, Robby successfully published his first mobile application for Windows Phone 7 and developed his initial Android application using Xamarin Forms. Beyond software development, he possesses additional expertise as a Windows Server Administrator, Postfix Administrator, and WordPress Designer and Administrator.
.NET MAUI Projects is a hands-on book in which you get to create nine applications from the ground up. You will gain the fundamental skills you need to set up your environment, and we will explain what .NET Mobile is before we transition into .NET MAUI 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, upgrading from Xamarin.Forms, animations, consuming REST interfaces, real-time communication using SignalR, and location tracking using a device’s GPS. There is also room for machine learning, a touch of .NET Blazor, and the must-have to-do list.
Happy coding!
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 .NET Mobile, and specifically .NET MAUI, to create applications using .NET and C#.
No knowledge of .NET Mobile is required in advance, but it would be a great help if you’ve worked with traditional .NET Mobile and want to take the step toward .NET MAUI.
Chapter 1, Introduction to .NET MAUI, explains the basic concepts of .NET Mobile and .NET MAUI. 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 will help you get started and set up your development environment.
Chapter 2, Building Our First .NET MAUI App, guides you through the concepts of Model-View-ViewModel (MVVM) and explains how to use the Inversion of Control pattern to simplify the creation of views and view models. We will create a to-do app that supports navigation, filtering, and the addition of to-do items to a list, and will also render a user interface that takes advantage of the powerful data-binding mechanisms in .NET MAUI.
Chapter 3, Converting a Xamarin.Forms App to .NET MAUI, walks through the steps to convert an existing Xamarin.Forms app running on Mono to a .NET MAUI app running on .NET 7. We will discuss two different methods for converting your Xamarin.Forms application to .NET MAUI. The first method will use a new .NET MAUI project and move our old Xamarin.Forms code into the new project, and the second method will use the .NET Upgrade Assistant tool to do some of the upgrades for us.
Chapter 4, Building a News App Using .NET MAUI Shell, explores the default navigation template in .NET MAUI, Shell, a standard way to define the structure of .NET MAUI apps. In this chapter, you will learn all you need to know to use Shell in a .NET MAUI app.
Chapter 5, 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 self-contained components.
Chapter 6, Building a Photo Gallery App Using CollectionView and CarouselView, details the .NET MAUI CollectionView and CarouselView controls. In this chapter, we will use them to build a photo gallery app to learn how to master the controls.
Chapter 7, Building a Location Tracking App Using GPS and Maps, taps into the use of 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 8, 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 9, Setting Up a Backend for a Game Using Azure Services, is the first of two parts in which we’ll set up a game 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 10, Building a Real-Time Game, follows on from the previous chapter and covers the frontend of the app – in this case, a .NET MAUI app that connects to the backend and 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 11, Building a Calculator Using .NET MAUI Blazor, explores a .NET Blazor app embedded within a .NET MAUI app. We will write part of the calculator app using Blazor and host that in .NET MAUI using BlazorWebView. We will also communicate between Blazor and .NET MAUI.
Chapter 12, 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.
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 would 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 will be.
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. However, you should 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 MVVM and Inversion of Control.
But, most of all, it’s a book you can use to kick-start your .NET MAUI development learning curve by focusing on what chapters interest you the most.
Software/Hardware covered in the book
OS requirements
Visual Studio Community Edition. A computer capable of running Windows 10 or later for UWP and Android. A Mac that is capable of running macOS Mojave 10.14 to use the iOS simulator
Windows 10 or later, macOS Sierra 10.12 or later
Xcode. A Mac that is capable of running macOS Sierra 10.14
macOS Mojave 10.14
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/MAUI-Projects-3rd-Edition. If there’s an update to the code, it will be updated in the GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “Since all .NET MAUI programs start with the MauiProgram.cs file, that seems like a good place to start.”
A block of code is set as follows:
.keypad { width: 300px; margin: auto; margin-top: -1.1em; }When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
builder.Services.AddMauiBlazorWebView(); #if DEBUG builder.Services.AddBlazorWebViewDeveloperTools(); builder.Logging.AddDebug(); #endifAny command-line input or output is written as follows:
$ mkdir ViewModels $ cd ViewModelsBold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Open Visual Studio 2022 and select Create a new project.”
Tips or important notes
Appear like this.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.
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/support/errata and fill in the form.
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.
Once you’ve read .NET MAUI Projects, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?
Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the link belowhttps://packt.link/free-ebook/9781837634910
2. Submit your proof of purchase
3. That’s it! We’ll send your free PDF and other benefits to your email directly
In this part, you will get an overview of .NET MAUI and learn how to install .NET MAUI in order to create your first .NET MAUI project. As you create your first projects, you will learn about the Model-View-ViewModel design pattern and how to use it in .NET MAUI apps. Xamarin users will also learn how to upgrade their projects to .NET MAUI either manually or by using the .NET Upgrade Assistant.
This part has the following chapters:
Chapter 1, Introduction to .NET MAUIChapter 2, Building Your First .NET MAUI AppChapter 3, Converting a Xamarin.Forms App to .NET MAUI