During development and everyday use, Substring is often the go-to choice for string manipulation. However, there are cases where Substring can negatively impact performance and result in unnecessary string memory allocation. 
In this article, we will explore how to enhance the performance of C# applications by making informed decisions when working with substrings. 
We'll compare the traditional Substring method with the newer AsSpan method and discuss when to use each for maximum efficiency

C# AsSpan VS Substring

Substring()

The Substring method is a commonly used tool for extracting substrings from a string in C#. While it's convenient and easy to use.
I have created a sample method that takes a full date string, splits the string, and returns the day, month, and year separated by commas.

๐ŸŒ Memory Allocation

When you call Substring, it creates a new string object and copies the characters from the original string to the new substring.

Improving C# Performance by Using AsSpan and Avoiding Substring

This can result in additional memory allocations, which can be problematic, particularly when handling large strings or frequent substring operations.

AsSpan

In contrast to Substring, the AsSpan method returns a ReadOnlySpan from the original string. A ReadOnlySpan is a lightweight, stack-allocated view over the data, and it doesn't create a new string object or copy the characters.

Same date full string convert into AsSpan method

๐Ÿš€ Improved Performance: 

By using AsSpan, you can significantly improve the performance of your code. It eliminates the overhead associated with creating new string objects and copying characters, making it an excellent choice for scenarios where performance is critical.

Reduced Memory Overhead: The lack of memory copying in AsSpan means that your application consumes less memory, reducing the load on the garbage collector and leading to a more efficient use of resources. You can refer to the statistics below for the results of the two methods.

Improving C# Performance by Using AsSpan and Avoiding Substring

When I can use AsSpan

The AsSpan method is particularly valuable in situations where you need to work with portions of a string without the need for actual string manipulation. Here are some common scenarios where using AsSpan is recommended

๐Ÿ’ก API Compatibility: 

Many APIs that accept strings now have overloads that accept a ReadOnlySpan argument. When such overloads are available, you can improve performance by calling AsSpan instead of Substring.

Performance-Critical Operations:

If your application performs extensive string manipulation operations, consider using AsSpan for better performance.

When I can use Substring

It's essential to note that there are still situations where using  Substring may be appropriate

✅ Creating a Copy

If you need to create a distinct copy of the substring (rather than a view), Substring remains a suitable choice.

Conclusion

In C# programming, optimizing string manipulation is crucial for enhancing the performance of your applications. While `Substring` is a well-known method for extracting substrings, it can introduce unnecessary memory overhead and reduce performance in some scenarios. On the other hand, `AsSpan` offers a lightweight, memory-efficient alternative that can significantly boost your application's speed. I hope this article more help you to 


Microsoft announced a new Foundational C# certification in collaboration with FreeCodeCamp. The Foundational C# certification is completely free for individuals in all regions. The certification includes a 35-hour C# training course hosted on Microsoft Learn and requires completing an 80-question C# certification exam. It's very interesting for those who want to start developing programming skills in C#. This is a great choice, as after completing this certification, you will acquire all the essential C# programming skills and learn tips and tricks. 

Free Microsoft Certification : C#

Without further delay, let's get started, and I will guide you through the certification process step by step.

Create an Account in the Microsoft Learn:


Creating an account on the Microsoft Learn website is a straightforward process, if you already have a Microsoft account, you can ignore all the steps. Microsoft Learn is a platform that offers a wide range of free learning resources, track certification, tutorials, and documentation for various Microsoft technologies and products. Here's a step-by-step guide on how to create an account:

Visit the Microsoft Learn Website: 

Go to the Microsoft Learn website by entering the following URL in your browser's address bar - https://learn.microsoft.com/

Choose a Microsoft Account or Create One: 

You'll be presented with two options: sign in with an existing Microsoft account (if you have one), or create a new Microsoft account. If you already have a Microsoft account, enter your credentials and proceed to sign in. If not, click on the option to create a new account, Here you can use any of Hotmail email IDs or create a Microsoft account using any other account like Gmail.

Create an Account in the Microsoft Learn


Microsoft will typically send a verification code to the email address you provided. Check your email inbox for a message from Microsoft and follow the instructions to verify your email. After verifying your email, you may need to provide additional information or agree to terms and conditions. Follow the on-screen instructions to complete the sign-up process.

Complete C# Self Learning Course in Microsoft Learn:


After successfully logging in, you can navigate to the following link: https://learn.microsoft.com/en-us/training/paths/get-started-c-sharp-part-1/ and complete Parts 1 through Part 6 of the Learn path while pursuing the Microsoft certification. 

Go beyond certification! Take the C# Challenge and compare your learning journey with global peers. The challenge begins on August 29th! Register here: https://aka.ms/csharp-challenge.

