Skip to content

Commit

Permalink
Merge pull request #25 from le-nn/feature/support_for_blazor_web_app
Browse files Browse the repository at this point in the history
Add Blazor Web App Samples
  • Loading branch information
le-nn authored Feb 14, 2024
2 parents a6f0938 + c8dddde commit 495c066
Show file tree
Hide file tree
Showing 20 changed files with 428 additions and 5 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/build-and-deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ jobs:

- name: Publish NuGet Package
if: (github.event_name == 'release')
run: dotnet nuget push 'artifacts/**/*.nupkg' -k ${{ secrets.NUGET_API_KEY }} -s https://api.nuget.org/v3/index.json --skip-duplicate
run: dotnet nuget push 'src/**/*.nupkg' -k ${{ secrets.NUGET_API_KEY }} -s https://api.nuget.org/v3/index.json --skip-duplicate

# Generate the website
- name: Publish Sample Page
Expand All @@ -51,5 +51,5 @@ jobs:
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./artifacts/publish/Memento.Sample.BlazorWasm/release_net8.0/wwwroot
publish_dir: ./samples/Memento.Sample.BlazorWasm/bin/Release/net8.0/publish/wwwroot
force_orphan: true
16 changes: 15 additions & 1 deletion Memento.sln
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_root", "_root", "{E9CA5D2D
.editorconfig = .editorconfig
.gitignore = .gitignore
.github\workflows\build-and-deploy.yml = .github\workflows\build-and-deploy.yml
Directory.Build.props = Directory.Build.props
src\Directory.Build.props = src\Directory.Build.props
docfx.json = docfx.json
README.md = README.md
toc.yml = toc.yml
Expand Down Expand Up @@ -53,6 +53,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Memento.Sample.BlazorWasm",
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Memento.Sample.ConsoleApp", "samples\Memento.Sample.ConsoleApp\Memento.Sample.ConsoleApp.csproj", "{A089BC00-80C4-4074-8127-C414F2B79585}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Memento.Samples.Blazor.WebApp", "samples\Memento.Samples.Blazor.WebApp\Memento.Samples.Blazor.WebApp\Memento.Samples.Blazor.WebApp.csproj", "{AC47BE86-40AF-47CF-BC23-8D0707AF8EA4}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Memento.Samples.Blazor.WebApp.Client", "samples\Memento.Samples.Blazor.WebApp\Memento.Samples.Blazor.WebApp.Client\Memento.Samples.Blazor.WebApp.Client.csproj", "{D4B0BC5F-E0AA-403C-9DDE-777D742FC13A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -99,6 +103,14 @@ Global
{A089BC00-80C4-4074-8127-C414F2B79585}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A089BC00-80C4-4074-8127-C414F2B79585}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A089BC00-80C4-4074-8127-C414F2B79585}.Release|Any CPU.Build.0 = Release|Any CPU
{AC47BE86-40AF-47CF-BC23-8D0707AF8EA4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AC47BE86-40AF-47CF-BC23-8D0707AF8EA4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AC47BE86-40AF-47CF-BC23-8D0707AF8EA4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AC47BE86-40AF-47CF-BC23-8D0707AF8EA4}.Release|Any CPU.Build.0 = Release|Any CPU
{D4B0BC5F-E0AA-403C-9DDE-777D742FC13A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D4B0BC5F-E0AA-403C-9DDE-777D742FC13A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D4B0BC5F-E0AA-403C-9DDE-777D742FC13A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D4B0BC5F-E0AA-403C-9DDE-777D742FC13A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -116,6 +128,8 @@ Global
{4481A230-D66C-486F-B06A-29DECB3940FA} = {AD16691B-0034-4F49-8F90-0932C029DA3C}
{8DA8C555-F65E-4419-8732-7CAD00507166} = {AD16691B-0034-4F49-8F90-0932C029DA3C}
{A089BC00-80C4-4074-8127-C414F2B79585} = {AD16691B-0034-4F49-8F90-0932C029DA3C}
{AC47BE86-40AF-47CF-BC23-8D0707AF8EA4} = {AD16691B-0034-4F49-8F90-0932C029DA3C}
{D4B0BC5F-E0AA-403C-9DDE-777D742FC13A} = {AD16691B-0034-4F49-8F90-0932C029DA3C}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {52122159-362B-41B0-BE89-5FC9BF19BE01}
Expand Down
2 changes: 1 addition & 1 deletion samples/Memento.Sample.Blazor/Components/Counter.razor
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<h1 class="">Async Counter Component</h1>
<h2>Current count: @AsyncCounterStore.State.Count</h2>
<p>Loading: @AsyncCounterStore.State.IsLoading</p>

<p>IsBrowser: @OperatingSystem.IsBrowser()</p>
<div>
<button class="mt-3 btn btn-primary" @onclick="IncrementCount">Count up</button>
<button class="mt-3 btn btn-primary" @onclick="CountUpMany">Count up 100 times</button>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
@page "/index2"

<PageTitle>Index2</PageTitle>
@System.OperatingSystem.IsBrowser()
<h1>Hello, world 22222222!</h1>

Welcome to your new app.


<button @onclick="IncrementCount">Click me: @count</button>

@code {
private int count = 0;

private void IncrementCount()
{
count++;
}

private void DecrementCount()
{
count--;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using Memento.Core;
using Microsoft.JSInterop;

namespace Memento.Sample.Blazor;

/// <summary>
/// Middleware for logging state changes.
/// </summary>
public sealed class LoggerMiddleware : Middleware {
/// <summary>
/// Creates a new instance of the LoggerMiddlewareHandler.
/// </summary>
/// <param name="provider">The service provider used to resolve required services.</param>
/// <returns>A new LoggerMiddlewareHandler instance.</returns>
protected override MiddlewareHandler Create(IServiceProvider provider) {
return new LoggerMiddlewareHandler(
provider.GetRequiredService<IJSRuntime>()
);
}

/// <summary>
/// Handler for logging state changes in the LoggerMiddleware.
/// </summary>
/// <remarks>
/// Creates a new instance of the LoggerMiddlewareHandler.
/// </remarks>
/// <param name="jSRuntime">The JavaScript runtime to be used for logging.</param>
public class LoggerMiddlewareHandler(IJSRuntime jSRuntime) : MiddlewareHandler {
private readonly IJSRuntime _jSRuntime = jSRuntime;

/// <summary>
/// Handles logging the state changes before passing them to the next middleware.
/// </summary>
/// <param name="state">The current state of the application.</param>
/// <param name="e">The state change event arguments.</param>
/// <param name="next">The next middleware in the pipeline.</param>
/// <returns>The updated state after processing by the middleware pipeline.</returns>
public override RootState? HandleProviderDispatch(
RootState? state,
IStateChangedEventArgs<object, object> e,
NextProviderMiddlewareCallback next
) {
_ = HandleLog(state, e);
return next(state, e);
}

/// <summary>
/// Logs the state changes using the JavaScript console.
/// </summary>
/// <param name="state">The current state of the application.</param>
/// <param name="e">The state change event arguments.</param>
/// <returns>A task representing the logging operation.</returns>
public async Task HandleLog(object? state, IStateChangedEventArgs<object, object> e) {
if (state is null) {
return;
}

await _jSRuntime.InvokeVoidAsync("console.log", new {
StateName = state.GetType().Name,
State = state,
EventArgs = e,
});
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<NoDefaultLaunchSettingsFile>true</NoDefaultLaunchSettingsFile>
<StaticWebAssetProjectMode>Default</StaticWebAssetProjectMode>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="8.0.2" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\src\Memento.Blazor\Memento.Blazor.csproj" />
<ProjectReference Include="..\..\..\src\Memento.Core\Memento.Core.csproj" />
<ProjectReference Include="..\..\..\src\Memento.ReduxDevTool.Browser\Memento.ReduxDevTool.Browser.csproj" />
<ProjectReference Include="..\..\Memento.Sample.Blazor\Memento.Sample.Blazor.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using Memento.Blazor;
using Memento.ReduxDevTool.Browser;
using Memento.Sample.Blazor;
using Memento.Sample.Blazor.Todos;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services
.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) })
.AddScoped<ITodoService, MockTodoService>()
// Memento
.AddMemento()
.AddMiddleware(() => new LoggerMiddleware())
.AddBrowserReduxDevToolMiddleware(new() {
StackTraceEnabled = true,
OpenDevTool = true,
})
.ScanAssemblyAndAddStores(typeof(Memento.Sample.Blazor.App).Assembly);
await builder.Build().RunAsync();
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
@using Memento.Sample.Blazor.Shared

<Memento.Blazor.MementoInitializer />

<Router AppAssembly="typeof(Program).Assembly" AdditionalAssemblies="[typeof(Sample.Blazor.App).Assembly]">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using static Microsoft.AspNetCore.Components.Web.RenderMode
@using Microsoft.AspNetCore.Components.Web.Virtualization
@using Microsoft.JSInterop
@using Memento.Samples.Blazor.WebApp.Client
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<base href="/" />

<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<link rel="stylesheet" href="Memento.Samples.Blazor.WebApp.styles.css" />
<HeadOutlet />
</head>

<body>
<Routes @rendermode="InteractiveAuto" />
<script src="_framework/blazor.web.js"></script>
</body>

</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
@page "/Error"
@using System.Diagnostics

<PageTitle>Error</PageTitle>

<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>

@if (ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@RequestId</code>
</p>
}

<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>

@code{
[CascadingParameter]
private HttpContext? HttpContext { get; set; }

private string? RequestId { get; set; }
private bool ShowRequestId => !string.IsNullOrEmpty(RequestId);

protected override void OnInitialized() =>
RequestId = Activity.Current?.Id ?? HttpContext?.TraceIdentifier;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using static Microsoft.AspNetCore.Components.Web.RenderMode
@using Microsoft.AspNetCore.Components.Web.Virtualization
@using Microsoft.JSInterop
@using Memento.Samples.Blazor.WebApp
@using Memento.Samples.Blazor.WebApp.Client
@using Memento.Samples.Blazor.WebApp.Components
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\Memento.Samples.Blazor.WebApp.Client\Memento.Samples.Blazor.WebApp.Client.csproj" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="8.0.2" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using Memento.Blazor;
using Memento.ReduxDevTool.Browser;
using Memento.Sample.Blazor;
using Memento.Sample.Blazor.Todos;
using Memento.Samples.Blazor.WebApp.Components;

var builder = WebApplication.CreateBuilder(args);

builder.Services
.AddScoped(sp => new HttpClient { BaseAddress = new Uri("https://localhost:7288/") })
.AddScoped<ITodoService, MockTodoService>()
// Memento
.AddMemento()
.AddMiddleware(() => new ServerLoggerMiddleware())
.AddBrowserReduxDevToolMiddleware(new() {
StackTraceEnabled = true,
OpenDevTool = true,
}, true)
.ScanAssemblyAndAddStores(typeof(Memento.Sample.Blazor._Imports).Assembly);

// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents()
.AddInteractiveWebAssemblyComponents();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
app.UseWebAssemblyDebugging();
}
else {
app.UseExceptionHandler("/Error", createScopeForErrors: true);
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();
app.UseAntiforgery();

app.MapRazorComponents<Memento.Samples.Blazor.WebApp.Components.App>()
.AddInteractiveServerRenderMode()
.AddInteractiveWebAssemblyRenderMode()
.AddAdditionalAssemblies(typeof(Memento.Sample.Blazor.App).Assembly) // shared project
.AddAdditionalAssemblies(typeof(Memento.Samples.Blazor.WebApp.Client._Imports).Assembly); // client project

app.Run();
Loading

0 comments on commit 495c066

Please sign in to comment.