Serialization.cs 23 KB

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