Create an Account with FreeCodeCamp:
FreeCodeCamp is a platform that offers free coding courses and tutorials. To create an account on the FreeCodeCamp website, Microsoft and Freecodecamp collaborated with the Provide More Efficient certificate You can follow these steps:

Visit the FreeCodeCamp Website:

Go to the FreeCodeCamp website by entering the following URL in your browser's address bar: www.freecodecamp.org/

On the FreeCodeCamp homepage, you'll typically find a "Sign in" or "Get Started (For Free)" button. Click on it.

Signup :

FreeCodeCamp usually offers a few sign-up methods, including signing up with your email address or using a social media account like GitHub.

Complete Your Profile :

After signing up, you may have the option to complete your profile by adding additional information such as your name, profile picture, and bio. This step is usually optional.

Create an Account with FreeCodeCamp


Earn Your Microsoft Certification:

Step 1: Go to the Foundational C# Certification path on freeCodeCamp. Here you’ll find the training content under Courses. Press Expand course to find all the modules within each course.

Earn Your Microsoft Certification

Step 2 : Click on each module in the course to find the link to the training content for that module.

Earn Your Microsoft Certification

Step 3: Complete the training content on Microsoft Learn. (Note: If you have previously completed the training content, you do not need to redo it)

A screenshot of a computer

Description automatically generated


Once you are done, complete the comprehension check question on freeCodeCamp.

  • Step 4: At the end of each course Module, you will receive a Trophy on Microsoft Learn. To complete this challenge, you must first link your Microsoft username to your freeCodeCamp account by following these instructions
      1. Using a browser where you are logged into your Microsoft account, go to https://learn.microsoft.com/users/me/transcript
      2. Find and click the "Share link" button.
      3. If you do not have a transcript link, click the "Create link" button to create one.
      4. Click the "Copy link" button to copy the transcript URL.
      5. Paste the URL into the input below, it should look similar to this:https://learn.microsoft.com/LOCALE/users/USERNAME/transcript/ID
      6. Click "Link Account" to link your Microsoft username.

Free Microsoft Exam

Unable to Verify Trophy in Microsoft Platform :

If any one of you has been unable to verify the trophy in the Microsoft platform and also internet seen many of the reports saying I was collecting my first trophy in the new Freecodecamp X Microsoft Foundational C# with Microsoft and I'm getting 500 status code when I try to connect my freecodecamp account to my Microsoft account to collect the trophy


Unable to Verify Trophy in Microsoft Platform

Issue Fix with the following steps :
This issue is because not every module has been completed. Before clicking on the trophy, ensure that you not only answer the questions correctly on FreeCodeCamp but also make sure that you have completed all the training modules on Microsoft Learn, and each section should have a green checkmark.


500 status code when I try to connect my freecodecamp account to my Microsoft account

Certification Day:
Once you have completed all six learning modules and earned six trophies from FreeCodeCamp, you are now eligible to take the Microsoft C# examination for free.

The exam consists of 80 questions, and you should complete it without closing the browser. The questions are based on the fundamental concepts you've learned in the six modules. After completing the exam, you will feel confident in your C# skills, and you can consider yourself a C# Guru. Enjoy the experience, and I wish you the very best of luck. I hope my article helps you navigate the examination process without confusion. Once again, best of luck!


Free Microsoft Certification : C#
Global usings were introduced in C# 10 and .NET Core 6.0 and later versions. This feature proves to be highly beneficial as it allows you to incorporate commonly used namespaces. As a developer, the emphasis is often on code reusability and maintaining clean, organized code.

Visual Studio 2022: C# Global Namespace

Global usings contribute significantly to achieving this goal. By employing global usings, there's no necessity to redundantly add the same namespace to every class file.

Determine the namespaces that are frequently used throughout your project and can be considered as candidates for global usings. These namespaces should be relevant and consistent across different parts of your codebase.

UI for Global Namespace in VS 2022:

Global namespaces UI screens are only available in the latest version of Visual Studio 2022. This feature is not present in earlier versions such as VS 2019 and VS 2022 for Mac. It allows you to define namespaces globally for your project, minimizing the need to repeatedly include the same namespaces in multiple class files. You can follow the below steps to implement Global name space in VS 2022 
  • Open your project in Visual Studio 2022, Here I have created a new MAUI application
  • Right-click on the project's  .csproj  file within the Solution Explorer.
  • Choose "Property" from the context menu.
As per the below screen Select below Global using and add your global usings and alias name

UI for Global Namespace in VS 2022

If you are using Visual Studio 2019 or an earlier version where the mentioned UI is not available, you can implement global use in your project by following the steps below.

