Skip to content

Commit

Permalink
Explore possible perf issues with static property loading (#4234)
Browse files Browse the repository at this point in the history
* If !SyncContextWithServer properly load empty session

* #2551 Updating ProjectTracker code

* #4182 Fix Blazor context manager issue

* Optimize code

* Fix issue where "non-mobile" objects don't serialize

Non-mobile objects now need to have an opportunity to be serialized by a custom formatter for that type, so all types should _try_ to serialize.

* Clarify test names

* #4182 Fix context manager accessor

* Update to latest CSLA

* #4182 Fix issue with IContextManager selection

* Provide better exception information
  • Loading branch information
rockfordlhotka authored Oct 21, 2024
1 parent 56c55fc commit e035ad7
Show file tree
Hide file tree
Showing 19 changed files with 128 additions and 115 deletions.
4 changes: 3 additions & 1 deletion Samples/ProjectTracker/Directory.Packages.props
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
<CslaVersion>9.0.0-alpha-g3aa97cd7dd</CslaVersion>
<CslaVersion>9.0.0-preview-gc9290534f6</CslaVersion>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Csla" Version="$(CslaVersion)" />
<PackageVersion Include="Csla.AspNetCore" Version="$(CslaVersion)" />
<PackageVersion Include="Csla.Blazor" Version="$(CslaVersion)" />
<PackageVersion Include="Csla.Blazor.WebAssembly" Version="$(CslaVersion)" />
<PackageVersion Include="Marimer.Blazor.RenderMode" Version="1.0.2" />
<PackageVersion Include="Marimer.Blazor.RenderMode.WebAssembly" Version="1.0.2" />
<PackageVersion Include="Microsoft.AspNetCore.Components.WebAssembly" Version="8.0.7" />
<PackageVersion Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="8.0.7" />
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="8.0.7" />
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
@page "/editproject"
@page "/editproject/{id:int}"
@using Microsoft.AspNetCore.Components.Authorization

@rendermode InteractiveAuto

@using Marimer.Blazor.RenderMode
@using Microsoft.AspNetCore.Components.Authorization

@inject NavigationManager NavigationManager
@inject Csla.Blazor.State.StateManager StateManager
@inject ProjectTracker.Blazor.RenderModeProvider renderModeProvider
@inject RenderModeProvider renderModeProvider
@inject Csla.IDataPortal<ProjectEdit> projectEditPortal
@inject Csla.Blazor.ViewModel<ProjectEdit> vm
@inject Csla.ApplicationContext ApplicationContext
Expand All @@ -17,19 +20,14 @@
<p class="alert-danger">@vm.Exception.ToString()</p>
}

