Column.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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 exists = columns.Any(x => x.Expression.ToString().Replace("x.", "").Equals(CoreUtils.GetFullPropertyName(expression, ".")));
  202. if (!exists)
  203. columns.Add(new Column<T>(expression));
  204. }
  205. catch (Exception e)
  206. {
  207. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  208. }
  209. return this;
  210. }
  211. public Columns<T> Add<TType>(Expression<Func<T, TType>> expression)
  212. {
  213. try
  214. {
  215. var exists = columns.Any(x => x.Expression.ToString().Replace("x.", "").Equals(CoreUtils.GetFullPropertyName(expression, ".")));
  216. if (!exists)
  217. {
  218. var property = CoreUtils.GetFullPropertyName(expression, ".");
  219. columns.Add(new Column<T>(property));
  220. }
  221. }
  222. catch (Exception e)
  223. {
  224. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  225. }
  226. return this;
  227. }
  228. public Columns<T> Remove(string column)
  229. {
  230. var col = new Column<T>(column);
  231. columns.RemoveAll(x => x.ToString() == col.ToString());
  232. return this;
  233. }
  234. public static explicit operator Columns<T>(Columns<Entity> vs)
  235. {
  236. var result = new Columns<T>();
  237. var items = vs.Items.Cast<Column<T>>().ToArray();
  238. result.Items = items;
  239. //List<Column<T>> cols = new List<Column<T>>();
  240. //foreach (var v in vs.Items)
  241. // cols.Add((Column<T>)v);
  242. //result.Items = cols.ToArray();
  243. return result;
  244. }
  245. public Columns<T> Default(params ColumnType[] types)
  246. {
  247. columns.Clear();
  248. var props = DatabaseSchema.Properties(typeof(T)).Where(x=>x.Setter() != null).OrderBy(x => CoreUtils.GetPropertySequence(typeof(T), x.Name)).ToList();
  249. if (types.Contains(ColumnType.All))
  250. {
  251. foreach (var prop in props)
  252. columns.Add(new Column<T>(prop.Name));
  253. return this;
  254. }
  255. if (typeof(T).IsSubclassOf(typeof(Entity)))
  256. columns.Add(new Column<T>("ID"));
  257. for (int iCol=0; iCol<props.Count; iCol++)
  258. {
  259. var prop = props[iCol];
  260. var bOK = true;
  261. var bIsForeignKey = false;
  262. var bNullEditor = prop.Editor is NullEditor;
  263. if (prop is CustomProperty)
  264. {
  265. if (!types.Any(x => x.Equals(ColumnType.IncludeUserProperties)))
  266. bOK = false;
  267. else
  268. columns.Add(new Column<T>(prop.Name));
  269. }
  270. if (bOK)
  271. if (prop.Name.Contains(".") && !(prop is CustomProperty))
  272. {
  273. var ancestors = prop.Name.Split('.');
  274. var anclevel = 2;
  275. for (var i = 1; i < ancestors.Length; i++)
  276. {
  277. var ancestor = string.Join(".", ancestors.Take(i));
  278. var ancprop = CoreUtils.GetProperty(typeof(T), ancestor);
  279. bNullEditor = bNullEditor || ancprop.GetCustomAttribute<NullEditor>() != null;
  280. if (ancprop.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity)))
  281. anclevel++;
  282. else if (ancprop.PropertyType.GetInterfaces().Contains(typeof(IEntityLink)))
  283. {
  284. if (types.Contains(ColumnType.IncludeLinked) || types.Contains(ColumnType.IncludeForeignKeys))
  285. {
  286. if (types.Contains(ColumnType.IncludeNestedLinks) || ancestors.Length <= anclevel)
  287. {
  288. if (prop.Name.EndsWith(".ID") && types.Contains(ColumnType.IncludeForeignKeys))
  289. {
  290. bIsForeignKey = true;
  291. break;
  292. }
  293. if (!types.Contains(ColumnType.IncludeLinked))
  294. {
  295. bOK = false;
  296. break;
  297. }
  298. }
  299. else
  300. {
  301. bOK = false;
  302. break;
  303. }
  304. }
  305. else
  306. {
  307. bOK = false;
  308. break;
  309. }
  310. }
  311. }
  312. }
  313. if (bOK)
  314. {
  315. var visible = prop.Editor != null
  316. ? bNullEditor
  317. ? Visible.Hidden
  318. : prop.Editor.Visible
  319. : Visible.Optional;
  320. var editable = prop.Editor != null
  321. ? bNullEditor
  322. ? Editable.Hidden
  323. : prop.Editor.Editable
  324. : Editable.Enabled;
  325. bOK = (types.Any(x => x.Equals(ColumnType.IncludeForeignKeys)) && bIsForeignKey) ||
  326. (!types.Any(x => x.Equals(ColumnType.ExcludeVisible)) && visible.Equals(Visible.Default)) ||
  327. (types.Any(x => x.Equals(ColumnType.IncludeOptional)) && visible.Equals(Visible.Optional)) ||
  328. (types.Any(x => x.Equals(ColumnType.IncludeEditable)) && !editable.Equals(Editable.Hidden));
  329. }
  330. var property = bOK ? DatabaseSchema.Property(typeof(T), prop.Name) : null;
  331. if (property is StandardProperty)
  332. {
  333. if (bOK && !types.Any(x => x.Equals(ColumnType.IncludeAggregates)))
  334. bOK = CoreUtils.GetProperty(typeof(T), prop.Name).GetCustomAttribute<AggregateAttribute>() == null;
  335. if (bOK && !types.Any(x => x.Equals(ColumnType.IncludeFormulae)))
  336. bOK = CoreUtils.GetProperty(typeof(T), prop.Name).GetCustomAttribute<FormulaAttribute>() == null;
  337. }
  338. if (bOK && !columns.Any(x => string.Equals(x.Property?.ToUpper(), prop.Name?.ToUpper())))
  339. {
  340. if (bOK && prop.Editor is LookupEditor)
  341. {
  342. var le = prop.Editor as LookupEditor;
  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. var property = CoreUtils.GetPropertyValue(value, "Expression") as Expression;
  366. var prop = CoreUtils.ExpressionToString(value.GetType().GenericTypeArguments[0], property, true);
  367. var name = CoreUtils.GetPropertyValue(value, "Property") as string;
  368. writer.WriteStartObject();
  369. writer.WritePropertyName("Expression");
  370. writer.WriteValue(prop);
  371. writer.WritePropertyName("Property");
  372. writer.WriteValue(name);
  373. writer.WriteEndObject();
  374. }
  375. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  376. {
  377. if (reader.TokenType == JsonToken.Null)
  378. return null;
  379. var data = new Dictionary<string, object>();
  380. while (reader.TokenType != JsonToken.EndObject && reader.Read())
  381. if (reader.Value != null)
  382. {
  383. var key = reader.Value.ToString();
  384. reader.Read();
  385. data[key] = reader.Value;
  386. }
  387. var prop = data["Property"].ToString();
  388. var result = Activator.CreateInstance(objectType, prop);
  389. return result;
  390. }
  391. public override bool CanConvert(Type objectType)
  392. {
  393. if (objectType.IsConstructedGenericType)
  394. {
  395. var ot = objectType.GetGenericTypeDefinition();
  396. var tt = typeof(Column<>);
  397. if (ot == tt)
  398. return true;
  399. }
  400. return false;
  401. }
  402. }
  403. }