Global Usings File for  VS 2019 and VS 2022 for Mac:
In C# 10 and .NET Core 6.0 or later, create a file named "GlobalUsings.cs" (or any appropriate name) in your project. Inside this file, use the "global" keyword followed by the "using" directives for the namespaces you want to make globally accessible. For example:



Accessing Namespaces
Once you've set up the global usings, any class file within your project can directly access the namespaces specified in the "GlobalUsings.cs" file. You won't need to explicitly include these namespaces in every individual class file that uses them.

For instance, if you've declared System.IO in your global usings, you won't need to include using System.IO; in each class file that utilizes file-related functionality from the System.IO namespace.



Summary:
I hope this article has provided you with valuable insights into Global Usings in Visual Studio 2022 and the Global Using file. If you have any questions or queries about global namespaces, please feel free to leave a comment in the designated comment section. I'll do my best to address and answer your inquiries.




In this article, we will discuss Microsoft introduced new types DateOnly and TimeOnly in C# and examine the unique functionalities offered by each, and assist in determining the suitable choice for different scenarios.

DateOnly and TimeOnly are value types introduced in .Net 6. These types are part of the .net Date and Time and offer unique advantages over using traditional DateTime for specific use cases that require working with only dates or times without the associated time zone information.

DateOnly And TimeOnly Types In  -.NET Core

DateOnly

Use DateOnly when you need to work with dates exclusively, without any time information. Examples of this include handling birthdays, anniversaries, and event dates.

For example, if you were to gather DOB from users, the optimum data type would be Date only as you wouldn't need timezone information and would only need the date, year, and month.
DateOnly And TimeOnly Types In .NET 6 -.NET Core

It allows you to work with dates precisely, ensuring that only the date information is considered without any ambiguity introduced by the time portion.

Here's how you can use DateOnly:


TimeOnly

Use TimeOnly when you require time values without any date information. Examples include representing opening/closing times, countdowns, and scheduling alarms.

DateOnly And TimeOnly Types In .NET 6 -.NET Core

Consider assigning variable check-in and check-out information during this period without requiring any date information. Since this information is more time-specific, we can use a TimeOnly type in this situation. It enables you to properly manipulate time values and saves you from having to deal with date information unnecessarily.

Here's how you can use TimeOnly:

Benefits of using DateOnly and TimeOnly

  • Clarity and Safety: These types provide clear and explicit representations of date and time values, reducing the risk of errors caused by time zone conversions and date/time mix-ups.
  • Immutability: DateOnly and TimeOnly are immutable types, meaning their values cannot be changed after creation. This helps prevent unintended modifications to date and time values.
  • Compact Storage: These types take up less memory compared to DateTime because they don't include time zone information, making them more efficient for certain use cases.
  • Performance: Operations involving only dates or only times can be more performant using DateOnly and TimeOnly, respectively, compared to DateTime.
  • Interoperability: The Date and Time provides easy conversion methods between DateTime, DateOnly, and TimeOnly, allowing seamless integration with existing code that uses DateTime.

DateTime

In C#, DateTime is a value type and commonly used in all the programming languages, You should use DateTime when you need to work with both date and time components together or when you require time zone information. 

DateTime provides a complete representation of a specific point in time, combining both date and time information along with an optional time zone offset. here you can find some use cases where DateTime is more appropriate than using DateOnly or TimeOnly

Benefits of using DateTime: 

  • Recording Events: When recording events or occurrences that happen at specific points in time, you need both the date and time components. For example, logging the exact timestamp of an event is best done with DateTime.
  • Time Zone Considerations: If you're dealing with events across different time zones or need to perform time zone conversions, DateTime can handle this with its time zone information. DateOnly and TimeOnly don't include time zone support.
  • Calculations Involving Both Date and Time: When performing calculations that involve both date and time components, such as calculating time intervals between two points in time, DateTime is more suitable.
  • Working with External APIs: Many external APIs and libraries work with DateTime objects. If you need to integrate your code with such APIs, using DateTime will simplify the data exchange.
  • Database Interactions: Databases often use DateTime to store date and time values. Using DateTime aligns well with database operations and prevents unnecessary conversions.
  • Serialization and Deserialization: When working with JSON or XML serialization, DateTime is the standard representation for date and time values, making it more compatible with serialization libraries.

Let's make a decision Here

Hope this article will help you, the choice between DateTime, DateOnly, and TimeOnly should be driven by the specific needs of your application.

If your application primarily deals with only dates or times, and you don't require time zone support or date and time together, then DateOnly and TimeOnly can be more appropriate for improved code clarity and safety. However, if you need to represent points in time with both date and time information, DateTime is the suitable choice.




