.NET MAUI Cross-Platform Application Development - Roger Ye - E-Book

.NET MAUI Cross-Platform Application Development E-Book

Roger Ye

0,0
32,76 €

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

Build apps for Android, iOS, macOS, and Windows using Microsoft's .NET Multi-platform App UI and Blazor

Key Features



  • Get familiar with Microsoft's UI toolkit to build amazing interfaces for iOS, Android, Windows, and macOS
  • Build a cross-platform password manager based on the famous Windows app, KeePass
  • Explore .NET MAUI development and Hybrid app development using Blazor

Book Description



An evolution of Xamarin.Forms, .NET Multi-platform App UI (.NET MAUI) is a cross-platform framework for creating native mobile and desktop apps with C# and XAML. Using .NET MAUI, you can develop apps that'll run on Android, iOS, macOS, and Windows from a single shared code-base. This step-by-step guide provides a comprehensive introduction to those who are new to .NET MAUI that will have you up to speed with app development using .NET MAUI in no time.



The book begins by showing you how to develop a cross-platform application using .NET MAUI and then helps you build an app throughout the chapters. You'll gain all the knowledge needed to create a cross-platform application for Android, iOS, the mac OS, and Windows from a single shared code-base using .NET MAUI. As you advance, you'll get to grips with the entire application development lifecycle, from design and implementation through to deployment to the app store through the development of a password manager app using KeePassLib. The concluding chapters will teach you how to integrate the latest frontend technology into your app through .NET MAUI Blazor.



By the end of this book, you'll have learned how to develop your own cross-platform applications using .NET MAUI.

What you will learn



  • Discover the latest features of .NET 6 that can be used in mobile and desktop app development
  • Find out how to build cross-platform apps with .NET MAUI and Blazor
  • Implement device-specific features using .NET MAUI Essentials
  • Integrate third-party libraries and add your own device-specific features
  • Discover .NET class unit test using xUnit.net and Razor components unit test using bUnit
  • Deploy apps in different app stores on mobile as well as desktop

Who this book is for



This book is an entry-level .NET MAUI book for mobile developers interested in cross-platform application development with working experience of the .NET Core framework, as well as fresh or junior engineers who've just begun their career in mobile app development. Native application developers (desktop) or Xamarin developers who want to migrate to .NET MAUI will also benefit from this book. Basic knowledge of modern object-oriented programming language, such as C#, Java or Kotlin, is assumed.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 378

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.



.NET MAUI Cross-Platform Application Development

Leverage a first-class cross-platform UI framework to build native apps on multiple platforms

Roger Ye

BIRMINGHAM—MUMBAI

.NET MAUI Cross-Platform Application Development

Copyright © 2023 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.

Group Product Manager: Rohit Rajkumar

Publishing Product Manager: Nitin Nainani

Senior Editor: Keagan Carneiro

Senior Content Development Editor: Debolina Acharyya

Technical Editor: Simran Udasi

Copy Editor: Safis Editing

Project Coordinator: Sonam Pandey

Proofreader: Safis Editing

Indexer: Rekha Nair

Production Designer: Aparna Bhagat

Marketing Coordinator: Nivedita Pandey

First published: February 2023

Production reference: 1050123

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80056-922-5

www.packt.com

To my family: my wife Bo Quan and my daughter Yuxin Ye, and the memory of my father and my mother.

– Roger Ye

Contributors

About the author

Roger Ye is a software engineering manager who has worked in the software industry for many years.

Roger started his career as a software engineer in embedded system development at companies such as Motorola, Emerson, and Intersil. During this period, he wrote two books about embedded system programming, Embedded Programming with Android and Android System Programming.

In 2013, Roger joined McAfee as a software engineering manager. He recently started working at EPAM Systems, moving from system programming to application programming. His first book on application programming is on .NET MAUI.

I want to thank the team at Packt, who worked very hard with me to keep to schedule.

About the reviewers

Glenn Stephens is a software developer and product designer, implementing solutions for the mobile-, desktop-, and cloud-centered worlds we all live in. Glenn has worked in many different roles, such as managing director, chief executive officer, solution architect, software development manager, and programmer; has worked in fields spanning high-end security, e-health, education, and finance; and has won several awards along the way. Glenn has a bachelor’s degree in computer science, an MBA with a specialization in e-business, and a Graduate Certificate in Arts in theatre and performance. He considers himself a lifelong learner.  

