using System.Reflection; namespace BotPages.Core; /// /// Базовый класс страницы с состоянием и аргументами. /// public abstract class StatefullPage : StatefullPage { /// Вход на страницу с аргументами. public virtual Task OnEnter(PageContext ctx, TArgs args, CancellationToken ct) => base.OnEnter(ctx, ct); } /// /// Базовый класс страницы с состоянием. /// Создается для каждого пользователя. /// public abstract class StatefullPage : Page { /// /// Загружает значения свойств из StateStorage. /// protected async Task LoadState(PageContext ctx, CancellationToken ct) { foreach (var prop in GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { var attr = prop.GetCustomAttribute(); if (attr is null) continue; var value = await ctx.StateStorage.GetAsync(ctx.SessionKey, attr.Key, ct); if (value is not null) { prop.SetValue(this, value); } } } /// /// Сохраняет значения свойств в StateStorage. /// protected async Task SaveState(PageContext ctx, CancellationToken ct) { foreach (var prop in GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { var attr = prop.GetCustomAttribute(); if (attr is null) continue; var value = prop.GetValue(this); await ctx.StateStorage.SetAsync(ctx.SessionKey, attr.Key, value, ct); } } }