Managing images, icons, and splash screens cross-platform is more challenging since we need to manage assert and resource folders specific to each platform, as well as image folders for each resolution. 
During testing, we received feedback from our QA friends that the images were not working on this device or at this resolution. Hopefully, all of you have encountered this problem in the past, and MAUI application has released great solutions for this issue.
.NET MAUI App Project:  MAUI app icon,  MAUI splash screen, and MAUI image to different mobile platform
In your .NET MAUI application, managing your resources is much simpler than in Xamarin and other hybrid applications, as it is not as complicated. Resources refers to the main topic of managing images. With NET MAUI, you can stop worrying about scaling and resizing your images to fit every platform and screen resolution. Better yet, you won't need to keep track of the website that generates everything for you. .NET MAUI will take care of the process for you at build time; just add your images to your project and make sure the build actions are set up. The purpose of this article is to demonstrate how the MAUI application manages its resources.
.NET MAUI App Project:  MAUI app icon,  MAUI splash screen, and MAUI images to different mobile platform
The ultimate design goal of one single project for all supported platforms the way to manage resources from one place. Be it fonts, images, splash screen, or raw assets. It is an incredible feature that MAUI introduced using SVG files and PNG files and have them automatically resized for all the different resolutions when they are uploaded. Regardless if you've already used ResizetizerNT in your Xamarin project, MAUI will do the same internally while the build process is running in the background.
Resource files should be placed in the Resources folder of your. NET MAUI app project, or in child folders of the Resources folder, and their build action should be correctly set. The following sections will be explained one by one as we go along.
  • Android resource naming rules is that image filenames must start with a letter character, end with a letter character, and contain only alphanumeric characters or underscores, so make sure your image name follows the same rules
  • The .NET MAUI app converts SVG files to PNG files. When adding an SVG file, reference it from XAML or C# with a .png extension. You should reference the SVG file in your project file as a best practice.
  • The values for the Foreground Color and Background Color can be specified either in hexadecimal or as a .NET MAUI color. For example, Color="Green" is valid.

MAUI Images

Images can be specified in one location in your app project, and at build time they are automatically resized and added to your app package. By doing this, you avoid manually duplicating and naming images per platform.
First Step, You can add images to your app project by dragging them into the Resources/Images folder of the app project which will allow you to add them to the project.
In the next step, you will be able to ensure that MauiImage build action is set automatically, if not set, you can ensure that the build action should be MAUIImage by selecting it from the Image Property.
NET MAUI App Icon and Splash screen cannot be customized

MAUI Image Guideline

  1. The default MAUIImage tag, which includes all images, can be found in the.csproj file, and you can also specify the image name. The wildcard character (*) indicates that all files in the folder are considered to be of the specified resource type.
  2. You can also add images to other folders(not only Image folder). In this scenario, MauiImage must be manually set in the Properties window.

MAUI Image Property

  • The base size is specified with the BaseSize="W,H" attribute, where W is the width of the icon and H is the height of the icon. The value specified as the base size must be divisible by 8. The following example sets the base size.                                                                               
 <MauiImage Include="Resources\Images\ msdevbuildlogo.jpg" BaseSize="376,678" />
  • It is also possible to stop the automatic resizing of the images. The following example code shows how to stop the automatic resizing
<MauiImage Include="Resources\Images\msdevbuildlogo.svg" Resize="false" />
  • A foreground image can be tinted, i.e., by specifying a color with the TintColor attribute, a color will be applied to the foreground image. Here is an example of how the foreground image can be tinted using the following code:
<MauiImage Include="Resources\Images\msdevbuildlogo.svg" TintColor="#66B3FF" />
  • The background image used in composing the app icon can be recolored using the Color attribute on the <MauiImage>. The following example sets the background color of the app icon to red
<MauiImage Include="Resources\Images\msdevbuildlogo.svg" Color="#512BD4" />

You can make use of your icon, image, and splash screen in the above property as specified above, so take note of that information.

MAUI Icon

In most apps, there is a logo icon that represents the app, and that icon appears in different places.
on iOS the app icon appears on the Home screen and throughout the system, such as in Settings, notifications, and search results, and in the App Store.
On Android, the app icon appears as a launcher icon and throughout the system, such as on the action bar, notifications, and in the Google Play Store.
On Windows, the app icon appears in the app list in the start menu, the taskbar, the app's tile, and in the Microsoft Store.
In a .NET Multi-platform App UI (.NET MAUI) app project, an app icon can be specified in a single location in your app project. At build time, this icon can be automatically resized to the correct resolution for the target platform and device, and added to your app package. This avoids having to manually duplicate and name the app icon on a per platform basis

MAUI Icon Include & ForgroundFile

On the .csproj file, the app icon can be composed of two images, one image representing the background and another representing the foreground.

<MauiIcon Include="Resources\AppIcon\appicon.svg" ForegroundFile="Resources\AppIcon\appiconf.svg" />
  1. Include attribute represents the icon background image( must specify)
  2. Foreground attribute represents the foreground image (optional)