An author, speaker, and product builder, he has been writing code since the 80s, with the musical taste to match. When he’s not working, he enjoys playing the piano, reading, and spending time with his children.  

Rohit Vinod Kelkar is an artist, a techie, and an experienced mobile application developer who is enthusiastic about cross-platform mobile application technologies. He has expertise in technologies such as Xamarin, Flutter, native iOS, and .NET as a full stack developer. He was an early adopter of .NET MAUI and works with a community of developers to share updates and blog about the technology. He also shares an interest in consulting and helping products in their initial stages. 

Siddharth Singh has over 12 years of software development experience, having worked on a variety of platforms such as Windows, web, and mobile applications. Having worked at Expedia, Adobe, and Salesforce, his experience ranges from COM-/ASP-based legacy apps to React/ASP.NET Core modern applications. While working on Xamarin apps, he developed a passion for the Microsoft cross-platform framework. 

He currently works at Microsoft as a senior developer for Azure Data Factory, writing data integration applications. When not at work, you can find him reading about theoretical computer science and artificial general intelligence. 

Table of Contents

Preface

Part 1: Exploring .NET MAUI

1

Getting Started with .NET MAUI

An overview of cross-platform technologies

Native applications

Web applications

Backend services

Cross-platform technologies

A comparison of .NET, Java, and JavaScript

Exploring the .NET landscape

.NET Framework

Mono

.NET Core

.NET Standard and portable class libraries

Using Xamarin for mobile development

Xamarin.Forms

Xamarin.Essentials

Moving to .NET MAUI

.NET MAUI Blazor apps

Choosing XAML versus Razor in .NET MAUI

Development environment setup

Installing .NET MAUI on Windows

Installing .NET MAUI on macOS

What you will learn in this book

The app that we will build in this book

Summary

Further reading

2

Building Our First .NET MAUI App

Technical requirements

Managing the source code in this book

Setting up a new .NET MAUI project

Creating a new project using Visual Studio

Creating a new project using the dotnet command

App startup and lifecycle

Lifecycle management

Configuring the resources

App icon

Splash screen

Setting custom font icons

Building and debugging

Windows

Android

iOS and macOS

Scaffolding a Model-View-ViewModel project

Migrating and reusing a Shell template from Xamarin.Forms

Visual Studio project template

Summary

3

User Interface Design with XAML

Technical requirements

Creating a XAML page

XAML syntax

Element

Attribute

XML namespaces and XAML namespaces

XAML markup extensions

Master-detail UI design

Side-by-side

Stacked

Controls in .NET MAUI

Layouts in .NET MAUI

Navigation in the master-detail UI design

Supporting multiple languages – localization

Creating a .resx file

Localizing text

Summary

Further reading

4

Exploring MVVM and Data Binding

Technical requirements

Understanding MVVM and MVC

MVVM in PassXYZ.Vault

Data binding

Binding mode

Changing notifications in viewmodels

Improving the data model and service

KPCLib

PassXYZLib

Updating the model

Updating the service

Binding to collections

Summary

Further reading

5

Navigation using .NET MAUI Shell and NavigationPage

Technical requirements

Implementing navigation

INavigation interface and NavigationPage

Using the navigation stack

Manipulating the navigation stack

Using Shell

Flyout

Tabs

Shell navigation

Improving our model

Understanding the data model and its services

Improving the login process

The Command interface

Summary

6

Introducing Dependency Injection and Platform-Specific Services

Technical requirements

A quick review of design principles

Exploring types of design principles

Using design principles

Using DI

Dependency Service

Using built-in MS.DI DI service

Connecting to the database

Initializing the database

Performing CRUD operations

Summary

Further reading

Part 2: Implementing .NET MAUI Blazor

7

Introducing Blazor Hybrid App Development

Technical requirements

What is Blazor?

Learning about Blazor Server

Understanding Blazor Wasm

Exploring Blazor Hybrid

Creating a new .NET MAUI Blazor project

Generating a .NET MAUI Blazor project with the dotnet command line

