Serialization.cs 35 KB

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