How to use MAUI Icon

Platform specific configuration for MAUI App icon

The project file declares what resources make up the app icon, but you must update the individual platform configurations to reference these icon references. On iPhone, Mac, and Android, the following settings need to be made in the configuration, but Windows does not require any specific configuration

Info.Plist
This configuration will be automatically updated in Info.plist if you don't change app icon names, but if you change app icon names, make sure you update the configuration in Info.plist.

The Info.plist file contains a <key>XSAppIconAssets</key> entry, with a corresponding <string> node defined after it. The value of this <string> node follows this format: Assets.xcassets/{image file name}.appiconset The value for { image file name } is derived from the .NET MAUI project file's <MauiIcon> item, specifically the file name defined by the Include attribute, without its path or extension.

Platform specific configuration for MAUI App icon
Android Manifest
The following Android configuration is defined by default, so all you need to do is migrate the application or make any modifications. Make sure the configuration is set correctly.

Platform specific configuration for MAUI App icon

Use a different MAUI icon per platform

If you want to use different icon resources or settings per platform, add the Condition attribute to the <MauiIcon> item, and query for the specific platform. If the condition is met, the <MauiIcon> item is processed.

Only the first valid <MauiIcon> item is used by .NET MAUI, so all conditional items should be declared first, followed by a default <MauiIcon> item without a condition.

For example, a condition that targets Android would be Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'".

The following XML demonstrates declaring a specific icon for Windows and a fallback icon for all other platforms:

<!-- App icon for Windows -->

<MauiIcon Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'"
Include="Resources\AppIcon\MSDEVBUILDicon.png" ForegroundFile="Resources\AppIcon\appiconfg.svg" TintColor="#40FF00FF" />

<!-- App icon for IOS -->

<MauiIcon Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'ios'"

Include="Resources\AppIcon\MSDEVBUILDicon.png" ForegroundFile="Resources\AppIcon\iosmsdevbuildappiconfg.svg" TintColor="#40FF00FF" />

<!-- App icon for Android -->

<MauiIcon Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'"

Include="Resources\AppIcon\MSDEVBUILDicon.png" ForegroundFile="Resources\AppIcon\androidmsdevbuildappiconfg.svg" TintColor="#40FF00FF" />

<!-- App icon for mac -->

<MauiIcon Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'maccatalyst'"

Include="Resources\AppIcon\MSDEVBUILDicon.png" ForegroundFile="Resources\AppIcon\macmsdevbuildappiconfg.svg" TintColor="#40FF00FF" />

<!-- App icon for all other platforms -->

<MauiIcon Include="Resources\AppIcon\Suthaharappicon.png" ForegroundFile="Resources\AppIcon\appiconfg.svg" TintColor="Yellow" />

Use a different MAUI icon per platform

MAUI Icon Guideline

  1. In your project file, the <MauiIcon> item designates the icon to use for your app. You may only have one icon defined for your app. Any subsequent <MauiIcon> items are ignored.
  2. After changing the icon file, you may need to clean the project in Visual Studio. To clean the project, right-click on the project file in the Solution Explorer pane, and select Clean. You also may need to uninstall the app from the target platform you're testing with.
  3. If you don't clean the project and uninstall the app from the target platform, you may not see your new icon.

MAUI Splash Screen

On Android and iOS, .NET Multi-platform App UI (.NET MAUI) apps can display a splash screen while their initialization process completes. The splash screen is displayed immediately when an app is launched, providing immediate feedback to users while app resources are initialized:

In a .NET MAUI app project, a splash screen can be specified in a single location in your app project, and at build time it can be automatically resized to the correct resolution for the target platform and device and added to your app package. This avoids having to manually duplicate and name the splash screen on a per platform basis.

A splash screen can be added to your app project by dragging an image into the Resources\Splash folder of the project, where its build action will automatically be set to MauiSplashScreen. This creates a corresponding entry in your project file as like below screen

How to use MAUI Splash Screen

At build time, the splash screen can be resized to the correct resolution for the target platform and device. The resulting splash screen is then added to your app package.

Platform specific configuration

The code that's specific to a platform automatically gets added to the code base, but you have to know where it goes and why, it'll help you with the migration process
On Android
the splash screen is added to your app package as Resourcs/values/maui_colors.xml and Resources/drawable/maui_splash_image.xml
.NET MAUI apps use the Maui.SplashTheme by default, which ensures that a splash screen will be displayed if present. Therefore, you should not specify a different theme in your manifest file or in your MainActivity class

using Android.App;
using Android.Content.PM;
using Android.OS;
namespace NewProjectFile7._0;

