Files
telegram-bot/Core/Data/BotUserValue.cs
T

45 lines
1.3 KiB
C#
Raw Normal View History

2020-03-08 01:55:50 +04:00
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
2021-12-25 23:52:09 +04:00
using System.Diagnostics.CodeAnalysis;
2020-03-08 01:55:50 +04:00
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
2021-12-25 23:52:09 +04:00
using System.Text.Json;
2022-01-22 17:13:38 +03:00
using System.Text.Json.Serialization;
2021-12-25 23:52:09 +04:00
using System.Xml.Serialization;
2020-03-08 01:55:50 +04:00
namespace Kruzya.TelegramBot.Core.Data
{
public class BotUserValue
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
2020-03-08 01:55:50 +04:00
[Key]
public Guid BotUserValueId { get; set; }
public BotUser BotUser { get; set; }
public string Name { get; set; }
2021-12-25 23:52:09 +04:00
public string ValueType { get; set; }
public byte[] Value { get; set; }
public T GetValue<T>(T defVal = default)
2020-03-08 01:55:50 +04:00
{
2021-12-25 23:52:09 +04:00
try
2020-03-08 01:55:50 +04:00
{
2021-12-25 23:52:09 +04:00
return JsonSerializer.Deserialize<T>(new ReadOnlySpan<byte>(Value));
2020-03-08 01:55:50 +04:00
}
2021-12-25 23:52:09 +04:00
catch (Exception)
2020-03-08 01:55:50 +04:00
{
2021-12-25 23:52:09 +04:00
return defVal;
2020-03-08 01:55:50 +04:00
}
}
2021-12-25 23:52:09 +04:00
public void SetValue<T>(T value)
{
Value = JsonSerializer.SerializeToUtf8Bytes(value, new JsonSerializerOptions { WriteIndented = false,
2022-01-22 17:13:38 +03:00
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull });
2021-12-25 23:52:09 +04:00
ValueType = value.GetType().FullName;
}
2020-03-08 01:55:50 +04:00
}
}