@if (!IsInteractive)
@if (!IsInteractive || vm.Model == null)
{
<h1>Edit Project</h1>
<p class="animated-box"></p>
<p class="animated-box"></p>
<p class="animated-box"></p>
<p class="animated-box"></p>
}
else if (vm.Model == null)
{
<h1>Edit Project</h1>
<p>Loading data...</p>
}
else
{
<h1>@vm.Model.Name</h1>
Expand Down Expand Up @@ -177,7 +175,7 @@ else
await StateManager.InitializeAsync();

var renderMode = renderModeProvider.GetRenderMode(this);
IsInteractive = renderMode == RenderModes.WasmInteractive || renderMode == RenderModes.ServerInteractive;
IsInteractive = renderMode.IsInteractive();
if (IsInteractive)
{
vm.Saved += () => NavigationManager.NavigateTo("projects");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
using Csla.Configuration;
using Marimer.Blazor.RenderMode.WebAssembly;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using ProjectTracker.Blazor;

var builder = WebAssemblyHostBuilder.CreateDefault(args);

builder.Services.AddAuthorizationCore();
builder.Services.AddCascadingAuthenticationState();

// Add render mode detection services
builder.Services.AddTransient<RenderModeProvider>();
builder.Services.AddScoped<ActiveCircuitState>();
builder.Services.AddRenderModeDetection();

builder.Services.AddMemoryCache();

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

builder.Services.AddCsla(o => o
.AddBlazorWebAssembly(o => o.SyncContextWithServer = true)
.DataPortal(o => o.AddClientSideDataPortal(o => o
.UseHttpProxy(o => o.DataPortalUrl = "/api/dataportal"))));
builder.Services.AddCsla(_ => _
.AddBlazorWebAssembly(_ => _.SyncContextWithServer = true)
.DataPortal(_ => _.AddClientSideDataPortal(_ => _
.UseHttpProxy(_ => _.DataPortalUrl = "/api/dataportal"))));

await builder.Build().RunAsync();
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

<ItemGroup>
<ProjectReference Include="..\..\ProjectTracker.BusinessLibrary\ProjectTracker.BusinessLibrary.csproj" />
<PackageReference Include="Marimer.Blazor.RenderMode.WebAssembly" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" />
<PackageReference Include="Csla.Blazor" />
<PackageReference Include="Csla.Blazor.WebAssembly" />
Expand Down

This file was deleted.

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace ProjectTracker.Blazor.Controllers
/// <param name="sessionManager"></param>
[ApiController]
[Route("[controller]")]
public class CslaStateController(ApplicationContext applicationContext, ISessionManager sessionManager) :
Csla.AspNetCore.Blazor.State.StateController(applicationContext, sessionManager)
public class CslaStateController(ApplicationContext applicationContext, ISessionManager sessionManager) :
Csla.AspNetCore.Blazor.State.StateController(applicationContext, sessionManager)
{ }
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using Csla.Configuration;
using Marimer.Blazor.RenderMode;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Components.Server.Circuits;
using ProjectTracker.Blazor;
using ProjectTracker.Blazor.Components;
using ProjectTracker.Configuration;

Expand All @@ -20,9 +19,7 @@
builder.Services.AddCascadingAuthenticationState();

// Add render mode detection services
builder.Services.AddTransient<RenderModeProvider>();
builder.Services.AddScoped<ActiveCircuitState>();
builder.Services.AddScoped(typeof(CircuitHandler), typeof(ActiveCircuitHandler));
builder.Services.AddRenderModeDetection();

// CSLA requires AddHttpContextAccessor
builder.Services.AddHttpContextAccessor();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,26 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<Compile Remove="Identity\**" />
<Content Remove="Identity\**" />
<EmbeddedResource Remove="Identity\**" />
<None Remove="Identity\**" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\ProjectTracker.BusinessLibrary\ProjectTracker.BusinessLibrary.csproj" />
<ProjectReference Include="..\..\ProjectTracker.DalEfCore\ProjectTracker.DalEfCore.csproj" />
<ProjectReference Include="..\..\ProjectTracker.DalMock\ProjectTracker.DalMock.csproj" />
<ProjectReference Include="..\..\ProjectTracker.Dal\ProjectTracker.Dal.csproj" />
<ProjectReference Include="..\ProjectTracker.Blazor.Client\ProjectTracker.Blazor.Client.csproj" />
<PackageReference Include="Marimer.Blazor.RenderMode" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" />
<PackageReference Include="Csla.AspNetCore" />
<PackageReference Include="Csla.Blazor" />
</ItemGroup>

<ItemGroup>
<Folder Include="Identity\" />
<Folder Include="wwwroot\images\" />
</ItemGroup>

Expand Down
38 changes: 26 additions & 12 deletions Source/Csla.AspNetCore/Blazor/ApplicationContextManagerBlazor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,7 @@ private void AuthenticationStateProvider_AuthenticationStateChanged(Task<Authent
/// context manager is valid for use in
/// the current environment.
/// </summary>
public bool IsValid
{
get { return HttpContext is not null || ActiveCircuitState.CircuitExists; }
}
public bool IsValid => ActiveCircuitState.CircuitExists;

/// <summary>
/// Gets a value indicating whether the context manager
Expand All @@ -137,19 +134,36 @@ public IPrincipal GetUser()
/// Not supported in Blazor.
/// </summary>
/// <param name="principal">Principal object.</param>
public virtual void SetUser(IPrincipal principal) => throw new NotSupportedException(nameof(SetUser));
public virtual void SetUser(IPrincipal principal)
{
ArgumentNullException.ThrowIfNull(principal);
if (HttpContext != null)
{
if (principal is ClaimsPrincipal claimsPrincipal)
HttpContext.User = claimsPrincipal;
else
throw new NotSupportedException($"{nameof(SetUser)}: {nameof(principal)}.GetType() != {nameof(ClaimsPrincipal)}");
}
else
{
throw new NotSupportedException($"{nameof(SetUser)}: {nameof(HttpContext)} == null");
}
}

private const string _localContextName = "Csla.LocalContext";
private const string _clientContextName = "Csla.ClientContext";

/// <summary>
/// Gets the local context.
/// </summary>
/// <exception cref="InvalidOperationException"><see cref="ApplicationContext"/> is <see langword="null"/>.</exception>
public IContextDictionary GetLocalContext()
public IContextDictionary? GetLocalContext()
{
ThrowIfApplicationContextIsNull();
IContextDictionary localContext;
IContextDictionary? localContext;
var sessionManager = ApplicationContext.GetRequiredService<ISessionManager>();
var session = sessionManager.GetSession();
session.TryGetValue("localContext", out var result);
session.TryGetValue(_localContextName, out var result);
if (result is IContextDictionary context)
{
localContext = context;
Expand All @@ -172,7 +186,7 @@ public void SetLocalContext(IContextDictionary? localContext)
ThrowIfApplicationContextIsNull();
var sessionManager = ApplicationContext.GetRequiredService<ISessionManager>();
var session = sessionManager.GetSession();
session["localContext"] = localContext;
session[_localContextName] = localContext;
}

/// <summary>
Expand All @@ -186,7 +200,7 @@ public IContextDictionary GetClientContext(ApplicationContext.ExecutionLocations
IContextDictionary clientContext;
var sessionManager = ApplicationContext.GetRequiredService<ISessionManager>();
var session = sessionManager.GetSession();
session.TryGetValue("clientContext", out var result);
session.TryGetValue(_clientContextName, out var result);
if (result is IContextDictionary context)
{
clientContext = context;
Expand All @@ -202,15 +216,15 @@ public IContextDictionary GetClientContext(ApplicationContext.ExecutionLocations
/// <summary>
/// Sets the client context.
/// </summary>
/// <param name="clientContext">Client context.</param>
/// <param name="clientContext"></param>
/// <param name="executionLocation"></param>
/// <exception cref="InvalidOperationException"><see cref="ApplicationContext"/> is <see langword="null"/>.</exception>
public void SetClientContext(IContextDictionary? clientContext, ApplicationContext.ExecutionLocations executionLocation)
{
ThrowIfApplicationContextIsNull();
var sessionManager = ApplicationContext.GetRequiredService<ISessionManager>();
var session = sessionManager.GetSession();
session["clientContext"] = clientContext;
session[_clientContextName] = clientContext;
}

/// <summary>
Expand Down
11 changes: 6 additions & 5 deletions Source/Csla.AspNetCore/Blazor/State/SessionIdManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,20 @@ public string GetSessionId()
if (httpContext == null)
throw new InvalidOperationException("HttpContext == null");

if (httpContext.Request.Cookies.ContainsKey(sessionIdName))
if (httpContext.Request.Cookies.TryGetValue(sessionIdName, out var requestItem))
{
result = httpContext.Request.Cookies[sessionIdName];
result = requestItem;
}
else if (httpContext.Items.TryGetValue(sessionIdName, out var item))
else if (httpContext.Items.TryGetValue(sessionIdName, out var itemsItem))
{
result = item as string;
result = itemsItem as string;
}
else
{
result = Guid.NewGuid().ToString();
httpContext.Response.Cookies.Append(sessionIdName, result);
httpContext.Items[sessionIdName] = result;
if (!httpContext.Response.HasStarted)
httpContext.Response.Cookies.Append(sessionIdName, result);
}

return result ?? throw new InvalidOperationException(Csla.Properties.Resources.SessionIdManagerIdMustBeNotNull);
Expand Down
Loading

0 comments on commit e035ad7

Please sign in to comment.