Serialization.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  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. public static BinarySerializationSettings Latest => V1_0;
  238. public static BinarySerializationSettings V1_0 = new BinarySerializationSettings("1.0")
  239. {
  240. IncludeNullables = false
  241. };
  242. public static BinarySerializationSettings V1_1 = new BinarySerializationSettings("1.1")
  243. {
  244. IncludeNullables = true
  245. };
  246. public static BinarySerializationSettings ConvertVersionString(string version) => version switch
  247. {
  248. "1.0" => V1_0,
  249. "1.1" => V1_1,
  250. _ => V1_0
  251. };
  252. private BinarySerializationSettings(string version)
  253. {
  254. Version = version;
  255. }
  256. }
  257. public static class SerializationUtils
  258. {
  259. public static void Write(this BinaryWriter writer, Guid guid)
  260. {
  261. writer.Write(guid.ToByteArray());
  262. }
  263. public static Guid ReadGuid(this BinaryReader reader)
  264. {
  265. return new Guid(reader.ReadBytes(16));
  266. }
  267. /// <summary>
  268. /// Binary serialize a bunch of different types of values. <see cref="WriteBinaryValue(CoreBinaryWriter, Type, object?)"/> and
  269. /// <see cref="ReadBinaryValue(CoreBinaryReader, Type)"/> are inverses of each other.
  270. /// </summary>
  271. /// <remarks>
  272. /// Handles <see cref="byte"/>[], <see cref="Array"/>s of serialisable values, <see cref="Enum"/>, <see cref="bool"/>, <see cref="string"/>,
  273. /// <see cref="Guid"/>, <see cref="byte"/>, <see cref="Int16"/>, <see cref="Int32"/>, <see cref="Int64"/>, <see cref="float"/>, <see cref="double"/>,
  274. /// <see cref="DateTime"/>, <see cref="TimeSpan"/>, <see cref="LoggablePropertyAttribute"/>, <see cref="IPackable"/>, <see cref="Nullable{T}"/>
  275. /// and <see cref="ISerializeBinary"/>.
  276. /// </remarks>
  277. /// <param name="writer"></param>
  278. /// <param name="type"></param>
  279. /// <param name="value"></param>
  280. /// <exception cref="Exception">If an object of <paramref name="type"/> is unable to be serialized.</exception>
  281. public static void WriteBinaryValue(this CoreBinaryWriter writer, Type type, object? value)
  282. {
  283. value ??= CoreUtils.GetDefault(type);
  284. if (type == typeof(byte[]) && value is byte[] bArray)
  285. {
  286. writer.Write(bArray.Length);
  287. writer.Write(bArray);
  288. }
  289. else if (type == typeof(byte[]) && value is null)
  290. {
  291. writer.Write(0);
  292. }
  293. else if (type.IsArray && value is Array array)
  294. {
  295. var elementType = type.GetElementType();
  296. writer.Write(array.Length);
  297. foreach (var val1 in array)
  298. {
  299. WriteBinaryValue(writer, elementType, val1);
  300. }
  301. }
  302. else if (type.IsArray && value is null)
  303. {
  304. writer.Write(0);
  305. }
  306. else if (type.IsEnum && value is Enum e)
  307. {
  308. var underlyingType = type.GetEnumUnderlyingType();
  309. WriteBinaryValue(writer, underlyingType, Convert.ChangeType(e, underlyingType));
  310. }
  311. else if (type == typeof(bool) && value is bool b)
  312. {
  313. writer.Write(b);
  314. }
  315. else if (type == typeof(string) && value is string str)
  316. {
  317. writer.Write(str);
  318. }
  319. else if (type == typeof(string) && value is null)
  320. {
  321. writer.Write("");
  322. }
  323. else if (type == typeof(Guid) && value is Guid guid)
  324. {
  325. writer.Write(guid);
  326. }
  327. else if (type == typeof(byte) && value is byte i8)
  328. {
  329. writer.Write(i8);
  330. }
  331. else if (type == typeof(Int16) && value is Int16 i16)
  332. {
  333. writer.Write(i16);
  334. }
  335. else if (type == typeof(Int32) && value is Int32 i32)
  336. {
  337. writer.Write(i32);
  338. }
  339. else if (type == typeof(Int64) && value is Int64 i64)
  340. {
  341. writer.Write(i64);
  342. }
  343. else if (type == typeof(float) && value is float f32)
  344. {
  345. writer.Write(f32);
  346. }
  347. else if (type == typeof(double) && value is double f64)
  348. {
  349. writer.Write(f64);
  350. }
  351. else if (type == typeof(DateTime) && value is DateTime date)
  352. {
  353. writer.Write(date.Ticks);
  354. }
  355. else if (type == typeof(TimeSpan) && value is TimeSpan time)
  356. {
  357. writer.Write(time.Ticks);
  358. }
  359. else if (type == typeof(LoggablePropertyAttribute))
  360. {
  361. writer.Write((value as LoggablePropertyAttribute)?.Format ?? "");
  362. }
  363. else if (typeof(IPackable).IsAssignableFrom(type) && value is IPackable pack)
  364. {
  365. if (writer.Settings.IncludeNullables)
  366. {
  367. writer.Write(true);
  368. }
  369. pack.Pack(writer);
  370. }
  371. else if (writer.Settings.IncludeNullables && typeof(IPackable).IsAssignableFrom(type) && value is null)
  372. {
  373. writer.Write(false);
  374. }
  375. else if (typeof(ISerializeBinary).IsAssignableFrom(type) && value is ISerializeBinary binary)
  376. {
  377. if (writer.Settings.IncludeNullables)
  378. {
  379. writer.Write(true);
  380. }
  381. binary.SerializeBinary(writer);
  382. }
  383. else if (writer.Settings.IncludeNullables && typeof(ISerializeBinary).IsAssignableFrom(type) && value is null)
  384. {
  385. writer.Write(false);
  386. }
  387. else if (Nullable.GetUnderlyingType(type) is Type t)
  388. {
  389. if (value == null)
  390. {
  391. writer.Write(false);
  392. }
  393. else
  394. {
  395. writer.Write(true);
  396. writer.WriteBinaryValue(t, value);
  397. }
  398. }
  399. else if (value is UserProperty userprop)
  400. {
  401. WriteBinaryValue(writer, userprop.Type, userprop.Value);
  402. }
  403. else
  404. {
  405. throw new Exception($"Invalid type; Target DataType is {type} and value DataType is {value?.GetType().ToString() ?? "null"}");
  406. }
  407. }
  408. /// <summary>
  409. /// Binary deserialize a bunch of different types of values. <see cref="WriteBinaryValue(CoreBinaryWriter, Type, object?)"/> and
  410. /// <see cref="ReadBinaryValue(CoreBinaryReader, Type)"/> are inverses of each other.
  411. /// </summary>
  412. /// <remarks>
  413. /// Handles <see cref="byte"/>[], <see cref="Array"/>s of serialisable values, <see cref="Enum"/>, <see cref="bool"/>, <see cref="string"/>,
  414. /// <see cref="Guid"/>, <see cref="byte"/>, <see cref="Int16"/>, <see cref="Int32"/>, <see cref="Int64"/>, <see cref="float"/>, <see cref="double"/>,
  415. /// <see cref="DateTime"/>, <see cref="TimeSpan"/>, <see cref="LoggablePropertyAttribute"/>, <see cref="IPackable"/>, <see cref="Nullable{T}"/>
  416. /// and <see cref="ISerializeBinary"/>.
  417. /// </remarks>
  418. /// <param name="reader"></param>
  419. /// <param name="type"></param>
  420. /// <exception cref="Exception">If an object of <paramref name="type"/> is unable to be deserialized.</exception>
  421. public static object? ReadBinaryValue(this CoreBinaryReader reader, Type type)
  422. {
  423. if (type == typeof(byte[]))
  424. {
  425. var length = reader.ReadInt32();
  426. return reader.ReadBytes(length);
  427. }
  428. else if (type.IsArray)
  429. {
  430. var length = reader.ReadInt32();
  431. var elementType = type.GetElementType();
  432. var array = Array.CreateInstance(elementType, length);
  433. for (int i = 0; i < array.Length; ++i)
  434. {
  435. array.SetValue(ReadBinaryValue(reader, elementType), i);
  436. }
  437. return array;
  438. }
  439. else if (type.IsEnum)
  440. {
  441. var val = ReadBinaryValue(reader, type.GetEnumUnderlyingType());
  442. return Enum.ToObject(type, val);
  443. }
  444. else if (type == typeof(bool))
  445. {
  446. return reader.ReadBoolean();
  447. }
  448. else if (type == typeof(string))
  449. {
  450. return reader.ReadString();
  451. }
  452. else if (type == typeof(Guid))
  453. {
  454. return reader.ReadGuid();
  455. }
  456. else if (type == typeof(byte))
  457. {
  458. return reader.ReadByte();
  459. }
  460. else if (type == typeof(Int16))
  461. {
  462. return reader.ReadInt16();
  463. }
  464. else if (type == typeof(Int32))
  465. {
  466. return reader.ReadInt32();
  467. }
  468. else if (type == typeof(Int64))
  469. {
  470. return reader.ReadInt64();
  471. }
  472. else if (type == typeof(float))
  473. {
  474. return reader.ReadSingle();
  475. }
  476. else if (type == typeof(double))
  477. {
  478. return reader.ReadDouble();
  479. }
  480. else if (type == typeof(DateTime))
  481. {
  482. return new DateTime(reader.ReadInt64());
  483. }
  484. else if (type == typeof(TimeSpan))
  485. {
  486. return new TimeSpan(reader.ReadInt64());
  487. }
  488. else if (type == typeof(LoggablePropertyAttribute))
  489. {
  490. String format = reader.ReadString();
  491. return String.IsNullOrWhiteSpace(format)
  492. ? null
  493. : new LoggablePropertyAttribute() { Format = format };
  494. }
  495. else if (typeof(IPackable).IsAssignableFrom(type))
  496. {
  497. if (!reader.Settings.IncludeNullables || reader.ReadBoolean()) // Note the short-circuit operator preventing reading a boolean.
  498. {
  499. var packable = (Activator.CreateInstance(type) as IPackable)!;
  500. packable.Unpack(reader);
  501. return packable;
  502. }
  503. else
  504. {
  505. return null;
  506. }
  507. }
  508. else if (typeof(ISerializeBinary).IsAssignableFrom(type))
  509. {
  510. if (!reader.Settings.IncludeNullables || reader.ReadBoolean()) // Note the short-circuit operator preventing reading a boolean.
  511. {
  512. var obj = (Activator.CreateInstance(type) as ISerializeBinary)!;
  513. obj.DeserializeBinary(reader);
  514. return obj;
  515. }
  516. else
  517. {
  518. return null;
  519. }
  520. }
  521. else if (Nullable.GetUnderlyingType(type) is Type t)
  522. {
  523. var isNull = reader.ReadBoolean();
  524. if (isNull)
  525. {
  526. return null;
  527. }
  528. else
  529. {
  530. return reader.ReadBinaryValue(t);
  531. }
  532. }
  533. else
  534. {
  535. throw new Exception($"Invalid type; Target DataType is {type}");
  536. }
  537. }
  538. public static IEnumerable<IProperty> SerializableProperties(Type type) =>
  539. DatabaseSchema.Properties(type)
  540. .Where(x => !(x is StandardProperty st) || st.Property.GetCustomAttribute<DoNotSerialize>() == null);
  541. private static void GetOriginalValues(BaseObject obj, string? parent, List<Tuple<Type, string, object?>> values)
  542. {
  543. parent = parent != null ? $"{parent}." : "";
  544. foreach (var (key, value) in obj.OriginalValues)
  545. {
  546. if (DatabaseSchema.Property(obj.GetType(), key) is IProperty prop)
  547. {
  548. values.Add(new Tuple<Type, string, object?>(prop.PropertyType, parent + key, value));
  549. }
  550. }
  551. var props = obj.GetType().GetProperties().Where(x =>
  552. x.GetCustomAttribute<DoNotSerialize>() == null
  553. && x.GetCustomAttribute<DoNotPersist>() == null
  554. && x.GetCustomAttribute<AggregateAttribute>() == null
  555. && x.GetCustomAttribute<FormulaAttribute>() == null
  556. && x.GetCustomAttribute<ConditionAttribute>() == null
  557. && x.CanWrite);
  558. foreach (var prop in props)
  559. {
  560. if (prop.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity)))
  561. {
  562. if (prop.GetValue(obj) is BaseObject child)
  563. GetOriginalValues(child, parent + prop.Name, values);
  564. }
  565. else if (prop.PropertyType.GetInterfaces().Contains(typeof(IEntityLink)))
  566. {
  567. if (prop.GetValue(obj) is BaseObject child && child.HasOriginalValue("ID"))
  568. {
  569. values.Add(new Tuple<Type, string, object?>(typeof(Guid), parent + prop.Name + ".ID", child.OriginalValues["ID"]));
  570. }
  571. }
  572. }
  573. }
  574. private static void WriteOriginalValues<TObject>(this CoreBinaryWriter writer, TObject obj)
  575. where TObject : BaseObject
  576. {
  577. var originalValues = new List<Tuple<Type, string, object?>>();
  578. GetOriginalValues(obj, null, originalValues);
  579. writer.Write(originalValues.Count);
  580. foreach (var (type, key, value) in originalValues)
  581. {
  582. writer.Write(key);
  583. writer.WriteBinaryValue(type, value);
  584. }
  585. }
  586. private static void ReadOriginalValues<TObject>(this CoreBinaryReader reader, TObject obj)
  587. where TObject : BaseObject
  588. {
  589. var nOriginalValues = reader.ReadInt32();
  590. for (int i = 0; i < nOriginalValues; ++i)
  591. {
  592. var key = reader.ReadString();
  593. if (DatabaseSchema.Property(typeof(TObject), key) is IProperty prop)
  594. {
  595. var value = reader.ReadBinaryValue(prop.PropertyType);
  596. if (prop.Parent is null)
  597. {
  598. obj.OriginalValues[prop.Name] = value;
  599. }
  600. else
  601. {
  602. if (prop.Parent.Getter()(obj) is BaseObject parent)
  603. {
  604. parent.OriginalValues[prop.Name.Split('.').Last()] = value;
  605. }
  606. }
  607. }
  608. }
  609. }
  610. /// <summary>
  611. /// An implementation of binary serialising a <typeparamref name="TObject"/>; this is the inverse of <see cref="ReadObject{TObject}(CoreBinaryReader)"/>.
  612. /// </summary>
  613. /// <remarks>
  614. /// Also serialises the names of properties along with the values.
  615. /// </remarks>
  616. /// <typeparam name="TObject"></typeparam>
  617. /// <param name="writer"></param>
  618. /// <param name="entity"></param>
  619. public static void WriteObject<TObject>(this CoreBinaryWriter writer, TObject entity)
  620. where TObject : BaseObject, new()
  621. {
  622. var properties = SerializableProperties(typeof(TObject)).ToList();
  623. writer.Write(properties.Count);
  624. foreach (var property in properties)
  625. {
  626. writer.Write(property.Name);
  627. writer.WriteBinaryValue(property.PropertyType, property.Getter()(entity));
  628. }
  629. writer.WriteOriginalValues(entity);
  630. }
  631. /// <summary>
  632. /// The inverse of <see cref="WriteObject{TObject}(CoreBinaryWriter, TObject)"/>.
  633. /// </summary>
  634. /// <typeparam name="TObject"></typeparam>
  635. /// <param name="reader"></param>
  636. /// <returns></returns>
  637. public static TObject ReadObject<TObject>(this CoreBinaryReader reader)
  638. where TObject : BaseObject, new()
  639. {
  640. var obj = new TObject();
  641. obj.SetObserving(false);
  642. var nProps = reader.ReadInt32();
  643. for (int i = 0; i < nProps; ++i)
  644. {
  645. var propName = reader.ReadString();
  646. var property = DatabaseSchema.Property(typeof(TObject), propName);
  647. property?.Setter()(obj, reader.ReadBinaryValue(property.PropertyType));
  648. }
  649. reader.ReadOriginalValues(obj);
  650. obj.SetObserving(true);
  651. return obj;
  652. }
  653. /// <summary>
  654. /// An implementation of binary serialising multiple <typeparamref name="TObject"/>s;
  655. /// this is the inverse of <see cref="ReadObjects{TObject}(CoreBinaryReader)"/>.
  656. /// </summary>
  657. /// <remarks>
  658. /// Also serialises the names of properties along with the values.
  659. /// </remarks>
  660. /// <typeparam name="TObject"></typeparam>
  661. /// <param name="writer"></param>
  662. /// <param name="objects"></param>
  663. public static void WriteObjects<TObject>(this CoreBinaryWriter writer, ICollection<TObject> objects)
  664. where TObject : BaseObject, new()
  665. {
  666. var properties = SerializableProperties(typeof(TObject)).ToList();
  667. writer.Write(objects.Count);
  668. writer.Write(properties.Count);
  669. foreach (var property in properties)
  670. {
  671. writer.Write(property.Name);
  672. }
  673. foreach (var obj in objects)
  674. {
  675. foreach (var property in properties)
  676. {
  677. writer.WriteBinaryValue(property.PropertyType, property.Getter()(obj));
  678. }
  679. writer.WriteOriginalValues(obj);
  680. }
  681. }
  682. /// <summary>
  683. /// The inverse of <see cref="WriteObjects{TObject}(CoreBinaryWriter, ICollection{TObject})"/>.
  684. /// </summary>
  685. /// <typeparam name="TObject"></typeparam>
  686. /// <param name="reader"></param>
  687. /// <returns></returns>
  688. public static List<TObject> ReadObjects<TObject>(this CoreBinaryReader reader)
  689. where TObject : BaseObject, new()
  690. {
  691. var objs = new List<TObject>();
  692. var properties = new List<IProperty>();
  693. var nObjs = reader.ReadInt32();
  694. var nProps = reader.ReadInt32();
  695. for (int i = 0; i < nProps; ++i)
  696. {
  697. var property = reader.ReadString();
  698. properties.Add(DatabaseSchema.Property(typeof(TObject), property));
  699. }
  700. for (int i = 0; i < nObjs; ++i)
  701. {
  702. var obj = new TObject();
  703. obj.SetObserving(false);
  704. foreach (var property in properties)
  705. {
  706. property?.Setter()(obj, reader.ReadBinaryValue(property.PropertyType));
  707. }
  708. reader.ReadOriginalValues(obj);
  709. obj.SetObserving(true);
  710. objs.Add(obj);
  711. }
  712. return objs;
  713. }
  714. }
  715. }