Serialization.cs 43 KB

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