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