diff --git a/BlazorAppClean.sln b/BlazorAppClean.sln index d845996..f0f2175 100644 --- a/BlazorAppClean.sln +++ b/BlazorAppClean.sln @@ -3,7 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.3.32929.385 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlazorAppClean", "BlazorAppClean\BlazorAppClean.csproj", "{8F965E61-DC11-4545-BF2B-F81850892269}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlazorAppClean", "BlazorAppClean\BlazorAppClean.csproj", "{8F965E61-DC11-4545-BF2B-F81850892269}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Minecraft.Crafting.Api", "..\minecraft_compagnonv0\Sources\Minecraft.Crafting.Api\Minecraft.Crafting.Api.csproj", "{C00E33A7-4E2E-404C-88A0-82902E652FC8}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -15,6 +17,10 @@ Global {8F965E61-DC11-4545-BF2B-F81850892269}.Debug|Any CPU.Build.0 = Debug|Any CPU {8F965E61-DC11-4545-BF2B-F81850892269}.Release|Any CPU.ActiveCfg = Release|Any CPU {8F965E61-DC11-4545-BF2B-F81850892269}.Release|Any CPU.Build.0 = Release|Any CPU + {C00E33A7-4E2E-404C-88A0-82902E652FC8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C00E33A7-4E2E-404C-88A0-82902E652FC8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C00E33A7-4E2E-404C-88A0-82902E652FC8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C00E33A7-4E2E-404C-88A0-82902E652FC8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/BlazorAppClean/App.razor b/BlazorAppClean/App.razor index 6fd3ed1..af15d68 100644 --- a/BlazorAppClean/App.razor +++ b/BlazorAppClean/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/BlazorAppClean/BlazorAppClean.csproj b/BlazorAppClean/BlazorAppClean.csproj index c78c9c7..d9f7e7f 100644 --- a/BlazorAppClean/BlazorAppClean.csproj +++ b/BlazorAppClean/BlazorAppClean.csproj @@ -6,4 +6,13 @@ enable + + + + + + + + + diff --git a/BlazorAppClean/Components/Card.razor b/BlazorAppClean/Components/Card.razor new file mode 100644 index 0000000..422077c --- /dev/null +++ b/BlazorAppClean/Components/Card.razor @@ -0,0 +1,6 @@ +@typeparam TItem +
+ @CardHeader(Item) + @CardBody(Item) + @CardFooter +
\ No newline at end of file diff --git a/BlazorAppClean/Components/Card.razor.cs b/BlazorAppClean/Components/Card.razor.cs new file mode 100644 index 0000000..8de8bd9 --- /dev/null +++ b/BlazorAppClean/Components/Card.razor.cs @@ -0,0 +1,19 @@ +using Microsoft.AspNetCore.Components; + +namespace BlazorAppClean.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/BlazorAppClean/Components/Crafting.razor b/BlazorAppClean/Components/Crafting.razor new file mode 100644 index 0000000..b60542a --- /dev/null +++ b/BlazorAppClean/Components/Crafting.razor @@ -0,0 +1,53 @@ + +
+
+
+ +
Available items:
+
+
+ + @foreach (var item in Items) + { + + + + } +
+
+ +
+ +
+
Recipe
+ +
+ +
+ + + + + + + + + +
+
+ +
Result
+
+ +
+
+ +
+
Actions
+
+ +
+
+
+
+
\ No newline at end of file diff --git a/BlazorAppClean/Components/Crafting.razor.cs b/BlazorAppClean/Components/Crafting.razor.cs new file mode 100644 index 0000000..dbecb4d --- /dev/null +++ b/BlazorAppClean/Components/Crafting.razor.cs @@ -0,0 +1,82 @@ +using BlazorAppClean.Models; +using Microsoft.AspNetCore.Components; +using Microsoft.JSInterop; +using System.Collections.ObjectModel; +using System.Collections.Specialized; + +namespace BlazorAppClean.Components +{ + public partial class Crafting + { + [CascadingParameter] + public Crafting Parent { get; set; } + 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/BlazorAppClean/Components/Crafting.razor.css b/BlazorAppClean/Components/Crafting.razor.css new file mode 100644 index 0000000..2a388f2 --- /dev/null +++ b/BlazorAppClean/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/BlazorAppClean/Components/Crafting.razor.js b/BlazorAppClean/Components/Crafting.razor.js new file mode 100644 index 0000000..8fdb58e --- /dev/null +++ b/BlazorAppClean/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/BlazorAppClean/Components/CraftingAction.cs b/BlazorAppClean/Components/CraftingAction.cs new file mode 100644 index 0000000..14c5d5d --- /dev/null +++ b/BlazorAppClean/Components/CraftingAction.cs @@ -0,0 +1,11 @@ +using BlazorAppClean.Models; + +namespace BlazorAppClean.Components +{ + public class CraftingAction + { + public string Action { get; set; } + public int Index { get; set; } + public Item Item { get; set; } + } +} diff --git a/BlazorAppClean/Components/CraftingItem.razor b/BlazorAppClean/Components/CraftingItem.razor new file mode 100644 index 0000000..c1043b8 --- /dev/null +++ b/BlazorAppClean/Components/CraftingItem.razor @@ -0,0 +1,14 @@ +
+ + @if (Item != null) + { + @Item.DisplayName + } +
\ No newline at end of file diff --git a/BlazorAppClean/Components/CraftingItem.razor.cs b/BlazorAppClean/Components/CraftingItem.razor.cs new file mode 100644 index 0000000..e7d4bd6 --- /dev/null +++ b/BlazorAppClean/Components/CraftingItem.razor.cs @@ -0,0 +1,64 @@ +using BlazorAppClean.Models; +using Blazorise; +using Microsoft.AspNetCore.Components; + +namespace BlazorAppClean.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/BlazorAppClean/Components/CraftingItem.razor.css b/BlazorAppClean/Components/CraftingItem.razor.css new file mode 100644 index 0000000..b2d4521 --- /dev/null +++ b/BlazorAppClean/Components/CraftingItem.razor.css @@ -0,0 +1,6 @@ +.item { + width: 64px; + height: 64px; + border: 1px solid; + overflow: hidden; +} diff --git a/BlazorAppClean/Components/CraftingRecipe.cs b/BlazorAppClean/Components/CraftingRecipe.cs new file mode 100644 index 0000000..dcfe392 --- /dev/null +++ b/BlazorAppClean/Components/CraftingRecipe.cs @@ -0,0 +1,10 @@ +using BlazorAppClean.Models; + +namespace BlazorAppClean.Components +{ + public class CraftingRecipe + { + public Item Give { get; set; } + public List> Have { get; set; } + } +} diff --git a/BlazorAppClean/Components/MyFirstChildComponent.razor b/BlazorAppClean/Components/MyFirstChildComponent.razor new file mode 100644 index 0000000..5607d8f --- /dev/null +++ b/BlazorAppClean/Components/MyFirstChildComponent.razor @@ -0,0 +1,14 @@ +@code { + [Parameter] + public RenderFragment ChildContent { get; set; } + + [Parameter] + public MyRootComponent RootComponent { get; set; } +} + +
+ MyFirstChildComponent - @RootComponent.Text +
+ @ChildContent +
+
\ No newline at end of file diff --git a/BlazorAppClean/Components/MyRootComponent.razor b/BlazorAppClean/Components/MyRootComponent.razor new file mode 100644 index 0000000..18895ba --- /dev/null +++ b/BlazorAppClean/Components/MyRootComponent.razor @@ -0,0 +1,16 @@ +@code { + [Parameter] + public RenderFragment ChildContent { get; set; } + + [Parameter] + public string Text { get; set; } +} + +
+ MyRootComponent - @Text +
+ + @ChildContent + +
+
\ No newline at end of file diff --git a/BlazorAppClean/Components/MySecondChildComponent.razor b/BlazorAppClean/Components/MySecondChildComponent.razor new file mode 100644 index 0000000..4d5647b --- /dev/null +++ b/BlazorAppClean/Components/MySecondChildComponent.razor @@ -0,0 +1,14 @@ +@code { + [Parameter] + public RenderFragment ChildContent { get; set; } + + [Parameter] + public MyRootComponent RootComponent { get; set; } +} + +
+ MySecondChildComponent - @RootComponent.Text +
+ @ChildContent +
+
\ No newline at end of file diff --git a/BlazorAppClean/Components/ShowItems.razor b/BlazorAppClean/Components/ShowItems.razor new file mode 100644 index 0000000..e8fccfd --- /dev/null +++ b/BlazorAppClean/Components/ShowItems.razor @@ -0,0 +1,11 @@ +@typeparam TItem + +
+ @if ((Items?.Count ?? 0) != 0) + { + @foreach (var item in Items) + { + @ShowTemplate(item); + } + } +
\ No newline at end of file diff --git a/BlazorAppClean/Components/ShowItems.razor.cs b/BlazorAppClean/Components/ShowItems.razor.cs new file mode 100644 index 0000000..f998e72 --- /dev/null +++ b/BlazorAppClean/Components/ShowItems.razor.cs @@ -0,0 +1,13 @@ +using Microsoft.AspNetCore.Components; + +namespace BlazorAppClean.Components +{ + public partial class ShowItems + { + [Parameter] + public List Items { get; set; } + + [Parameter] + public RenderFragment ShowTemplate { get; set; } + } +} diff --git a/BlazorAppClean/Components/TestRenderFragment.razor b/BlazorAppClean/Components/TestRenderFragment.razor new file mode 100644 index 0000000..176ee34 --- /dev/null +++ b/BlazorAppClean/Components/TestRenderFragment.razor @@ -0,0 +1,8 @@ +

TestRenderFragment

+ +@code { + [Parameter] + public RenderFragment ChildContent { get; set; } +} + +@ChildContent \ No newline at end of file diff --git a/BlazorAppClean/Controllers/CultureController.cs b/BlazorAppClean/Controllers/CultureController.cs new file mode 100644 index 0000000..328c28e --- /dev/null +++ b/BlazorAppClean/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/BlazorAppClean/Factories/ItemFactory.cs b/BlazorAppClean/Factories/ItemFactory.cs new file mode 100644 index 0000000..e2cf178 --- /dev/null +++ b/BlazorAppClean/Factories/ItemFactory.cs @@ -0,0 +1,54 @@ +using BlazorAppClean.Models; + +namespace BlazorAppClean.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/BlazorAppClean/Modals/DeleteConfirmation.razor b/BlazorAppClean/Modals/DeleteConfirmation.razor new file mode 100644 index 0000000..93f7a46 --- /dev/null +++ b/BlazorAppClean/Modals/DeleteConfirmation.razor @@ -0,0 +1,10 @@ +
+ +

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

+ + + + +
\ No newline at end of file diff --git a/BlazorAppClean/Modals/DeleteConfirmation.razor.cs b/BlazorAppClean/Modals/DeleteConfirmation.razor.cs new file mode 100644 index 0000000..cc9fb67 --- /dev/null +++ b/BlazorAppClean/Modals/DeleteConfirmation.razor.cs @@ -0,0 +1,38 @@ +using BlazorAppClean.Models; +using BlazorAppClean.Services; +using Blazored.Modal; +using Blazored.Modal.Services; +using Microsoft.AspNetCore.Components; + +namespace BlazorAppClean.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/BlazorAppClean/Models/Cake.cs b/BlazorAppClean/Models/Cake.cs new file mode 100644 index 0000000..d66d01a --- /dev/null +++ b/BlazorAppClean/Models/Cake.cs @@ -0,0 +1,9 @@ +namespace BlazorAppClean.Models +{ + public class Cake + { + public int Id { get; set; } + public string Name { get; set; } + public decimal Cost { get; set; } + } +} diff --git a/BlazorAppClean/Models/Item.cs b/BlazorAppClean/Models/Item.cs new file mode 100644 index 0000000..0723657 --- /dev/null +++ b/BlazorAppClean/Models/Item.cs @@ -0,0 +1,16 @@ +namespace BlazorAppClean.Models +{ + public class Item + { + public int Id { get; set; } + public string DisplayName { get; set; } + public string Name { get; set; } + public int StackSize { get; set; } + public int MaxDurability { get; set; } + public List EnchantCategories { get; set; } + public List RepairWith { get; set; } + public DateTime CreatedDate { get; set; } + public DateTime? UpdatedDate { get; set; } + public string ImageBase64 { get; set; } + } +} diff --git a/BlazorAppClean/Models/ItemModel.cs b/BlazorAppClean/Models/ItemModel.cs new file mode 100644 index 0000000..dc8ed6e --- /dev/null +++ b/BlazorAppClean/Models/ItemModel.cs @@ -0,0 +1,39 @@ +using System.ComponentModel.DataAnnotations; + +namespace BlazorAppClean.Models +{ + public class ItemModel + { + public int Id { get; set; } + + [Required] + [StringLength(50, ErrorMessage = "Le nom affiché ne doit pas dépasser 50 caractères.")] + public string DisplayName { get; set; } + + [Required] + [StringLength(50, ErrorMessage = "Le nom ne doit pas dépasser 50 caractères.")] + [RegularExpression(@"^[a-z''-'\s]{1,40}$", ErrorMessage = "Seulement les caractères en minuscule sont acceptées.")] + public string Name { get; set; } + + [Required] + [Range(1, 64)] + public int StackSize { get; set; } + + [Required] + [Range(1, 125)] + public int MaxDurability { get; set; } + + public List EnchantCategories { get; set; } + + public List RepairWith { get; set; } + + [Required] + [Range(typeof(bool), "true", "true", ErrorMessage = "Vous devez accepter les conditions.")] + public bool AcceptCondition { get; set; } + + [Required(ErrorMessage = "L'image de l'item est obligatoire !")] + public byte[] ImageContent { get; set; } + + public string ImageBase64 { get; set; } + } +} diff --git a/BlazorAppClean/Pages/Add.razor b/BlazorAppClean/Pages/Add.razor new file mode 100644 index 0000000..64b1710 --- /dev/null +++ b/BlazorAppClean/Pages/Add.razor @@ -0,0 +1,69 @@ +@page "/add" + +

Add

+ + + + + +

+ +

+

+ +

+

+ +

+

+ +

+

+ Enchant categories: +

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

+

+ Repair with: +

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

+

+ +

+

+ +

+ + +
\ No newline at end of file diff --git a/BlazorAppClean/Pages/Add.razor.cs b/BlazorAppClean/Pages/Add.razor.cs new file mode 100644 index 0000000..e9d4042 --- /dev/null +++ b/BlazorAppClean/Pages/Add.razor.cs @@ -0,0 +1,89 @@ +using BlazorAppClean.Models; +using Blazored.LocalStorage; +using Microsoft.AspNetCore.Components.Forms; +using Microsoft.AspNetCore.Components; +using BlazorAppClean.Services; + +namespace BlazorAppClean.Pages +{ + public partial class Add + { + /// + /// 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; } + + private async void HandleValidSubmit() + { + await DataService.Add(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/BlazorAppClean/Pages/CallJsExample1.razor b/BlazorAppClean/Pages/CallJsExample1.razor new file mode 100644 index 0000000..4dcb555 --- /dev/null +++ b/BlazorAppClean/Pages/CallJsExample1.razor @@ -0,0 +1,35 @@ +@page "/call-js-example-1" +@inject IJSRuntime JS + +

Call JS convertArray Function

+ +

+ +

+ +

+ @text +

+ +

+ Serenity
+ David Krumholtz on IMDB +

+ +@code { + private MarkupString text; + + private uint[] quoteArray = + new uint[] + { + 60, 101, 109, 62, 67, 97, 110, 39, 116, 32, 115, 116, 111, 112, 32, + 116, 104, 101, 32, 115, 105, 103, 110, 97, 108, 44, 32, 77, 97, + 108, 46, 60, 47, 101, 109, 62, 32, 45, 32, 77, 114, 46, 32, 85, 110, + 105, 118, 101, 114, 115, 101, 10, 10, + }; + + private async Task ConvertArray() + { + text = new(await JS.InvokeAsync("convertArray", quoteArray)); + } +} \ No newline at end of file diff --git a/BlazorAppClean/Pages/CallJsExample3.razor b/BlazorAppClean/Pages/CallJsExample3.razor new file mode 100644 index 0000000..3da3dff --- /dev/null +++ b/BlazorAppClean/Pages/CallJsExample3.razor @@ -0,0 +1,36 @@ +@page "/call-js-example-3" +@inject IJSRuntime JS + +

Call JS Example 3

+ +

+ +

+ +@if (stockSymbol is not null) +{ +

@stockSymbol price: @price.ToString("c")

+} + +@if (result is not null) +{ +

@result

+} + +@code { + private Random r = new(); + private string? stockSymbol; + private decimal price; + private string? result; + + private async Task SetStock() + { + stockSymbol = + $"{(char)('A' + r.Next(0, 26))}{(char)('A' + r.Next(0, 26))}"; + price = r.Next(1, 101); + var interopResult = + await JS.InvokeAsync("displayTickerAlert2", stockSymbol, price); + result = $"Result of TickerChanged call for {stockSymbol} at " + + $"{price.ToString("c")}: {interopResult}"; + } +} \ No newline at end of file diff --git a/BlazorAppClean/Pages/Config.razor b/BlazorAppClean/Pages/Config.razor new file mode 100644 index 0000000..fe41403 --- /dev/null +++ b/BlazorAppClean/Pages/Config.razor @@ -0,0 +1,9 @@ +@page "/config" +

Config

+ +
+
MyKey: @Configuration["MyKey"]
+
Position:Title: @Configuration["Position:Title"]
+
Position:Name: @Configuration["Position:Name"]
+
Logging:LogLevel:Default: @Configuration["Logging:LogLevel:Default"]
+
\ No newline at end of file diff --git a/BlazorAppClean/Pages/Config.razor.cs b/BlazorAppClean/Pages/Config.razor.cs new file mode 100644 index 0000000..12d6eb1 --- /dev/null +++ b/BlazorAppClean/Pages/Config.razor.cs @@ -0,0 +1,8 @@ +using Microsoft.AspNetCore.Components; +using Microsoft.Extensions.Configuration; + +public partial class Config +{ + [Inject] + public IConfiguration Configuration { get; set; } +} \ No newline at end of file diff --git a/BlazorAppClean/Pages/Edit.razor b/BlazorAppClean/Pages/Edit.razor new file mode 100644 index 0000000..30d8037 --- /dev/null +++ b/BlazorAppClean/Pages/Edit.razor @@ -0,0 +1,75 @@ +@page "/edit/{Id:int}" + +

Edit

+ + + + + +

+ +

+

+ +

+

+ +

+

+ +

+

+ Enchant categories: +

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

+

+ Repair with: +

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

+

+ +

+

+ +

+

+ +

+ + +
\ No newline at end of file diff --git a/BlazorAppClean/Pages/Edit.razor.cs b/BlazorAppClean/Pages/Edit.razor.cs new file mode 100644 index 0000000..7c2515c --- /dev/null +++ b/BlazorAppClean/Pages/Edit.razor.cs @@ -0,0 +1,110 @@ +using BlazorAppClean.Factories; +using BlazorAppClean.Models; +using BlazorAppClean.Services; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Forms; + +namespace BlazorAppClean.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"); + + if (File.Exists($"{WebHostEnvironment.WebRootPath}/images/{itemModel.Name}.png")) + { + fileContent = await File.ReadAllBytesAsync($"{WebHostEnvironment.WebRootPath}/images/{item.Name}.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/BlazorAppClean/Pages/Episodes.razor b/BlazorAppClean/Pages/Episodes.razor new file mode 100644 index 0000000..14abb26 --- /dev/null +++ b/BlazorAppClean/Pages/Episodes.razor @@ -0,0 +1,22 @@ +@page "/episodes" +@layout DoctorWhoLayout + +

Episodes

+ + \ No newline at end of file diff --git a/BlazorAppClean/Pages/Episodes.razor.cs b/BlazorAppClean/Pages/Episodes.razor.cs new file mode 100644 index 0000000..6cc3073 --- /dev/null +++ b/BlazorAppClean/Pages/Episodes.razor.cs @@ -0,0 +1,6 @@ +namespace BlazorAppClean.Pages +{ + public partial class Episodes + { + } +} diff --git a/BlazorAppClean/Pages/EventHandlerExample1.razor b/BlazorAppClean/Pages/EventHandlerExample1.razor new file mode 100644 index 0000000..536aa55 --- /dev/null +++ b/BlazorAppClean/Pages/EventHandlerExample1.razor @@ -0,0 +1,36 @@ +@page "/event-handler-example-1" + +

@currentHeading

+ +

+ +

+ +

+ +

+ +@code { + private string currentHeading = "Initial heading"; + private string? newHeading; + private string checkedMessage = "Not changed yet"; + + private void UpdateHeading() + { + currentHeading = $"{newHeading}!!!"; + } + + private void CheckChanged() + { + checkedMessage = $"Last changed at {DateTime.Now}"; + } +} \ No newline at end of file diff --git a/BlazorAppClean/Pages/EventHandlerExample2.razor b/BlazorAppClean/Pages/EventHandlerExample2.razor new file mode 100644 index 0000000..28679d9 --- /dev/null +++ b/BlazorAppClean/Pages/EventHandlerExample2.razor @@ -0,0 +1,25 @@ +@page "/event-handler-example-2" + +

@currentHeading

+ +

+ + +

+ +@code { + private string currentHeading = "Initial heading"; + private string? newHeading; + + private async Task UpdateHeading() + { + await Task.Delay(2000); + + currentHeading = $"{newHeading}!!!"; + } +} \ No newline at end of file diff --git a/BlazorAppClean/Pages/EventHandlerExample3.razor b/BlazorAppClean/Pages/EventHandlerExample3.razor new file mode 100644 index 0000000..dcc16c6 --- /dev/null +++ b/BlazorAppClean/Pages/EventHandlerExample3.razor @@ -0,0 +1,21 @@ +@page "/event-handler-example-3" + +@for (var i = 0; i < 4; i++) +{ +

+ +

+} + +

@mousePointerMessage

+ +@code { + private string? mousePointerMessage; + + private void ReportPointerLocation(MouseEventArgs e) + { + mousePointerMessage = $"Mouse coordinates: {e.ScreenX}:{e.ScreenY}"; + } +} \ No newline at end of file diff --git a/BlazorAppClean/Pages/ExampleTabSet.razor b/BlazorAppClean/Pages/ExampleTabSet.razor new file mode 100644 index 0000000..09c22e1 --- /dev/null +++ b/BlazorAppClean/Pages/ExampleTabSet.razor @@ -0,0 +1,28 @@ +@page "/example-tab-set" + + + +

Greetings from the first tab!

+ + +
+ + +

Hello from the second tab!

+
+ + @if (showThirdTab) + { + +

Welcome to the disappearing third tab!

+

Toggle this tab from the first tab.

+
+ } +
+ +@code { + private bool showThirdTab; +} \ No newline at end of file diff --git a/BlazorAppClean/Pages/Index.razor b/BlazorAppClean/Pages/Index.razor index 6085c4a..436d8e3 100644 --- a/BlazorAppClean/Pages/Index.razor +++ b/BlazorAppClean/Pages/Index.razor @@ -1,9 +1,12 @@ @page "/" - +@using System.Globalization +@using BlazorAppClean.Components Index - +

+ CurrentCulture: @CultureInfo.CurrentCulture +

Hello, world!

-Welcome to your new app. - + + \ No newline at end of file diff --git a/BlazorAppClean/Pages/Index.razor.cs b/BlazorAppClean/Pages/Index.razor.cs new file mode 100644 index 0000000..7c344b5 --- /dev/null +++ b/BlazorAppClean/Pages/Index.razor.cs @@ -0,0 +1,34 @@ + + +using BlazorAppClean.Components; +using BlazorAppClean.Models; +using BlazorAppClean.Services; +using Microsoft.AspNetCore.Components; + +namespace BlazorAppClean.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/BlazorAppClean/Pages/List.razor b/BlazorAppClean/Pages/List.razor new file mode 100644 index 0000000..1797a66 --- /dev/null +++ b/BlazorAppClean/Pages/List.razor @@ -0,0 +1,51 @@ +@page "/list" +@using BlazorAppClean.Models; + +

@Localizer["Title"]

+
+ + Ajouter + +
+ + + + + + @if (!string.IsNullOrWhiteSpace(context.ImageBase64)) + { + @context.DisplayName + } + else + { + @context.DisplayName + } + + + + + + + + @(string.Join(", ", ((Item)context).EnchantCategories)) + + + + + @(string.Join(", ", ((Item)context).RepairWith)) + + + + + + Editer + + + + \ No newline at end of file diff --git a/BlazorAppClean/Pages/List.razor.cs b/BlazorAppClean/Pages/List.razor.cs new file mode 100644 index 0000000..f080a56 --- /dev/null +++ b/BlazorAppClean/Pages/List.razor.cs @@ -0,0 +1,67 @@ + +using BlazorAppClean.Modals; +using BlazorAppClean.Models; +using BlazorAppClean.Services; +using Blazored.LocalStorage; +using Blazored.Modal; +using Blazored.Modal.Services; +using Blazorise.DataGrid; +using Microsoft.AspNetCore.Components; +using Microsoft.Extensions.Localization; + +namespace BlazorAppClean.Pages +{ + public partial class List + { + [Inject] + public IStringLocalizer Localizer { get; set; } + + private List items; + + private int totalItem; + + [Inject] + public NavigationManager NavigationManager { get; set; } + + [CascadingParameter] + public IModalService Modal { get; set; } + + [Inject] + public IDataService DataService { get; set; } + + [Inject] + public IWebHostEnvironment WebHostEnvironment { get; set; } + + private async Task OnReadData(DataGridReadDataEventArgs e) + { + if (e.CancellationToken.IsCancellationRequested) + { + return; + } + + if (!e.CancellationToken.IsCancellationRequested) + { + 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/BlazorAppClean/Pages/Pets1.razor b/BlazorAppClean/Pages/Pets1.razor new file mode 100644 index 0000000..065feec --- /dev/null +++ b/BlazorAppClean/Pages/Pets1.razor @@ -0,0 +1,29 @@ +@page "/pets1" + +

Pets

+ + + + ID + Name + + + @pet.PetId + @pet.Name + + + +@code { + private List pets = new() + { + new Pet { PetId = 2, Name = "Mr. Bigglesworth" }, + new Pet { PetId = 4, Name = "Salem Saberhagen" }, + new Pet { PetId = 7, Name = "K-9" } + }; + + private class Pet + { + public int PetId { get; set; } + public string? Name { get; set; } + } +} \ No newline at end of file diff --git a/BlazorAppClean/Pages/Pets2.razor b/BlazorAppClean/Pages/Pets2.razor new file mode 100644 index 0000000..c545e37 --- /dev/null +++ b/BlazorAppClean/Pages/Pets2.razor @@ -0,0 +1,29 @@ +@page "/pets2" + +

Pets

+ + + + ID + Name + + + @pet.PetId + @pet.Name + + + +@code { + private List pets = new() + { + new Pet { PetId = 2, Name = "Mr. Bigglesworth" }, + new Pet { PetId = 4, Name = "Salem Saberhagen" }, + new Pet { PetId = 7, Name = "K-9" } + }; + + private class Pet + { + public int PetId { get; set; } + public string? Name { get; set; } + } +} \ No newline at end of file diff --git a/BlazorAppClean/Pages/Pets3.razor b/BlazorAppClean/Pages/Pets3.razor new file mode 100644 index 0000000..fd52259 --- /dev/null +++ b/BlazorAppClean/Pages/Pets3.razor @@ -0,0 +1,29 @@ +@page "/pets3" + +

Pets

+ + + + ID + Name + + + @context.PetId + @context.Name + + + +@code { + private List pets = new() + { + new Pet { PetId = 2, Name = "Mr. Bigglesworth" }, + new Pet { PetId = 4, Name = "Salem Saberhagen" }, + new Pet { PetId = 7, Name = "K-9" } + }; + + private class Pet + { + public int PetId { get; set; } + public string? Name { get; set; } + } +} \ No newline at end of file diff --git a/BlazorAppClean/Pages/Pets4.razor b/BlazorAppClean/Pages/Pets4.razor new file mode 100644 index 0000000..ac0d918 --- /dev/null +++ b/BlazorAppClean/Pages/Pets4.razor @@ -0,0 +1,29 @@ +@page "/pets4" + +

Pets

+ + + + ID + Name + + + @context.PetId + @context.Name + + + +@code { + private List pets = new() + { + new Pet { PetId = 2, Name = "Mr. Bigglesworth" }, + new Pet { PetId = 4, Name = "Salem Saberhagen" }, + new Pet { PetId = 7, Name = "K-9" } + }; + + private class Pet + { + public int PetId { get; set; } + public string? Name { get; set; } + } +} \ No newline at end of file diff --git a/BlazorAppClean/Pages/ThemedCounter.razor b/BlazorAppClean/Pages/ThemedCounter.razor new file mode 100644 index 0000000..5dec5e7 --- /dev/null +++ b/BlazorAppClean/Pages/ThemedCounter.razor @@ -0,0 +1,32 @@ +@page "/themed-counter" +@using BlazorSample.UIThemeClasses + +

Themed Counter

+ +

Current count: @currentCount

+ +

+ +

+ +

+ +

+ +@code { + private int currentCount = 0; + + [CascadingParameter] + protected ThemeInfo? ThemeInfo { get; set; } + + private void IncrementCount() + { + currentCount++; + } +} \ No newline at end of file diff --git a/BlazorAppClean/Pages/_Layout.cshtml b/BlazorAppClean/Pages/_Layout.cshtml index 14ad137..c97af6c 100644 --- a/BlazorAppClean/Pages/_Layout.cshtml +++ b/BlazorAppClean/Pages/_Layout.cshtml @@ -11,6 +11,10 @@ + + + + @@ -26,7 +30,14 @@ Reload 🗙 + + + + + + + diff --git a/BlazorAppClean/Program.cs b/BlazorAppClean/Program.cs index e1a3708..ce153d0 100644 --- a/BlazorAppClean/Program.cs +++ b/BlazorAppClean/Program.cs @@ -1,13 +1,66 @@ +using Blazored.Modal; using BlazorAppClean.Data; +using BlazorAppClean.Services; +using Blazored.LocalStorage; +using Blazorise; +using Blazorise.Bootstrap; +using Blazorise.Icons.FontAwesome; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; +using Microsoft.AspNetCore.Localization; +using System.Globalization; +using Microsoft.Extensions.Options; +using Microsoft.Net.Http.Headers; var builder = WebApplication.CreateBuilder(args); +builder.Services.AddHttpClient("GitHub", httpClient => +{ + httpClient.BaseAddress = new Uri("https://api.github.com/"); + + // using Microsoft.Net.Http.Headers; + // The GitHub API requires two headers. + httpClient.DefaultRequestHeaders.Add(HeaderNames.Accept, "application/vnd.github.v3+json"); + httpClient.DefaultRequestHeaders.Add(HeaderNames.UserAgent, "HttpRequestsSample"); +}); + +builder.Services.AddBlazoredModal(); + +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"; }); + +// 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") }; +}); + // Add services to the container. builder.Services.AddRazorPages(); builder.Services.AddServerSideBlazor(); builder.Services.AddSingleton(); +builder.Services.AddHttpClient(); + +builder.Services + .AddBlazorise() + .AddBootstrapProviders() + .AddFontAwesomeIcons(); + +builder.Services.AddBlazoredLocalStorage(); + + +builder.Services.AddScoped(); + var app = builder.Build(); @@ -25,6 +78,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/BlazorAppClean/Resources/Pages.List.en-US.resx b/BlazorAppClean/Resources/Pages.List.en-US.resx new file mode 100644 index 0000000..75c79be --- /dev/null +++ b/BlazorAppClean/Resources/Pages.List.en-US.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 + + + List of elements + + \ No newline at end of file diff --git a/BlazorAppClean/Resources/Pages.List.fr-FR.resx b/BlazorAppClean/Resources/Pages.List.fr-FR.resx new file mode 100644 index 0000000..50bb302 --- /dev/null +++ b/BlazorAppClean/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 des éléments + + \ No newline at end of file diff --git a/BlazorAppClean/Resources/Pages.List.resx b/BlazorAppClean/Resources/Pages.List.resx new file mode 100644 index 0000000..ae67689 --- /dev/null +++ b/BlazorAppClean/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/BlazorAppClean/Services/DataApiService.cs b/BlazorAppClean/Services/DataApiService.cs new file mode 100644 index 0000000..0ff45b9 --- /dev/null +++ b/BlazorAppClean/Services/DataApiService.cs @@ -0,0 +1,59 @@ +using BlazorAppClean.Components; +using BlazorAppClean.Factories; +using BlazorAppClean.Models; + +namespace BlazorAppClean.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://localhost:7234/api/Crafting/", item); + } + + public async Task Count() + { + return await _http.GetFromJsonAsync("https://localhost:7234/api/Crafting/count"); + } + + public async Task> List(int currentPage, int pageSize) + { + return await _http.GetFromJsonAsync>($"https://localhost:7234/api/Crafting/?currentPage={currentPage}&pageSize={pageSize}"); + } + + public async Task GetById(int id) + { + return await _http.GetFromJsonAsync($"https://localhost:7234/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://localhost:7234/api/Crafting/recipe"); + } + } +} diff --git a/BlazorAppClean/Services/DataLocalService.cs b/BlazorAppClean/Services/DataLocalService.cs new file mode 100644 index 0000000..695b16a --- /dev/null +++ b/BlazorAppClean/Services/DataLocalService.cs @@ -0,0 +1,196 @@ +using BlazorAppClean.Components; +using BlazorAppClean.Factories; +using BlazorAppClean.Models; +using Blazored.LocalStorage; +using Microsoft.AspNetCore.Components; + +namespace BlazorAppClean.Services +{ + 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 image + var imagePathInfo = new DirectoryInfo($"{_webHostEnvironment.WebRootPath}/images"); + + // Check if the folder "images" exist + if (!imagePathInfo.Exists) + { + imagePathInfo.Create(); + } + + // Determine the image name + var fileName = new FileInfo($"{imagePathInfo}/{model.Name}.png"); + + // Write the file content + await File.WriteAllBytesAsync(fileName.FullName, model.ImageContent); + + // 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(); + } + 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}"); + } + + // 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 + 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); + + // Delete the image + var imagePathInfo = new DirectoryInfo($"{_webHostEnvironment.WebRootPath}/images"); + var fileName = new FileInfo($"{imagePathInfo}/{item.Name}.png"); + + if (fileName.Exists) + { + File.Delete(fileName.FullName); + } + + // 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); + } + } +} diff --git a/BlazorAppClean/Services/IDataService.cs b/BlazorAppClean/Services/IDataService.cs new file mode 100644 index 0000000..a225fe0 --- /dev/null +++ b/BlazorAppClean/Services/IDataService.cs @@ -0,0 +1,21 @@ +using BlazorAppClean.Components; +using BlazorAppClean.Models; + +namespace BlazorAppClean.Services +{ + public interface IDataService + { + Task Add(ItemModel model); + + Task Count(); + + Task> List(int currentPage, int pageSize); + Task GetById(int id); + + Task Update(int id, ItemModel model); + + Task Delete(int id); + + Task> GetRecipes(); + } +} diff --git a/BlazorAppClean/Shared/CultureSelector.razor b/BlazorAppClean/Shared/CultureSelector.razor new file mode 100644 index 0000000..6d7f012 --- /dev/null +++ b/BlazorAppClean/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); + } + } +} \ No newline at end of file diff --git a/BlazorAppClean/Shared/DoctorWhoLayout.razor b/BlazorAppClean/Shared/DoctorWhoLayout.razor new file mode 100644 index 0000000..b64449c --- /dev/null +++ b/BlazorAppClean/Shared/DoctorWhoLayout.razor @@ -0,0 +1,23 @@ +@inherits LayoutComponentBase + +
+

Doctor Who™ Episode Database

+
+ + + +@Body + +
+ @TrademarkMessage +
+ +@code { + public string TrademarkMessage { get; set; } = + "Doctor Who is a registered trademark of the BBC. " + + "https://www.doctorwho.tv/"; +} \ No newline at end of file diff --git a/BlazorAppClean/Shared/MainLayout.razor b/BlazorAppClean/Shared/MainLayout.razor index 93b782e..850c6dc 100644 --- a/BlazorAppClean/Shared/MainLayout.razor +++ b/BlazorAppClean/Shared/MainLayout.razor @@ -10,6 +10,9 @@
About +
+ +
diff --git a/BlazorAppClean/Shared/NavMenu.razor b/BlazorAppClean/Shared/NavMenu.razor index e154355..19df572 100644 --- a/BlazorAppClean/Shared/NavMenu.razor +++ b/BlazorAppClean/Shared/NavMenu.razor @@ -9,6 +9,11 @@