Column.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. namespace InABox.Core
  10. {
  11. public interface IColumn
  12. {
  13. string Property { get; }
  14. Type Type { get; }
  15. }
  16. public class Column<T> : SerializableExpression<T>, IColumn
  17. {
  18. public Type Type
  19. {
  20. get
  21. {
  22. if (Expression == null)
  23. throw new Exception(string.Format("Expression [{0}] may not be null!", Property));
  24. if (Expression is IndexExpression)
  25. return DatabaseSchema.Property(typeof(T), Property).PropertyType;
  26. return Expression.Type;
  27. }
  28. }
  29. public bool IsEqualTo(String name) =>
  30. !String.IsNullOrWhiteSpace(name) && String.Equals(Property, name);
  31. public bool IsParentOf(String name) =>
  32. !String.IsNullOrWhiteSpace(name) && name.StartsWith(Property + ".");
  33. public Column()
  34. {
  35. }
  36. public Column(Expression<Func<T, object?>> expression) : base(expression)
  37. {
  38. //String[] parts = expression.ToString().Split(new String[] { "=>" }, StringSplitOptions.RemoveEmptyEntries);
  39. //string property = String.Join(".", parts.Last().Split('.').Skip(1));
  40. //property = property.Replace("Convert(", "").Replace("(","").Replace(")", "");
  41. Property = CoreUtils.GetFullPropertyName(expression, ".");
  42. }
  43. public Column(string property)
  44. {
  45. Property = property;
  46. var iprop = DatabaseSchema.Property(typeof(T), property);
  47. if (iprop != null)
  48. Expression = iprop.Expression();
  49. else
  50. Expression = CoreUtils.CreateMemberExpression(typeof(T), property);
  51. }
  52. public string Property { get; private set; }
  53. public override void Deserialize(SerializationInfo info, StreamingContext context)
  54. {
  55. }
  56. public override void Serialize(SerializationInfo info, StreamingContext context)
  57. {
  58. }
  59. public static explicit operator Column<T>(Column<Entity> v)
  60. {
  61. var result = new Column<T>();
  62. var exp = CoreUtils.ExpressionToString(typeof(T), v.Expression, true);
  63. result.Expression = CoreUtils.StringToExpression(exp);
  64. result.Property = v.Property;
  65. return result;
  66. }
  67. public override string ToString()
  68. {
  69. var name = Expression.ToString().Replace("x => ", "").Replace("x.", "");
  70. if (Expression.NodeType == System.Linq.Expressions.ExpressionType.Index)
  71. {
  72. var chars = name.SkipWhile(x => !x.Equals('[')).TakeWhile(x => !x.Equals(']'));
  73. name = string.Join("", chars).Replace("[", "").Replace("]", "").Replace("\"", "");
  74. }
  75. return name;
  76. //return Property.ToString();
  77. }
  78. }
  79. public interface IColumns
  80. {
  81. int Count { get; }
  82. bool Any();
  83. IEnumerable<IColumn> GetColumns();
  84. IEnumerable<string> ColumnNames();
  85. Dictionary<String, Type> AsDictionary();
  86. IColumns Add(string column);
  87. IColumns Add(IColumn column);
  88. IColumns Add<T>(Expression<Func<T, object?>> column);
  89. IColumns DefaultColumns(params ColumnType[] types);
  90. }
  91. public enum ColumnType
  92. {
  93. ExcludeVisible,
  94. ExcludeID,
  95. IncludeOptional,
  96. IncludeForeignKeys,
  97. IncludeLinked,
  98. IncludeAggregates,
  99. IncludeFormulae,
  100. IncludeUserProperties,
  101. IncludeNestedLinks,
  102. IncludeEditable,
  103. All
  104. }
  105. public static class Columns
  106. {
  107. public static IColumns Create<T>(Type concrete)
  108. {
  109. if (!typeof(T).IsAssignableFrom(concrete))
  110. throw new Exception($"Columns: {concrete.EntityName()} does not implement {typeof(T).EntityName()}");
  111. var type = typeof(Columns<>).MakeGenericType(concrete);
  112. var result = Activator.CreateInstance(type);
  113. return (result as IColumns)!;
  114. }
  115. public static IColumns Create(Type concrete)
  116. {
  117. var type = typeof(Columns<>).MakeGenericType(concrete);
  118. var result = Activator.CreateInstance(type) as IColumns;
  119. return result!;
  120. }
  121. }
  122. public class Columns<T> : IColumns
  123. {
  124. private readonly List<Column<T>> columns;
  125. public Columns()
  126. {
  127. columns = new List<Column<T>>();
  128. }
  129. public int IndexOf(String columnname)
  130. {
  131. return ColumnNames().ToList().IndexOf(columnname);
  132. }
  133. public int IndexOf(Expression<Func<T, object>> expression)
  134. {
  135. return ColumnNames().ToList().IndexOf(CoreUtils.GetFullPropertyName(expression,"."));
  136. }
  137. public Columns(params Expression<Func<T, object?>>[] expressions) : this()
  138. {
  139. foreach (var expression in expressions)
  140. columns.Add(new Column<T>(expression));
  141. }
  142. public Columns(IEnumerable<string> properties) : this()
  143. {
  144. foreach (var property in properties)
  145. columns.Add(new Column<T>(property));
  146. }
  147. public Column<T>[] Items
  148. {
  149. get { return columns != null ? columns.ToArray() : new Column<T>[] { }; }
  150. set
  151. {
  152. columns.Clear();
  153. columns.AddRange(value);
  154. }
  155. }
  156. public int Count => Items.Length;
  157. public IEnumerable<IColumn> GetColumns() => columns;
  158. public bool Any() => columns.Any();
  159. public IColumns Add(string column)
  160. {
  161. if(CoreUtils.TryGetProperty(typeof(T), column, out var propertyInfo))
  162. {
  163. if (!propertyInfo.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity)) &&
  164. !propertyInfo.PropertyType.GetInterfaces().Any(x => x == typeof(IEntityLink)))
  165. {
  166. var exists = columns.Any(x => x.Expression.ToString().Replace("x.", "").Equals(column));
  167. if (!exists)
  168. columns.Add(new Column<T>(column));
  169. }
  170. }
  171. else
  172. {
  173. var prop = DatabaseSchema.Property(typeof(T), column);
  174. if (prop != null)
  175. {
  176. var exists = columns.Any(x => x.Expression.Equals(prop.Expression()));
  177. if (!exists)
  178. columns.Add(new Column<T>(column));
  179. }
  180. }
  181. return this;
  182. }
  183. public IColumns Add<TEntity>(Expression<Func<TEntity, object?>> expression)
  184. {
  185. return Add(CoreUtils.GetFullPropertyName(expression, "."));
  186. }
  187. public Columns<T> Add(Column<T> column)
  188. {
  189. if(!columns.Any(x => x.Property.Equals(column.Property)))
  190. {
  191. columns.Add(column);
  192. }
  193. return this;
  194. }
  195. public IColumns Add(IColumn column)
  196. {
  197. if (column is Column<T> col)
  198. return Add(col);
  199. return this;
  200. }
  201. public IEnumerable<string> ColumnNames()
  202. {
  203. return Items.Select(c => c.Property);
  204. //List<String> result = new List<string>();
  205. //foreach (var col in Items)
  206. // result.Add(col.Property);
  207. //return result;
  208. }
  209. public Dictionary<String, Type> AsDictionary()
  210. {
  211. Dictionary< String, Type> result = new Dictionary< String, Type>();
  212. foreach (var column in Items)
  213. result[column.Property] = column.Type;
  214. return result;
  215. }
  216. public IColumns DefaultColumns(params ColumnType[] types)
  217. {
  218. return Default(types);
  219. }
  220. public Columns<T> Add(params string[] columnnames)
  221. {
  222. foreach (var name in columnnames)
  223. Add(name);
  224. return this;
  225. }
  226. public Columns<T> Add(IEnumerable<string> columnnames)
  227. {
  228. foreach (var name in columnnames)
  229. Add(name);
  230. return this;
  231. }
  232. public Columns<T> Add(Expression<Func<T, object?>> expression)
  233. {
  234. try
  235. {
  236. var property = CoreUtils.GetFullPropertyName(expression, ".");
  237. var exists = columns.Any(x => x.Expression.ToString().Replace("x.", "").Equals(property));
  238. if (!exists)
  239. columns.Add(new Column<T>(expression));
  240. }
  241. catch (Exception e)
  242. {
  243. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  244. }
  245. return this;
  246. }
  247. public Columns<T> Add<TType>(Expression<Func<T, TType>> expression)
  248. {
  249. try
  250. {
  251. var property = CoreUtils.GetFullPropertyName(expression, ".");
  252. var exists = columns.Any(x => x.Expression.ToString().Replace("x.", "").Equals(property));
  253. if (!exists)
  254. {
  255. columns.Add(new Column<T>(property));
  256. }
  257. }
  258. catch (Exception e)
  259. {
  260. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  261. }
  262. return this;
  263. }
  264. public Columns<T> Remove(string column)
  265. {
  266. var col = new Column<T>(column);
  267. columns.RemoveAll(x => x.ToString() == col.ToString());
  268. return this;
  269. }
  270. public static explicit operator Columns<T>(Columns<Entity> vs)
  271. {
  272. var result = new Columns<T>();
  273. var items = vs.Items.Cast<Column<T>>().ToArray();
  274. result.Items = items;
  275. //List<Column<T>> cols = new List<Column<T>>();
  276. //foreach (var v in vs.Items)
  277. // cols.Add((Column<T>)v);
  278. //result.Items = cols.ToArray();
  279. return result;
  280. }
  281. public Columns<T> Default(params ColumnType[] types)
  282. {
  283. columns.Clear();
  284. var props = DatabaseSchema.Properties(typeof(T)).Where(x=>x.Setter() != null).OrderBy(x => CoreUtils.GetPropertySequence(typeof(T), x.Name)).ToList();
  285. if (types.Contains(ColumnType.All))
  286. {
  287. foreach (var prop in props)
  288. columns.Add(new Column<T>(prop.Name));
  289. return this;
  290. }
  291. if (typeof(T).IsSubclassOf(typeof(Entity)) && !types.Contains(ColumnType.ExcludeID))
  292. columns.Add(new Column<T>("ID"));
  293. for (int iCol=0; iCol<props.Count; iCol++)
  294. {
  295. var prop = props[iCol];
  296. var bOK = true;
  297. var bIsForeignKey = false;
  298. var bNullEditor = prop.Editor is NullEditor;
  299. if (prop is CustomProperty)
  300. {
  301. if (!types.Any(x => x.Equals(ColumnType.IncludeUserProperties)))
  302. bOK = false;
  303. else
  304. columns.Add(new Column<T>(prop.Name));
  305. }
  306. if (bOK)
  307. if (prop.Name.Contains(".") && !(prop is CustomProperty))
  308. {
  309. var ancestors = prop.Name.Split('.');
  310. var anclevel = 2;
  311. for (var i = 1; i < ancestors.Length; i++)
  312. {
  313. var ancestor = string.Join(".", ancestors.Take(i));
  314. var ancprop = CoreUtils.GetProperty(typeof(T), ancestor);
  315. bNullEditor = bNullEditor || ancprop.GetCustomAttribute<NullEditor>() != null;
  316. if (ancprop.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity)))
  317. anclevel++;
  318. else if (ancprop.PropertyType.GetInterfaces().Contains(typeof(IEntityLink)))
  319. {
  320. if (types.Contains(ColumnType.IncludeLinked) || types.Contains(ColumnType.IncludeForeignKeys))
  321. {
  322. if (types.Contains(ColumnType.IncludeNestedLinks) || ancestors.Length <= anclevel)
  323. {
  324. if (prop.Name.EndsWith(".ID") && types.Contains(ColumnType.IncludeForeignKeys))
  325. {
  326. bIsForeignKey = true;
  327. break;
  328. }
  329. if (!types.Contains(ColumnType.IncludeLinked))
  330. {
  331. bOK = false;
  332. break;
  333. }
  334. }
  335. else
  336. {
  337. bOK = false;
  338. break;
  339. }
  340. }
  341. else
  342. {
  343. bOK = false;
  344. break;
  345. }
  346. }
  347. }
  348. }
  349. if (bOK)
  350. {
  351. var visible = prop.Editor != null
  352. ? bNullEditor
  353. ? Visible.Hidden
  354. : prop.Editor.Visible
  355. : Visible.Optional;
  356. var editable = prop.Editor != null
  357. ? bNullEditor
  358. ? Editable.Hidden
  359. : prop.Editor.Editable
  360. : Editable.Enabled;
  361. bOK = (types.Any(x => x.Equals(ColumnType.IncludeForeignKeys)) && bIsForeignKey) ||
  362. (!types.Any(x => x.Equals(ColumnType.ExcludeVisible)) && visible.Equals(Visible.Default)) ||
  363. (types.Any(x => x.Equals(ColumnType.IncludeOptional)) && visible.Equals(Visible.Optional)) ||
  364. (types.Any(x => x.Equals(ColumnType.IncludeEditable)) && !editable.Equals(Editable.Hidden));
  365. }
  366. var property = bOK ? DatabaseSchema.Property(typeof(T), prop.Name) : null;
  367. if (property is StandardProperty)
  368. {
  369. if (bOK && !types.Any(x => x.Equals(ColumnType.IncludeAggregates)))
  370. bOK = CoreUtils.GetProperty(typeof(T), prop.Name).GetCustomAttribute<AggregateAttribute>() == null;
  371. if (bOK && !types.Any(x => x.Equals(ColumnType.IncludeFormulae)))
  372. bOK = CoreUtils.GetProperty(typeof(T), prop.Name).GetCustomAttribute<FormulaAttribute>() == null;
  373. }
  374. if (bOK && !columns.Any(x => string.Equals(x.Property?.ToUpper(), prop.Name?.ToUpper())))
  375. {
  376. if (bOK && prop.Editor is LookupEditor le)
  377. {
  378. if (le.OtherColumns != null)
  379. {
  380. var prefix = String.Join(".",prop.Name.Split('.').Reverse().Skip(1).Reverse());
  381. foreach (var col in le.OtherColumns)
  382. {
  383. String newcol = prefix + "." + col.Key;
  384. if (!columns.Any(x => String.Equals(newcol, x.Property)))
  385. columns.Add(new Column<T>(newcol));
  386. }
  387. }
  388. }
  389. if (!columns.Any(x => String.Equals(prop.Name, x.Property)))
  390. columns.Add(new Column<T>(prop.Name));
  391. }
  392. }
  393. return this;
  394. }
  395. }
  396. public class ColumnJsonConverter : JsonConverter
  397. {
  398. public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
  399. {
  400. if(value is null)
  401. {
  402. writer.WriteNull();
  403. return;
  404. }
  405. var property = (CoreUtils.GetPropertyValue(value, "Expression") as Expression)
  406. ?? throw new Exception("'Column.Expression' may not be null");
  407. var prop = CoreUtils.ExpressionToString(value.GetType().GenericTypeArguments[0], property, true);
  408. var name = CoreUtils.GetPropertyValue(value, "Property") as string;
  409. writer.WriteStartObject();
  410. writer.WritePropertyName("Expression");
  411. writer.WriteValue(prop);
  412. writer.WritePropertyName("Property");
  413. writer.WriteValue(name);
  414. writer.WriteEndObject();
  415. }
  416. public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
  417. {
  418. if (reader.TokenType == JsonToken.Null)
  419. return null;
  420. var data = new Dictionary<string, object>();
  421. while (reader.TokenType != JsonToken.EndObject && reader.Read())
  422. if (reader.Value != null)
  423. {
  424. var key = reader.Value.ToString();
  425. reader.Read();
  426. data[key] = reader.Value;
  427. }
  428. var prop = data["Property"].ToString();
  429. var result = Activator.CreateInstance(objectType, prop);
  430. return result;
  431. }
  432. public override bool CanConvert(Type objectType)
  433. {
  434. if (objectType.IsConstructedGenericType)
  435. {
  436. var ot = objectType.GetGenericTypeDefinition();
  437. var tt = typeof(Column<>);
  438. if (ot == tt)
  439. return true;
  440. }
  441. return false;
  442. }
  443. }
  444. }