Serialization.cs 33 KB

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