La Electricidad Y La Electrónica Trabajo Tecnología.pdf
Azure Tech Frogs La vida despues de Xamarin NET MAUI y el desarrollo de apps.pptx
1. La vida después de
Xamarin: .NET MAUI y el
desarrollo de apps móviles
Luis Beltrán
Microsoft MVP
@darkicebeam
2. Luis Beltrán
• Investigador en Tomás Bata
University in Zlín
• Docente en Tecnológico
Nacional de México en Celaya
• Microsoft MVP en IA y
Tecnologías de Desarrollador
@darkicebeam
luis@luisbeltran.mx
3. Xamarin
Una plataforma de aplicaciones open source de Microsoft para construir apps iOS,
Android, macOS, Windows, watchOS, & tvOS modernas y de
alto rendimiento con .NET.
6. .NET Unificado: .NET 6
• Un SDK, un BCL, herramientas unificadas
• Interfaz de usuario móvil, desktop y cross-platform nativa
• Interfaz de usuario web cross-platform
• Inversión en nube nativa
• Mejora en el rendimiento y productividad
.NET
.NET tiene las mejores
soluciones para todas las
cargas de trabajo en una única
plataforma unificada de
7. Principales características de .NET 6
• Simplifica y escribe menos
código con C # 10
• .NET Multi-Platform App UI (.NET
MAUI) para aplicaciones nativas
móviles y de escritorio
• Aplicaciones web de escritorio
Blazor con capacidades de
dispositivo nativas
• Minimal web APIs para
aplicaciones nativas de la nube
• Más dispositivos soportados,
incluido Apple M1
• Windows Forms y WPF en ARM64
e implementación de EXE de un
solo archivo
• Mejoras en la productividad del
desarrollador, como Hot Reload
para todos los tipos de proyectos
• Mejoras continuas de rendimiento
en tiempo de ejecución y tiempo
de compilación
8. .NET 6 Previews
• .NET MAUI es compatible con Visual Studio
• Aplicaciones de escritorio híbridas con ASP.NET
Blazor
• Minimal web APIs y microservicios más pequeños y
rápidos
• Más dispositivos, implementación más flexible
• Mejoras de rendimiento y productividad dot.net/get-dotnet6
9. .NET Multi-platform App UI (.NET MAUI)
• .NET MAUI es un framework multiplataforma para crear
aplicaciones nativas de escritorio y móviles con C # y XAML.
• Con .NET MAUI, puedes desarrollar aplicaciones nativas que
pueden ejecutarse en Android, iOS, iPadOS, macOS y
Windows desde una única base de código compartida.
• Moderna y de alta productividad.
10. Los SDKs de Xamarin SDKs ahora son
.NET for Android
iOS
macOS
Mac Catalyst
tvOS
.NET Multi-platform App UI (MAUI)
11. .NET MAUI
• Interfaz de usuario nativa, multiplataforma
• Sistema de proyecto único
• Una sola base de código compartido
• Implementa en varios dispositivos: móviles
y de escritorio
• Disponibilidad general en .NET 6
.NET 6
.NET Multi-platform App UI
WinUI
Mac
Catalyst
Android
iOS
iOS
macOS
github.com/dotnet/maui
https://docs.microsoft.com/en-us/dotnet/maui/
12. ¿Cómo funciona .NET MAUI?
Android iOS macOS Windows
.NET for Android .NET for iOS / Mac Catalyst WinUI
.NET Multi-platform App UI
.NET Runtime
.NET Base Class Library (BCL)
App Code
iOS macOS
19. Opciones de estilizado
• Tema oscuro y claro
• Estilos estáticos y dinámicos
• XAML y CSS
• Visual State Manager
• Fuentes personalizadas y de
íconos
• Imágenes de distintos
formatos (SGV incluido)
20. Personalización de controles
#if ANDROID
Handlers.EntryHandler
.EntryMapper[nameof(IEntry.BackgroundColor)] = (h, v) =>
{
(h.NativeView as global::Android.Views.Entry).UnderlineVisible = false
};
#endif
#ifdef if platform specific
Access the handler from anywhere
Dictionary of all props
21. Dibujando UI con Maui.Graphics (Experimental)
• Gráficos nativos o SkiaSharp
• Fluent y Material design
22. Single Project
Simplifica el desarrollo de apps que se implementan
en distintas plataformas:
• Un solo proyecto
• Implementa en múltiples dispositivos y
plataformas
• Una sola ubicación para recursos (fuentes,
imágenes, íconos de aplicación, splash screens,
assets)
• Organización de código específico de plataforma
Productivity
23. Single Project
Productivity
Simplifica el desarrollo de apps que se implementan
en distintas plataformas:
• Un solo proyecto
• Implementa en múltiples dispositivos y
plataformas
• Una sola ubicación para recursos (fuentes,
imágenes, íconos de aplicación, splash screens,
assets)
• Organización de código específico de plataforma
24. Fundamentos
• Clase App Punto de entrada de la app
• Clase Startup
• Registro de fuentes
• Registro de handlers
• Registro de renderers
26. • Conecta cualquier dispositivo iOS
directamente a Windows y comienza a
escribir código en Visual Studio 2022.
• Los cambios se envían desde Visual
Studio directamente a la aplicación que
se ejecuta en el dispositivo, no se
requiere un host de compilación de Mac.
• Cuando estés listo para publicar y
distribuir, conecta una Mac o usa un
servicio en la nube para terminar el
trabajo.
Productivity
27. Remote iOS Simulator
Para obtener más funciones de Apple,
conecta Visual Studio 2022 en Windows
a una Mac en la red local. Con esto
obtienes:
• Xcode nativo se compila sobre SSH
• Simulador remoto
• Soporte de pantalla táctil
Productivity
28. Essentials
Utiliza Maui.Essentials para acceder a los servicios del dispositivo
en todos los destinos .NET MAUI.
• Próxima versión de Xamarin.Essentials
• Acelerómetro
• App Actions
• Información de la aplicación
• Barómetro
• Batería
• Portapapeles
• Brújula
• Conectividad
• Y más
Bonus
29. Blazor Hybrid
Combina tu aplicación Blazor y .NET MAUI
para crear una experiencia híbrida perfecta en
computadoras de escritorio y dispositivos
móviles.
• BlazorWebView hospeda la aplicación web.
• Accede a cualquier api .NET MAUI desde
Razor
• Combina web UI y native UI
Bonus
30. Microsoft.Maui.Graphics
Lo que .NET MAUI es para los kits de
herramientas de interfaz de usuario de la
plataforma, Maui.Graphics es para la
representación de gráficos de plataforma.
• Canvas con tipos de dibujo primitivos
• Fuentes
• Texto con atributos
• Mapas de bits
• Archivos PDF
• Tipos de colores unificados
• Soporte de plataforma amplia
• Compatible con SkiaSharp
Bonus
31. 🐱🏍
.NET 6 GA
Nov 9, 2021
Ignite Conference
Oct 13, 2021
Bug Fixes
.NET 6 RC2
Oct 12, 2021
Android S & iOS 15 may
be stable sometime in this
timeframe
Bug Fixes
.NET 6 RC1
Sept 14, 2021
VS 2022 Templates
C# Hot Reload
XAML Hot Reload
Hot Restart
iOS Remote Simulator
try-convert support
FEATURE COMPLETE
.NET 6 Preview 7
Aug 10, 2021
dotnet install
.NET 6 Preview 6
Jul 14, 2021
.NET MAUI timeline (*) https://github.com/dotnet/maui/wiki/roadmap
49. ¿Qué debo usar ahora?
¿Xamarin.Forms o
esperar a .NET MAUI?
Xamarin.Forms
Tu proyecto lo podrás actualizar a .NET MAUI posteriormente
50. Pre-requisitos
Para una mejor probabilidad de éxito al migrar a .NET 6 se
recomienda:
• Actualiza cualquier proyecto PCL a .NET Standard
• Actualiza los proyectos Xamarin.Forms a la versión 5.0
• Actualiza packages.config a PackageReference
Herramientas recomendadas:
• Visual Studio 2022 para Windows o Mac (link)
• .NET 6 (link)
• .NET Upgrade Assistant (link)
51. Pasos de actualización
Ejecuta el .NET Upgrade Assistant para:
1. Respaldar tu proyecto existente
2. Convertir *.csproj al SDK Style
3. Migrar namespaces de Xamarin.* to Microsoft.Maui.*
4. Revisar y reemplazar paquetes NuGet con versiones compatibles de .NET 6
Abre el proyecto en Visual Studio 2022 para:
1. Gestionar las dependencias de NuGet
2. Compilar y corregir errores
Tiempo estimado: depende de la complejidad del proyecto (pero no
debería ser demasiado…)
52. Compatibilidad de NuGet
¿Cómo saber si se necesita actualizar o reemplazar una
dependencia de NuGet?
Caso 1
Los NuGets que son .NET Standard y no hacen referencia a
ningún tipo de Xamarin.Forms probablemente funcionarán como
están.
Caso 2
Los NuGets que hacen referencia a los tipos de Xamarin.Forms
deben actualizarse a los tipos de Microsoft.Maui.Controls y volver
a publicarse con TFM de .NET 6 (Target Framework Moniker)
53. ¿El proyecto se debe
migrar a “Single Project”?
No, tus proyectos existentes seguirán funcionando sin Single Project.
Migraremos los proyectos existentes al sistema de proyecto común de .NET 6.
Se proporcionará documentación si desea adoptar Single Project manualmente.
55. Xamarin.Forms a Microsoft.Maui
.NET MAUI puede ejecutar Effects y Custom Renderers
Actualiza los namespaces en tu implementación de plataforma a Microsoft.Maui
1. Registra tu Effect en Startup.cs:
2. Registra tu Renderer en Startup.cs:
No se requiere cambio alguno en XAML
appBuilder.ConfigureEffects(builder => {
builder.Add<FocusRoutingEffect, FocusPlatformEffect>();
});
appBuilder.ConfigureMauiHandlers(builder => {
#if __ANDROID__
handlers.AddCompatibilityRenderer(typeof(CustomEntry),
typeof(Droid.Renderers.CustomEntryRenderer));
#endif
});
56. Xamarin.Forms a Microsoft.Maui
(Opcional)
• Migra los Effects y Renderers a la nueva arquitectura de
Handlers
• Migra soluciones de múltiples proyectos a Single project
Ejemplos y recursos: https://github.com/jsuarezruiz/xamarin-forms-to-net-maui
58. ¿.NET MAUI podrá
ejecutarse en Linux?
Linux no es una plataforma compatible con esta versión de
.NET MAUI.
Hay un backend no oficial implementado con GTK.
59. ¿Qué “sabor” de XAML
utilzará .NET MAUI?
El mismo XAML que utilizas en Xamarin.Forms hoy en día.
Revisaremos algunos cambios de nombres más adelante en los previews.
63. Invitación: Call for Speakers .NET Conf
Latam 2021
https://sessionize.com/dotnetconflatam2021/
64. Invitación: Call for Speakers Global AI
Back Together Latinoamérica 2021
https://sessionize.com/global-ai-back-together-latinoamerica-2021/
65. ¡Gracias por tu atención!
Luis Beltrán
Tomás Bata University in Zlín
Tecnológico Nacional de México en Celaya
luis@luisbeltran.mx luisbeltran.mx @darkicebeam
/icebeam /darkicebeam /luisantoniobeltran
/icebeam7 about.me/luis-beltran
Notes de l'éditeur
.NET 6, the next generation of the company’s software development platform that will finish the parts of the .NET unification begun in .NET 5.
Due as a production release in November, .NET 6 is set to deliver improvements for cloud, desktop, and mobile apps.
Microsoft .NET 6 will integrate capabilities for Android, iOS, and MacOS that currently reside in the Xamarin open source mobile .NET platform. Microsoft also is extending the Blazor client web app development tool, so developers can build a hybrid client app that combines web and native UIs for desktop and mobile usage. Blazor WebAssembly was the first unified platform deliverable in .NET 5
The .NET unification creates one .NET from the separate .NET Core, .NET Framework, and Xamarin/Mono technologies. Parts of .NET Framework already had moved to .NET Core; .NET 5 began the journey of combining .NET Core and Mono/Xamarin on a base class library and toolchain.
.NET Multi-platform App UI (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 can run on Android, iOS, macOS, and Windows from a single shared code-base.
.NET MAUI is open-source and is the evolution of Xamarin.Forms, extended from mobile to desktop scenarios, with UI controls rebuilt from the ground up for performance and extensibility. If you've previously used Xamarin.Forms to build cross-platform user interfaces, you'll notice many similarities with .NET MAUI. However, there are also some differences. Using .NET MAUI, you can create multi-platform apps using a single project, but you can add platform-specific source code and resources if necessary. One of the key aims of .NET MAUI is to enable you to implement as much of your app logic and UI layout as possible in a single code-base.
Las API de Android, iOS, macOS y Windows están unificadas en una API abstracta que permite una experiencia de desarrollo que permita escribir una vez y ejecutar en cualquier plataforma, al tiempo que proporciona un acceso total a todos los aspectos de cada plataforma nativa.
App Code interactúa principalmente con .NET MAUI API (1). Según sea necesario, App Code puede acceder directamente las API de la plataforma (2) a través Handlers, etc. .NET MAUI accede directamente las API de la plataforma nativa (3).
How is it native?
Everything starts with your app code. This is where you want to spend all your time being productive. And you want to deliver your app on 1+ devices
The first layer of the technology cake is the native platform SDK. This what Google, Android, and Microsoft ship for those platforms
So how do we get from our .NET app code to those platforms and running on devices?
First we need something that can run .NET code: the .NET Runtime. (Yes, it uses MonoVM on mobile and Mac, and CoreCLR on Windows, but that’s not terribly important because...)
Next we need a common .NET API we can write our code against, and that’s the Base Class Library (BCL). New in .NET 6 app runtimes use the same BCL.
To use .NET against native platform SDKs we need a .NET representation of them. We do this via binding a .NET API and implementation to the native API. When you call a native method from C#, it’s just as if you had done it from Obj-C, Swift, Java, Kotlin, or C++.
The final layer of the cake that really makes it delicious is .NET MAUI. .NET MAUI provides a rich library of controls, layouts, and services that work across all of the platforms supported, so you need only master one API to get native apps.
(next slide) With .NET MAUI, all of that complexity is delivered in a single framework that gives you access to it all.
With .NET MAUI, all of that complexity is delivered in a single framework that gives you access to it all.
You have more than 40 controls, layouts, and pages to mix and match from.
These are all of the controls you have out of the box, you can of course create your own.
What is unique is you get the native control and have access to it.
And, our partners building controls make much of this possible, creating gorgeous pre-built UI controls for you to drop right in to your app
.NET Multi-platform App UI (MAUI) provides a collection of controls that can be used to display data, initiate actions, indicate activity, display collections, pick data, and more. By default, handlers map these cross-platform controls to native controls on each platform. For example, on iOS a .NET MAUI handler will map a .NET MAUI Button to an iOS UIButton. On Android, the Button will be mapped to a AppCompatButton:
Handlers can be accessed through a control-specific interface provided by .NET MAUI, such as IButton for a Button. This avoids the cross-platform control having to reference its handler, and the handler having to reference the cross-platform control. The mapping of the cross-platform control API to the platform API is provided by a mapper.
Handlers expose the native control that implements the .NET MAUI cross-platform control via the NativeView property. This property can be accessed to set platform properties, invoke platform methods, and subscribe to platform events.
Handlers are global and therefore customization can occur anywhere in your .NET MAUI app. For example, customizing a handler for a control in your App class will result in all controls of that type being customized in the app. Similarly, customizing a handler for a control in the first page of your app will also result in all controls of that type in the app being customized.
The new handler architecture makes it easy to hook into any property and add/modify behavior right in .NET MAUI
In this example we hook into the background color and change the Android underline visibility on the Entry.
We could also, with a little more effort, add a custom property mapping specific to the underline and implement that with almost identical code.
One project can now publish to any of the platforms supported.
Images are optimized at build time for the multiple densities of screens required across all the platforms you target.
Fonts are registered in one location for every platform, and you can alias the name as you desire.
Platform code can all live within this one, multi-targeted project.
Splash screen support makes it easy to declare a visual asset (PNG or SVG for example) and a background color.
The App class should derive from the Application class, and must override the CreateWindow method to provide a Window within which your app runs, and that defines the UI for the initial page of the app:
In the example above, MainPage is a ContentPage that defines the UI for the initial page of the app.
To register your own handlers, call the ConfigureMauiHandlers method on the IAppHostBuilder object. Then, on the IMauiHandlersCollection object, call the AddHandler method to add the required handler:
In this example, the MyEntryHandler handler is registered against the MyEntry control. Therefore, any instances of the MyEntry control will be handled by the MyEntryHandler.
Code live whether it’s C#, CSS, Razor, or XAML. Less time building and more time coding.
In a future Visual Studio 2022 release you’ll also be able to see your app right inside the IDE where you can inspect elements and set UI guides.
(this is showing Xamarin.Forms and will be replaced with a .NET MAUI example. Same technology)
Aka “Hot Restart” enables you to use your Apple developer account, a Windows dev machine, and any iOS device to build and test iOS apps.
Code live whether it’s C#, CSS, Razor, or XAML. Less time building and more time coding.
In a future Visual Studio 2022 release you’ll also be able to see your app right inside the IDE where you can inspect elements and set UI guides.
(this is showing Xamarin.Forms and will be replaced with a .NET MAUI example. Same technology)