Creating a .NET MAUI Blazor project using Visual Studio on Windows

Running the new project

The startup code of the .NET MAUI Blazor app

Migrating to a .NET MAUI Blazor app

Understanding Razor syntax

Code blocks in Razor

Implicit Razor expressions

Explicit Razor expressions

Expression encoding

Directives

Directive attributes

Creating a Razor component

Redesigning the login page using a Razor component

The Model-View-ViewModel (MVVM) pattern in Blazor

Dependency injection in Blazor

CSS isolation

Summary

8

Understanding the Blazor Layout and Routing

Technical requirements

Understanding client-side routing

Setup of BlazorWebView

Setup of Router

Defining routes

Using Blazor layout components

Applying a layout to a component

Nesting layouts

Implementing navigation elements

Implementing a list view

Adding a new item and navigating back

Summary

9

Implementing Blazor Components

Technical requirements

Understanding Razor components

Inheritance

Creating a Razor class library

Using static assets in the Razor class library

Creating reusable Razor components

Creating a base modal dialog component

Data binding

Component parameters

Nested components

Two-way data binding

Communicating with cascading values and parameters

Understanding the component lifecycle

SetParametersAsync

OnInitialized and OnInitializedAsync

OnParametersSet and OnParametersSetAsync

ShouldRender

OnAfterRender and OnAfterRenderAsync

Implementing CRUD operations

CRUD operations of items

CRUD operations of fields

Summary

10

Advanced Topics in Creating Razor Components

Technical requirements

Creating more Razor components

Creating the Navbar component

Creating a Dropdown component for the context menu

Using templated components

Creating a ListView component

Using the ListView component

Built-in components and validation

Using built-in components

Using the EditForm component

Creating an EditFormDialog component

Summary

Further reading

Part 3: Testing and Deployment

11

Developing Unit Tests

Technical requirements

Unit testing in .NET

Setting up the unit test project

Creating test cases to test the IDataStore interface

Sharing context between tests

Razor component testing using bUnit

Changing project configuration for bUnit

Creating a bUnit test case

Creating test cases in Razor files

Using the RenderFragment delegate

Testing Razor pages

Summary

Further reading

12

Deploying and Publishing in App Stores

Technical requirements

Preparing application packages for publishing

What to prepare for publishing

Publishing to Microsoft Store

Publishing to the Google Play Store

Publishing to Apple’s App Store

GitHub Actions

Understanding GitHub Actions

Summary

Index

Other Books You May Enjoy

Part 1: Exploring .NET MAUI

In the first part of this book, we will learn about .NET MAUI programming. We will start with the introduction of .NET MAUI and its ancestor Xamarin.Forms. After that, we will create a code base using the Visual Studio template for our application. We will build a password manager app called PassXYZ.Vault step by step in this book. During the development of this app, we will introduce user interface design using XAML, the MVVM pattern, data binding, the shell, dependency injection, and so on. By the end of Part 1, we will have a fully functional password manager application.

This section comprises the following chapters:

Chapter 1, Getting Started with .NET MAUIChapter 2, Building Our First .NET MAUI AppChapter 3, User Interface Design with XAMLChapter 4, Exploring MVVM and Data BindingChapter 5,Navigation using .NET MAUI Shell and NavigationPageChapter 6,Introducing Dependency Injection and Platform-Specific Services

1

Getting Started with .NET MAUI

Since the release of .NET 5, Microsoft has been trying to unify different .NET implementations into one .NET release. .NET Multi-platform App UI (or .NET MAUI) is an effort to provide a unified cross-platform UI framework. We will learn how to use .NET MAUI to develop cross-platform applications in this book.

The following is what we will learn in this chapter:

An overview of cross-platform technologiesA comparison of cross-platform technologies (.NET, Java, and JavaScript)The .NET landscape and the history of Xamarin.NET MAUI features.NET MAUI Blazor appsA development environment setup

If you’re new to .NET development, this chapter will help you to understand the .NET landscape. For Xamarin developers, many topics in this book may sound familiar, and this chapter will give you an overview of what we will discuss in this book.

An overview of cross-platform technologies

Before discussing cross-platform technologies, let’s review the application development landscape first to understand the different cross-platform technologies better.

