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

Chapter 9 Local Data

are different kinds of databases, ranging from relational databases to distributed databases, cloud databases, and NoSQL databases. In this chapter, you will focus on relational and NoSQL databases.

Every application I have ever built has required some form of database, and I suspect that most of the applications that you will build will also require one. A database really provides value when you need to link data together or filter and sort the data in an efficient manner.

In your application, you are going to provide the ability to save a board and return a list of boards that the user has created. To abstract this slightly, you will be using the repository pattern. You will also provide the ability to store where the widgets have been placed so that they will be remembered when a user loads the board back up. Figure 9-1 shows the entity relationship diagram for the database you will be creating.

Figure 9-1.  The entity relationship diagram of your database models

Repository Pattern

The repository pattern allows you to hide all the logic that deals with creating, reading, updating, and deleting (also known as CRUD) entities within your application. By using this pattern, it allows you to keep all the knowledge around how entities are loaded, saved, and more in a single place. This has the added benefit that if you want to completely change where your data is loaded from, you only need to change the implementation inside the repository. It also allows you to provide mock

implementations when wanting to perform things like unit testing and you don’t want to have to rely on an actual database existing.

262

Chapter 9 Local Data

Let’s add a new folder called Data and then add an interface for your repository to that folder called IBoardRepository. Change the code to look as follows:

using WidgetBoard.Models;

namespace WidgetBoard.Data;

public interface IBoardRepository

{

void CreateBoard(Board board);

void CreateBoardWidget(BoardWidget boardWidget);

void DeleteBoard(Board board);

IReadOnlyList<Board> ListBoards();

Board LoadBoard(int boardId);

void UpdateBoard(Board board);

}

Now that you have defined your interface, you can update your application’s codebase to use this interface when loading and saving your boards.

Creating aBoard

The first place to update is your BoardDetailsPageViewModel class, which provides support for creating a new board. Open up the class and make the following modifications.

Add a new IBoardRepository field.

private readonly IBoardRepository boardRepository;

263

Chapter 9 Local Data

Assign a valid instance to the boardRepository field; the modifications are in bold.

public BoardDetailsPageViewModel( ISemanticScreenReader semanticScreenReader, IBoardRepository boardRepository)

{

this.semanticScreenReader = semanticScreenReader; this.boardRepository = boardRepository;

SaveCommand = new Command( () => Save(),

() => !string.IsNullOrWhiteSpace(BoardName));

}

Use the boardRepository field when saving; the modifications are in bold.

private async void Save()

{

var board = new Board

{

Name = BoardName,

NumberOfColumns = NumberOfColumns, NumberOfRows = NumberOfRows

};

this.boardRepository.CreateBoard(board);

semanticScreenReader.Announce($"A new board with the name {BoardName} was created successfully.");

await Shell.Current.GoToAsync( "fixedboard",

264

Chapter 9 Local Data

new Dictionary<string, object>

{

{ "Board", board}

});

}

Listing Your Boards

In the previous chapters, you just added a fixed board and added it to the Boards collection in your AppShellViewModel class. Now you are going to modify it so that it can be populated by the boards the user creates and you store in the database. Open the AppShellViewModel.cs file and make the following changes.

Add a field for your IBoardRepository.

private readonly IBoardRepository boardRepository;

Modify your constructor to use the IBoardRepository as a dependency.

public AppShellViewModel( IBoardRepository boardRepository)

{

this.boardRepository = boardRepository;

}

Load the list of boards and populate your collection.

public void LoadBoards()

{

var boards = this.boardRepository.ListBoards();

foreach (var board in boards)

{

265

Chapter 9 Local Data

Boards.Add(board);

}

}

There is a further change that you need to make in order to allow your AppShellViewModel class to actually load the board. You need to hook into some of the lifecycle events that apply to Pages in .NET MAUI. AppShell inherits from Page, which means you get full access to those lifecycle events. The specific event you care about now is the OnAppearing event. It is called when your page is displayed on screen.

The OnAppearing method can be called multiple times during the lifetime of the page, so it is recommended to make your method idempotent or check whether it has been called before in order to prevent odd behavior when called a second time.

OnAppearing is a great choice for your scenario because it will result in your code being executed every time the view appears; this can be every time your flyout menu is opened. This provides you with the ability to refresh your list of boards every time the user opens the flyout menu. The main reason it is fine for your scenario is because you will be loading data from a local database with a limited number of boards to load, so it will be pretty quick. In scenarios where you are loading from an external webservice, it can take much more time to perform it and therefore

you may wish to maintain some level of caching and prevent calling the webservice every time the view appears. A better option under this

scenario and probably most typical scenarios in .NET MAUI applications is to use the OnNavigatedTo method.

Let’s open your AppShell.xaml.cs file and make use of this lifecycle method.

protected override void OnAppearing()

266

Chapter 9 Local Data

{

base.OnAppearing();

((AppShellViewModel)BindingContext).LoadBoards();

}

When the method gets called, you use the newly added LoadBoards method on your view model. The main reason you hook into this lifecycle event is when you eventually try to navigate to the last used board in the LoadBoards method, you need to make sure the application has started rendering; otherwise the navigation will fail.

Loading aBoard

Up until this point you have relied on passing the Board into the FixedBoardPageViewModel and displaying the details of that. The loading process would become rather inefficient if you were to load all boards and the associated BoardWidgets when listing all boards in the system, so you need to do this in a two-step process: first, list the boards as you did in the previous section and, second, load the board in the view model. This will be a slightly involved process so let’s walk through it step-by-step. Open the FixedBoardPageViewModel.cs file and make the following changes

Add the following fields to store the board that is loaded and the repository to perform the load:

private Board board;

private readonly IBoardRepository boardRepository;

In your constructor, add the board repository dependency and assign to the newly created field. Changes are in bold.

public FixedBoardPageViewModel( WidgetTemplateSelector widgetTemplateSelector, WidgetFactory widgetFactory,

267

Chapter 9 Local Data

IBoardRepository boardRepository)

{

WidgetTemplateSelector = widgetTemplateSelector; this.widgetFactory = widgetFactory; this.boardRepository = boardRepository;

Widgets = new ObservableCollection<IWidgetViewModel>();

AddWidgetCommand = new Command(OnAddWidget);

AddNewWidgetCommand = new Command<int>(index =>

{

IsAddingWidget = true; addingPosition = index;

});

}

Now let’s load the Board inside your ApplyQueryAttributes method. The changes are in bold.

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

{

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

board = boardRepository.LoadBoard(boardParameter.Id);

BoardName = board.Name;

NumberOfColumns = board.NumberOfColumns;

NumberOfRows = board.NumberOfRows;

foreach (var boardWidget in board.BoardWidgets)

{

268

Chapter 9 Local Data

var widgetViewModel = widgetFactory.CreateWidgetViewMod el(boardWidget.WidgetType);

widgetViewModel.Position = boardWidget.Position;

Widgets.Add(widgetViewModel);

}

}

Next, add the ability to save a widget’s position on the board.

private void SaveWidget(IWidgetViewModel widgetViewModel)

{

var boardWidget = new BoardWidget

{

BoardId = board.Id,

Position = widgetViewModel.Position, WidgetType = widgetViewModel.Type

};

boardRepository.CreateBoardWidget(boardWidget);

}

The above method will create a new BoardWidget model class and save it into the database for you.

Finally, you need to call the SaveWidget method. For the purpose of your application, you are going to provide an auto save feature, so each time a widget is added to the board, you will save it immediately to the database. In order to achieve this, you just need to add the bold line into your AddWidget method.

private void OnAddWidget()

{

if (SelectedWidget is null)

269