Serialization.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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. pack.Pack(writer);
  304. }
  305. else if (typeof(ISerializeBinary).IsAssignableFrom(type) && value is ISerializeBinary binary)
  306. {
  307. binary.SerializeBinary(writer);
  308. }
  309. else if (Nullable.GetUnderlyingType(type) is Type t)
  310. {
  311. if(value == null)
  312. {
  313. writer.Write(false);
  314. }
  315. else
  316. {
  317. writer.Write(true);
  318. writer.WriteBinaryValue(t, value);
  319. }
  320. }
  321. else
  322. {
  323. throw new Exception($"Invalid type; Target DataType is {type} and value DataType is {value?.GetType().ToString() ?? "null"}");
  324. }
  325. }
  326. /// <summary>
  327. /// Binary deserialize a bunch of different types of values. <see cref="WriteBinaryValue(BinaryWriter, Type, object?)"/> and
  328. /// <see cref="ReadBinaryValue(BinaryReader, Type)"/> are inverses of each other.
  329. /// </summary>
  330. /// <remarks>
  331. /// Handles <see cref="byte"/>[], <see cref="Array"/>s of serialisable values, <see cref="Enum"/>, <see cref="bool"/>, <see cref="string"/>,
  332. /// <see cref="Guid"/>, <see cref="byte"/>, <see cref="Int16"/>, <see cref="Int32"/>, <see cref="Int64"/>, <see cref="float"/>, <see cref="double"/>,
  333. /// <see cref="DateTime"/>, <see cref="TimeSpan"/>, <see cref="LoggablePropertyAttribute"/>, <see cref="IPackable"/>, <see cref="Nullable{T}"/>
  334. /// and <see cref="ISerializeBinary"/>.
  335. /// </remarks>
  336. /// <param name="writer"></param>
  337. /// <param name="type"></param>
  338. /// <param name="value"></param>
  339. /// <exception cref="Exception">If an object of <paramref name="type"/> is unable to be deserialized.</exception>
  340. public static object? ReadBinaryValue(this BinaryReader reader, Type type)
  341. {
  342. if (type == typeof(byte[]))
  343. {
  344. var length = reader.ReadInt32();
  345. return reader.ReadBytes(length);
  346. }
  347. else if (type.IsArray)
  348. {
  349. var length = reader.ReadInt32();
  350. var elementType = type.GetElementType();
  351. var array = Array.CreateInstance(elementType, length);
  352. for (int i = 0; i < array.Length; ++i)
  353. {
  354. array.SetValue(ReadBinaryValue(reader, elementType), i);
  355. }
  356. return array;
  357. }
  358. else if (type.IsEnum)
  359. {
  360. var val = ReadBinaryValue(reader, type.GetEnumUnderlyingType());
  361. return Enum.ToObject(type, val);
  362. }
  363. else if (type == typeof(bool))
  364. {
  365. return reader.ReadBoolean();
  366. }
  367. else if (type == typeof(string))
  368. {
  369. return reader.ReadString();
  370. }
  371. else if (type == typeof(Guid))
  372. {
  373. return reader.ReadGuid();
  374. }
  375. else if (type == typeof(byte))
  376. {
  377. return reader.ReadByte();
  378. }
  379. else if (type == typeof(Int16))
  380. {
  381. return reader.ReadInt16();
  382. }
  383. else if (type == typeof(Int32))
  384. {
  385. return reader.ReadInt32();
  386. }
  387. else if (type == typeof(Int64))
  388. {
  389. return reader.ReadInt64();
  390. }
  391. else if (type == typeof(float))
  392. {
  393. return reader.ReadSingle();
  394. }
  395. else if (type == typeof(double))
  396. {
  397. return reader.ReadDouble();
  398. }
  399. else if (type == typeof(DateTime))
  400. {
  401. return new DateTime(reader.ReadInt64());
  402. }
  403. else if (type == typeof(TimeSpan))
  404. {
  405. return new TimeSpan(reader.ReadInt64());
  406. }
  407. else if (type == typeof(LoggablePropertyAttribute))
  408. {
  409. String format = reader.ReadString();
  410. return String.IsNullOrWhiteSpace(format)
  411. ? null
  412. : new LoggablePropertyAttribute() { Format = format };
  413. }
  414. else if (typeof(IPackable).IsAssignableFrom(type))
  415. {
  416. var packable = (Activator.CreateInstance(type) as IPackable)!;
  417. packable.Unpack(reader);
  418. return packable;
  419. }
  420. else if (typeof(ISerializeBinary).IsAssignableFrom(type))
  421. {
  422. var obj = (Activator.CreateInstance(type) as ISerializeBinary)!;
  423. obj.DeserializeBinary(reader);
  424. return obj;
  425. }
  426. else if (Nullable.GetUnderlyingType(type) is Type t)
  427. {
  428. var isNull = reader.ReadBoolean();
  429. if (isNull)
  430. {
  431. return null;
  432. }
  433. else
  434. {
  435. return reader.ReadBinaryValue(t);
  436. }
  437. }
  438. else
  439. {
  440. throw new Exception($"Invalid type; Target DataType is {type}");
  441. }
  442. }
  443. public static IEnumerable<IProperty> SerializableProperties(Type type) =>
  444. DatabaseSchema.Properties(type)
  445. .Where(x => !(x is StandardProperty st) || st.Property.GetCustomAttribute<DoNotSerialize>() == null);
  446. /// <summary>
  447. /// An implementation of binary serialising a <typeparamref name="TObject"/>; this is the inverse of <see cref="ReadObject{TObject}(BinaryReader)"/>.
  448. /// </summary>
  449. /// <remarks>
  450. /// Also serialises the names of properties along with the values.
  451. /// </remarks>
  452. /// <typeparam name="TObject"></typeparam>
  453. /// <param name="writer"></param>
  454. /// <param name="entity"></param>
  455. public static void WriteObject<TObject>(this BinaryWriter writer, TObject entity)
  456. where TObject : BaseObject, new()
  457. {
  458. var properties = SerializableProperties(typeof(TObject)).ToList();
  459. writer.Write(properties.Count);
  460. foreach (var property in properties)
  461. {
  462. writer.Write(property.Name);
  463. writer.WriteBinaryValue(property.PropertyType, property.Getter()(entity));
  464. }
  465. }
  466. /// <summary>
  467. /// The inverse of <see cref="WriteObject{TObject}(BinaryWriter, TObject)"/>.
  468. /// </summary>
  469. /// <typeparam name="TObject"></typeparam>
  470. /// <param name="reader"></param>
  471. /// <returns></returns>
  472. public static TObject ReadObject<TObject>(this BinaryReader reader)
  473. where TObject : BaseObject, new()
  474. {
  475. var obj = new TObject();
  476. var nProps = reader.ReadInt32();
  477. for(int i = 0; i < nProps; ++i)
  478. {
  479. var propName = reader.ReadString();
  480. var property = DatabaseSchema.Property(typeof(TObject), propName);
  481. property?.Setter()(obj, reader.ReadBinaryValue(property.PropertyType));
  482. }
  483. return obj;
  484. }
  485. /// <summary>
  486. /// An implementation of binary serialising multiple <typeparamref name="TObject"/>s;
  487. /// this is the inverse of <see cref="ReadObjects{TObject}(BinaryReader)"/>.
  488. /// </summary>
  489. /// <remarks>
  490. /// Also serialises the names of properties along with the values.
  491. /// </remarks>
  492. /// <typeparam name="TObject"></typeparam>
  493. /// <param name="writer"></param>
  494. /// <param name="entity"></param>
  495. public static void WriteObjects<TObject>(this BinaryWriter writer, ICollection<TObject> objects)
  496. where TObject : BaseObject, new()
  497. {
  498. var properties = SerializableProperties(typeof(TObject)).ToList();
  499. writer.Write(objects.Count);
  500. writer.Write(properties.Count);
  501. foreach (var property in properties)
  502. {
  503. writer.Write(property.Name);
  504. }
  505. foreach (var obj in objects)
  506. {
  507. foreach (var property in properties)
  508. {
  509. writer.WriteBinaryValue(property.PropertyType, property.Getter()(obj));
  510. }
  511. }
  512. }
  513. /// <summary>
  514. /// The inverse of <see cref="WriteObjects{TObject}(BinaryWriter, IList{TObject})"/>.
  515. /// </summary>
  516. /// <typeparam name="TObject"></typeparam>
  517. /// <param name="reader"></param>
  518. /// <returns></returns>
  519. public static List<TObject> ReadObjects<TObject>(this BinaryReader reader)
  520. where TObject : BaseObject, new()
  521. {
  522. var objs = new List<TObject>();
  523. var properties = new List<IProperty>();
  524. var nObjs = reader.ReadInt32();
  525. var nProps = reader.ReadInt32();
  526. for(int i = 0; i < nProps; ++i)
  527. {
  528. var property = reader.ReadString();
  529. properties.Add(DatabaseSchema.Property(typeof(TObject), property));
  530. }
  531. for(int i = 0; i < nObjs; ++i)
  532. {
  533. var obj = new TObject();
  534. foreach(var property in properties)
  535. {
  536. property?.Setter()(obj, reader.ReadBinaryValue(property.PropertyType));
  537. }
  538. objs.Add(obj);
  539. }
  540. return objs;
  541. }
  542. }
  543. }