Files
BotPages/BotPages.Core/Pages/StatefullPage.cs
FrigaT 7f81ca85b8
All checks were successful
CI / build-test (push) Successful in 32s
Доработано сохранение состояния
2025-12-05 13:45:38 +03:00

64 lines
2.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Reflection;
namespace BotPages.Core;
/// <summary>
/// Базовый класс страницы с состоянием и аргументами.
/// </summary>
public abstract class StatefullPage<TArgs> : StatefullPage
{
/// <summary>Вход на страницу с аргументами.</summary>
public virtual Task OnEnter(PageContext ctx, TArgs args, CancellationToken ct)
=> base.OnEnter(ctx, ct);
}
/// <summary>
/// Базовый класс страницы с состоянием.
/// Создается для каждого пользователя.
/// </summary>
public abstract class StatefullPage : Page
{
/// <summary>
/// Загружает значения свойств из StateStorage.
/// </summary>
protected async Task LoadState(PageContext ctx, CancellationToken ct)
{
foreach (var prop in GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
var attr = prop.GetCustomAttribute<StatefullAttribute>();
if (attr is null) continue;
var value = await ctx.StateStorage.GetAsync<object>(ctx.SessionKey, attr.Key, ct);
if (value is not null)
{
prop.SetValue(this, value);
}
}
}
/// <summary>
/// Сохраняет значения свойств в StateStorage.
/// </summary>
protected async Task SaveState(PageContext ctx, CancellationToken ct)
{
var t = GetType();
foreach (var prop in t.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
{
var attr = prop.GetCustomAttribute<StatefullAttribute>();
if (attr is null) continue;
var value = prop.GetValue(this);
await ctx.StateStorage.SetAsync(ctx.SessionKey, attr.Key, value, ct);
}
foreach (var prop in t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
{
var attr = prop.GetCustomAttribute<StatefullAttribute>();
if (attr is null) continue;
var value = prop.GetValue(this);
await ctx.StateStorage.SetAsync(ctx.SessionKey, attr.Key, value, ct);
}
}
}