Serialization.cs 29 KB

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