Serialization.cs 32 KB

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