Serialization.cs 33 KB

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