.NET MAUI is a cross-platform development framework from Microsoft for building apps, targeting both mobile and desktop form factors on Android, iOS, macOS, Windows, and Tizen.

Generally, software development can be divided into two categories – systems programming and application programming. Application programming aims to produce software that provides services to the user directly, whereas system programming aims to produce software and software platforms that provide services to other software. In the .NET domain, the development of the .NET platform itself belongs to systems programming, whereas the application development on top of the .NET platform belongs to application programming.

The design or architecture in a modern system includes the client and server side of software, which we can refer to as the frontend and backend.

For the software on the client side, we can further divide it into two categories – native applications and web applications.

Native applications

In native application development, we usually refer to application development for a particular operating system. With desktop applications, this could be Windows applications, macOS applications, or Linux applications. With mobile applications, this could be Android or iOS.

When we develop a native application, we have to develop it for each platform (Windows, Linux, Android, or macOS/iOS). We need to use different programming languages, tools, and libraries to develop each of them individually.

Web applications

Web application development has gone through several generations of evolution over the past few decades, from a Netscape browser with static web pages to a modern single-page application (SPA) using JavaScript frameworks (such as React or Angular). In web application development, JavaScript and various JavaScript-based frameworks dominate the market. In the .NET ecosystem, Blazor is trying to catch up in this area.

Backend services

Both native applications and web applications usually need some backend services to access business logic or a database. For backend development, many languages and frameworks can be used, such as Java/Spring, .NET, Node.js, Ruby on Rails, or Python/Django. Usually, native applications and web applications can share the same backend service. Java and .NET are the most popular choices for backend service developments.

Cross-platform technologies

Technologies used in web application development and backend services development are not platform-specific and can be used on different platforms as they are. When we talk about cross-platform development, we usually refer to native application development. In native application development, cross-platform development technologies can help to reduce costs and improve efficiency. The most popular cross-platform development technologies in this category include Flutter, .NET MAUI/Xamarin, and React Native. Table 1.1 provides an overview of available cross-platform technologies and alternative solutions from Microsoft. The technologies listed here are not exhaustive. I just want to give you a feeling of what kind of technologies exist in each category and what Microsoft solution can be used as an alternative.

Category

Cross-platform technologies

Microsoft solution

Language

Framework

Web application

JavaScript

React, Angular, or Vue

Blazor/Razor Pages

Native application

JavaScript

React Native, Cordova, Ionic, Electron, or NW.js

.NET MAUI/Blazor/Xamarin

Dart

Flutter

Java/Kotlin

Swing/Codename One

Backend services

Java

Spring

ASP.NET Core

JavaScript

Node.js

Python

Diango/Flask/Tornado

Table 1.1: A comparison of languages and frameworks with Microsoft solutions

There is no best choice of cross-platform tool or framework. The final choice is usually decided according to business requirements. However, from the preceding table, we can see that the .NET ecosystem provides a full spectrum of tools for your requirements. The development team for a large system usually requires people with experience in different programming languages and frameworks. With .NET, the complexity of programming languages and frameworks can be dramatically simplified.

A comparison of .NET, Java, and JavaScript

We had an overview of the tools and frameworks used in web apps, native apps, and backend services development. If we look at a higher level, that is, at the .NET ecosystem level, the ecosystem of Java or JavaScript can match almost what we have in a .NET solution. Java, JavaScript, or .NET solutions can provide tools or frameworks at nearly all layers. It would be interesting to compare Java, JavaScript, and .NET at a higher level.

Java is developed as a language with the goal to write once and run anywhere. It is built around the Java programming language and the Java Virtual Machine (JVM). The JVM is a mechanism to run on supported platforms that helps to remove platform dependency for developers. With this cross-platform capability, Java becomes a common choice for cross-platform applications and services development.

JavaScript is a language created for web browsers, and its capability is extensive due to the demands of web development. The limitation of JavaScript is that it is a scripting language, so it lacks the language features that can be found in Java or C#. However, this limitation doesn’t limit its usage and popularity. Table 1.2 offers a comparison of three technologies:

Area of comparison

.NET

Java

JavaScript

Programming languages

