Serialization.cs 39 KB

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