using System; using System.Collections.Generic; using System.IO; using System.Linq; using ProtoBuf; namespace CC_Functions.AspNet { /// /// An implementation of SaveLoadDict that uses Protobuf-net for serialization and Guid keys /// /// The data type public abstract class SerialDict : SaveLoadDict { //Interface /// /// Gets the directory containing databases /// public abstract string DatabasesDir { get; } /// /// Gets the file name for this database. Must not contain the path /// public abstract string DatabaseFileName { get; } /// /// Called when the database is loaded. Use for preparing initial entries /// public event LoadedD Loaded; /// /// Called when the database is loaded. Use for preparing initial entries /// /// The current dictionary content public delegate void LoadedD(IDictionary v); /// /// Loads the dictionary and replaces Guids with strings. Use for sending /// /// The simplified dictionary public IDictionary GetSendable() => Load().ToDictionary(s => s.Key.ToString(), s => s.Value); //Internal private string GetRel() => Path.Combine(DatabasesDir, DatabaseFileName); /// protected override IDictionary Load() { if (!Directory.Exists(DatabasesDir)) Directory.CreateDirectory(DatabasesDir); IDictionary v; if (File.Exists(GetRel())) { using (FileStream file = File.OpenRead(GetRel())) v = Serializer.Deserialize>(file); Loaded?.Invoke(v); return v; } else { v = new Dictionary(); Loaded?.Invoke(v); Save(v); return v; } } /// protected override void Save(IDictionary dict) { if (!Directory.Exists(DatabasesDir)) Directory.CreateDirectory(DatabasesDir); using FileStream file = File.Create(GetRel()); Serializer.Serialize(file, dict); } } }