Serialization.cs 28 KB

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