Column.cs 21 KB

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