diff --git a/BlazorTp1/App.razor b/BlazorTp1/App.razor index 6fd3ed1..36bc2e6 100644 --- a/BlazorTp1/App.razor +++ b/BlazorTp1/App.razor @@ -1,12 +1,14 @@ - - - - - - - Not found - -

Sorry, there's nothing at this address.

-
-
-
+ + + + + + + + Not found + +

Sorry, there's nothing at this address.

+
+
+
+
diff --git a/BlazorTp1/BlazorTp1.csproj b/BlazorTp1/BlazorTp1.csproj index c0eacf6..2b73896 100644 --- a/BlazorTp1/BlazorTp1.csproj +++ b/BlazorTp1/BlazorTp1.csproj @@ -6,11 +6,18 @@ enable + + + + + + + diff --git a/BlazorTp1/Components/Card.razor b/BlazorTp1/Components/Card.razor new file mode 100644 index 0000000..00d680f --- /dev/null +++ b/BlazorTp1/Components/Card.razor @@ -0,0 +1,6 @@ +@typeparam TItem +
+ @CardHeader(Item) + @CardBody(Item) + @CardFooter +
diff --git a/BlazorTp1/Components/Card.razor.cs b/BlazorTp1/Components/Card.razor.cs new file mode 100644 index 0000000..03dc91e --- /dev/null +++ b/BlazorTp1/Components/Card.razor.cs @@ -0,0 +1,21 @@ +using Blazorise; +using BlazorTp1.Models; +using Microsoft.AspNetCore.Components; + +namespace BlazorTp1.Components +{ + public partial class Card + { + [Parameter] + public RenderFragment CardBody { get; set; } + + [Parameter] + public RenderFragment CardFooter { get; set; } + + [Parameter] + public RenderFragment CardHeader { get; set; } + + [Parameter] + public TItem Item { get; set; } + } +} diff --git a/BlazorTp1/Components/Crafting.razor b/BlazorTp1/Components/Crafting.razor new file mode 100644 index 0000000..97b8a76 --- /dev/null +++ b/BlazorTp1/Components/Crafting.razor @@ -0,0 +1,50 @@ + +
+
+
+ +
Available items:
+
+
+ + @foreach (var item in Items) + { + + } +
+
+ +
+ +
+
Recipe
+ +
+ +
+ + + + + + + + + +
+
+ +
Result
+
+ +
+
+
+
Actions
+
+ +
+
+
+
+
diff --git a/BlazorTp1/Components/Crafting.razor.cs b/BlazorTp1/Components/Crafting.razor.cs new file mode 100644 index 0000000..4282903 --- /dev/null +++ b/BlazorTp1/Components/Crafting.razor.cs @@ -0,0 +1,81 @@ +using BlazorTp1.Models; +using Microsoft.AspNetCore.Components; +using Microsoft.JSInterop; +using System.Collections.ObjectModel; +using System.Collections.Specialized; + +namespace BlazorTp1.Components +{ + public partial class Crafting + { + private Item _recipeResult; + + public Crafting() + { + Actions = new ObservableCollection(); + Actions.CollectionChanged += OnActionsCollectionChanged; + this.RecipeItems = new List { null, null, null, null, null, null, null, null, null }; + } + + public ObservableCollection Actions { get; set; } + public Item CurrentDragItem { get; set; } + + [Parameter] + public List Items { get; set; } + + public List RecipeItems { get; set; } + + public Item RecipeResult + { + get => this._recipeResult; + set + { + if (this._recipeResult == value) + { + return; + } + + this._recipeResult = value; + this.StateHasChanged(); + } + } + + [Parameter] + public List Recipes { get; set; } + + /// + /// Gets or sets the java script runtime. + /// + [Inject] + internal IJSRuntime JavaScriptRuntime { get; set; } + + public void CheckRecipe() + { + RecipeResult = null; + + // Get the current model + var currentModel = string.Join("|", this.RecipeItems.Select(s => s != null ? s.Name : string.Empty)); + + this.Actions.Add(new CraftingAction { Action = $"Items : {currentModel}" }); + + foreach (var craftingRecipe in Recipes) + { + // Get the recipe model + var recipeModel = string.Join("|", craftingRecipe.Have.SelectMany(s => s)); + + this.Actions.Add(new CraftingAction { Action = $"Recipe model : {recipeModel}" }); + + if (currentModel == recipeModel) + { + RecipeResult = craftingRecipe.Give; + } + } + } + + private void OnActionsCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) + { + JavaScriptRuntime.InvokeVoidAsync("Crafting.AddActions", e.NewItems); + } + } +} + diff --git a/BlazorTp1/Components/Crafting.razor.css b/BlazorTp1/Components/Crafting.razor.css new file mode 100644 index 0000000..2a388f2 --- /dev/null +++ b/BlazorTp1/Components/Crafting.razor.css @@ -0,0 +1,19 @@ +.css-grid { + grid-template-columns: repeat(4,minmax(0,1fr)); + gap: 10px; + display: grid; + width: 286px; +} + +.css-recipe { + grid-template-columns: repeat(3,minmax(0,1fr)); + gap: 10px; + display: grid; + width: 212px; +} + +.actions { + border: 1px solid black; + height: 250px; + overflow: scroll; +} diff --git a/BlazorTp1/Components/Crafting.razor.js b/BlazorTp1/Components/Crafting.razor.js new file mode 100644 index 0000000..8fdb58e --- /dev/null +++ b/BlazorTp1/Components/Crafting.razor.js @@ -0,0 +1,16 @@ +window.Crafting = +{ + AddActions: function (data) { + + data.forEach(element => { + var div = document.createElement('div'); + div.innerHTML = 'Action: ' + element.action + ' - Index: ' + element.index; + + if (element.item) { + div.innerHTML += ' - Item Name: ' + element.item.name; + } + + document.getElementById('actions').appendChild(div); + }); + } +} \ No newline at end of file diff --git a/BlazorTp1/Components/CraftingAction.cs b/BlazorTp1/Components/CraftingAction.cs new file mode 100644 index 0000000..f682f85 --- /dev/null +++ b/BlazorTp1/Components/CraftingAction.cs @@ -0,0 +1,11 @@ +using BlazorTp1.Models; + +namespace BlazorTp1.Components +{ + public class CraftingAction + { + public string Action { get; set; } + public int Index { get; set; } + public Item Item { get; set; } + } +} diff --git a/BlazorTp1/Components/CraftingItem.razor b/BlazorTp1/Components/CraftingItem.razor new file mode 100644 index 0000000..3e488b6 --- /dev/null +++ b/BlazorTp1/Components/CraftingItem.razor @@ -0,0 +1,14 @@ +
+ + @if (Item != null) + { + @Item.DisplayName + } +
diff --git a/BlazorTp1/Components/CraftingItem.razor.cs b/BlazorTp1/Components/CraftingItem.razor.cs new file mode 100644 index 0000000..e4d225b --- /dev/null +++ b/BlazorTp1/Components/CraftingItem.razor.cs @@ -0,0 +1,64 @@ +using Blazorise; +using BlazorTp1.Models; +using Microsoft.AspNetCore.Components; + +namespace BlazorTp1.Components +{ + public partial class CraftingItem + { + [Parameter] + public int Index { get; set; } + + [Parameter] + public Item Item { get; set; } + + [Parameter] + public bool NoDrop { get; set; } + + [CascadingParameter] + public Crafting Parent { get; set; } + + internal void OnDragEnter() + { + if (NoDrop) + { + return; + } + + Parent.Actions.Add(new CraftingAction { Action = "Drag Enter", Item = this.Item, Index = this.Index }); + } + + internal void OnDragLeave() + { + if (NoDrop) + { + return; + } + + Parent.Actions.Add(new CraftingAction { Action = "Drag Leave", Item = this.Item, Index = this.Index }); + } + + internal void OnDrop() + { + if (NoDrop) + { + return; + } + + this.Item = Parent.CurrentDragItem; + Parent.RecipeItems[this.Index] = this.Item; + + Parent.Actions.Add(new CraftingAction { Action = "Drop", Item = this.Item, Index = this.Index }); + + // Check recipe + Parent.CheckRecipe(); + } + + private void OnDragStart() + { + Parent.CurrentDragItem = this.Item; + + Parent.Actions.Add(new CraftingAction { Action = "Drag Start", Item = this.Item, Index = this.Index }); + } + } +} diff --git a/BlazorTp1/Components/CraftingItem.razor.css b/BlazorTp1/Components/CraftingItem.razor.css new file mode 100644 index 0000000..b2d4521 --- /dev/null +++ b/BlazorTp1/Components/CraftingItem.razor.css @@ -0,0 +1,6 @@ +.item { + width: 64px; + height: 64px; + border: 1px solid; + overflow: hidden; +} diff --git a/BlazorTp1/Components/CraftingRecipe.cs b/BlazorTp1/Components/CraftingRecipe.cs new file mode 100644 index 0000000..2da1ed1 --- /dev/null +++ b/BlazorTp1/Components/CraftingRecipe.cs @@ -0,0 +1,10 @@ +using BlazorTp1.Models; + +namespace BlazorTp1.Components +{ + public class CraftingRecipe + { + public Item Give { get; set; } + public List> Have { get; set; } + } +} diff --git a/BlazorTp1/Components/ShowItems.razor b/BlazorTp1/Components/ShowItems.razor new file mode 100644 index 0000000..7739061 --- /dev/null +++ b/BlazorTp1/Components/ShowItems.razor @@ -0,0 +1,12 @@ +@typeparam TItem + +
+ @if ((Items?.Count ?? 0) != 0) + { + @foreach (var item in Items) + { + @ShowTemplate(item) + ; + } + } +
\ No newline at end of file diff --git a/BlazorTp1/Components/ShowItems.razor.cs b/BlazorTp1/Components/ShowItems.razor.cs new file mode 100644 index 0000000..a452fcc --- /dev/null +++ b/BlazorTp1/Components/ShowItems.razor.cs @@ -0,0 +1,13 @@ +using Microsoft.AspNetCore.Components; + +namespace BlazorTp1.Components +{ + public partial class ShowItems + { + [Parameter] + public List Items { get; set; } + + [Parameter] + public RenderFragment ShowTemplate { get; set; } + } +} diff --git a/BlazorTp1/Controllers/CultureController.cs b/BlazorTp1/Controllers/CultureController.cs new file mode 100644 index 0000000..328c28e --- /dev/null +++ b/BlazorTp1/Controllers/CultureController.cs @@ -0,0 +1,31 @@ +using Microsoft.AspNetCore.Localization; +using Microsoft.AspNetCore.Mvc; + +/// +/// The culture controller. +/// +[Route("[controller]/[action]")] +public class CultureController : Controller +{ + /// + /// Sets the culture. + /// + /// The culture. + /// The redirect URI. + /// + /// The action result. + /// + public IActionResult SetCulture(string culture, string redirectUri) + { + if (culture != null) + { + // Define a cookie with the selected culture + this.HttpContext.Response.Cookies.Append( + CookieRequestCultureProvider.DefaultCookieName, + CookieRequestCultureProvider.MakeCookieValue( + new RequestCulture(culture))); + } + + return this.LocalRedirect(redirectUri); + } +} \ No newline at end of file diff --git a/BlazorTp1/Factories/ItemFactory.cs b/BlazorTp1/Factories/ItemFactory.cs new file mode 100644 index 0000000..8a87eb4 --- /dev/null +++ b/BlazorTp1/Factories/ItemFactory.cs @@ -0,0 +1,51 @@ +using BlazorTp1.Models; + +namespace BlazorTp1.Factories +{ + public static class ItemFactory + { + public static ItemModel ToModel(Item item, byte[] imageContent) + { + return new ItemModel + { + Id = item.Id, + DisplayName = item.DisplayName, + Name = item.Name, + RepairWith = item.RepairWith, + EnchantCategories = item.EnchantCategories, + MaxDurability = item.MaxDurability, + StackSize = item.StackSize, + ImageContent = imageContent, + ImageBase64 = string.IsNullOrWhiteSpace(item.ImageBase64) ? Convert.ToBase64String(imageContent) : item.ImageBase64 + }; + } + + public static Item Create(ItemModel model) + { + return new Item + { + Id = model.Id, + DisplayName = model.DisplayName, + Name = model.Name, + RepairWith = model.RepairWith, + EnchantCategories = model.EnchantCategories, + MaxDurability = model.MaxDurability, + StackSize = model.StackSize, + CreatedDate = DateTime.Now, + ImageBase64 = Convert.ToBase64String(model.ImageContent) + }; + } + + public static void Update(Item item, ItemModel model) + { + 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; + item.ImageBase64 = Convert.ToBase64String(model.ImageContent); + } + } +} diff --git a/BlazorTp1/Modals/DeleteConfirmation.razor b/BlazorTp1/Modals/DeleteConfirmation.razor new file mode 100644 index 0000000..6435118 --- /dev/null +++ b/BlazorTp1/Modals/DeleteConfirmation.razor @@ -0,0 +1,12 @@ +

DeleteConfirmation

+ +
+ +

+ Are you sure you want to delete @item.DisplayName ? +

+ + + + +
diff --git a/BlazorTp1/Modals/DeleteConfirmation.razor.cs b/BlazorTp1/Modals/DeleteConfirmation.razor.cs new file mode 100644 index 0000000..1b4c6e7 --- /dev/null +++ b/BlazorTp1/Modals/DeleteConfirmation.razor.cs @@ -0,0 +1,37 @@ +using Blazored.Modal.Services; +using Blazored.Modal; +using BlazorTp1.Models; +using Microsoft.AspNetCore.Components; + +namespace BlazorTp1.Modals +{ + public partial class DeleteConfirmation + { + [CascadingParameter] + public BlazoredModalInstance ModalInstance { get; set; } + + [Inject] + public IDataService DataService { get; set; } + + [Parameter] + public int Id { get; set; } + + private Item item = new Item(); + + protected override async Task OnInitializedAsync() + { + // Get the item + item = await DataService.GetById(Id); + } + + void ConfirmDelete() + { + ModalInstance.CloseAsync(ModalResult.Ok(true)); + } + + void Cancel() + { + ModalInstance.CancelAsync(); + } + } +} diff --git a/BlazorTp1/Models/Item.cs b/BlazorTp1/Models/Item.cs index e697f5a..2ca8525 100644 --- a/BlazorTp1/Models/Item.cs +++ b/BlazorTp1/Models/Item.cs @@ -11,5 +11,6 @@ public List RepairWith { get; set; } public DateTime CreatedDate { get; set; } public DateTime? UpdatedDate { get; set; } + public string ImageBase64 { get; set; } } } diff --git a/BlazorTp1/Models/ItemModel.cs b/BlazorTp1/Models/ItemModel.cs index cf93333..7790cc2 100644 --- a/BlazorTp1/Models/ItemModel.cs +++ b/BlazorTp1/Models/ItemModel.cs @@ -33,5 +33,6 @@ namespace BlazorTp1.Models [Required(ErrorMessage = "The image of the item is mandatory!")] public byte[] ImageContent { get; set; } + public string ImageBase64 { get; set; } } } diff --git a/BlazorTp1/Pages/Add.razor.cs b/BlazorTp1/Pages/Add.razor.cs index 794e331..fc1fdf9 100644 --- a/BlazorTp1/Pages/Add.razor.cs +++ b/BlazorTp1/Pages/Add.razor.cs @@ -7,25 +7,11 @@ namespace BlazorTp1.Pages { public partial class Add { - [Inject] - public ILocalStorageService LocalStorage { get; set; } - - [Inject] - public NavigationManager NavigationManager { get; set; } - - [Inject] - public IWebHostEnvironment WebHostEnvironment { get; set; } - /// /// The default enchant categories. /// private List enchantCategories = new List() { "armor", "armor_head", "armor_chest", "weapon", "digger", "breakable", "vanishable" }; - /// - /// The default repair with. - /// - private List repairWith = new List() { "oak_planks", "spruce_planks", "birch_planks", "jungle_planks", "acacia_planks", "dark_oak_planks", "crimson_planks", "warped_planks" }; - /// /// The current item model /// @@ -35,44 +21,20 @@ namespace BlazorTp1.Pages RepairWith = new List() }; - private async void HandleValidSubmit() - { - // Get the current data - var currentData = await LocalStorage.GetItemAsync>("data"); - - // Simulate the Id - itemModel.Id = currentData.Max(s => s.Id) + 1; - - // Add the item to the current data - currentData.Add(new Item - { - Id = itemModel.Id, - DisplayName = itemModel.DisplayName, - Name = itemModel.Name, - RepairWith = itemModel.RepairWith, - EnchantCategories = itemModel.EnchantCategories, - MaxDurability = itemModel.MaxDurability, - StackSize = itemModel.StackSize, - CreatedDate = DateTime.Now - }); - - // Save the image - var imagePathInfo = new DirectoryInfo($"{WebHostEnvironment.WebRootPath}/images"); - - // Check if the folder "images" exist - if (!imagePathInfo.Exists) - { - imagePathInfo.Create(); - } + /// + /// The default repair with. + /// + private List repairWith = new List() { "oak_planks", "spruce_planks", "birch_planks", "jungle_planks", "acacia_planks", "dark_oak_planks", "crimson_planks", "warped_planks" }; - // Determine the image name - var fileName = new FileInfo($"{imagePathInfo}/{itemModel.Name}.png"); + [Inject] + public IDataService DataService { get; set; } - // Write the file content - await File.WriteAllBytesAsync(fileName.FullName, itemModel.ImageContent); + [Inject] + public NavigationManager NavigationManager { get; set; } - // Save the data - await LocalStorage.SetItemAsync("data", currentData); + private async void HandleValidSubmit() + { + await DataService.Add(itemModel); NavigationManager.NavigateTo("list"); } diff --git a/BlazorTp1/Pages/Edit.razor b/BlazorTp1/Pages/Edit.razor new file mode 100644 index 0000000..28c1f8f --- /dev/null +++ b/BlazorTp1/Pages/Edit.razor @@ -0,0 +1,88 @@ +@page "/edit/{Id:int}" + +

Edit

+ + + + + +

+ +

+

+ +

+

+ +

+

+ +

+

+ Enchant categories: +

+ @foreach (var item in enchantCategories) + { + + } +
+

+

+ Repair with: +

+ @foreach (var item in repairWith) + { + + } +
+

+

+ +

+

+ +

+

+ +

+

+ +

+ + +
diff --git a/BlazorTp1/Pages/Edit.razor.cs b/BlazorTp1/Pages/Edit.razor.cs new file mode 100644 index 0000000..1267de9 --- /dev/null +++ b/BlazorTp1/Pages/Edit.razor.cs @@ -0,0 +1,104 @@ +using BlazorTp1.Factories; +using BlazorTp1.Models; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Forms; + +namespace BlazorTp1.Pages +{ + public partial class Edit + { + [Parameter] + public int Id { get; set; } + + /// + /// The default enchant categories. + /// + private List enchantCategories = new List() { "armor", "armor_head", "armor_chest", "weapon", "digger", "breakable", "vanishable" }; + + /// + /// The current item model + /// + private ItemModel itemModel = new() + { + EnchantCategories = new List(), + RepairWith = new List() + }; + + /// + /// The default repair with. + /// + private List repairWith = new List() { "oak_planks", "spruce_planks", "birch_planks", "jungle_planks", "acacia_planks", "dark_oak_planks", "crimson_planks", "warped_planks" }; + + [Inject] + public IDataService DataService { get; set; } + + [Inject] + public NavigationManager NavigationManager { get; set; } + + [Inject] + public IWebHostEnvironment WebHostEnvironment { get; set; } + + protected override async Task OnInitializedAsync() + { + var item = await DataService.GetById(Id); + + var fileContent = await File.ReadAllBytesAsync($"{WebHostEnvironment.WebRootPath}/images/default.png"); + + // Set the model with the item + itemModel = ItemFactory.ToModel(item, fileContent); + } + + private async void HandleValidSubmit() + { + await DataService.Update(Id, itemModel); + + NavigationManager.NavigateTo("list"); + } + + private async Task LoadImage(InputFileChangeEventArgs e) + { + // Set the content of the image to the model + using (var memoryStream = new MemoryStream()) + { + await e.File.OpenReadStream().CopyToAsync(memoryStream); + itemModel.ImageContent = memoryStream.ToArray(); + } + } + + private void OnEnchantCategoriesChange(string item, object checkedValue) + { + if ((bool)checkedValue) + { + if (!itemModel.EnchantCategories.Contains(item)) + { + itemModel.EnchantCategories.Add(item); + } + + return; + } + + if (itemModel.EnchantCategories.Contains(item)) + { + itemModel.EnchantCategories.Remove(item); + } + } + + private void OnRepairWithChange(string item, object checkedValue) + { + if ((bool)checkedValue) + { + if (!itemModel.RepairWith.Contains(item)) + { + itemModel.RepairWith.Add(item); + } + + return; + } + + if (itemModel.RepairWith.Contains(item)) + { + itemModel.RepairWith.Remove(item); + } + } + } +} diff --git a/BlazorTp1/Pages/Index.razor b/BlazorTp1/Pages/Index.razor index 6085c4a..b0e6e78 100644 --- a/BlazorTp1/Pages/Index.razor +++ b/BlazorTp1/Pages/Index.razor @@ -1,9 +1,21 @@ @page "/" +@using System.Globalization +@using BlazorTp1.Components Index -

Hello, world!

+

Tp Blazor Nicolas Franco

Welcome to your new app. +

+ CurrentCulture: @CultureInfo.CurrentCulture +

+ +
+ +
+ + + diff --git a/BlazorTp1/Pages/Index.razor.cs b/BlazorTp1/Pages/Index.razor.cs new file mode 100644 index 0000000..36832ff --- /dev/null +++ b/BlazorTp1/Pages/Index.razor.cs @@ -0,0 +1,31 @@ +using BlazorTp1.Components; +using BlazorTp1.Models; +using Microsoft.AspNetCore.Components; + +namespace BlazorTp1.Pages +{ + public partial class Index + { + [Inject] + public IDataService? DataService { get; set; } + + public List Items { get; set; } = new List(); + + private List Recipes { get; set; } = new List(); + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + base.OnAfterRenderAsync(firstRender); + + if (!firstRender) + { + return; + } + + Items = await DataService.List(0, await DataService.Count()); + Recipes = await DataService.GetRecipes(); + + StateHasChanged(); + } + } +} diff --git a/BlazorTp1/Pages/List.razor b/BlazorTp1/Pages/List.razor index 640d9f2..bde242a 100644 --- a/BlazorTp1/Pages/List.razor +++ b/BlazorTp1/Pages/List.razor @@ -1,7 +1,7 @@ @page "/list" @using BlazorTp1.Models -

List

+

@Localizer["Title"]

@@ -19,9 +19,9 @@ - @if (File.Exists($"{WebHostEnvironment.WebRootPath}/images/{context.Name}.png")) + @if (!string.IsNullOrWhiteSpace(context.ImageBase64)) { - @context.DisplayName + @context.DisplayName } else { @@ -42,5 +42,11 @@ @(string.Join(", ", ((Item)context).RepairWith)) - + + + + Editer + + + diff --git a/BlazorTp1/Pages/List.razor.cs b/BlazorTp1/Pages/List.razor.cs index 4fd69ef..f20a1fb 100644 --- a/BlazorTp1/Pages/List.razor.cs +++ b/BlazorTp1/Pages/List.razor.cs @@ -2,6 +2,10 @@ using BlazorTp1.Models; using Blazorise.DataGrid; using Blazored.LocalStorage; +using Blazored.Modal.Services; +using Blazored.Modal; +using BlazorTp1.Modals; +using Microsoft.Extensions.Localization; namespace BlazorTp1.Pages { @@ -12,7 +16,7 @@ namespace BlazorTp1.Pages private int totalItem; [Inject] - public HttpClient Http { get; set; } + public IDataService DataService { get; set; } [Inject] public IWebHostEnvironment WebHostEnvironment { get; set; } @@ -20,6 +24,12 @@ namespace BlazorTp1.Pages [Inject] public NavigationManager NavigationManager { get; set; } + [CascadingParameter] + public IModalService Modal { get; set; } + + [Inject] + public IStringLocalizer Localizer { get; set; } + private async Task OnReadData(DataGridReadDataEventArgs e) { if (e.CancellationToken.IsCancellationRequested) @@ -27,15 +37,29 @@ namespace BlazorTp1.Pages return; } - // When you use a real API, we use this follow code - //var response = await Http.GetJsonAsync( $"http://my-api/api/data?page={e.Page}&pageSize={e.PageSize}" ); - var response = (await Http.GetFromJsonAsync($"{NavigationManager.BaseUri}fake-data.json")).Skip((e.Page - 1) * e.PageSize).Take(e.PageSize).ToList(); - if (!e.CancellationToken.IsCancellationRequested) { - totalItem = (await Http.GetFromJsonAsync>($"{NavigationManager.BaseUri}fake-data.json")).Count; - items = new List(response); // an actual data for the current page + items = await DataService.List(e.Page, e.PageSize); + totalItem = await DataService.Count(); } } + private async void OnDelete(int id) + { + var parameters = new ModalParameters(); + parameters.Add(nameof(Item.Id), id); + + var modal = Modal.Show("Delete Confirmation", parameters); + var result = await modal.Result; + + if (result.Cancelled) + { + return; + } + + await DataService.Delete(id); + + // Reload the page + NavigationManager.NavigateTo("list", true); + } } } diff --git a/BlazorTp1/Pages/_Layout.cshtml b/BlazorTp1/Pages/_Layout.cshtml index 641ca97..a2962dc 100644 --- a/BlazorTp1/Pages/_Layout.cshtml +++ b/BlazorTp1/Pages/_Layout.cshtml @@ -4,35 +4,38 @@ - - - - - - - - - - - @RenderBody() + + + + + + + + + + + + @RenderBody() -
- - An error has occurred. This application may no longer respond until reloaded. - - - An unhandled exception has occurred. See browser dev tools for details. - - Reload - 🗙 -
+
+ + An error has occurred. This application may no longer respond until reloaded. + + + An unhandled exception has occurred. See browser dev tools for details. + + Reload + 🗙 +
- + + + - + - - + + - + diff --git a/BlazorTp1/Program.cs b/BlazorTp1/Program.cs index 8d82ec6..a52bc75 100644 --- a/BlazorTp1/Program.cs +++ b/BlazorTp1/Program.cs @@ -1,10 +1,13 @@ using Blazored.LocalStorage; +using Blazored.Modal; using Blazorise; using Blazorise.Bootstrap; using Blazorise.Icons.FontAwesome; using BlazorTp1.Data; -using Microsoft.AspNetCore.Components; -using Microsoft.AspNetCore.Components.Web; +using BlazorTp1.Services; +using Microsoft.AspNetCore.Localization; +using Microsoft.Extensions.Options; +using System.Globalization; var builder = WebApplication.CreateBuilder(args); @@ -15,6 +18,8 @@ builder.Services.AddSingleton(); builder.Services.AddHttpClient(); +builder.Services.AddBlazoredModal(); + builder.Services .AddBlazorise() .AddBootstrapProviders() @@ -22,6 +27,29 @@ builder.Services builder.Services.AddBlazoredLocalStorage(); +builder.Services.AddScoped(); + +builder.Services.AddScoped(); + +// Add the controller of the app +builder.Services.AddControllers(); + +// Add the localization to the app and specify the resources path +builder.Services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; }); + +builder.Logging.AddConfiguration(builder.Configuration.GetSection("Logging")); + +// Configure the localtization +builder.Services.Configure(options => +{ + // Set the default culture of the web site + options.DefaultRequestCulture = new RequestCulture(new CultureInfo("en-US")); + + // Declare the supported culture + options.SupportedCultures = new List { new CultureInfo("en-US"), new CultureInfo("fr-FR") }; + options.SupportedUICultures = new List { new CultureInfo("en-US"), new CultureInfo("fr-FR") }; +}); + var app = builder.Build(); // Configure the HTTP request pipeline. @@ -38,6 +66,21 @@ app.UseStaticFiles(); app.UseRouting(); +// Get the current localization options +var options = ((IApplicationBuilder)app).ApplicationServices.GetService>(); + +if (options?.Value != null) +{ + // use the default localization + app.UseRequestLocalization(options.Value); +} + +// Add the controller to the endpoint +app.UseEndpoints(endpoints => +{ + endpoints.MapControllers(); +}); + app.MapBlazorHub(); app.MapFallbackToPage("/_Host"); diff --git a/BlazorTp1/Resources/Pages.List.fr-FR.resx b/BlazorTp1/Resources/Pages.List.fr-FR.resx new file mode 100644 index 0000000..941e1c7 --- /dev/null +++ b/BlazorTp1/Resources/Pages.List.fr-FR.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Liste d'éléments + + \ No newline at end of file diff --git a/BlazorTp1/Resources/Pages.List.resx b/BlazorTp1/Resources/Pages.List.resx new file mode 100644 index 0000000..ae67689 --- /dev/null +++ b/BlazorTp1/Resources/Pages.List.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Items List + + \ No newline at end of file diff --git a/BlazorTp1/Services/DataApiService.cs b/BlazorTp1/Services/DataApiService.cs new file mode 100644 index 0000000..661478e --- /dev/null +++ b/BlazorTp1/Services/DataApiService.cs @@ -0,0 +1,58 @@ +using BlazorTp1.Factories; +using BlazorTp1.Components; +using BlazorTp1.Models; +namespace BlazorTp1.Services +{ + public class DataApiService : IDataService + { + private readonly HttpClient _http; + + public DataApiService( + HttpClient http) + { + _http = http; + } + + public async Task Add(ItemModel model) + { + // Get the item + var item = ItemFactory.Create(model); + + // Save the data + await _http.PostAsJsonAsync("https://codefirst.iut.uca.fr/containers/container-blazor-web-api-julienriboulet/api/Crafting/", item); + } + + public async Task Count() + { + return await _http.GetFromJsonAsync("https://codefirst.iut.uca.fr/containers/container-blazor-web-api-julienriboulet/api/Crafting/count"); + } + + public async Task> List(int currentPage, int pageSize) + { + return await _http.GetFromJsonAsync>($"https://codefirst.iut.uca.fr/containers/container-blazor-web-api-julienriboulet/api/Crafting/?currentPage={currentPage}&pageSize={pageSize}"); + } + + public async Task GetById(int id) + { + return await _http.GetFromJsonAsync($"https://codefirst.iut.uca.fr/containers/container-blazor-web-api-julienriboulet/api/Crafting/{id}"); + } + + public async Task Update(int id, ItemModel model) + { + // Get the item + var item = ItemFactory.Create(model); + + await _http.PutAsJsonAsync($"https://localhost:7234/api/Crafting/{id}", item); + } + + public async Task Delete(int id) + { + await _http.DeleteAsync($"https://localhost:7234/api/Crafting/{id}"); + } + + public async Task> GetRecipes() + { + return await _http.GetFromJsonAsync>("https://codefirst.iut.uca.fr/containers/container-blazor-web-api-julienriboulet/api/Crafting/recipe"); + } + } +} diff --git a/BlazorTp1/Services/DataLocalService.cs b/BlazorTp1/Services/DataLocalService.cs new file mode 100644 index 0000000..1dca040 --- /dev/null +++ b/BlazorTp1/Services/DataLocalService.cs @@ -0,0 +1,145 @@ +using Blazored.LocalStorage; +using BlazorTp1.Components; +using BlazorTp1.Factories; +using BlazorTp1.Models; +using Microsoft.AspNetCore.Components; + +public class DataLocalService : IDataService +{ + private readonly HttpClient _http; + private readonly ILocalStorageService _localStorage; + private readonly NavigationManager _navigationManager; + private readonly IWebHostEnvironment _webHostEnvironment; + + public DataLocalService( + ILocalStorageService localStorage, + HttpClient http, + IWebHostEnvironment webHostEnvironment, + NavigationManager navigationManager) + { + _localStorage = localStorage; + _http = http; + _webHostEnvironment = webHostEnvironment; + _navigationManager = navigationManager; + } + + public async Task Add(ItemModel model) + { + // Get the current data + var currentData = await _localStorage.GetItemAsync>("data"); + + // Simulate the Id + model.Id = currentData.Max(s => s.Id) + 1; + + // Add the item to the current data + currentData.Add(ItemFactory.Create(model)); + + // Save the data + await _localStorage.SetItemAsync("data", currentData); + } + + public async Task Count() + { + // Load data from the local storage + var currentData = await _localStorage.GetItemAsync("data"); + + // Check if data exist in the local storage + if (currentData == null) + { + // this code add in the local storage the fake data + var originalData = await _http.GetFromJsonAsync($"{_navigationManager.BaseUri}fake-data.json"); + await _localStorage.SetItemAsync("data", originalData); + } + return (await _localStorage.GetItemAsync("data")).Length; + } + + public async Task> List(int currentPage, int pageSize) + { + // Load data from the local storage + var currentData = await _localStorage.GetItemAsync("data"); + + // Check if data exist in the local storage + if (currentData == null) + { + // this code add in the local storage the fake data + var originalData = await _http.GetFromJsonAsync($"{_navigationManager.BaseUri}fake-data.json"); + await _localStorage.SetItemAsync("data", originalData); + } + + return (await _localStorage.GetItemAsync("data")).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList(); + } + + //new methods + + public async Task GetById(int id) + { + // Get the current data + var currentData = await _localStorage.GetItemAsync>("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>("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}"); + } + + // Modify the content of the item + ItemFactory.Update(item, model); + + // Save the data + await _localStorage.SetItemAsync("data", currentData); + } + + public async Task Delete(int id) + { + // Get the current data + var currentData = await _localStorage.GetItemAsync>("data"); + + // Get the item int the list + var item = currentData.FirstOrDefault(w => w.Id == id); + + // Delete item in + currentData.Remove(item); + + // Save the data + await _localStorage.SetItemAsync("data", currentData); + } + + public Task> GetRecipes() + { + var items = new List + { + new CraftingRecipe + { + Give = new Item { DisplayName = "Diamond", Name = "diamond" }, + Have = new List> + { + new List { "dirt", "dirt", "dirt" }, + new List { "dirt", null, "dirt" }, + new List { "dirt", "dirt", "dirt" } + } + } + }; + + return Task.FromResult(items); + } +} \ No newline at end of file diff --git a/BlazorTp1/Services/IDataService.cs b/BlazorTp1/Services/IDataService.cs new file mode 100644 index 0000000..a03b7ad --- /dev/null +++ b/BlazorTp1/Services/IDataService.cs @@ -0,0 +1,20 @@ +using BlazorTp1.Components; +using BlazorTp1.Models; +using System; + +public interface IDataService +{ + Task Add(ItemModel model); + + Task Count(); + + Task> List(int currentPage, int pageSize); + + Task GetById(int id); + + Task Update(int id, ItemModel item); + + Task Delete(int id); + + Task> GetRecipes(); +} diff --git a/BlazorTp1/Shared/CultureSelector.razor b/BlazorTp1/Shared/CultureSelector.razor new file mode 100644 index 0000000..0f46a4e --- /dev/null +++ b/BlazorTp1/Shared/CultureSelector.razor @@ -0,0 +1,43 @@ +@using System.Globalization +@inject NavigationManager NavigationManager + +

+ +

+ +@code +{ + private CultureInfo[] supportedCultures = new[] + { + new CultureInfo("en-US"), + new CultureInfo("fr-FR") + }; + + private CultureInfo Culture + { + get => CultureInfo.CurrentCulture; + set + { + if (CultureInfo.CurrentUICulture == value) + { + return; + } + + var culture = value.Name.ToLower(CultureInfo.InvariantCulture); + + var uri = new Uri(this.NavigationManager.Uri).GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped); + var query = $"?culture={Uri.EscapeDataString(culture)}&" + $"redirectUri={Uri.EscapeDataString(uri)}"; + + // Redirect the user to the culture controller to set the cookie + this.NavigationManager.NavigateTo("/Culture/SetCulture" + query, forceLoad: true); + } + } +} diff --git a/BlazorTp1/Shared/MainLayout.razor b/BlazorTp1/Shared/MainLayout.razor index 46ade29..e497265 100644 --- a/BlazorTp1/Shared/MainLayout.razor +++ b/BlazorTp1/Shared/MainLayout.razor @@ -12,6 +12,10 @@ About
+
+ +
+
@Body
diff --git a/BlazorTp1/_Imports.razor b/BlazorTp1/_Imports.razor index 009cdfc..fb7258e 100644 --- a/BlazorTp1/_Imports.razor +++ b/BlazorTp1/_Imports.razor @@ -9,3 +9,5 @@ @using BlazorTp1 @using BlazorTp1.Shared @using Blazorise.DataGrid +@using Blazored.Modal +@using Blazored.Modal.Services \ No newline at end of file diff --git a/BlazorTp1/wwwroot/appsettings.json b/BlazorTp1/wwwroot/appsettings.json new file mode 100644 index 0000000..ef6372d --- /dev/null +++ b/BlazorTp1/wwwroot/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Trace", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } +} \ No newline at end of file diff --git a/BlazorTp1/wwwroot/index.html b/BlazorTp1/wwwroot/index.html new file mode 100644 index 0000000..8cb9f7a --- /dev/null +++ b/BlazorTp1/wwwroot/index.html @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file