Column.cs 17 KB

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