Column.cs 18 KB

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