Column.cs 23 KB

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