Column.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.Linq;
  6. using System.Linq.Expressions;
  7. using System.Reflection;
  8. using System.Runtime.Serialization;
  9. using Newtonsoft.Json;
  10. using Newtonsoft.Json.Linq;
  11. namespace InABox.Core
  12. {
  13. public interface IColumn
  14. {
  15. string Property { get; }
  16. Expression Expression { get; }
  17. Type Type { get; }
  18. }
  19. public static class Column
  20. {
  21. public static IColumn Create(Type concrete, string property)
  22. {
  23. var type = typeof(Column<>).MakeGenericType(concrete);
  24. var result = Activator.CreateInstance(type, property) as IColumn;
  25. return result!;
  26. }
  27. }
  28. public class Column<T> : SerializableExpression<T>, IColumn
  29. {
  30. public Type Type
  31. {
  32. get
  33. {
  34. if (Expression == null)
  35. throw new Exception(string.Format("Expression [{0}] may not be null!", Property));
  36. if (Expression is IndexExpression)
  37. return DatabaseSchema.Property(typeof(T), Property).PropertyType;
  38. return Expression.Type;
  39. }
  40. }
  41. public bool IsEqualTo(string name) =>
  42. !string.IsNullOrWhiteSpace(name) && string.Equals(Property, name);
  43. public bool IsEqualTo(Column<T> column) => string.Equals(Property, column.Property);
  44. public bool IsParentOf(string name) =>
  45. !string.IsNullOrWhiteSpace(name) && name.StartsWith(Property + ".");
  46. public Column()
  47. {
  48. }
  49. public Column(IProperty property)
  50. {
  51. Property = property.Name;
  52. Expression = property.Expression();
  53. }
  54. public Column(Expression<Func<T, object?>> expression) : base(expression)
  55. {
  56. //String[] parts = expression.ToString().Split(new String[] { "=>" }, StringSplitOptions.RemoveEmptyEntries);
  57. //string property = String.Join(".", parts.Last().Split('.').Skip(1));
  58. //property = property.Replace("Convert(", "").Replace("(","").Replace(")", "");
  59. Property = CoreUtils.GetFullPropertyName(expression, ".");
  60. }
  61. public Column(string property)
  62. {
  63. Property = property;
  64. var iprop = DatabaseSchema.Property(typeof(T), property);
  65. if (iprop != null)
  66. Expression = iprop.Expression();
  67. else
  68. Expression = CoreUtils.CreateMemberExpression(typeof(T), property);
  69. }
  70. public Column<TNew> Cast<TNew>()
  71. where TNew: T
  72. {
  73. return new Column<TNew>(Property);
  74. }
  75. public bool TryCast<TNew>([NotNullWhen(true)] out Column<TNew>? newColumn)
  76. {
  77. if(DatabaseSchema.Property(typeof(TNew), Property) is IProperty property)
  78. {
  79. newColumn = new Column<TNew>(property);
  80. return true;
  81. }
  82. else
  83. {
  84. newColumn = null;
  85. return false;
  86. }
  87. }
  88. public string Property { get; private set; }
  89. public override void Deserialize(SerializationInfo info, StreamingContext context)
  90. {
  91. }
  92. public override void Serialize(SerializationInfo info, StreamingContext context)
  93. {
  94. }
  95. public static explicit operator Column<T>(Column<Entity> v)
  96. {
  97. var result = new Column<T>();
  98. var exp = CoreUtils.ExpressionToString(typeof(T), v.Expression, true);
  99. result.Expression = CoreUtils.StringToExpression(exp);
  100. result.Property = v.Property;
  101. return result;
  102. }
  103. public override string ToString()
  104. {
  105. var name = Expression.ToString().Replace("x => ", "").Replace("x.", "");
  106. if (Expression.NodeType == System.Linq.Expressions.ExpressionType.Index)
  107. {
  108. var chars = name.SkipWhile(x => !x.Equals('[')).TakeWhile(x => !x.Equals(']'));
  109. name = string.Join("", chars).Replace("[", "").Replace("]", "").Replace("\"", "");
  110. }
  111. return name;
  112. //return Property.ToString();
  113. }
  114. }
  115. public interface IColumns : ISerializeBinary
  116. {
  117. int Count { get; }
  118. bool Any();
  119. IEnumerable<IColumn> GetColumns();
  120. IEnumerable<string> ColumnNames();
  121. Dictionary<String, Type> AsDictionary();
  122. IColumns Add(string column);
  123. IColumns Add(IColumn column);
  124. IColumns Add<T>(Expression<Func<T, object?>> column);
  125. IColumns DefaultColumns(params ColumnType[] types);
  126. }
  127. public enum ColumnType
  128. {
  129. ExcludeVisible,
  130. /// <summary>
  131. /// Do not include <see cref="Entity.ID"/> in the columns.
  132. /// </summary>
  133. ExcludeID,
  134. IncludeOptional,
  135. IncludeForeignKeys,
  136. /// <summary>
  137. /// Include all columns that are accessible through entity links present in the root class.
  138. /// </summary>
  139. IncludeLinked,
  140. IncludeAggregates,
  141. IncludeFormulae,
  142. /// <summary>
  143. /// Include any columns that are a <see cref="CustomProperty"/>.
  144. /// </summary>
  145. IncludeUserProperties,
  146. /// <summary>
  147. /// Include all columns that are accessible through entity links, even nested ones.
  148. /// </summary>
  149. IncludeNestedLinks,
  150. IncludeEditable,
  151. /// <summary>
  152. /// Add all columns that are data actually on the entity, and not on entity links or calculated fields.
  153. /// </summary>
  154. DataColumns,
  155. /// <summary>
  156. /// Add all columns found.
  157. /// </summary>
  158. All
  159. }
  160. public static class Columns
  161. {
  162. public static IColumns Create<T>(Type concrete)
  163. {
  164. if (!typeof(T).IsAssignableFrom(concrete))
  165. throw new Exception($"Columns: {concrete.EntityName()} does not implement {typeof(T).EntityName()}");
  166. var type = typeof(Columns<>).MakeGenericType(concrete);
  167. var result = Activator.CreateInstance(type);
  168. return (result as IColumns)!;
  169. }
  170. public static IColumns Create(Type concrete)
  171. {
  172. var type = typeof(Columns<>).MakeGenericType(concrete);
  173. var result = Activator.CreateInstance(type) as IColumns;
  174. return result!;
  175. }
  176. public static IColumns Create(Type concrete, IEnumerable<string> columns)
  177. {
  178. var type = typeof(Columns<>).MakeGenericType(concrete);
  179. var result = (IColumns)Activator.CreateInstance(type);
  180. foreach (var column in columns)
  181. result.Add(column);
  182. return result;
  183. }
  184. public static IColumns Create(Type concrete, params string[] columns)
  185. {
  186. var type = typeof(Columns<>).MakeGenericType(concrete);
  187. var result = (IColumns)Activator.CreateInstance(type);
  188. foreach (var column in columns)
  189. result.Add(column);
  190. return result;
  191. }
  192. }
  193. public class Columns<T> : IColumns, IEnumerable<Column<T>>
  194. {
  195. private readonly List<Column<T>> columns;
  196. public Columns()
  197. {
  198. columns = new List<Column<T>>();
  199. }
  200. /// <summary>
  201. /// Create a new <see cref="Columns{T}"/>, using <paramref name="columns"/> as the internal list.
  202. /// </summary>
  203. /// <remarks>
  204. /// <paramref name="columns"/> is passed by reference and is stored as the internal list of the <see cref="Columns{T}"/>;
  205. /// hence if one wishes <paramref name="columns"/> to not be modified, one should pass a copy of the list.
  206. /// </remarks>
  207. /// <param name="columns"></param>
  208. public Columns(List<Column<T>> columns)
  209. {
  210. this.columns = columns;
  211. }
  212. public Columns<TNew> Cast<TNew>()
  213. where TNew : T
  214. {
  215. var cols = new Columns<TNew>();
  216. foreach(var column in columns)
  217. {
  218. cols.Add(column.Cast<TNew>());
  219. }
  220. return cols;
  221. }
  222. /// <summary>
  223. /// Cast the columns to <typeparamref name="TNew"/>, keeping the columns that are found in both <typeparamref name="T"/> and <typeparamref name="TNew"/>.
  224. /// </summary>
  225. /// <typeparam name="TNew"></typeparam>
  226. /// <returns></returns>
  227. public Columns<TNew> CastIntersection<TNew>()
  228. {
  229. var cols = new Columns<TNew>();
  230. foreach(var column in columns)
  231. {
  232. if (column.TryCast<TNew>(out var newColumn))
  233. {
  234. cols.Add(newColumn);
  235. }
  236. }
  237. return cols;
  238. }
  239. public override string ToString()
  240. {
  241. return String.Join("; ", columns.Select(x => x.Property));
  242. }
  243. public int IndexOf(String columnname)
  244. {
  245. return ColumnNames().ToList().IndexOf(columnname);
  246. }
  247. public int IndexOf(Expression<Func<T, object>> expression)
  248. {
  249. return ColumnNames().ToList().IndexOf(CoreUtils.GetFullPropertyName(expression,"."));
  250. }
  251. public Columns(params Expression<Func<T, object?>>[] expressions) : this()
  252. {
  253. foreach (var expression in expressions)
  254. columns.Add(new Column<T>(expression));
  255. }
  256. public Columns(IEnumerable<string> properties) : this()
  257. {
  258. foreach (var property in properties)
  259. columns.Add(new Column<T>(property));
  260. }
  261. public Column<T>[] Items
  262. {
  263. get { return columns != null ? columns.ToArray() : new Column<T>[] { }; }
  264. set
  265. {
  266. columns.Clear();
  267. columns.AddRange(value);
  268. }
  269. }
  270. public int Count => columns.Count;
  271. public IEnumerable<IColumn> GetColumns() => columns;
  272. public bool Any() => columns.Any();
  273. public bool Contains(string column) => Items.Any(x => x.IsEqualTo(column));
  274. public bool Contains(Column<T> column) => Items.Any(x => x.IsEqualTo(column));
  275. public IColumns Add(string column)
  276. {
  277. if(CoreUtils.TryGetProperty(typeof(T), column, out var propertyInfo))
  278. {
  279. if (!propertyInfo.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity)) &&
  280. !propertyInfo.PropertyType.GetInterfaces().Any(x => x == typeof(IEntityLink)))
  281. {
  282. var exists = columns.Any(x => x.Expression.ToString().Replace("x.", "").Equals(column));
  283. if (!exists)
  284. columns.Add(new Column<T>(column));
  285. }
  286. }
  287. else
  288. {
  289. var prop = DatabaseSchema.Property(typeof(T), column);
  290. if (prop != null)
  291. {
  292. var exists = columns.Any(x => x.Expression.Equals(prop.Expression()));
  293. if (!exists)
  294. columns.Add(new Column<T>(column));
  295. }
  296. }
  297. return this;
  298. }
  299. public Columns<T> AddSubColumns<TSub>(Expression<Func<T, TSub>> super, Columns<TSub>? sub)
  300. {
  301. sub ??= CoreUtils.GetColumns(sub);
  302. var prefix = CoreUtils.GetFullPropertyName(super, ".") + ".";
  303. foreach(var column in sub.ColumnNames())
  304. {
  305. columns.Add(new Column<T>(prefix + column));
  306. }
  307. return this;
  308. }
  309. public IColumns Add<TEntity>(Expression<Func<TEntity, object?>> expression)
  310. {
  311. return Add(CoreUtils.GetFullPropertyName(expression, "."));
  312. }
  313. public Columns<T> Add(Column<T> column)
  314. {
  315. if(!columns.Any(x => x.Property.Equals(column.Property)))
  316. {
  317. columns.Add(column);
  318. }
  319. return this;
  320. }
  321. public IColumns Add(IColumn column)
  322. {
  323. if (column is Column<T> col)
  324. return Add(col);
  325. return this;
  326. }
  327. public IEnumerable<string> ColumnNames()
  328. {
  329. return Items.Select(c => c.Property);
  330. //List<String> result = new List<string>();
  331. //foreach (var col in Items)
  332. // result.Add(col.Property);
  333. //return result;
  334. }
  335. public Dictionary<String, Type> AsDictionary()
  336. {
  337. Dictionary< String, Type> result = new Dictionary< String, Type>();
  338. foreach (var column in Items)
  339. result[column.Property] = column.Type;
  340. return result;
  341. }
  342. public IColumns DefaultColumns(params ColumnType[] types)
  343. {
  344. return Default(types);
  345. }
  346. public Columns<T> Add(IEnumerable<Column<T>> columns)
  347. {
  348. this.columns.AddRange(columns);
  349. return this;
  350. }
  351. public Columns<T> Add(params string[] columnnames)
  352. {
  353. foreach (var name in columnnames)
  354. Add(name);
  355. return this;
  356. }
  357. public Columns<T> Add(IEnumerable<string> columnnames)
  358. {
  359. foreach (var name in columnnames)
  360. Add(name);
  361. return this;
  362. }
  363. public Columns<T> Add(Expression<Func<T, object?>> expression)
  364. {
  365. try
  366. {
  367. var property = CoreUtils.GetFullPropertyName(expression, ".");
  368. var exists = columns.Any(x => x.Expression.ToString().Replace("x.", "").Equals(property));
  369. if (!exists)
  370. columns.Add(new Column<T>(expression));
  371. }
  372. catch (Exception e)
  373. {
  374. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  375. }
  376. return this;
  377. }
  378. public Columns<T> Add<TType>(Expression<Func<T, TType>> expression)
  379. {
  380. try
  381. {
  382. var property = CoreUtils.GetFullPropertyName(expression, ".");
  383. var exists = columns.Any(x => x.Expression.ToString().Replace("x.", "").Equals(property));
  384. if (!exists)
  385. {
  386. columns.Add(new Column<T>(property));
  387. }
  388. }
  389. catch (Exception e)
  390. {
  391. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  392. }
  393. return this;
  394. }
  395. public Columns<T> Remove(string column)
  396. {
  397. var col = new Column<T>(column);
  398. columns.RemoveAll(x => x.ToString() == col.ToString());
  399. return this;
  400. }
  401. public static explicit operator Columns<T>(Columns<Entity> vs)
  402. {
  403. var result = new Columns<T>();
  404. var items = vs.Items.Cast<Column<T>>().ToArray();
  405. result.Items = items;
  406. //List<Column<T>> cols = new List<Column<T>>();
  407. //foreach (var v in vs.Items)
  408. // cols.Add((Column<T>)v);
  409. //result.Items = cols.ToArray();
  410. return result;
  411. }
  412. public Columns<T> Default(params ColumnType[] types)
  413. {
  414. columns.Clear();
  415. var props = DatabaseSchema.Properties(typeof(T))
  416. .Where(x => x.Setter() != null)
  417. .OrderBy(x => x.PropertySequence()).ToList();
  418. if (types.Contains(ColumnType.All))
  419. {
  420. foreach (var prop in props)
  421. columns.Add(new Column<T>(prop.Name));
  422. return this;
  423. }
  424. else if (types.Contains(ColumnType.DataColumns))
  425. {
  426. foreach(var prop in props)
  427. {
  428. if (prop.IsCalculated)
  429. {
  430. continue;
  431. }
  432. if (prop.HasParentEntityLink())
  433. {
  434. if(prop.Parent?.HasParentEntityLink() == true || !prop.Name.EndsWith(".ID"))
  435. {
  436. continue;
  437. }
  438. }
  439. columns.Add(new Column<T>(prop.Name));
  440. }
  441. if(types.Length == 1)
  442. {
  443. return this;
  444. }
  445. }
  446. if (typeof(T).IsSubclassOf(typeof(Entity)) && !types.Contains(ColumnType.ExcludeID))
  447. columns.Add(new Column<T>("ID"));
  448. for (int iCol = 0; iCol < props.Count; iCol++)
  449. {
  450. var prop = props[iCol];
  451. var bOK = true;
  452. var bIsForeignKey = false;
  453. var bNullEditor = prop.Editor is NullEditor;
  454. if (prop is CustomProperty)
  455. {
  456. if (!types.Any(x => x.Equals(ColumnType.IncludeUserProperties)))
  457. bOK = false;
  458. else
  459. columns.Add(new Column<T>(prop.Name));
  460. }
  461. if (bOK)
  462. if (prop.Name.Contains(".") && !(prop is CustomProperty))
  463. {
  464. var ancestors = prop.Name.Split('.');
  465. var anclevel = 2;
  466. for (var i = 1; i < ancestors.Length; i++)
  467. {
  468. var ancestor = string.Join(".", ancestors.Take(i));
  469. var ancprop = CoreUtils.GetProperty(typeof(T), ancestor);
  470. bNullEditor = bNullEditor || ancprop.GetCustomAttribute<NullEditor>() != null;
  471. if (ancprop.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity)))
  472. anclevel++;
  473. else if (ancprop.PropertyType.GetInterfaces().Contains(typeof(IEntityLink)))
  474. {
  475. if (types.Contains(ColumnType.IncludeLinked) || types.Contains(ColumnType.IncludeForeignKeys))
  476. {
  477. if (types.Contains(ColumnType.IncludeNestedLinks) || ancestors.Length <= anclevel)
  478. {
  479. if (prop.Name.EndsWith(".ID") && types.Contains(ColumnType.IncludeForeignKeys))
  480. {
  481. bIsForeignKey = true;
  482. break;
  483. }
  484. if (!types.Contains(ColumnType.IncludeLinked))
  485. {
  486. bOK = false;
  487. break;
  488. }
  489. }
  490. else
  491. {
  492. bOK = false;
  493. break;
  494. }
  495. }
  496. else
  497. {
  498. bOK = false;
  499. break;
  500. }
  501. }
  502. }
  503. }
  504. if (bOK)
  505. {
  506. var visible = prop.Editor != null
  507. ? bNullEditor
  508. ? Visible.Hidden
  509. : prop.Editor.Visible
  510. : Visible.Optional;
  511. var editable = prop.Editor != null
  512. ? bNullEditor
  513. ? Editable.Hidden
  514. : prop.Editor.Editable
  515. : Editable.Enabled;
  516. bOK = (types.Any(x => x.Equals(ColumnType.IncludeForeignKeys)) && bIsForeignKey) ||
  517. (!types.Any(x => x.Equals(ColumnType.ExcludeVisible)) && visible.Equals(Visible.Default)) ||
  518. (types.Any(x => x.Equals(ColumnType.IncludeOptional)) && visible.Equals(Visible.Optional)) ||
  519. (types.Any(x => x.Equals(ColumnType.IncludeEditable)) && editable.ColumnVisible());
  520. }
  521. var property = bOK ? DatabaseSchema.Property(typeof(T), prop.Name) : null;
  522. if (property is StandardProperty)
  523. {
  524. if (bOK && !types.Any(x => x.Equals(ColumnType.IncludeAggregates)))
  525. bOK = CoreUtils.GetProperty(typeof(T), prop.Name).GetCustomAttribute<AggregateAttribute>() == null;
  526. if (bOK && !types.Any(x => x.Equals(ColumnType.IncludeFormulae)))
  527. bOK = CoreUtils.GetProperty(typeof(T), prop.Name).GetCustomAttribute<FormulaAttribute>() == null;
  528. }
  529. if (bOK && !columns.Any(x => string.Equals(x.Property?.ToUpper(), prop.Name?.ToUpper())))
  530. {
  531. if (prop.Editor is LookupEditor le)
  532. {
  533. if (le.OtherColumns != null)
  534. {
  535. var prefix = String.Join(".",prop.Name.Split('.').Reverse().Skip(1).Reverse());
  536. foreach (var col in le.OtherColumns)
  537. {
  538. String newcol = prefix + "." + col.Key;
  539. if (!columns.Any(x => String.Equals(newcol, x.Property)))
  540. columns.Add(new Column<T>(newcol));
  541. }
  542. }
  543. }
  544. if (!columns.Any(x => String.Equals(prop.Name, x.Property)))
  545. columns.Add(new Column<T>(prop.Name));
  546. }
  547. }
  548. return this;
  549. }
  550. #region Binary Serialization
  551. public void SerializeBinary(CoreBinaryWriter writer)
  552. {
  553. writer.Write(columns.Count);
  554. foreach(var column in columns)
  555. {
  556. writer.Write(column.Property);
  557. }
  558. }
  559. public void DeserializeBinary(CoreBinaryReader reader)
  560. {
  561. columns.Clear();
  562. var nColumns = reader.ReadInt32();
  563. for(int i = 0; i < nColumns; ++i)
  564. {
  565. var property = reader.ReadString();
  566. columns.Add(new Column<T>(property));
  567. }
  568. }
  569. #endregion
  570. public IEnumerator<Column<T>> GetEnumerator()
  571. {
  572. return columns.GetEnumerator();
  573. }
  574. IEnumerator IEnumerable.GetEnumerator()
  575. {
  576. return columns.GetEnumerator();
  577. }
  578. }
  579. public static class ColumnsExtensions
  580. {
  581. public static Columns<T> ToColumns<T>(this IEnumerable<Column<T>> columns)
  582. {
  583. return new Columns<T>(columns.ToList());
  584. }
  585. }
  586. public static class ColumnSerialization
  587. {
  588. /// <summary>
  589. /// Inverse of <see cref="Write{T}(CoreBinaryWriter, Columns{T}?)"/>.
  590. /// </summary>
  591. /// <param name="reader"></param>
  592. /// <returns></returns>
  593. public static Columns<T>? ReadColumns<T>(this CoreBinaryReader reader)
  594. {
  595. if (reader.ReadBoolean())
  596. {
  597. var columns = new Columns<T>();
  598. columns.DeserializeBinary(reader);
  599. return columns;
  600. }
  601. return null;
  602. }
  603. /// <summary>
  604. /// Inverse of <see cref="ReadColumns{T}(CoreBinaryReader)"/>.
  605. /// </summary>
  606. /// <param name="filter"></param>
  607. /// <param name="writer"></param>
  608. public static void Write<T>(this CoreBinaryWriter writer, Columns<T>? columns)
  609. {
  610. if (columns is null)
  611. {
  612. writer.Write(false);
  613. }
  614. else
  615. {
  616. writer.Write(true);
  617. columns.SerializeBinary(writer);
  618. }
  619. }
  620. }
  621. public class ColumnJsonConverter : JsonConverter
  622. {
  623. public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
  624. {
  625. if(value is null)
  626. {
  627. writer.WriteNull();
  628. return;
  629. }
  630. var property = (CoreUtils.GetPropertyValue(value, "Expression") as Expression)
  631. ?? throw new Exception("'Column.Expression' may not be null");
  632. var prop = CoreUtils.ExpressionToString(value.GetType().GenericTypeArguments[0], property, true);
  633. var name = CoreUtils.GetPropertyValue(value, "Property") as string;
  634. writer.WriteStartObject();
  635. writer.WritePropertyName("$type");
  636. writer.WriteValue(value.GetType().FullName);
  637. writer.WritePropertyName("Expression");
  638. writer.WriteValue(prop);
  639. writer.WritePropertyName("Property");
  640. writer.WriteValue(name);
  641. writer.WriteEndObject();
  642. }
  643. public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
  644. {
  645. if (reader.TokenType == JsonToken.Null)
  646. return null;
  647. var data = new Dictionary<string, object>();
  648. while (reader.TokenType != JsonToken.EndObject && reader.Read())
  649. if (reader.Value != null)
  650. {
  651. var key = reader.Value.ToString();
  652. reader.Read();
  653. if (String.Equals(key, "$type"))
  654. objectType = Type.GetType(reader.Value.ToString()) ?? objectType;
  655. else
  656. data[key] = reader.Value;
  657. }
  658. var prop = data["Property"].ToString();
  659. var result = Activator.CreateInstance(objectType, prop);
  660. return result;
  661. }
  662. public override bool CanConvert(Type objectType)
  663. {
  664. if (objectType.IsConstructedGenericType)
  665. {
  666. var ot = objectType.GetGenericTypeDefinition();
  667. var tt = typeof(Column<>);
  668. if (ot == tt)
  669. return true;
  670. }
  671. return false;
  672. }
  673. }
  674. }