Serialization.cs 33 KB

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