Serialization.cs 33 KB

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