Column.cs 24 KB

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