Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor Boilerplate sales module's product page response cache purge (#9870) #9876

Merged
merged 4 commits into from
Feb 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,14 @@ public partial class AppComponentBase : ComponentBase, IAsyncDisposable


private CancellationTokenSource cts = new();
protected CancellationToken CurrentCancellationToken => cts.Token;
protected CancellationToken CurrentCancellationToken
{
get
{
cts.Token.ThrowIfCancellationRequested();
return cts.Token;
}
}

protected bool InPrerenderSession => AppPlatform.IsBlazorHybrid is false && JSRuntime.IsInitialized() is false;

Expand Down Expand Up @@ -222,13 +229,13 @@ public virtual Func<T, Task> WrapHandled<T>(Func<T, Task> func,
/// <summary>
/// Cancells running codes inside current component.
/// </summary>
protected void Abort()
protected async Task Abort()
{
if (cts.IsCancellationRequested is false)
{
cts.Cancel();
cts.Dispose();
await cts.CancelAsync();
}
cts.Dispose();
cts = new();
}

Expand All @@ -244,7 +251,6 @@ protected virtual async ValueTask DisposeAsync(bool disposing)
if (disposing)
{
await PrerenderStateService.DisposeAsync();
cts.Cancel();
cts.Dispose();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ public async Task PropagateUserId(bool firstRun, Task<AuthenticationState> task)
var userId = isAuthenticated ? user.GetUserId() : (Guid?)null;
if (lastPropagatedUserId == userId)
return;
Abort(); // Cancels ongoing user id propagation, because the new authentication state is available.
await Abort(); // Cancels ongoing user id propagation, because the new authentication state is available.
lastPropagatedUserId = userId;
TelemetryContext.UserId = userId;
TelemetryContext.UserSessionId = isAuthenticated ? user.GetSessionId() : null;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
@attribute [Route(Urls.ProductPage + "/{Id:guid}")]
@attribute [Route(Urls.ProductPage + "/{Id:guid}/{Name}")]
@attribute [Route("{culture?}" + Urls.ProductPage + "/{Id:guid}")]
@attribute [Route(Urls.ProductPage + "/{Id:guid}/{Name}")]
@attribute [Route("{culture?}" + Urls.ProductPage + "/{Id:guid}/{Name}")]
@attribute [AppResponseCache(SharedMaxAge = 3600 * 24)]
@inherits AppPageBase
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,9 @@ private async Task LoadSimilarProducts()

try
{
similarProducts = await productViewController.GetSimilar(product.Id, CurrentCancellationToken);
similarProducts = await productViewController
.WithQuery(new ODataQuery { Top = 10 })
.GetSimilar(product.Id, CurrentCancellationToken);
}
finally
{
Expand All @@ -73,7 +75,9 @@ private async Task LoadSiblingProducts()

try
{
siblingProducts = await productViewController.WithQuery(new ODataQuery { Filter = $"{nameof(ProductDto.Id)} ne {product.Id}" }).GetSiblings(product.CategoryId.Value, CurrentCancellationToken);
siblingProducts = await productViewController
.WithQuery(new ODataQuery { Top = 10, Filter = $"{nameof(ProductDto.Id)} ne {product.Id}" })
.GetSiblings(product.CategoryId.Value, CurrentCancellationToken);
}
finally
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
@using System.Reflection
@using System.Runtime.Loader
@using System.Globalization
@using System.Runtime.Loader
@using Microsoft.JSInterop
@using Microsoft.Extensions.Logging
@using Microsoft.AspNetCore.Components
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public async Task<ProductDto> Update(ProductDto dto, CancellationToken cancellat

await DbContext.SaveChangesAsync(cancellationToken);

await responseCacheService.PurgeCache("/", $"product/{dto.Id}", $"api/ProductView/Get/{dto.Id}" /*You can also use Url.Action to build urls.*/);
await responseCacheService.PurgeCache("/", $"/product/{dto.Id}/{Uri.EscapeDataString(dto.Name!)}", $"/api/ProductView/Get/{dto.Id}" /*You can also use Url.Action to build urls.*/);

//#if (signalR == true)
await PublishDashboardDataChanged(cancellationToken);
Expand All @@ -90,11 +90,16 @@ public async Task<ProductDto> Update(ProductDto dto, CancellationToken cancellat
[HttpDelete("{id}/{concurrencyStamp}")]
public async Task Delete(Guid id, string concurrencyStamp, CancellationToken cancellationToken)
{
DbContext.Products.Remove(new() { Id = id, ConcurrencyStamp = Convert.FromHexString(concurrencyStamp) });
var entityToDelete = await DbContext.Products.FindAsync([id], cancellationToken)
?? throw new ResourceNotFoundException(Localizer[nameof(AppStrings.ProductCouldNotBeFound)]);

entityToDelete.ConcurrencyStamp = Convert.FromHexString(concurrencyStamp);

DbContext.Remove(entityToDelete);

await DbContext.SaveChangesAsync(cancellationToken);

await responseCacheService.PurgeCache("/", $"product/{id}", $"api/ProductView/Get/{id}" /*You can also use Url.Action to build urls.*/);
await responseCacheService.PurgeCache("/", $"/product/{entityToDelete.Id}/{Uri.EscapeDataString(entityToDelete.Name!)}", $"/api/ProductView/Get/{entityToDelete.Id}" /*You can also use Url.Action to build urls.*/);

//#if (signalR == true)
await PublishDashboardDataChanged(cancellationToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ private void ReplaceOriginalConcurrencyStamp()
//#endif
ChangeTracker.DetectChanges();

foreach (var entityEntry in ChangeTracker.Entries().Where(e => e.State is EntityState.Modified))
foreach (var entityEntry in ChangeTracker.Entries().Where(e => e.State is EntityState.Modified or EntityState.Deleted))
{
if (entityEntry.CurrentValues.TryGetValue<object>("ConcurrencyStamp", out var currentConcurrencyStamp) is false
|| currentConcurrencyStamp is not byte[])
Expand Down
Loading