SBI.Maui.Tools
1.0.7
dotnet add package SBI.Maui.Tools --version 1.0.7
NuGet\Install-Package SBI.Maui.Tools -Version 1.0.7
<PackageReference Include="SBI.Maui.Tools" Version="1.0.7" />
<PackageVersion Include="SBI.Maui.Tools" Version="1.0.7" />
<PackageReference Include="SBI.Maui.Tools" />
paket add SBI.Maui.Tools --version 1.0.7
#r "nuget: SBI.Maui.Tools, 1.0.7"
#:package SBI.Maui.Tools@1.0.7
#addin nuget:?package=SBI.Maui.Tools&version=1.0.7
#tool nuget:?package=SBI.Maui.Tools&version=1.0.7
Maui.Tools
Maui.Tools is a comprehensive library designed for .NET MAUI applications, developed by SBI-TECHNOLOGY. It provides essential services for managing API interactions, user notifications, image processing, and more. With a focus on simplicity, reusability, and robust error handling, this library streamlines the development of applications that require seamless communication with web services.
Installation
Use the package manager console to install.
dotnet add package SBI.Maui.Tools --version 1.0.0
Initialization
Create the Logger class implementing the interface "Maui.Tools.Infrastructure.ILogger".
namespace Example.App.Logs
{
public class Logger : Maui.Tools.Infrastructure.ILogger
{
public void LogError(Exception exception)
{
Debug.Write("--------------------- ERROR ---------------------");
Debug.Write(exception.Message);
Debug.Write(exception.StackTrace);
}
public void LogInfo(string message)
{
Debug.Write(message);
}
}
}
Initialize the library in "MauiProgram.cs" by sending the API URL, and using the Logger class created above. If it is not necessary, an empty string can be sent.
builder.Services.MauiToolsInit<Logs.Logger>("https://sbi-technology.development/api");
Usage
ViewModels
You can extend "Maui.Tools.ViewModels.ViewModelBase" and use the following features:
- Navigation
- Loading popup for asynchronous invocations
... and the following properties:
- CurrentPage: represents the current page (the one from which the navigation is , initiated).
- Title: title to be show in Page.
- IsBusy: indicates whether a long-running operation is currently in progress. When true, it typically means the UI should show some loading indicator, and user interactions might be disabled.
- IsRefreshing: similar to IsBusy, this property usually indicates that data is being refreshed, often used in scenarios like pull-to-refresh in lists.
Implementation
You must inject "Maui.Tools.Services.Navigation.INavigationService" and "Maui.Tools.Infrastructure.ILogger".
public partial class MainPageViewModel(
INavigationService navigationService,
ILogger logger) : ViewModelBase(navigationService, logger)
{ }
Services
These services collectively provide a foundation for building mobile applications with intuitive user interactions and robust functionality. By centralizing operations such as permission management, location access, and navigation, we can maintain cleaner code and enhance maintainability.
Api Service
The ApiService class provides a robust and flexible foundation for making HTTP requests within your application. It extends the HttpClientService, offering a structured way to handle API interactions while incorporating logging and timeout management. This service is designed to simplify the communication with RESTful APIs and ensure efficient error handling and response logging. It also has support for JWT login with AccessToken and RefreshToken, sending the token and trying to do a RefreshToken if possible. This service is ideal for applications that require reliable communication with web services. By centralizing API interactions, it promotes code reusability and simplifies the process of making HTTP requests.
How to use it
As ApiService instance is injected by MAUI.Tools, we can use it like an httpClient instance. Below is an example of a class UsersService that handles HTTP requests to fetch a list of users from a given API.
public partial class UsersService(
ApiService httpService
) : IUsersService
{
private readonly ApiService httpService = httpService;
public async Task<IEnumerable<User>> Get(GetAllUsersRequest request)
{
var response = await httpService.GetAsync<BaseRequest, Response<GetAllUsersResponse>>(request, $"/Endpoint/Name/And/Params");
if (response.Status)
{
// Handle successful response
return response.ObjectResponse.Users; // Adjust according to your response structure
} else
{
// Handle error response
return Enumerable.Empty<User>(); // Return an empty list or handle as needed
}
}
}
You can also use the Notification Service to throw an alert to give a feedback to the user. Here is the example code:
public partial class UsersService(
ApiService httpService,
INotificationService notificationService
) : IUsersService
{
private readonly ApiService httpService = httpService;
private readonly INotificationService notificationService = notificationService;
public async Task<IEnumerable<User>> Get(GetAllUsersRequest request)
{
var response = await httpService.GetAsync<BaseRequest, Response<GetAllUsersResponse>>(request, $"/Endpoint/Name/And/Params");
if (response.Status)
{
// Handle successful response
return response.ObjectResponse.Users; // Adjust according to your response structure
} else
{
// Handle error response
await notificationService.ShowAlert(response.Message); // Example error handling
return Enumerable.Empty<User>(); // Return an empty list or handle as needed
}
}
}
NOTE: API URL is set in initialization.
Image Service
The ImageService class provides functionality for image manipulation, specifically for converting and compressing images into a Base64 string format. This service is designed to handle image processing tasks seamlessly within your application, leveraging the capabilities of the Microsoft Maui graphics library and SkiaSharp for efficient image handling.
How to use it
You can utilize the ImageService within your application to convert and compress images as needed. Below is an example of how to use this service.
public partial class SomeViewModel(
INavigationService navigationService,
ILogger logger,
IImageService imageService,
) : ViewModelBase(navigationService, logger)
{
private readonly IImageService imageService = imageService;
public async Task<string> ProcessImageAsync(string base64Image)
{
await LoadingAsync(async () =>
{
var compressedImage = imageService.ConvertAndCompressImageToBase64StringAsync(base64Image));
if (compressedImage != null)
{
// Handle the compressed image (e.g., save to server, display in UI, etc.)
return compressedImage;
}
// Handle the case where compression failed
return null;
}
}
}
Location Service
The LocationService class provides a reliable interface for retrieving the user's current geographical location within a mobile application. It implements the ILocationService interface, ensuring a structured approach to location services while handling errors and logging effectively.
How to use it
You can utilize the LocationService to access the user's location as shown in the following example:
public partial class SomeViewModel(
INavigationService navigationService,
ILogger logger,
ILocationService locationService,
) : ViewModelBase(navigationService, logger)
{
private readonly ILocationService locationService = locationService;
public async Task<Microsoft.Maui.Devices.Sensors.Location> RetrieveUserLocationAsync()
{
var location = await locationService.GetUserLocation();
if (location != null)
{
// Use the retrieved location (e.g., display on a map, send to a server, etc.)
return location;
}
// Handle the case where the location could not be retrieved
return null;
}
}
Navigation Service
The NavigationService class manages application navigation, providing a clean and efficient way to transition between pages in the application. It implements navigation locking to prevent multiple taps from triggering repeated navigations, ensuring a smooth user experience. The service supports both parameterized and standard navigation, facilitating complex routing scenarios. The NavigationService class provides methods for navigating to and from pages with optional parameters, handling of navigation states to avoid conflicts from rapid user actions and support for openning and closing popups using the MopupService.
How to use it
public partial class SomeViewModel(
INavigationService navigationService,
ILogger logger,
) : ViewModelBase(navigationService, logger)
{
[RelayCommand]
private async void NavigateToNewPage() {
navigationService.GoTo(nameof(NewPage),
new NavigationParameter() { Name = nameof(NewPageViewModel.MyPropName), Value = MyPropValue });
}
}
Remember to add the [QueryProperty] attribute in the View Model if you are passing props.
You can also use the NavigationService to open a PopUp and subscribe/unsubscribe to an event handler, in case you need to handle a PopUp response. Here is an example:
public partial class SomeViewModel(
INavigationService navigationService,
ILogger logger,
) : ViewModelBase(navigationService, logger)
{
[RelayCommand]
private async void NavigateToPopUpPage() {
navigationService.SubscribeToResult(HandleYourPopUpResult);
await navigationService.OpenPopup(CustomPopUpPage);
}
private void HandleYourPopUpResult(object result) {
// do something with result
navigationService.UnsubscribeToResult();
}
}
You have to remember to unsubscribe the event handler to avoid repeated executions on navigation results.
Notification Service
The NotificationService class provides a simple and efficient way to display alerts and notifications within your application. Implementing the INotificationService interface, this service utilizes the Mopup library to present modal alert dialogs to the user, ensuring a smooth user experience. Using NotificationService you can easily display alert messages to users with a single method call. It is designed to work seamslessly with asynchronous programming, ensuring non-blocking UI updates. It also leverages the Mopup NuGet for clean and customizable alert presentations.
How to use it
public partial class SomeFormViewModel(
INavigationService navigationService,
ILogger logger,
INotificationService notificationService
) : ViewModelBase(navigationService, logger)
{
private readonly INotificationService notificationService = notificationService;
[RelayCommand]
private async void SendForm() {
if (Form.hasErrors) {
await notificationService.ShowAlert("Show form errors or custom error message");
return;
}
// do something if there are no errors
}
}
Permission Service
The PermissionService class is a straightforward implementation of a service that handles permission requests. It utilizes generics to support various types of permissions, ensuring that users are prompted to grant necessary access for the app's functionality. By encapsulating permission requests, this service enhances user experience by handling permission checks and displaying informative alerts when permissions are denied.
How to use it
Here is an example of how to use the PermissionService to request camera permissions.
public partial class SomeViewModel(
INavigationService navigationService,
ILogger logger,
IPermissionService permissionService
) : ViewModelBase(navigationService, logger)
{
private readonly INotificationService notificationService = notificationService;
[RelayCommand]
private async void OpenCamera() {
var hasCameraPermissions = await permissionService.HavePermission<Permissions.Camera>();
if (!hasCameraPermissions) {
// handle permissions or show error message
return;
}
// continue opening camera
}
}
Utilities
MAUI.Tools includes a set of utility classes designed to simplify common tasks in .NET MAUI applications. These utilities enhance the development experience by providing reusable methods for email validation, error message handling, and browser interaction.
EmailValidator
The EmailValidator class provides a straightforward method to validate email addresses using a regular expression. This utility ensures that email inputs conform to standard formats, helping to maintain data integrity in your applications.
Usage Example:
In your View Model
var isValid = EmailValidator.IsEmailValid(YourEmailProp);
OpenInBrowser
The OpenInBrowser method allows you to open a specified URL in the user's default web browser. It handles exceptions gracefully, providing feedback to the user if something goes wrong.
Usage Example:
In your View Model
private void OpenInBrowser() {
Utils.OpenInBrowser("https://www.example.com");
// This will attempt to open the URL and display an alert if it fails.
}
Authors
![]()
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-android34.0 is compatible. net8.0-browser was computed. net8.0-ios was computed. net8.0-ios18.0 is compatible. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.0
- CommunityToolkit.Mvvm (>= 8.3.2)
- Microsoft.AppCenter (>= 5.0.5)
- Microsoft.AppCenter.Crashes (>= 5.0.5)
- Mopups (>= 1.3.1)
- Newtonsoft.Json (>= 13.0.3)
- Polly (>= 8.4.1)
- SkiaSharp (>= 2.88.8)
- SkiaSharp.Views (>= 2.88.8)
-
net8.0-android34.0
- CommunityToolkit.Mvvm (>= 8.3.2)
- Microsoft.AppCenter (>= 5.0.5)
- Microsoft.AppCenter.Crashes (>= 5.0.5)
- Mopups (>= 1.3.1)
- Newtonsoft.Json (>= 13.0.3)
- Polly (>= 8.4.1)
- SkiaSharp (>= 2.88.8)
- SkiaSharp.Views (>= 2.88.8)
-
net8.0-ios18.0
- CommunityToolkit.Mvvm (>= 8.3.2)
- Microsoft.AppCenter (>= 5.0.5)
- Microsoft.AppCenter.Crashes (>= 5.0.5)
- Mopups (>= 1.3.1)
- Newtonsoft.Json (>= 13.0.3)
- Polly (>= 8.4.1)
- SkiaSharp (>= 2.88.8)
- SkiaSharp.Views (>= 2.88.8)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|