Column.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  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, params 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. }
  160. public class Columns<T> : IColumns
  161. {
  162. private readonly List<Column<T>> columns;
  163. public Columns()
  164. {
  165. columns = new List<Column<T>>();
  166. }
  167. public Columns<TNew> Cast<TNew>()
  168. where TNew : T
  169. {
  170. var cols = new Columns<TNew>();
  171. foreach(var column in columns)
  172. {
  173. cols.Add(column.Cast<TNew>());
  174. }
  175. return cols;
  176. }
  177. public override string ToString()
  178. {
  179. return String.Join("; ", columns.Select(x => x.Property));
  180. }
  181. public int IndexOf(String columnname)
  182. {
  183. return ColumnNames().ToList().IndexOf(columnname);
  184. }
  185. public int IndexOf(Expression<Func<T, object>> expression)
  186. {
  187. return ColumnNames().ToList().IndexOf(CoreUtils.GetFullPropertyName(expression,"."));
  188. }
  189. public Columns(params Expression<Func<T, object?>>[] expressions) : this()
  190. {
  191. foreach (var expression in expressions)
  192. columns.Add(new Column<T>(expression));
  193. }
  194. public Columns(IEnumerable<string> properties) : this()
  195. {
  196. foreach (var property in properties)
  197. columns.Add(new Column<T>(property));
  198. }
  199. public Column<T>[] Items
  200. {
  201. get { return columns != null ? columns.ToArray() : new Column<T>[] { }; }
  202. set
  203. {
  204. columns.Clear();
  205. columns.AddRange(value);
  206. }
  207. }
  208. public int Count => columns.Count;
  209. public IEnumerable<IColumn> GetColumns() => columns;
  210. public bool Any() => columns.Any();
  211. public IColumns Add(string column)
  212. {
  213. if(CoreUtils.TryGetProperty(typeof(T), column, out var propertyInfo))
  214. {
  215. if (!propertyInfo.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity)) &&
  216. !propertyInfo.PropertyType.GetInterfaces().Any(x => x == typeof(IEntityLink)))
  217. {
  218. var exists = columns.Any(x => x.Expression.ToString().Replace("x.", "").Equals(column));
  219. if (!exists)
  220. columns.Add(new Column<T>(column));
  221. }
  222. }
  223. else
  224. {
  225. var prop = DatabaseSchema.Property(typeof(T), column);
  226. if (prop != null)
  227. {
  228. var exists = columns.Any(x => x.Expression.Equals(prop.Expression()));
  229. if (!exists)
  230. columns.Add(new Column<T>(column));
  231. }
  232. }
  233. return this;
  234. }
  235. public Columns<T> AddSubColumns<TSub>(Expression<Func<T, TSub>> super, Columns<TSub> sub)
  236. {
  237. var prefix = CoreUtils.GetFullPropertyName(super, ".") + ".";
  238. foreach(var column in sub.ColumnNames())
  239. {
  240. columns.Add(new Column<T>(prefix + column));
  241. }
  242. return this;
  243. }
  244. public IColumns Add<TEntity>(Expression<Func<TEntity, object?>> expression)
  245. {
  246. return Add(CoreUtils.GetFullPropertyName(expression, "."));
  247. }
  248. public Columns<T> Add(Column<T> column)
  249. {
  250. if(!columns.Any(x => x.Property.Equals(column.Property)))
  251. {
  252. columns.Add(column);
  253. }
  254. return this;
  255. }
  256. public IColumns Add(IColumn column)
  257. {
  258. if (column is Column<T> col)
  259. return Add(col);
  260. return this;
  261. }
  262. public IEnumerable<string> ColumnNames()
  263. {
  264. return Items.Select(c => c.Property);
  265. //List<String> result = new List<string>();
  266. //foreach (var col in Items)
  267. // result.Add(col.Property);
  268. //return result;
  269. }
  270. public Dictionary<String, Type> AsDictionary()
  271. {
  272. Dictionary< String, Type> result = new Dictionary< String, Type>();
  273. foreach (var column in Items)
  274. result[column.Property] = column.Type;
  275. return result;
  276. }
  277. public IColumns DefaultColumns(params ColumnType[] types)
  278. {
  279. return Default(types);
  280. }
  281. public Columns<T> Add(params string[] columnnames)
  282. {
  283. foreach (var name in columnnames)
  284. Add(name);
  285. return this;
  286. }
  287. public Columns<T> Add(IEnumerable<string> columnnames)
  288. {
  289. foreach (var name in columnnames)
  290. Add(name);
  291. return this;
  292. }
  293. public Columns<T> Add(Expression<Func<T, object?>> expression)
  294. {
  295. try
  296. {
  297. var property = CoreUtils.GetFullPropertyName(expression, ".");
  298. var exists = columns.Any(x => x.Expression.ToString().Replace("x.", "").Equals(property));
  299. if (!exists)
  300. columns.Add(new Column<T>(expression));
  301. }
  302. catch (Exception e)
  303. {
  304. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  305. }
  306. return this;
  307. }
  308. public Columns<T> Add<TType>(Expression<Func<T, TType>> expression)
  309. {
  310. try
  311. {
  312. var property = CoreUtils.GetFullPropertyName(expression, ".");
  313. var exists = columns.Any(x => x.Expression.ToString().Replace("x.", "").Equals(property));
  314. if (!exists)
  315. {
  316. columns.Add(new Column<T>(property));
  317. }
  318. }
  319. catch (Exception e)
  320. {
  321. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  322. }
  323. return this;
  324. }
  325. public Columns<T> Remove(string column)
  326. {
  327. var col = new Column<T>(column);
  328. columns.RemoveAll(x => x.ToString() == col.ToString());
  329. return this;
  330. }
  331. public static explicit operator Columns<T>(Columns<Entity> vs)
  332. {
  333. var result = new Columns<T>();
  334. var items = vs.Items.Cast<Column<T>>().ToArray();
  335. result.Items = items;
  336. //List<Column<T>> cols = new List<Column<T>>();
  337. //foreach (var v in vs.Items)
  338. // cols.Add((Column<T>)v);
  339. //result.Items = cols.ToArray();
  340. return result;
  341. }
  342. public Columns<T> Default(params ColumnType[] types)
  343. {
  344. columns.Clear();
  345. var props = DatabaseSchema.Properties(typeof(T)).Where(x=>x.Setter() != null).OrderBy(x => CoreUtils.GetPropertySequence(typeof(T), x.Name)).ToList();
  346. if (types.Contains(ColumnType.All))
  347. {
  348. foreach (var prop in props)
  349. columns.Add(new Column<T>(prop.Name));
  350. return this;
  351. }
  352. if (typeof(T).IsSubclassOf(typeof(Entity)) && !types.Contains(ColumnType.ExcludeID))
  353. columns.Add(new Column<T>("ID"));
  354. for (int iCol = 0; iCol < props.Count; iCol++)
  355. {
  356. var prop = props[iCol];
  357. var bOK = true;
  358. var bIsForeignKey = false;
  359. var bNullEditor = prop.Editor is NullEditor;
  360. if (prop is CustomProperty)
  361. {
  362. if (!types.Any(x => x.Equals(ColumnType.IncludeUserProperties)))
  363. bOK = false;
  364. else
  365. columns.Add(new Column<T>(prop.Name));
  366. }
  367. if (bOK)
  368. if (prop.Name.Contains(".") && !(prop is CustomProperty))
  369. {
  370. var ancestors = prop.Name.Split('.');
  371. var anclevel = 2;
  372. for (var i = 1; i < ancestors.Length; i++)
  373. {
  374. var ancestor = string.Join(".", ancestors.Take(i));
  375. var ancprop = CoreUtils.GetProperty(typeof(T), ancestor);
  376. bNullEditor = bNullEditor || ancprop.GetCustomAttribute<NullEditor>() != null;
  377. if (ancprop.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity)))
  378. anclevel++;
  379. else if (ancprop.PropertyType.GetInterfaces().Contains(typeof(IEntityLink)))
  380. {
  381. if (types.Contains(ColumnType.IncludeLinked) || types.Contains(ColumnType.IncludeForeignKeys))
  382. {
  383. if (types.Contains(ColumnType.IncludeNestedLinks) || ancestors.Length <= anclevel)
  384. {
  385. if (prop.Name.EndsWith(".ID") && types.Contains(ColumnType.IncludeForeignKeys))
  386. {
  387. bIsForeignKey = true;
  388. break;
  389. }
  390. if (!types.Contains(ColumnType.IncludeLinked))
  391. {
  392. bOK = false;
  393. break;
  394. }
  395. }
  396. else
  397. {
  398. bOK = false;
  399. break;
  400. }
  401. }
  402. else
  403. {
  404. bOK = false;
  405. break;
  406. }
  407. }
  408. }
  409. }
  410. if (bOK)
  411. {
  412. var visible = prop.Editor != null
  413. ? bNullEditor
  414. ? Visible.Hidden
  415. : prop.Editor.Visible
  416. : Visible.Optional;
  417. var editable = prop.Editor != null
  418. ? bNullEditor
  419. ? Editable.Hidden
  420. : prop.Editor.Editable
  421. : Editable.Enabled;
  422. bOK = (types.Any(x => x.Equals(ColumnType.IncludeForeignKeys)) && bIsForeignKey) ||
  423. (!types.Any(x => x.Equals(ColumnType.ExcludeVisible)) && visible.Equals(Visible.Default)) ||
  424. (types.Any(x => x.Equals(ColumnType.IncludeOptional)) && visible.Equals(Visible.Optional)) ||
  425. (types.Any(x => x.Equals(ColumnType.IncludeEditable)) && editable.ColumnVisible());
  426. }
  427. var property = bOK ? DatabaseSchema.Property(typeof(T), prop.Name) : null;
  428. if (property is StandardProperty)
  429. {
  430. if (bOK && !types.Any(x => x.Equals(ColumnType.IncludeAggregates)))
  431. bOK = CoreUtils.GetProperty(typeof(T), prop.Name).GetCustomAttribute<AggregateAttribute>() == null;
  432. if (bOK && !types.Any(x => x.Equals(ColumnType.IncludeFormulae)))
  433. bOK = CoreUtils.GetProperty(typeof(T), prop.Name).GetCustomAttribute<FormulaAttribute>() == null;
  434. }
  435. if (bOK && !columns.Any(x => string.Equals(x.Property?.ToUpper(), prop.Name?.ToUpper())))
  436. {
  437. if (prop.Editor is LookupEditor le)
  438. {
  439. if (le.OtherColumns != null)
  440. {
  441. var prefix = String.Join(".",prop.Name.Split('.').Reverse().Skip(1).Reverse());
  442. foreach (var col in le.OtherColumns)
  443. {
  444. String newcol = prefix + "." + col.Key;
  445. if (!columns.Any(x => String.Equals(newcol, x.Property)))
  446. columns.Add(new Column<T>(newcol));
  447. }
  448. }
  449. }
  450. if (!columns.Any(x => String.Equals(prop.Name, x.Property)))
  451. columns.Add(new Column<T>(prop.Name));
  452. }
  453. }
  454. return this;
  455. }
  456. #region Binary Serialization
  457. public void SerializeBinary(CoreBinaryWriter writer)
  458. {
  459. writer.Write(columns.Count);
  460. foreach(var column in columns)
  461. {
  462. writer.Write(column.Property);
  463. }
  464. }
  465. public void DeserializeBinary(CoreBinaryReader reader)
  466. {
  467. columns.Clear();
  468. var nColumns = reader.ReadInt32();
  469. for(int i = 0; i < nColumns; ++i)
  470. {
  471. var property = reader.ReadString();
  472. columns.Add(new Column<T>(property));
  473. }
  474. }
  475. #endregion
  476. }
  477. public static class ColumnSerialization
  478. {
  479. /// <summary>
  480. /// Inverse of <see cref="Write{T}(CoreBinaryWriter, Columns{T}?)"/>.
  481. /// </summary>
  482. /// <param name="reader"></param>
  483. /// <returns></returns>
  484. public static Columns<T>? ReadColumns<T>(this CoreBinaryReader reader)
  485. {
  486. if (reader.ReadBoolean())
  487. {
  488. var columns = new Columns<T>();
  489. columns.DeserializeBinary(reader);
  490. return columns;
  491. }
  492. return null;
  493. }
  494. /// <summary>
  495. /// Inverse of <see cref="ReadColumns{T}(CoreBinaryReader)"/>.
  496. /// </summary>
  497. /// <param name="filter"></param>
  498. /// <param name="writer"></param>
  499. public static void Write<T>(this CoreBinaryWriter writer, Columns<T>? columns)
  500. {
  501. if (columns is null)
  502. {
  503. writer.Write(false);
  504. }
  505. else
  506. {
  507. writer.Write(true);
  508. columns.SerializeBinary(writer);
  509. }
  510. }
  511. }
  512. public class ColumnJsonConverter : JsonConverter
  513. {
  514. public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
  515. {
  516. if(value is null)
  517. {
  518. writer.WriteNull();
  519. return;
  520. }
  521. var property = (CoreUtils.GetPropertyValue(value, "Expression") as Expression)
  522. ?? throw new Exception("'Column.Expression' may not be null");
  523. var prop = CoreUtils.ExpressionToString(value.GetType().GenericTypeArguments[0], property, true);
  524. var name = CoreUtils.GetPropertyValue(value, "Property") as string;
  525. writer.WriteStartObject();
  526. writer.WritePropertyName("$type");
  527. writer.WriteValue(value.GetType().FullName);
  528. writer.WritePropertyName("Expression");
  529. writer.WriteValue(prop);
  530. writer.WritePropertyName("Property");
  531. writer.WriteValue(name);
  532. writer.WriteEndObject();
  533. }
  534. public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
  535. {
  536. if (reader.TokenType == JsonToken.Null)
  537. return null;
  538. var data = new Dictionary<string, object>();
  539. while (reader.TokenType != JsonToken.EndObject && reader.Read())
  540. if (reader.Value != null)
  541. {
  542. var key = reader.Value.ToString();
  543. reader.Read();
  544. if (String.Equals(key, "$type"))
  545. objectType = Type.GetType(reader.Value.ToString()) ?? objectType;
  546. else
  547. data[key] = reader.Value;
  548. }
  549. var prop = data["Property"].ToString();
  550. var result = Activator.CreateInstance(objectType, prop);
  551. return result;
  552. }
  553. public override bool CanConvert(Type objectType)
  554. {
  555. if (objectType.IsConstructedGenericType)
  556. {
  557. var ot = objectType.GetGenericTypeDefinition();
  558. var tt = typeof(Column<>);
  559. if (ot == tt)
  560. return true;
  561. }
  562. return false;
  563. }
  564. }
  565. }