C#, F#, VB, C++, PHP, Ruby, Python, and more

Java, Kotlin, Clojure, Groovy, Scala, and more

JavaScript, TypeScript, CoffeeScript, and more

Runtime

CLR

JVM

V8/SpiderMonkey/JavaScriptCore

Supported IDE

Microsoft Visual Studio, Rider, MonoDevelop, and Visual Studio Code

Eclipse, IntelliJ Idea, Oracle NetBeans, and Oracle JDeveloper

Visual Studio Code, Webstorm, and Atom

Frontend framework

ASP.NET Core Razor/Blazor

Only supports server-side rendering such as JSP or Thymeleaf

React, Angular, or Vue

Desktop apps

WinForms, Win UI, WPF, UWP, and more

Swing, JavaFX, and more

Electron, NW.js, and more

Mobile apps

.NET MAUI/Xamarin

Codename One

React Native, Cordova, Iconic, and more

Backend framework

ASP.NET Core

The Spring Framework

Node.js

Table 1.2: A comparison of Java, JavaScript, and .NET

From Table 1.2, we can see that both .NET and Java have a good infrastructure to support multiple languages. JavaScript has its limitation as a scripting language, so TypeScript and CoffeeScript were invented to enhance it. TypeScript was developed by Microsoft to bring modern object-oriented language features to JavaScript. TypeScript is compiled into JavaScript for execution, so it can work well with existing JavaScript libraries.

Java is built around the JVM while .NET is built around the Common Language Runtime (CLR) and the Common Type System (CTS). With the CTS and CLR as the core of a .NET implementation, it supports multiple languages naturally with the capability to share a Base Class Library (BCL) in all supported languages.

While there are multiple languages that use the JVM as the abstraction layer for cross-platform capability, the interoperation between Java-derived languages is not at the same level as .NET languages. All .NET languages are built on one architecture and share the same BCL, while Java languages, such as Java, Kotlin, or Scala, are developed separately for very different purposes.

This comparison helps us to choose or evaluate a tech stack for cross-platform development. As a .NET MAUI developer, this analysis can help you understand your choice better. To understand where .NET MAUI is located in the .NET ecosystem, let’s have a quick overview of the history of the .NET landscape in the next section.

Exploring the .NET landscape

Before we dive into the details of .NET MAUI, let’s have an overview of the .NET landscape. This section is relevant if you are new to .NET. If you are a .NET developer, you can skip this section.

Since Microsoft introduced the .NET platform, it has evolved from a proprietary software framework for Windows to a cross-platform and open source platform.

There are many ways to look at the .NET technology stack. Basically, it contains the following components:

Common infrastructure (Compiler and tools suite)BCLsRuntime (Windows Runtime (WinRT) or Mono)

.NET Framework

The history of .NET history begins with .NET Framework. It is a proprietary software framework developed by Microsoft that runs primarily on Microsoft Windows. .NET Framework started as a future-oriented application framework to standardize the software stack in the Windows ecosystem. It is built around a Common Language Infrastructure (CLI) and C#. Even though the primary programming language is C#, it is designed to be a language-agnostic framework. Supported languages can share the same CTS and CLR. Most Windows desktop applications are developed using .NET Framework, and it is shipped as a part of the Windows operating system.

Mono

The first attempt to make .NET an open source framework was made by a company called Ximian. When the CLI and C# were ratified by ECMA in 2001 and ISO in 2003, it provided a potential opportunity for independent implementations.

In 2001, the open source project Mono was launched, aimed at implementing .NET Framework on Linux desktop software.

Since .NET Framework was a proprietary technology at that time, .NET Framework and Mono had their own compiler, BCL, and runtime.

Over time, Microsoft moved toward open source, and .NET source code became open source. The Mono project adopted some source code and tools from the .NET code base.

At the same time, Mono projects went through many changes as well. At the time that Mono was owned by the Xamarin company, Xamarin developed the Xamarin platform based on Mono to support the .NET platform on Android, iOS, Universal Windows Platform (UWP), and macOS. In 2016, Microsoft acquired Xamarin, which became the cross-platform solution in the .NET ecosystem.

.NET Core

