Column.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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 Columns(params Expression<Func<T, object?>>[] expressions) : this()
  130. {
  131. foreach (var expression in expressions)
  132. columns.Add(new Column<T>(expression));
  133. }
  134. public Columns(IEnumerable<string> properties) : this()
  135. {
  136. foreach (var property in properties)
  137. columns.Add(new Column<T>(property));
  138. }
  139. public Column<T>[] Items
  140. {
  141. get { return columns != null ? columns.ToArray() : new Column<T>[] { }; }
  142. set
  143. {
  144. columns.Clear();
  145. columns.AddRange(value);
  146. }
  147. }
  148. public int Count => Items.Length;
  149. public IEnumerable<IColumn> GetColumns() => columns;
  150. public bool Any() => columns.Any();
  151. public IColumns Add(string column)
  152. {
  153. if(CoreUtils.TryGetProperty(typeof(T), column, out var propertyInfo))
  154. {
  155. if (!propertyInfo.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity)) &&
  156. !propertyInfo.PropertyType.GetInterfaces().Any(x => x == typeof(IEntityLink)))
  157. {
  158. var exists = columns.Any(x => x.Expression.ToString().Replace("x.", "").Equals(column));
  159. if (!exists)
  160. columns.Add(new Column<T>(column));
  161. }
  162. }
  163. else
  164. {
  165. var prop = DatabaseSchema.Property(typeof(T), column);
  166. if (prop != null)
  167. {
  168. var exists = columns.Any(x => x.Expression.Equals(prop.Expression()));
  169. if (!exists)
  170. columns.Add(new Column<T>(column));
  171. }
  172. }
  173. return this;
  174. }
  175. public IColumns Add<TEntity>(Expression<Func<TEntity, object?>> expression)
  176. {
  177. return Add(CoreUtils.GetFullPropertyName(expression, "."));
  178. }
  179. public Columns<T> Add(Column<T> column)
  180. {
  181. if(!columns.Any(x => x.Property.Equals(column.Property)))
  182. {
  183. columns.Add(column);
  184. }
  185. return this;
  186. }
  187. public IColumns Add(IColumn column)
  188. {
  189. if (column is Column<T> col)
  190. return Add(col);
  191. return this;
  192. }
  193. public IEnumerable<string> ColumnNames()
  194. {
  195. return Items.Select(c => c.Property);
  196. //List<String> result = new List<string>();
  197. //foreach (var col in Items)
  198. // result.Add(col.Property);
  199. //return result;
  200. }
  201. public Dictionary<String, Type> AsDictionary()
  202. {
  203. Dictionary< String, Type> result = new Dictionary< String, Type>();
  204. foreach (var column in Items)
  205. result[column.Property] = column.Type;
  206. return result;
  207. }
  208. public IColumns DefaultColumns(params ColumnType[] types)
  209. {
  210. return Default(types);
  211. }
  212. public Columns<T> Add(params string[] columnnames)
  213. {
  214. foreach (var name in columnnames)
  215. Add(name);
  216. return this;
  217. }
  218. public Columns<T> Add(IEnumerable<string> columnnames)
  219. {
  220. foreach (var name in columnnames)
  221. Add(name);
  222. return this;
  223. }
  224. public Columns<T> Add(Expression<Func<T, object?>> expression)
  225. {
  226. try
  227. {
  228. var property = CoreUtils.GetFullPropertyName(expression, ".");
  229. var exists = columns.Any(x => x.Expression.ToString().Replace("x.", "").Equals(property));
  230. if (!exists)
  231. columns.Add(new Column<T>(expression));
  232. }
  233. catch (Exception e)
  234. {
  235. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  236. }
  237. return this;
  238. }
  239. public Columns<T> Add<TType>(Expression<Func<T, TType>> expression)
  240. {
  241. try
  242. {
  243. var property = CoreUtils.GetFullPropertyName(expression, ".");
  244. var exists = columns.Any(x => x.Expression.ToString().Replace("x.", "").Equals(property));
  245. if (!exists)
  246. {
  247. columns.Add(new Column<T>(property));
  248. }
  249. }
  250. catch (Exception e)
  251. {
  252. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  253. }
  254. return this;
  255. }
  256. public Columns<T> Remove(string column)
  257. {
  258. var col = new Column<T>(column);
  259. columns.RemoveAll(x => x.ToString() == col.ToString());
  260. return this;
  261. }
  262. public static explicit operator Columns<T>(Columns<Entity> vs)
  263. {
  264. var result = new Columns<T>();
  265. var items = vs.Items.Cast<Column<T>>().ToArray();
  266. result.Items = items;
  267. //List<Column<T>> cols = new List<Column<T>>();
  268. //foreach (var v in vs.Items)
  269. // cols.Add((Column<T>)v);
  270. //result.Items = cols.ToArray();
  271. return result;
  272. }
  273. public Columns<T> Default(params ColumnType[] types)
  274. {
  275. columns.Clear();
  276. var props = DatabaseSchema.Properties(typeof(T)).Where(x=>x.Setter() != null).OrderBy(x => CoreUtils.GetPropertySequence(typeof(T), x.Name)).ToList();
  277. if (types.Contains(ColumnType.All))
  278. {
  279. foreach (var prop in props)
  280. columns.Add(new Column<T>(prop.Name));
  281. return this;
  282. }
  283. if (typeof(T).IsSubclassOf(typeof(Entity)) && !types.Contains(ColumnType.ExcludeID))
  284. columns.Add(new Column<T>("ID"));
  285. for (int iCol=0; iCol<props.Count; iCol++)
  286. {
  287. var prop = props[iCol];
  288. var bOK = true;
  289. var bIsForeignKey = false;
  290. var bNullEditor = prop.Editor is NullEditor;
  291. if (prop is CustomProperty)
  292. {
  293. if (!types.Any(x => x.Equals(ColumnType.IncludeUserProperties)))
  294. bOK = false;
  295. else
  296. columns.Add(new Column<T>(prop.Name));
  297. }
  298. if (bOK)
  299. if (prop.Name.Contains(".") && !(prop is CustomProperty))
  300. {
  301. var ancestors = prop.Name.Split('.');
  302. var anclevel = 2;
  303. for (var i = 1; i < ancestors.Length; i++)
  304. {
  305. var ancestor = string.Join(".", ancestors.Take(i));
  306. var ancprop = CoreUtils.GetProperty(typeof(T), ancestor);
  307. bNullEditor = bNullEditor || ancprop.GetCustomAttribute<NullEditor>() != null;
  308. if (ancprop.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity)))
  309. anclevel++;
  310. else if (ancprop.PropertyType.GetInterfaces().Contains(typeof(IEntityLink)))
  311. {
  312. if (types.Contains(ColumnType.IncludeLinked) || types.Contains(ColumnType.IncludeForeignKeys))
  313. {
  314. if (types.Contains(ColumnType.IncludeNestedLinks) || ancestors.Length <= anclevel)
  315. {
  316. if (prop.Name.EndsWith(".ID") && types.Contains(ColumnType.IncludeForeignKeys))
  317. {
  318. bIsForeignKey = true;
  319. break;
  320. }
  321. if (!types.Contains(ColumnType.IncludeLinked))
  322. {
  323. bOK = false;
  324. break;
  325. }
  326. }
  327. else
  328. {
  329. bOK = false;
  330. break;
  331. }
  332. }
  333. else
  334. {
  335. bOK = false;
  336. break;
  337. }
  338. }
  339. }
  340. }
  341. if (bOK)
  342. {
  343. var visible = prop.Editor != null
  344. ? bNullEditor
  345. ? Visible.Hidden
  346. : prop.Editor.Visible
  347. : Visible.Optional;
  348. var editable = prop.Editor != null
  349. ? bNullEditor
  350. ? Editable.Hidden
  351. : prop.Editor.Editable
  352. : Editable.Enabled;
  353. bOK = (types.Any(x => x.Equals(ColumnType.IncludeForeignKeys)) && bIsForeignKey) ||
  354. (!types.Any(x => x.Equals(ColumnType.ExcludeVisible)) && visible.Equals(Visible.Default)) ||
  355. (types.Any(x => x.Equals(ColumnType.IncludeOptional)) && visible.Equals(Visible.Optional)) ||
  356. (types.Any(x => x.Equals(ColumnType.IncludeEditable)) && !editable.Equals(Editable.Hidden));
  357. }
  358. var property = bOK ? DatabaseSchema.Property(typeof(T), prop.Name) : null;
  359. if (property is StandardProperty)
  360. {
  361. if (bOK && !types.Any(x => x.Equals(ColumnType.IncludeAggregates)))
  362. bOK = CoreUtils.GetProperty(typeof(T), prop.Name).GetCustomAttribute<AggregateAttribute>() == null;
  363. if (bOK && !types.Any(x => x.Equals(ColumnType.IncludeFormulae)))
  364. bOK = CoreUtils.GetProperty(typeof(T), prop.Name).GetCustomAttribute<FormulaAttribute>() == null;
  365. }
  366. if (bOK && !columns.Any(x => string.Equals(x.Property?.ToUpper(), prop.Name?.ToUpper())))
  367. {
  368. if (bOK && prop.Editor is LookupEditor le)
  369. {
  370. if (le.OtherColumns != null)
  371. {
  372. var prefix = String.Join(".",prop.Name.Split('.').Reverse().Skip(1).Reverse());
  373. foreach (var col in le.OtherColumns)
  374. {
  375. String newcol = prefix + "." + col.Key;
  376. if (!columns.Any(x => String.Equals(newcol, x.Property)))
  377. columns.Add(new Column<T>(newcol));
  378. }
  379. }
  380. }
  381. if (!columns.Any(x => String.Equals(prop.Name, x.Property)))
  382. columns.Add(new Column<T>(prop.Name));
  383. }
  384. }
  385. return this;
  386. }
  387. }
  388. public class ColumnJsonConverter : JsonConverter
  389. {
  390. public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
  391. {
  392. if(value is null)
  393. {
  394. writer.WriteNull();
  395. return;
  396. }
  397. var property = (CoreUtils.GetPropertyValue(value, "Expression") as Expression)
  398. ?? throw new Exception("'Column.Expression' may not be null");
  399. var prop = CoreUtils.ExpressionToString(value.GetType().GenericTypeArguments[0], property, true);
  400. var name = CoreUtils.GetPropertyValue(value, "Property") as string;
  401. writer.WriteStartObject();
  402. writer.WritePropertyName("Expression");
  403. writer.WriteValue(prop);
  404. writer.WritePropertyName("Property");
  405. writer.WriteValue(name);
  406. writer.WriteEndObject();
  407. }
  408. public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
  409. {
  410. if (reader.TokenType == JsonToken.Null)
  411. return null;
  412. var data = new Dictionary<string, object>();
  413. while (reader.TokenType != JsonToken.EndObject && reader.Read())
  414. if (reader.Value != null)
  415. {
  416. var key = reader.Value.ToString();
  417. reader.Read();
  418. data[key] = reader.Value;
  419. }
  420. var prop = data["Property"].ToString();
  421. var result = Activator.CreateInstance(objectType, prop);
  422. return result;
  423. }
  424. public override bool CanConvert(Type objectType)
  425. {
  426. if (objectType.IsConstructedGenericType)
  427. {
  428. var ot = objectType.GetGenericTypeDefinition();
  429. var tt = typeof(Column<>);
  430. if (ot == tt)
  431. return true;
  432. }
  433. return false;
  434. }
  435. }
  436. }