Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
lawrence_shaun_introducing_net_maui_build_and_deploy_crosspl.pdf
Скачиваний:
46
Добавлен:
26.06.2023
Размер:
5.15 Mб
Скачать

Chapter 9 Local Data

Database Summary

There is an abundance of options when it comes to choosing not only which database but then also the ORM layer on top of it. The aim of this section is to give a taste of what some options offer and to encourage you to decide which will benefit your application and team most.

Both options I covered provide support for encryption.

I strongly encourage you to evaluate which database will provide you with the best development experience and the users of your application with the best user experience. Some databases perform better in different scenarios.

Moving forward with this application you will continue to use LiteDB.

Application Settings (Preferences)

Quite often you will want to persist data about your application that you really do not need a database for. I like to refer to these bits of data as application settings. If you have previous experience with building .NET applications, this would be similar to an app.config or appsettings.json file. The .NET MAUI term is Preferences, though, and this is the API that you will look at accessing.

An item in Preferences is stored as a key-value pair. The key is a string and it is recommended to keep the name short in length.

As with all of the other APIs provided by .NET MAUI, you register the Preferences implementation with the app builder in the MauiProgram.cs file. You can add the following line into the CreateMauiApp method:

builder.Services.AddSingleton(Preferences.Default);

285

Chapter 9 Local Data

What Can Be Stored in Preferences?

There is a limitation on the type of data that can be stored in Preferences. The API provides the ability to store the following .NET types:

•\ Boolean

•\ Double

•\ Int32

•\ Single

•\ Int64

•\ String

•\ DateTime

Having the ability to provide a String value surely means you could in theory store anything in there, right? While this is technically possible it is highly recommended that you only store small amounts of text.

Otherwise the performance of storing and retrieval can be impacted in your applications.

Setting a Value in Preferences

You can store a value in Preferences through the use of the Set method. You can provide a key, the value, and also an optional sharedName. The preferences stored in your application are only visible to that application. You can also create a shared preference that can be used by other extensions or a watch application.

A perfect use case for your application is to store the id of the last accessed board and open it the next time the application loads. Let’s store the id initially. Inside your FixedBoardPageViewModel class you can make the following changes.

Add the preferences field.

286

Chapter 9 Local Data

private readonly IPreferences preferences;

Update the constructor to set the preferences field; changes in bold.

public FixedBoardPageViewModel( WidgetTemplateSelector widgetTemplateSelector, IPreferences preferences)

{

WidgetTemplateSelector = widgetTemplateSelector; this.preferences = preferences;

Widgets = new ObservableCollection<IWidgetViewModel>();

}

Finally, record the id of the board that was supplied when navigating to the page. You can do this by adding the bold line to your

ApplyQueryAttributes method:

public void ApplyQueryAttributes(IDictionary<string, object> query)

{

var board = query["Board"] as Board;

preferences.Set("LastUsedBoardId", board.Id);

BoardName = board.Name;

NumberOfColumns = board.NumberOfColumns; NumberOfRows = board.NumberOfRows;

}

This means that every time a user opens a board to view it, the id will be remembered in Preferences. When the application is opened again in the future, it will use that id to open the last viewed board.

287

Chapter 9 Local Data

A possible alternative way of achieving this type of functionality could be to maintain a last opened column in the database and always find the latest of that set.

Getting a Value in Preferences

You can retrieve a value from Preferences using the Get method. You are required to supply the key identifying the setting and a default value to be returned if the key does not exist. You can optionally provide a sharedName, much like with the Set method covered in the previous section.

You have already written the code to store your LastUsedBoardId in Preferences so let’s read it back when loading your boards up to display. Open up your AppShellViewModel.cs file and make the following changes

Add the preferences field.

private readonly IPreferences preferences;

Set the preferences field in the constructor; changes in bold.

public AppShellViewModel( IBoardRepository boardRepository,

IPreferences preferences)

{

this.boardRepository = boardRepository; this.preferences = preferences;

}

Update your LoadBoards method to support navigating to the last used board; changes in bold.

public void LoadBoards()

{

var boards = this.boardRepository.ListBoards();

288

Chapter 9 Local Data

var lastUsedBoardId = preferences. Get("LastUsedBoardId", -1);

Board lastUsedBoard = null;

foreach (var board in boards)

{

Boards.Add(board);

if (lastUsedBoardId == board.Id)

{

lastUsedBoard = board;

}

}

if (lastUsedBoard is not null)

{

Dispatcher.GetForCurrentThread().Dispatch(() =>

{

BoardSelected(lastUsedBoard);

});

}

}

There are a few new concepts here, so let’s break them down in to understandable chunks.

Use of the preferences.Get method, as you learned about before writing the above code. You supply the key name and the default value to be returned if the key does not exist. You use -1 for the default because it is not a valid id for a database key.

The final new concept is the use of Dispatcher. This allows you to trigger a deferred action and make sure that it is dispatched onto the UI thread. Your method will be called on the UI thread, but you want the OnAppearing logic to finish before you attempt to navigate somewhere, by

289