Before the acquisition of Xamarin, Microsoft has already started work to make .NET a cross-platform framework. The first attempt was the release of .NET Core 1.0 in 2016. .NET Core is a free and open source framework, available for Windows, Linux, and macOS. It can be used to create modern web apps, microservices, libraries, and console applications. Since .NET Core applications can run on Linux, we can build microservices using containers and cloud infrastructure.

After .NET Core 3.x was released, Microsoft worked toward integrating and unifying .NET technology on various platforms. This unified version was to supersede both .NET Core and .NET Framework. To avoid confusion with .NET Framework 4.x, this unified framework was named .NET 5. Since .NET 5, a common BCL can be used on all platforms. In .NET 5, there are still two runtimes, which are WinRT (used for Windows) and the Mono runtime (used for mobile and macOS).

In this book, we use will the .NET 6 release.

.NET Standard and portable class libraries

Before the .NET 5 releases, with .NET Framework, Mono, and .NET Core, we had a different subset of BCLs on different platforms. In order to share code between different runtimes or platforms, a technique called Portable Class Libraries (PCLs) was used. When you create a PCL, you have to choose a combination of platforms that you want to support. The level of compatibility choices is decided by the developers. If you want to reuse any PCL, you must carefully study the list of platforms that can be supported.

Even though a PCL provides a way to share code, it cannot resolve compatibility issues nicely. To overcome the compatibility issues, Microsoft introduced .NET Standard.

.NET Standard is not a separate .NET release but instead a specification of a set of .NET APIs that must be supported by most .NET implementations (.NET Framework, Mono, .NET Core, .NET 5 or 6, and so on).

After .NET 5 and later versions, a unified BCL is available, but .NET Standard will be still part of this unified BCL. If your applications only need to support .NET 5 or later, you don’t really need to care too much about .NET Standard. However, if you want to be compatible with old .NET releases, .NET Standard is still the best choice for you. We will use .NET Standard 2.0 in this book to build our data model, since this is a version that can support most existing .NET implementations and all future .NET releases.

There will be no new versions of .NET Standard from Microsoft, but .NET 5, .NET 6, and all future versions will continue to support .NET Standard 2.1 and earlier. Table 1.3 shows the platforms and versions that .NET Standard 2.0 can support, and this is also the compatible list for our data model in this book.

.NET implementation

Version support

.NET and .NET Core

2.0, 2.1, 2.2, 3.0, 3.1, 5.0, and 6.0

.NET Framework 1

4.6.1 2, 4.6.2, 4.7, 4.7.1, 4.7.2, and 4.8

Mono

5.4 and 6.4

Xamarin.iOS

10.14 and 12.16

Xamarin.Mac

3.8 and 5.16

Xamarin.Android

8.0 and 10.0

UWP

10.0.16299, TBD

Unity

2018.1

Table 1.3: .NET Standard 2.0-compatible implementations

The open-source project KPCLib is a .NET Standard 2.0 library, and we will use it in our app. In Table 1.3, we can see that .NET Standard libraries can be used in both Xamarin and .NET MAUI apps.

Using Xamarin for mobile development

As we mentioned in an earlier section, Xamarin was part of the Mono project and was an effort to support .NET on Android, iOS, and macOS. Xamarin.Forms is a cross-platform UI framework from Xamarin. .NET MAUI is an evolution of Xamarin.Forms. Before we discuss .NET MAUI and Xamarin.Forms, let us review the following diagram of Xamarin implementation on various platforms.

Figure 1.1: Xamarin implementations

Figure 1.1 shows the overall architecture of Xamarin. Xamarin allows developers to create native UIs on each platform and write business logic in C# that can be shared across platforms.

On supported platforms, Xamarin contains bindings for nearly the entire underlying platform SDKs. Xamarin also provides facilities for directly invoking the Objective-C, Java, C, and C++ libraries, giving you the power to use a wide array of third-party code. You can use existing Android, iOS, or macOS libraries written in Objective-C, Swift, Java, or C/C++.

The Mono runtime is used as the .NET runtime on these platforms. It has two modes of operation – Just-in-Time (JIT) and Ahead-of-Time (AOT). JIT compilation generates code dynamically as it is executed. In AOT compilation mode, Mono precompiles everything, so it can be used on operating systems where dynamic code generation is not possible.