[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
public class MainActivity : MauiAppCompatActivity
{

}
On iOS
It is not necessary for you to do iOS-specific settings because the build will automatically take care of this for you. the splash screen is added to the app package as a storyboard named MauiSplash.storyboard, which is set as value of the UILaunchStoryboardName key in the app package's Info.plist automatically add UILaunchStoryboardName as a key and string value is MauiSplash

Summary

If you have any further questions regarding MAUI app icon, MAUI splash screen, or MAUI image, please don't hesitate to let me know in the comment section. I hope that this article can help you to understand MAUI app icon, MAUI splash screen, and MAUI image to different mobile platforms. . In case you missed my previous article, you can refer to the links below.

Xamarin MAUI: First iOS, Android and Windows Mobile App using Visual studio 2022


The name MAUI stands for .NET Multi-platform App UI. Many IT companies struggle with deciding whether to migrate from XAMARIN or to start from scratch with a new hybrid application. You should not make any mistakes, better choose to move to MAUI. Prior to migration, you must understand what the main project file and platform specific changes are that differ from XAMARIN. It is not the purpose of this article to explain migration, but you should know before you migrate what the main changes have been to the project files in MAUI. To gain a deeper understanding of MAUI project files, let's follow me one by one in this article
.NET MAUI : Runs on multiple platforms in one project  (iOS, Android, and Windows)
Prerequisites
Visual Studio 2022 with the MAUI workload installed
Xamarin, MAUI Support for Visual Studio Mac
As we all know, Microsoft supports MAUI from Visual Studio 2022 latest version in Macs and Windows. Several people asked me if I could install Visual 2022 from my Mac, and if so, could it keep creating/modify Xamarin Forms, and the answer is yes, which means Microsoft continues to support Xamarin for now, so the latest Visual studio 2022 has both Xamairn and MAUI project templates, so if you are starting a new project, choose MAUI as the template, because it has wonderful features.

Xamarin, MAUI Support for Visual Studio Mac
MAUI Project File
A user can build a .NET MAUI application for Android, iOS, macOS, and Windows in one project file. Xamarin Forms uses different project files for Individual platforms. the .NET MAUI application is focused on Android, iOS, macOS, and Windows, simplifying and standardizing the cross-platform development experience for all four platforms.
MAUI Project File
MAUI SDK-style format
The .NET SDK is the base SDK for .NET. Projects associated with the other SDKs have access to all the .NET SDK properties. The default .Net Framework project is not SDK style and the default .Net Core, MAUI and .Net Standard project will be SDK style by default, Right click on your project and see the project file Below is the code for the MAUI project file, which is an XML file. The Sdk attribute defines which SDK is targeted.
MAUI SDK-style format
All project-level properties are enclosed within the PropertyGroup node. ItemGroup node holds dependencies, such as Project(s) referenced, NuGet package(s) added, Resource definitions, etc, will check line by line here
Multiple Target Platform
MAUI is multi-targeting by design, hence the TargetFrameworks list (which is separated by a semicolon).The Target Framework Monikers are all prefixed with net7.0-.The reason for this is that there is only one BCL.The actual platform is then specified (iOS, Android, MacCatalyst, and Windows).
Multiple Target Platform
Use MAUI & Output Type
OutPutType : This MAUI project will produce an executable (an App) on each of the platforms as the output type.

UseMAUI: UseWPF introduced in .NET Core 3 is familiar to developers with WinForms/WPF backgrounds.Whether or not to include references to MAUI libraries is controlled by the UseMAUI property.The MSBuild pipeline is also altered to correctly process a MAUI project and related files. Instead of referencing NuGet packages, set the UseMAUI property to true to add MAUI packages
Use MAUI & Output Type
SingleProject
The SingleProject tag represents .NET MAUI's main design goal, multi-targeting.
MAUI SingleProject
RootNamespace
RootNamespace, the root namespace for the types contained within this project.(My Project name - NewProjectFile7._0)
MAUI RootNamespace
ImplicitUsings
.NET 6 introduces implicit namespace support for C# projects. To reduce the amount of using directives boilerplate in .NET C# project templates, namespaces are implicitly included by utilizing the global using feature introduced in C# 10. When you create a new .NET 6 and above project it will enable this new property
MAUI ImplicitUsings
Mobile App Shared Configuration (App manifest)
Since we only have one project, we don't have to manage different platform configurations. We are able to configure in one project and we are not required to manage different platform configurations.
Mobile App Shared Configuration (App manifest)
MAUI Image
MAUI Image is a newly introduced node, which helps in including SVG images and is based on the popular resize component, which resizes the images internally based on the platform.Provides developers with a much easier process for including images across multiple platforms.

In a .NET Multi-platform App UI (.NET MAUI) app project, images can be specified in a single location in your app project, and at build time they can be automatically resized to the correct resolution for the target platform and device, and added to your app package. This avoids having to manually duplicate and name images on a per platform basis. By default, bitmap (non-vector) image formats, including animated GIFs, are not automatically resized by .NET MAUI.

.NET MAUI images can use any of the standard platform image formats, including Scalable Vector Graphics (SVG) files
MAUI Image
MAUI Icon
An app icon can be specified in a single location in your .NET Multi-platform App UI (.NET MAUI) project. Your app package can automatically resize this icon to the appropriate resolution for the target platform and device at build time.

By doing this, it will be possible to avoid having to duplicate and name app icons on a platform-by-platform basis. .NET MAUI does not automatically resize bitmap (non-vector) image formats.

MAUI Icon
Maui Splash Screen
At build time, a splash screen can be automatically resized to the correct resolution for the target platform and device, and added to the app package for a .NET MAUI app project. This eliminates having to duplicate and name splash screens on a platform-by-platform basis.

MauiSplashScreen
SVG Image convert to PNG
SVG files are converted to PNG files by NET MAUI. When adding an SVG file to your .NET MAUI app project, it should be referenced from XAML or C# with a .png extension. SVG files should only be referenced in project files.

MAUI Mobile Target Version
I'll explain this part of the configuration UI screen, select your Root project from solutions and click the Properties afterward.

The Target platform shows all the basic details of a mobile app platform, such as Target .Net Run time, Target mobile OS version, and the Min mobile OS version. You can choose your app's Min and Max target mobile OS version.
MAUI Mobile Target Version
MAUI Shared Application Setting
On the below screen, you will see that .NET MAUI project settings are shared among all target mobile platforms.
MAUI Shared Application Setting
  • Application Title - It is the name that appears as the Title in installed apps.
  • Application ID - the unique identifier of the application in reverse domain name format, for example com.msdevbuild.maui.
  • Application ID (GUID) - The identifier of the application in GUID format.
  • Application Display Version - The version of the application. This should be a single digit integer. Defaults to 1.
Platform Specific Configuration
You can add all your platform specific configurations for iOS, Android, Windows and Mac by selecting the section. This was previously done in a platform-specific project in an target project, but now it can be done in a shared project configuration.

MAUI Platform Specific Configuration
Platform-specific code
A .NET MAUI app project contains a Platforms folder, with each child folder representing a platform that .NET MAUI can target, The folders for each platform contain platform-specific resources, and code that starts the app on each platform and there are platform-specific configuration files for every platform, like the App manifest, info.plist, and other configuration files.

MAUi Platform-specific code
Summary
I hope that this article helps you to understand how you can create one project for multiple platforms. In case you missed my previous article, you can refer to the links below.

Xamarin MAUI: First iOS, Android and Windows Mobile App using Visual studio 2022

.NET MAUI provides different techniques for local storage, in my previous article, explain preferences. This article will explain how to use secure storage in your mobile iOS, Android, and windows applications.

Secure storage is like a shared preference. It stores data in key and value pairs. The data is encrypted and users a key made from a unique device key to encrypt and decrypt the data stored. The data is stored in a secure storage directory where only the OS can access it.
  Secure storage - .NET MAUI - Microsoft Docs
You must keep in mind Do and Don’t Do things about Secure Storage.
  1. There are no storage limitations for secure storage, best practices, and performance, secure storage may be impacted if you store large amounts of text, as the API was designed to store small amounts of text.
  2. You can store an unlimited number of keys inside
  3. The data gets deleted once the app is uninstalled.
  4. Best practice, you can choose to disable Auto Backup for your entire application, or You can create a custom rule set to exclude Secure Store items from being backed up.

Don’t Do in Secure Storage

  1. Secure storage to store data that should be encrypted and hidden from the user. That data should store only store users' sensitive data such as their API keys and not your server private keys and server connection string. Although data stored in secure storage are encrypted, it isn't entirely secure. Users can root/jailbreak their devices which gives them full control of the OS. There are tools that can intercept keys as they are provided and use them to decrypt the data. The only way to prevent that is to never save the server details and non-user-related data to the user device. You should store it on a server that you can control.
  2. When you try to save the max length string into the Preferences and secure storage to your device, it throws a Memory Exception when Preferences and secure storage data exceed 1.42 MB so don’t try to save a large amount of text, so if you have more than 1.42 MB data size to save it’s better to save use File storage or SQLite database.

Secure Storage VS. preferences

You probably already know about preferences, which is very useful when you want to save non-private information, but where you need to use secure storage, the following key difference will help you to understand.
Local Settings: Preferences and Secure Storage

Getting started with MAUI Secure Storage

The following steps are to create/get / Clear secure storage using.Net MAUI application. The .Net MAUI Secure Storage and ISecureStorage types are available in Microsoft.Maui.Storage namespace.

Secure storage will work on all the platforms iOS, macOS, Android, and windows, Only iOS simulator debugging require extra setup will explain in the last section.

Create New project

You can open visual studio 2022 from your Windows / Mac machine. You must follow the below 3 steps to create a new MAUI application.

Step 1: Select Create a new project

Step 2: Search the MAUI project template or choose Project Type > MAUI from the drop-down.

Step 3: Provide the configuration Details as a project name, Location, and Solutions name.
Xamarin.Essentials: Secure Storage

Namespace

Secure storage is storing data in key-value pairs and can be easily managed via the secure storage class from Microsoft.Maui.Storage namespace, so accesses secure storage add the Microsoft.MAUI. storage namespace

Save Secure Storage

SetAsync method, providing the key and value. it supports strings only. If you want to store other types of data, you can encode them as a string. The most convenient way to do that is probably JSON. You can use JSON serialize and deserialize.

await SecureStorage.SetAsync("Key String ", "Value String ");

For Example, while using implementation you can use like below

await SecureStorage.SetAsync("UserPassword", "MSdevBuild@123");

The Mobile Secure storage will work as per the platform-specific; the below section will show how different platforms store the secure storage in the device.

Android Device Secure Storage

Secure Storage uses the preference API and follows the same data persistence with a filename

[YOUR APP Package name ID].microsoft.maui.essential.preferences

However, data is encrypted with the Android EncryptedSharedPreference Class, and the secure storage value is encrypted with AES-256 GCM.

iOS Device Secure Storage

Key Chain is used to store values securely on iOS devices. The SecRecord used to store the value has a Service value set to

[YOUR-APP-BUNDLE-ID].microsoft.maui.essentials.preferences.

Windows Device Secure Storage

DataProtectionProvider is used to encrypt values securely on Windows devices.Encrypted values are stored in ApplicationData.Current.LocalSettings, inside a container with a name of

[YOUR-APP-ID].microsoft.maui.essentials.preferences.

Read Secure Storage

In the above code snippets, you understood the saved the secure storage string value, in the below statement will get the value from existing secure storage.

await SecureStorage.GetAsync("Existing save Key");

Here you don’t have the option to check the key already available or not, but you can check values there or not using strining.IsnullorEmpty.

string securepassword = await SecureStorage.GetAsync("UserPassword");

if(!string.IsNullOrEmpty(securepassword))
{
//Statement
}

Remove Secure Storage

Remove and Remove all will use for dropping the Secure Storage key and value, suppose if you are doing any logout or switching to a different user this will help to clear all the Secure storage from your device.

Remove will give the confirmation with the bool return type, this will help us for navigation after confirmation.

bool isremoved = SecureStorage.Remove("UserPassword");


Suppose, User tries to log out or switch to different users, the best way to use remove all secure storage

SecureStorage.RemoveAll();

IOS Specific Secure Storage Setup

You must follow the below steps for only IOS simulator

Secure Storage Setup for IOS Simulator

I have received this question from many of them, “I want to use Secure Storage on iOS and Android mobile phones and tablets, but I get this error message on iOS simulator but it works well in Android emulator, devices and IOS devices”

SecureStorage requires Entitlements.plist update for iOS

The above issue is common for Xamarin and MAUI, you can follow the below steps will work in IOS simulator.

When developing on the iOS simulator, enable the Keychain entitlement and add a keychain access group for the application's bundle identifier.
Step 1: Create or open the Entitlements.plist in the project and This will automatically add the application's identifier as a group
Step 2: In the project properties, under iOS Bundle Signing set the Custom Entitlements to Entitlements.plist.

Secure Storage plugin not working in ios simulator

Export compliance documentation for encryption, while Uploading AppStore

Complying with Encryption Export Regulations screen when uploading to the apple store, suppose you app makes calls to a web service via HTTPS and MAUI Xamarin Secure Storage to store secure information, in this case, you don’t worry about Encryption export Regulation, as per Apple documentation No documentation required.

Complying with Encryption Export Regulations

If you do the below steps, next time you won’t get the above Dialog wizard.

Add the ITSAppUsesNonExemptEncryption key to your app’s Info.plist file with a Boolean value that indicates whether your app uses encryption. Set the value to NO if your app using only Secure Storage and https API call, next

Is HTTPS exempt from export compliance?

Summary

The Secure Storage class is intended to store small pieces of secure storage information. If you need to locally save and retrieve more complex and structured data, a good option is to use a local database.

Featured Post

Improving C# Performance by Using AsSpan and Avoiding Substring

During development and everyday use, Substring is often the go-to choice for string manipulation. However, there are cases where Substring c...

MSDEVBUILD - English Channel

MSDEVBUILD - Tamil Channel

Popular Posts