64 lines
2.2 KiB
C#
64 lines
2.2 KiB
C#
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);
|
||
}
|
||
}
|
||
} |