As we can see in Figure 1.1, JIT can be used on Android and macOS, while AOT is used for iOS where dynamic code generation is not allowed.

There are two ways to develop native applications using Xamarin.

You can develop native applications just like Android, iOS, or macOS developers, using native APIs on each platform. The difference is that you use .NET libraries and C# instead of the platform-specific language and libraries directly. The advantage of this approach is you can use one language and share a lot of components through the .NET BCL, even if you work on different platforms. You can also leverage the power of underlying platforms like native application developers.

If you want to reuse code on the user interface layer, you can use Xamarin.Forms instead of the native UI.

Xamarin.Forms

Xamarin.Android, Xamarin.iOS, and Xamarin.Mac provide a .NET environment that exposes almost the entire original SDK capability on their respective platforms. For example, as a developer, you have almost the same capability with Xamarin.Android as you do with the original Android SDK. To further improve code sharing, an open source UI framework, Xamarin.Forms, was created. Xamarin.Forms includes a collection of cross-platform user interface components. The user interface design can be implemented using the XAML markup language, which is similar to Windows user interface design in WinUI or WPF.

Xamarin.Essentials

Since Xamarin exposes the capability of the underlying platform SDKs, you can access device features using the .NET API. However, the implementation is platform-specific. For example, when you use a location service on Android or iOS, the .NET API can be different. To further improve code sharing across platforms, Xamarin.Essentials can be used to access native device features. Xamarin.Essentials provides a unified .NET interface for native device features. If you use Xamarin.Essentials instead of native APIs, your code can be reused across platforms.

Some examples of functionalities provided by Xamarin.Essentials include the following:

Device infoThe filesystemAn accelerometerA phone dialerText-to-speechScreen lock

Using Xamarin.Forms together with Xamarin.Essentials, most implementations, including business logic, user interface design, and some level of device-specific features, can be shared across platforms.

Comparing user interface design on different platforms

Most modern application development on various platforms uses the Model-View-Controller (MVC) design pattern. To separate the business logic and user interface design, there are different approaches used on Android, iOS/macOS, and Windows. On all the platforms involved, even though the programming languages used are different, they all use XML-based markup language to design user interfaces.

On an iOS/macOS platform, developers can use Interface Builder in XCode to generate .storyboard or .xib files. Both are XML-based script files used to keep user interface information, and this script is interpreted at runtime together with Swift or Objective-C code to create the user interface. In 2019, Apple announced a new framework, SwiftUI. Using SwiftUI, developers can build user interfaces using the Swift language in a declarative way directly.

On the Android platform, developers can use Layout Editor in Android Studio to create a user interface graphically and store the result in layout files. The layout files are in the XML format as well and can be loaded at runtime to create the user interface.

On the Windows platform, Extensible Application Markup Language (XAML) is used in user interface design. XAML is an XML-based language used for user interface design on the Windows platform. For a WPF or UWP application, the XAML Designer can be used for user interface design. In .NET MAUI, the XAML-based UI is the default application UI. Another pattern, the Model View Update (MVU) pattern, can also be used. In the MVU pattern, the user interface is implemented in C# directly without XAML. The coding style of MVU is similar to SwiftUI.

Even though SwiftUI on Apple platforms or MVU in .NET MAUI can be used, but the classic user interface implementation is the XML-based markup language. Let us do a comparison in Table 1.4.

Platform

IDE

Editor

Language

File extension

Windows

Visual Studio

XAML Designer

XAML/C#

.xaml

Android

Android Studio

Layout Editor

XML/Java/Kotlin

.layout

iOS/macOS

Xcode

Interface Builder

XML/Swift/Objective C

.storyboardor .xib

.NET MAUI/Xamarin.Forms

Visual Studio

N.A.

XAML/C#

.xaml

.NET MAUI Blazor

Razor/C#

.razor

Table 1.4: A comparison of user interface design

In Table 1.4, we can see a comparison of user interface design on different platforms.

.NET MAUI and Xamarin.Forms use a dialect of XAML to design user interfaces on all supported platforms. For .NET MAUI, we have another choice for user interface design, which is Blazor. We will discuss Blazor later in this chapter.

