using System; using System.Data; using System.IO; using Newtonsoft.Json; using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBase.Interfaces; namespace TelegramBotBase.Extensions.Serializer.Legacy.NewtonsoftJson { /// /// Is used for all complex data types. Use if other default machines are not working. /// public class NewtonsoftJsonStateMachine : IStateMachine { /// /// Will initialize the state machine. /// /// Path of the file and name where to save the session details. /// /// Type of Form which will be saved instead of Form which has /// attribute declared. Needs to be subclass of /// . /// /// Declares of the file could be overwritten. public NewtonsoftJsonStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true) { FallbackStateForm = fallbackStateForm; if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase))) { throw new ArgumentException($"{nameof(FallbackStateForm)} is not a subclass of {nameof(FormBase)}"); } FilePath = file ?? throw new ArgumentNullException(nameof(file)); Overwrite = overwrite; } public string FilePath { get; set; } public bool Overwrite { get; set; } public Type FallbackStateForm { get; } public StateContainer LoadFormStates() { try { var content = File.ReadAllText(FilePath); var sc = JsonConvert.DeserializeObject(content, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All, TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple }); return sc; } catch { } return new StateContainer(); } public void SaveFormStates(SaveStatesEventArgs e) { if (File.Exists(FilePath)) { if (!Overwrite) { throw new Exception("File exists already."); } File.Delete(FilePath); } try { var content = JsonConvert.SerializeObject(e.States, Formatting.Indented, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All, TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple }); File.WriteAllText(FilePath, content); } catch { } } } }