Serialization.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text.Json;
  8. using System.Text.Json.Serialization;
  9. using System.Text.Json.Serialization.Metadata;
  10. using InABox.Clients;
  11. namespace InABox.Core
  12. {
  13. public enum SerializationFormat
  14. {
  15. Json,
  16. Binary
  17. }
  18. public class SerialisationException : Exception
  19. {
  20. public SerialisationException(string message): base(message) { }
  21. }
  22. public interface ISerializeBinary
  23. {
  24. public void SerializeBinary(CoreBinaryWriter writer);
  25. public void DeserializeBinary(CoreBinaryReader reader);
  26. }
  27. public static class Serialization
  28. {
  29. /// <summary>
  30. /// TypeInfoResolver modifier that removes properties that don't have setters.
  31. /// </summary>
  32. /// <param name="typeInfo"></param>
  33. public static void WritablePropertiesOnly(JsonTypeInfo typeInfo)
  34. {
  35. if(typeInfo.Kind == JsonTypeInfoKind.Object)
  36. {
  37. var toRemove = typeInfo.Properties.Where(x => x.Set is null).ToList();
  38. foreach(var prop in toRemove)
  39. {
  40. typeInfo.Properties.Remove(prop);
  41. }
  42. }
  43. }
  44. private static JsonConverter[]? _converters;
  45. private static JsonConverter[] GetConverters()
  46. {
  47. _converters ??= CoreUtils.Entities.Where(x => typeof(JsonConverter).IsAssignableFrom(x))
  48. .Select(x => Activator.CreateInstance(x) as JsonConverter)
  49. .NotNull()
  50. .ToArray();
  51. return _converters;
  52. }
  53. private static JsonSerializerOptions SerializerSettings(bool indented = true, bool populateObject = false)
  54. {
  55. return CreateSerializerSettings(indented, populateObject);
  56. }
  57. public static JsonSerializerOptions CreateSerializerSettings(bool indented = true, bool populateObject = false)
  58. {
  59. var settings = new JsonSerializerOptions { };
  60. foreach (var converter in GetConverters())
  61. {
  62. settings.Converters.Add(converter);
  63. }
  64. if (populateObject)
  65. {
  66. settings.TypeInfoResolver = new PopulateTypeInfoResolver(new DefaultJsonTypeInfoResolver());
  67. }
  68. settings.WriteIndented = indented;
  69. return settings;
  70. }
  71. public static string Serialize(object? o, bool indented = false)
  72. {
  73. var json = JsonSerializer.Serialize(o, SerializerSettings(indented));
  74. return json;
  75. }
  76. public static void Serialize(object o, Stream stream, bool indented = false)
  77. {
  78. var settings = SerializerSettings(indented);
  79. JsonSerializer.Serialize(stream, o, settings);
  80. }
  81. [return: MaybeNull]
  82. public static T Deserialize<T>(Stream? stream, bool strict = false)
  83. {
  84. if (stream == null)
  85. return default;
  86. try
  87. {
  88. var settings = SerializerSettings();
  89. return JsonSerializer.Deserialize<T>(stream, settings);
  90. }
  91. catch (Exception e)
  92. {
  93. if (strict)
  94. throw;
  95. Logger.Send(LogType.Error, ClientFactory.UserID, $"Error in Deserialize<{typeof(T)}>(): {e.Message}");
  96. return default;
  97. }
  98. }
  99. public static object? Deserialize(Type type, Stream? stream)
  100. {
  101. if (stream == null)
  102. return null;
  103. object? result = null;
  104. var settings = SerializerSettings();
  105. result = JsonSerializer.Deserialize(stream, type, settings);
  106. return result;
  107. }
  108. [return: MaybeNull]
  109. public static T Deserialize<T>(string? json, bool strict = false) // where T : new()
  110. {
  111. var ret = default(T);
  112. if (string.IsNullOrWhiteSpace(json))
  113. return ret;
  114. try
  115. {
  116. var settings = SerializerSettings();
  117. if (typeof(T).IsArray)
  118. {
  119. ret = JsonSerializer.Deserialize<T>(json, settings);
  120. }
  121. else
  122. {
  123. ret = JsonSerializer.Deserialize<T>(json, settings);
  124. }
  125. }
  126. catch (Exception e)
  127. {
  128. if (strict)
  129. {
  130. throw;
  131. }
  132. CoreUtils.LogException("", e);
  133. if (typeof(T).IsArray)
  134. {
  135. ret = (T)(object)Array.CreateInstance(typeof(T).GetElementType(), 0);
  136. }
  137. else
  138. {
  139. ret = (T)Activator.CreateInstance(typeof(T), true);
  140. }
  141. }
  142. return ret;
  143. }
  144. [return: MaybeNull]
  145. public static void DeserializeInto<T>(string? json, T obj, bool strict = false)
  146. {
  147. if (string.IsNullOrWhiteSpace(json))
  148. return;
  149. try
  150. {
  151. var settings = SerializerSettings(populateObject: true);
  152. PopulateTypeInfoResolver.t_populateObject = obj;
  153. if (typeof(T).IsArray)
  154. {
  155. JsonSerializer.Deserialize<T>(json, settings);
  156. }
  157. else
  158. {
  159. JsonSerializer.Deserialize<T>(json, settings);
  160. }
  161. }
  162. catch (Exception e)
  163. {
  164. if (strict)
  165. {
  166. throw;
  167. }
  168. CoreUtils.LogException("", e);
  169. }
  170. finally
  171. {
  172. PopulateTypeInfoResolver.t_populateObject = null;
  173. }
  174. }
  175. public static object? Deserialize(Type T, string json) // where T : new()
  176. {
  177. var ret = T.GetDefault();
  178. if (string.IsNullOrWhiteSpace(json))
  179. return ret;
  180. try
  181. {
  182. var settings = SerializerSettings();
  183. if (T.IsArray)
  184. {
  185. object o = Array.CreateInstance(T.GetElementType(), 0);
  186. ret = o;
  187. }
  188. else
  189. {
  190. ret = JsonSerializer.Deserialize(json, T, settings);
  191. }
  192. }
  193. catch (Exception)
  194. {
  195. ret = Activator.CreateInstance(T, true);
  196. }
  197. return ret;
  198. }
  199. #region Binary Serialization
  200. public static byte[] WriteBinary(this ISerializeBinary obj, BinarySerializationSettings settings)
  201. {
  202. using var stream = new MemoryStream();
  203. obj.SerializeBinary(new CoreBinaryWriter(stream, settings));
  204. return stream.ToArray();
  205. }
  206. public static void WriteBinary(this ISerializeBinary obj, Stream stream, BinarySerializationSettings settings)
  207. {
  208. obj.SerializeBinary(new CoreBinaryWriter(stream, settings));
  209. }
  210. public static T ReadBinary<T>(byte[] data, BinarySerializationSettings settings)
  211. where T : ISerializeBinary, new() => (T)ReadBinary(typeof(T), data, settings);
  212. public static T ReadBinary<T>(Stream stream, BinarySerializationSettings settings)
  213. where T : ISerializeBinary, new() => (T)ReadBinary(typeof(T), stream, settings);
  214. public static object ReadBinary(Type T, byte[] data, BinarySerializationSettings settings)
  215. {
  216. using var stream = new MemoryStream(data);
  217. return ReadBinary(T, stream, settings);
  218. }
  219. public static object ReadBinary(Type T, Stream stream, BinarySerializationSettings settings)
  220. {
  221. var obj = (Activator.CreateInstance(T) as ISerializeBinary)!;
  222. obj.DeserializeBinary(new CoreBinaryReader(stream, settings));
  223. return obj;
  224. }
  225. #endregion
  226. }
  227. internal class PopulateTypeInfoResolver : IJsonTypeInfoResolver
  228. {
  229. private readonly IJsonTypeInfoResolver? _jsonTypeInfoResolver;
  230. [ThreadStatic]
  231. internal static object? t_populateObject;
  232. public PopulateTypeInfoResolver(IJsonTypeInfoResolver? jsonTypeInfoResolver)
  233. {
  234. _jsonTypeInfoResolver = jsonTypeInfoResolver;
  235. }
  236. public JsonTypeInfo? GetTypeInfo(Type type, JsonSerializerOptions options)
  237. {
  238. var typeInfo = _jsonTypeInfoResolver?.GetTypeInfo(type, options);
  239. if(typeInfo != null && typeInfo.Kind != JsonTypeInfoKind.None)
  240. {
  241. var defaultCreateObject = typeInfo.CreateObject;
  242. if(defaultCreateObject != null)
  243. {
  244. typeInfo.CreateObject = () =>
  245. {
  246. if (t_populateObject != null)
  247. {
  248. var result = t_populateObject;
  249. t_populateObject = null;
  250. return result;
  251. }
  252. else
  253. {
  254. return defaultCreateObject.Invoke();
  255. }
  256. };
  257. }
  258. }
  259. return typeInfo;
  260. }
  261. }
  262. public class CoreBinaryReader : BinaryReader
  263. {
  264. public BinarySerializationSettings Settings { get; set; }
  265. public CoreBinaryReader(Stream stream, BinarySerializationSettings settings) : base(stream)
  266. {
  267. Settings = settings;
  268. }
  269. }
  270. public class CoreBinaryWriter : BinaryWriter
  271. {
  272. public BinarySerializationSettings Settings { get; set; }
  273. public CoreBinaryWriter(Stream stream, BinarySerializationSettings settings) : base(stream)
  274. {
  275. Settings = settings;
  276. }
  277. }
  278. /// <summary>
  279. /// A class to maintain the consistency of serialisation formats across versions.
  280. /// The design of this is such that specific versions of serialisation have different parameters set,
  281. /// and the versions are maintained as static properties. Please keep the constructor private.
  282. /// </summary>
  283. /// <remarks>
  284. /// Note that <see cref="Latest"/> should always be updated to point to the latest version.
  285. /// <br/>
  286. /// Note also that all versions should have an entry in the <see cref="ConvertVersionString(string)"/> function.
  287. /// <br/>
  288. /// Also, if you create a new format, it would probably be a good idea to add a database update script to get all
  289. /// <see cref="IPackable"/> and <see cref="ISerializeBinary"/> properties and update the version of the format.
  290. /// (Otherwise, we'd basically be nullifying all data that is currently binary serialised.)
  291. /// </remarks>
  292. public class BinarySerializationSettings
  293. {
  294. /// <summary>
  295. /// Should the Info() call return RPC and Rest Ports? This is
  296. /// To workaround a bug in RPCsockets that crash on large uploads
  297. /// </summary>
  298. /// <remarks>
  299. /// True in all serialization versions >= 1.2
  300. /// </remarks>
  301. public bool RPCClientWorkaround { get; set; }
  302. /// <summary>
  303. /// Should reference types include a flag for nullability? (Adds an extra boolean field for whether the value is null or not).
  304. /// </summary>
  305. /// <remarks>
  306. /// True in all serialisation versions >= 1.1.
  307. /// </remarks>
  308. public bool IncludeNullables { get; set; }
  309. public string Version { get; set; }
  310. public static BinarySerializationSettings Latest => V1_2;
  311. public static BinarySerializationSettings V1_0 = new BinarySerializationSettings("1.0")
  312. {
  313. IncludeNullables = false,
  314. RPCClientWorkaround = false
  315. };
  316. public static BinarySerializationSettings V1_1 = new BinarySerializationSettings("1.1")
  317. {
  318. IncludeNullables = true,
  319. RPCClientWorkaround = false
  320. };
  321. public static BinarySerializationSettings V1_2 = new BinarySerializationSettings("1.2")
  322. {
  323. IncludeNullables = true,
  324. RPCClientWorkaround = true
  325. };
  326. public static BinarySerializationSettings ConvertVersionString(string version) => version switch
  327. {
  328. "1.0" => V1_0,
  329. "1.1" => V1_1,
  330. "1.2" => V1_2,
  331. _ => V1_0
  332. };
  333. private BinarySerializationSettings(string version)
  334. {
  335. Version = version;
  336. }
  337. }
  338. public static class SerializationUtils
  339. {
  340. public static void Write(this BinaryWriter writer, Guid guid)
  341. {
  342. writer.Write(guid.ToByteArray());
  343. }
  344. public static Guid ReadGuid(this BinaryReader reader)
  345. {
  346. return new Guid(reader.ReadBytes(16));
  347. }
  348. public static void Write(this BinaryWriter writer, DateTime dateTime)
  349. {
  350. writer.Write(dateTime.Ticks);
  351. }
  352. public static DateTime ReadDateTime(this BinaryReader reader)
  353. {
  354. return new DateTime(reader.ReadInt64());
  355. }
  356. private static bool MatchType<T1>(Type t) => typeof(T1) == t;
  357. private static bool MatchType<T1,T2>(Type t) => (typeof(T1) == t) || (typeof(T2) == t);
  358. /// <summary>
  359. /// Binary serialize a bunch of different types of values. <see cref="WriteBinaryValue(CoreBinaryWriter, Type, object?)"/> and
  360. /// <see cref="ReadBinaryValue(CoreBinaryReader, Type)"/> are inverses of each other.
  361. /// </summary>
  362. /// <remarks>
  363. /// Handles <see cref="byte"/>[], <see cref="Array"/>s of serialisable values, <see cref="Enum"/>, <see cref="bool"/>, <see cref="string"/>,
  364. /// <see cref="Guid"/>, <see cref="byte"/>, <see cref="Int16"/>, <see cref="Int32"/>, <see cref="Int64"/>, <see cref="float"/>, <see cref="double"/>,
  365. /// <see cref="DateTime"/>, <see cref="TimeSpan"/>, <see cref="LoggablePropertyAttribute"/>, <see cref="IPackable"/>, <see cref="Nullable{T}"/>
  366. /// and <see cref="ISerializeBinary"/>.
  367. /// </remarks>
  368. /// <param name="writer"></param>
  369. /// <param name="type"></param>
  370. /// <param name="value"></param>
  371. /// <exception cref="Exception">If an object of <paramref name="type"/> is unable to be serialized.</exception>
  372. public static void WriteBinaryValue(this CoreBinaryWriter writer, Type type, object? value)
  373. {
  374. value ??= CoreUtils.GetDefault(type);
  375. if (value == null)
  376. {
  377. if (MatchType<string>(type))
  378. writer.Write("");
  379. else if (writer.Settings.IncludeNullables && typeof(IPackable).IsAssignableFrom(type))
  380. writer.Write(false);
  381. else if (writer.Settings.IncludeNullables && typeof(ISerializeBinary).IsAssignableFrom(type))
  382. writer.Write(false);
  383. else if (Nullable.GetUnderlyingType(type) is Type t)
  384. writer.Write(false);
  385. else if (MatchType<LoggablePropertyAttribute, object>(type))
  386. writer.Write("");
  387. else
  388. writer.Write(0);
  389. }
  390. else if (MatchType<byte[], object>(type) && value is byte[] bArray)
  391. {
  392. writer.Write(bArray.Length);
  393. writer.Write(bArray);
  394. }
  395. else if (type.IsArray && value is Array array)
  396. {
  397. var elementType = type.GetElementType();
  398. writer.Write(array.Length);
  399. foreach (var val1 in array)
  400. {
  401. WriteBinaryValue(writer, elementType, val1);
  402. }
  403. }
  404. else if (type.IsEnum && value is Enum e)
  405. {
  406. var underlyingType = type.GetEnumUnderlyingType();
  407. WriteBinaryValue(writer, underlyingType, Convert.ChangeType(e, underlyingType));
  408. }
  409. else if (MatchType<bool, object>(type) && value is bool b)
  410. {
  411. writer.Write(b);
  412. }
  413. else if (MatchType<string, object>(type) && value is string str)
  414. writer.Write(str);
  415. else if (MatchType<Guid, object>(type) && value is Guid guid)
  416. writer.Write(guid);
  417. else if (MatchType<byte, object>(type) && value is byte i8)
  418. writer.Write(i8);
  419. else if (MatchType<Int16, object>(type) && value is Int16 i16)
  420. writer.Write(i16);
  421. else if (MatchType<Int32, object>(type) && value is Int32 i32)
  422. writer.Write(i32);
  423. else if (MatchType<Int64, object>(type) && value is Int64 i64)
  424. writer.Write(i64);
  425. else if (MatchType<float, object>(type) && value is float f32)
  426. writer.Write(f32);
  427. else if (MatchType<double, object>(type) && value is double f64)
  428. writer.Write(f64);
  429. else if (MatchType<DateTime, object>(type) && value is DateTime date)
  430. writer.Write(date.Ticks);
  431. else if (MatchType<TimeSpan, object>(type) && value is TimeSpan time)
  432. writer.Write(time.Ticks);
  433. else if (MatchType<LoggablePropertyAttribute, object>(type) && value is LoggablePropertyAttribute lpa)
  434. writer.Write(lpa.Format ?? string.Empty);
  435. else if (typeof(IPackable).IsAssignableFrom(type) && value is IPackable pack)
  436. {
  437. if (writer.Settings.IncludeNullables)
  438. writer.Write(true);
  439. pack.Pack(writer);
  440. }
  441. else if (typeof(ISerializeBinary).IsAssignableFrom(type) && value is ISerializeBinary binary)
  442. {
  443. if (writer.Settings.IncludeNullables)
  444. writer.Write(true);
  445. binary.SerializeBinary(writer);
  446. }
  447. else if (Nullable.GetUnderlyingType(type) is Type t)
  448. {
  449. writer.Write(true);
  450. writer.WriteBinaryValue(t, value);
  451. }
  452. else if (value is UserProperty userprop)
  453. WriteBinaryValue(writer, userprop.Type, userprop.Value);
  454. else
  455. throw new SerialisationException($"Invalid type; Target DataType is {type} and value DataType is {value?.GetType().ToString() ?? "null"}");
  456. }
  457. public static void WriteBinaryValue<T>(this CoreBinaryWriter writer, T value)
  458. => WriteBinaryValue(writer, typeof(T), value);
  459. /// <summary>
  460. /// Binary deserialize a bunch of different types of values. <see cref="WriteBinaryValue(CoreBinaryWriter, Type, object?)"/> and
  461. /// <see cref="ReadBinaryValue(CoreBinaryReader, Type)"/> are inverses of each other.
  462. /// </summary>
  463. /// <remarks>
  464. /// Handles <see cref="byte"/>[], <see cref="Array"/>s of serialisable values, <see cref="Enum"/>, <see cref="bool"/>, <see cref="string"/>,
  465. /// <see cref="Guid"/>, <see cref="byte"/>, <see cref="Int16"/>, <see cref="Int32"/>, <see cref="Int64"/>, <see cref="float"/>, <see cref="double"/>,
  466. /// <see cref="DateTime"/>, <see cref="TimeSpan"/>, <see cref="LoggablePropertyAttribute"/>, <see cref="IPackable"/>, <see cref="Nullable{T}"/>
  467. /// and <see cref="ISerializeBinary"/>.
  468. /// </remarks>
  469. /// <param name="reader"></param>
  470. /// <param name="type"></param>
  471. /// <exception cref="Exception">If an object of <paramref name="type"/> is unable to be deserialized.</exception>
  472. public static object? ReadBinaryValue(this CoreBinaryReader reader, Type type)
  473. {
  474. if (type == typeof(byte[]))
  475. {
  476. var length = reader.ReadInt32();
  477. return reader.ReadBytes(length);
  478. }
  479. else if (type.IsArray)
  480. {
  481. var length = reader.ReadInt32();
  482. var elementType = type.GetElementType();
  483. var array = Array.CreateInstance(elementType, length);
  484. for (int i = 0; i < array.Length; ++i)
  485. {
  486. array.SetValue(ReadBinaryValue(reader, elementType), i);
  487. }
  488. return array;
  489. }
  490. else if (type.IsEnum)
  491. {
  492. var val = ReadBinaryValue(reader, type.GetEnumUnderlyingType());
  493. return Enum.ToObject(type, val);
  494. }
  495. else if (type == typeof(bool))
  496. {
  497. return reader.ReadBoolean();
  498. }
  499. else if (type == typeof(string))
  500. {
  501. return reader.ReadString();
  502. }
  503. else if (type == typeof(Guid))
  504. {
  505. return reader.ReadGuid();
  506. }
  507. else if (type == typeof(byte))
  508. {
  509. return reader.ReadByte();
  510. }
  511. else if (type == typeof(Int16))
  512. {
  513. return reader.ReadInt16();
  514. }
  515. else if (type == typeof(Int32))
  516. {
  517. return reader.ReadInt32();
  518. }
  519. else if (type == typeof(Int64))
  520. {
  521. return reader.ReadInt64();
  522. }
  523. else if (type == typeof(float))
  524. {
  525. return reader.ReadSingle();
  526. }
  527. else if (type == typeof(double))
  528. {
  529. return reader.ReadDouble();
  530. }
  531. else if (type == typeof(DateTime))
  532. {
  533. return new DateTime(reader.ReadInt64());
  534. }
  535. else if (type == typeof(TimeSpan))
  536. {
  537. return new TimeSpan(reader.ReadInt64());
  538. }
  539. else if (type == typeof(LoggablePropertyAttribute))
  540. {
  541. String format = reader.ReadString();
  542. return String.IsNullOrWhiteSpace(format)
  543. ? null
  544. : new LoggablePropertyAttribute() { Format = format };
  545. }
  546. else if (typeof(IPackable).IsAssignableFrom(type))
  547. {
  548. if (!reader.Settings.IncludeNullables || reader.ReadBoolean()) // Note the short-circuit operator preventing reading a boolean.
  549. {
  550. var packable = (Activator.CreateInstance(type) as IPackable)!;
  551. packable.Unpack(reader);
  552. return packable;
  553. }
  554. else
  555. {
  556. return null;
  557. }
  558. }
  559. else if (typeof(ISerializeBinary).IsAssignableFrom(type))
  560. {
  561. if (!reader.Settings.IncludeNullables || reader.ReadBoolean()) // Note the short-circuit operator preventing reading a boolean.
  562. {
  563. var obj = (Activator.CreateInstance(type, true) as ISerializeBinary)!;
  564. obj.DeserializeBinary(reader);
  565. return obj;
  566. }
  567. else
  568. {
  569. return null;
  570. }
  571. }
  572. else if (Nullable.GetUnderlyingType(type) is Type t)
  573. {
  574. var isNull = reader.ReadBoolean();
  575. if (isNull)
  576. {
  577. return null;
  578. }
  579. else
  580. {
  581. return reader.ReadBinaryValue(t);
  582. }
  583. }
  584. else
  585. {
  586. throw new SerialisationException($"Invalid type; Target DataType is {type}");
  587. }
  588. }
  589. public static T ReadBinaryValue<T>(this CoreBinaryReader reader)
  590. {
  591. var result = ReadBinaryValue(reader, typeof(T));
  592. return (result != null ? (T)result : default)!;
  593. }
  594. public static IEnumerable<IProperty> SerializableProperties(Type type, Predicate<IProperty>? filter = null) =>
  595. DatabaseSchema.Properties(type)
  596. .Where(x => (!(x is StandardProperty st) || st.IsSerializable) && (filter?.Invoke(x) ?? true));
  597. private static void WriteOriginalValues<TObject>(this CoreBinaryWriter writer, TObject obj)
  598. where TObject : BaseObject
  599. {
  600. var originalValues = new List<Tuple<Type, string, object?>>();
  601. foreach (var (key, value) in obj.OriginalValueList)
  602. {
  603. if (DatabaseSchema.Property(obj.GetType(), key) is IProperty prop && prop.IsSerializable)
  604. {
  605. originalValues.Add(new Tuple<Type, string, object?>(prop.PropertyType, key, value));
  606. }
  607. }
  608. writer.Write(originalValues.Count);
  609. foreach (var (type, key, value) in originalValues)
  610. {
  611. writer.Write(key);
  612. try
  613. {
  614. writer.WriteBinaryValue(type, value);
  615. }
  616. catch (Exception e)
  617. {
  618. CoreUtils.LogException("", e, "Error serialising OriginalValues");
  619. }
  620. }
  621. }
  622. private static void ReadOriginalValues<TObject>(this CoreBinaryReader reader, TObject obj)
  623. where TObject : BaseObject
  624. {
  625. var nOriginalValues = reader.ReadInt32();
  626. for (int i = 0; i < nOriginalValues; ++i)
  627. {
  628. var key = reader.ReadString();
  629. if (DatabaseSchema.Property(obj.GetType(), key) is IProperty prop)
  630. {
  631. var value = reader.ReadBinaryValue(prop.PropertyType);
  632. obj.OriginalValueList[prop.Name] = value;
  633. }
  634. }
  635. }
  636. public static void WriteObject<TObject>(this CoreBinaryWriter writer, TObject entity, Type type)
  637. where TObject : BaseObject
  638. {
  639. if (!typeof(TObject).IsAssignableFrom(type))
  640. throw new SerialisationException($"{type.EntityName()} is not a subclass of {typeof(TObject).EntityName()}");
  641. var properties = SerializableProperties(type).ToList();
  642. writer.Write(properties.Count);
  643. foreach (var property in properties)
  644. {
  645. writer.Write(property.Name);
  646. writer.WriteBinaryValue(property.PropertyType, property.Getter()(entity));
  647. }
  648. writer.WriteOriginalValues(entity);
  649. }
  650. /// <summary>
  651. /// An implementation of binary serialising a <typeparamref name="TObject"/>; this is the inverse of <see cref="ReadObject{TObject}(CoreBinaryReader)"/>.
  652. /// </summary>
  653. /// <remarks>
  654. /// Also serialises the names of properties along with the values.
  655. /// </remarks>
  656. /// <typeparam name="TObject"></typeparam>
  657. /// <param name="writer"></param>
  658. /// <param name="entity"></param>
  659. public static void WriteObject<TObject>(this CoreBinaryWriter writer, TObject entity)
  660. where TObject : BaseObject, new() => WriteObject(writer, entity, typeof(TObject));
  661. public static TObject ReadObject<TObject>(this CoreBinaryReader reader, Type type)
  662. where TObject : BaseObject
  663. {
  664. if (!typeof(TObject).IsAssignableFrom(type))
  665. throw new SerialisationException($"{type.EntityName()} is not a subclass of {typeof(TObject).EntityName()}");
  666. var obj = (Activator.CreateInstance(type) as TObject)!;
  667. obj.SetObserving(false);
  668. var nProps = reader.ReadInt32();
  669. for (int i = 0; i < nProps; ++i)
  670. {
  671. var propName = reader.ReadString();
  672. var property = DatabaseSchema.Property(type, propName)
  673. ?? throw new SerialisationException($"Property {propName} does not exist on {type.EntityName()}");
  674. property.Setter()(obj, reader.ReadBinaryValue(property.PropertyType));
  675. }
  676. reader.ReadOriginalValues(obj);
  677. obj.SetObserving(true);
  678. return obj;
  679. }
  680. /// <summary>
  681. /// The inverse of <see cref="WriteObject{TObject}(CoreBinaryWriter, TObject)"/>.
  682. /// </summary>
  683. /// <typeparam name="TObject"></typeparam>
  684. /// <param name="reader"></param>
  685. /// <returns></returns>
  686. public static TObject ReadObject<TObject>(this CoreBinaryReader reader)
  687. where TObject : BaseObject, new() => reader.ReadObject<TObject>(typeof(TObject));
  688. /// <summary>
  689. /// An implementation of binary serialising multiple <typeparamref name="TObject"/>s;
  690. /// this is the inverse of <see cref="ReadObjects{TObject}(CoreBinaryReader)"/>.
  691. /// </summary>
  692. /// <remarks>
  693. /// Also serialises the names of properties along with the values.
  694. /// </remarks>
  695. /// <typeparam name="TObject"></typeparam>
  696. /// <param name="writer"></param>
  697. /// <param name="objects"></param>
  698. public static void WriteObjects<TObject>(this CoreBinaryWriter writer, ICollection<TObject>? objects)
  699. where TObject : BaseObject, new() => WriteObjects(writer, typeof(TObject), objects);
  700. public static void WriteObjects<TObject>(this CoreBinaryWriter writer, Type type, ICollection<TObject>? objects, Predicate<IProperty>? filter = null)
  701. where TObject : BaseObject
  702. {
  703. if (!typeof(TObject).IsAssignableFrom(type))
  704. throw new SerialisationException($"{type.EntityName()} is not a subclass of {typeof(TObject).EntityName()}");
  705. var nObjs = objects?.Count ?? 0;
  706. writer.Write(nObjs);
  707. if (nObjs == 0)
  708. {
  709. return;
  710. }
  711. var properties = SerializableProperties(type, filter).ToList();
  712. writer.Write(properties.Count);
  713. foreach (var property in properties)
  714. {
  715. writer.Write(property.Name);
  716. }
  717. if(objects != null)
  718. {
  719. foreach (var obj in objects)
  720. {
  721. foreach (var property in properties)
  722. {
  723. writer.WriteBinaryValue(property.PropertyType, property.Getter()(obj));
  724. }
  725. writer.WriteOriginalValues(obj);
  726. }
  727. }
  728. }
  729. /// <summary>
  730. /// The inverse of <see cref="WriteObjects{TObject}(CoreBinaryWriter, ICollection{TObject})"/>.
  731. /// </summary>
  732. /// <typeparam name="TObject"></typeparam>
  733. /// <param name="reader"></param>
  734. /// <returns></returns>
  735. public static List<TObject> ReadObjects<TObject>(this CoreBinaryReader reader)
  736. where TObject : BaseObject, new()
  737. {
  738. return ReadObjects<TObject>(reader, typeof(TObject));
  739. }
  740. public static List<TObject> ReadObjects<TObject>(this CoreBinaryReader reader, Type type) where TObject : BaseObject
  741. {
  742. if (!typeof(TObject).IsAssignableFrom(type))
  743. throw new SerialisationException($"{type.EntityName()} is not a subclass of {typeof(TObject).EntityName()}");
  744. var objs = new List<TObject>();
  745. var properties = new List<IProperty>();
  746. var nObjs = reader.ReadInt32();
  747. if(nObjs == 0)
  748. {
  749. return objs;
  750. }
  751. var nProps = reader.ReadInt32();
  752. for (int i = 0; i < nProps; ++i)
  753. {
  754. var propertyName = reader.ReadString();
  755. var property = DatabaseSchema.Property(type, propertyName)
  756. ?? throw new SerialisationException($"Property {propertyName} does not exist on {type.EntityName()}");
  757. properties.Add(property);
  758. }
  759. for (int i = 0; i < nObjs; ++i)
  760. {
  761. var obj = (Activator.CreateInstance(type) as TObject)!;
  762. obj.SetObserving(false);
  763. foreach (var property in properties)
  764. {
  765. property.Setter()(obj, reader.ReadBinaryValue(property.PropertyType));
  766. }
  767. reader.ReadOriginalValues(obj);
  768. obj.SetObserving(true);
  769. objs.Add(obj);
  770. }
  771. return objs;
  772. }
  773. }
  774. public abstract class CustomJsonConverter<T> : JsonConverter<T>
  775. {
  776. protected object? ReadJson(ref Utf8JsonReader reader)
  777. {
  778. switch (reader.TokenType)
  779. {
  780. case JsonTokenType.String:
  781. return reader.GetString();
  782. case JsonTokenType.Number:
  783. if (reader.TryGetInt32(out int intValue))
  784. return intValue;
  785. if (reader.TryGetDouble(out double doubleValue))
  786. return doubleValue;
  787. return null;
  788. case JsonTokenType.True:
  789. return true;
  790. case JsonTokenType.False:
  791. return false;
  792. case JsonTokenType.Null:
  793. return null;
  794. case JsonTokenType.StartArray:
  795. var values = new List<object?>();
  796. reader.Read();
  797. while(reader.TokenType != JsonTokenType.EndArray)
  798. {
  799. values.Add(ReadJson(ref reader));
  800. reader.Read();
  801. }
  802. return values;
  803. default:
  804. return null;
  805. }
  806. }
  807. /// <summary>
  808. /// Write a value as a JSON object; note that some data types, like
  809. /// <see cref="Guid"/> and <see cref="DateTime"/> will be encoded as
  810. /// strings, and therefore will be returned as strings when read by
  811. /// <see cref="ReadJson(Utf8JsonReader)"/>. However, all types that
  812. /// this can write should be able to be retrieved by calling <see
  813. /// cref="CoreUtils.ChangeType(object?, Type)"/> on the resultant
  814. /// value.
  815. /// </summary>
  816. protected void WriteJson(Utf8JsonWriter writer, object? value)
  817. {
  818. if (value == null)
  819. writer.WriteNullValue();
  820. else if (value is string sVal)
  821. writer.WriteStringValue(sVal);
  822. else if (value is bool bVal)
  823. writer.WriteBooleanValue(bVal);
  824. else if (value is byte b)
  825. writer.WriteNumberValue(b);
  826. else if (value is short i16)
  827. writer.WriteNumberValue(i16);
  828. else if (value is int i32)
  829. writer.WriteNumberValue(i32);
  830. else if (value is long i64)
  831. writer.WriteNumberValue(i64);
  832. else if (value is float f)
  833. writer.WriteNumberValue(f);
  834. else if (value is double dVal)
  835. writer.WriteNumberValue(dVal);
  836. else if (value is DateTime dtVal)
  837. writer.WriteStringValue(dtVal.ToString());
  838. else if (value is TimeSpan tsVal)
  839. writer.WriteStringValue(tsVal.ToString());
  840. else if (value is Guid guid)
  841. writer.WriteStringValue(guid.ToString());
  842. else if(value is byte[] arr)
  843. {
  844. writer.WriteBase64StringValue(arr);
  845. }
  846. else if(value is Array array)
  847. {
  848. writer.WriteStartArray();
  849. foreach(var val1 in array)
  850. {
  851. WriteJson(writer, val1);
  852. }
  853. writer.WriteEndArray();
  854. }
  855. else if(value is Enum e)
  856. {
  857. WriteJson(writer, Convert.ChangeType(e, e.GetType().GetEnumUnderlyingType()));
  858. }
  859. else
  860. {
  861. Logger.Send(LogType.Error, "", $"Could not write object of type {value.GetType()} as JSON");
  862. }
  863. }
  864. protected void WriteJson(Utf8JsonWriter writer, string name, object? value)
  865. {
  866. writer.WritePropertyName(name);
  867. WriteJson(writer, value);
  868. }
  869. }
  870. }