In Xamarin.Forms, we create user interfaces in XAML and code-behind in C#. The underlying implementation is still the native controls on each platform, so the look and feel of Xamarin.Forms applications are the same as native ones.

Some examples of features provided by Xamarin.Forms include the following:

XAML user interface languageData bindingGesturesEffectsStyling

Even though we can share almost all UI code with Xamarin.Forms, we still need to handle most of the resources used by an application in each platform individually. These resources could be images, fonts, or strings. In the project structure of Xamarin.Forms, we have a common .NET standard project and multiple platform-specific projects. Most of the development work will be done in the common project, but the resources are still handled in the platform-specific projects separately.

Moving to .NET MAUI

With the .NET unification, Xamarin has become a part of the .NET platform, and Xamarin.Forms integrates with .NET in the form of .NET MAUI.

.NET MAUI is a first-class .NET citizen with the Microsoft.Maui namespace.

Making the move to .NET MAUI is also an opportunity for Microsoft to redesign and rebuild Xamarin.Forms from the ground up and tackle some of the issues that have been lingering at a lower level. Compared to Xamarin.Forms, .NET MAUI uses a single project structure, supports hot reloads better, and supports MVU and Blazor development patterns.

From Figure 1.2, we can see that there is a common BCL for all supported operating systems. Under the BCL, there are two runtimes, WinRT and the Mono Runtime, according to the platform. For each platform, there is a dedicated .NET implementation to provide full support for native application development.

Figure 1.2: .NET MAUI architecture

Comparing to Xamarin.Forms, we can see from Table 1.5, there are many improvements in .NET MAUI.

.NET MAUI uses a single project structure to simplify project management. We can manage resources, dependency injection, and configurations in one location instead of managing them separately per platform.

.NET MAUI is fully integrated as part of .NET, so we can create and build projects using the .NET SDK command line. In this case, we have more choices in terms of development environments.

.NET MAUI

Xamarin.Forms

Project structure

Single project

Multiple projects

Resource management

One location for all platforms

Managed per platform

Fully integrated with .NET

Namespace in Microsoft.Maui and other IDEs can be chosen beside Visual Studio.

Command-line support. We can create, build, and run in a console:

dotnet new maui dotnet build -t:Run -f net6.0-android dotnet build -t:Run -f net6.0-ios dotnet build -t:Run -f net6.0-maccatalyst

Namespace in Xamarin.Forms and it uses Visual Studio as an IDE

Design improvement

Configuration through .NET Generic HostDependency injection supportConfiguration scattered in different locations

MVU pattern

A modern type of UI implementation

No

Blazor Hybrid

Support through BlazorWebView

No

Table 1.5: .NET MAUI improvement

In Table 1.5, we can see that .NET MAUI supports application configuration using .NET generic host, can work with multiple IDE environments, supports dependency injection, and can use the MVVM toolkit, etc. It also supports the MVU pattern and Blazor Hybrid UI. Next, we will look at the Blazor Hybrid app.

.NET MAUI Blazor apps

In Table 1.4, where we compared the user interface design options on different platforms, we mentioned that there is another way to design cross-platform user interfaces in .NET MAUI, which is Blazor.

Released in ASP.NET Core 3.0, Blazor is a framework for building an interactive client-side web UI with .NET. With .NET MAUI and Blazor, we can build cross-platform apps in the form of Blazor Hybrid apps. This way, the boundary between a native application and a web application becomes blurred. .NET MAUI Blazor Hybrid apps enable Blazor components to be integrated with native platform features and UI controls. The Blazor components have full access to the native capabilities of a device.

The way to use the Blazor web framework in .NET MAUI is through a BlazorWebView component. .NET MAUI Blazor enables both native and web UIs in a single application, and they can co-exist in a single view. With .NET MAUI Blazor, applications can leverage the Blazor component model (Razor components), which uses HTML, CSS, and the Razor syntax. The Blazor part of an app can reuse components, layouts, and styles that are used in an existing regular web app. BlazorWebView can be composed alongside native elements; additionally, they leverage platform features and share states with their native counterparts.

Choosing XAML versus Razor in .NET MAUI

To design the user interface of your .NET MAUI application, you have a few choices for implementation:

XAML