Serialization.cs 29 KB

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