You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2.5 KiB

sidebar_position title
2 Changing the data service

In order to take into account the modification of an element, we will first add the following functionalities to our data service:

  • Retrieve an item by its identifier
  • Update an item

Add the methods to the interface

Open the Services/IDataService.cs file and add the highlighted items:

public interface IDataService
{
	Task Add(ItemModel model);

	Task<int> Count();

	Task<List<Item>> List(int currentPage, int pageSize);

// highlight-start
	Task<Item> GetById(int id);
	
	Task Update(int id, ItemModel model);
// highlight-end
}

Add the methods to the implementation

Open the Services/DataLocalService.cs file and add the following methods:

...

public async Task<Item> GetById(int id)
{
	// Get the current data
	var currentData = await _localStorage.GetItemAsync<List<Item>>("data");

	// Get the item int the list
	var item = currentData.FirstOrDefault(w => w.Id == id);

	// Check if item exist
	if (item == null)
	{
		throw new Exception($"Unable to found the item with ID: {id}");
	}

	return item;
}

public async Task Update(int id, ItemModel model)
{
	// Get the current data
	var currentData = await _localStorage.GetItemAsync<List<Item>>("data");

	// Get the item int the list
	var item = currentData.FirstOrDefault(w => w.Id == id);

	// Check if item exist
	if (item == null)
	{
		throw new Exception($"Unable to found the item with ID: {id}");
	}

	// Save the image
	var imagePathInfo = new DirectoryInfo($"{_webHostEnvironment.WebRootPath}/images");

	// Check if the folder "images" exist
	if (!imagePathInfo.Exists)
	{
		imagePathInfo.Create();
	}

	// Delete the previous image
	if (item.Name != model.Name)
	{
		var oldFileName = new FileInfo($"{imagePathInfo}/{item.Name}.png");

		if (oldFileName.Exists)
		{
			File.Delete(oldFileName.FullName);
		}
	}

	// Determine the image name
	var fileName = new FileInfo($"{imagePathInfo}/{model.Name}.png");

	// Write the file content
	await File.WriteAllBytesAsync(fileName.FullName, model.ImageContent);

	// Modify the content of the item
	item.DisplayName = model.DisplayName;
	item.Name = model.Name;
	item.RepairWith = model.RepairWith;
	item.EnchantCategories = model.EnchantCategories;
	item.MaxDurability = model.MaxDurability;
	item.StackSize = model.StackSize;
	item.UpdatedDate = DateTime.Now;

	// Save the data
	await _localStorage.SetItemAsync("data", currentData);
}