ExpressionEditor.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. namespace InABox.Core
  7. {
  8. public interface IExpressionModelGenerator
  9. {
  10. public List<string> GetVariables(object?[] items);
  11. }
  12. public delegate DataModel GetVariables();
  13. public class ExpressionEditor : BaseEditor
  14. {
  15. /// <summary>
  16. /// The <see cref="IExpressionModel"/> to use for this expression; if set to null, the variables must be manually set for the editor.
  17. /// </summary>
  18. public Type? ModelType { get; set; }
  19. private IExpressionModelGenerator? _modelGenerator;
  20. public Type? ModelGenerator { get; }
  21. public event GetVariables OnGetVariables;
  22. [DoNotSerialize]
  23. [JsonIgnore]
  24. public List<string>? VariableNames { get; set; }
  25. public ExpressionEditor(Type? modelType, Type? modelGenerator = null)
  26. {
  27. ModelType = modelType;
  28. if (modelGenerator != null)
  29. {
  30. if (!typeof(IExpressionModelGenerator).IsAssignableFrom(modelGenerator))
  31. {
  32. throw new Exception($"Model generator must be a {nameof(IExpressionModelGenerator)}");
  33. }
  34. ModelGenerator = modelGenerator;
  35. }
  36. }
  37. protected override BaseEditor DoClone()
  38. {
  39. return new ExpressionEditor(ModelType, ModelGenerator)
  40. {
  41. VariableNames = VariableNames
  42. };
  43. }
  44. public List<string> GetVariables(object?[] items)
  45. {
  46. if (VariableNames != null)
  47. return VariableNames;
  48. if (ModelGenerator != null)
  49. {
  50. _modelGenerator ??= (Activator.CreateInstance(ModelGenerator) as IExpressionModelGenerator)!;
  51. return _modelGenerator.GetVariables(items);
  52. }
  53. if (ModelType != null)
  54. return CoreExpression.GetModelVariables(ModelType);
  55. var model = OnGetVariables?.Invoke();
  56. if (model != null)
  57. return GetVariablesFromDataModel(model);
  58. return new List<string>();
  59. }
  60. private List<string> GetVariablesFromDataModel(DataModel model)
  61. {
  62. List<string> list = new List<string>();
  63. foreach (var table in model.DefaultTables)
  64. {
  65. foreach (var col in table.Columns)
  66. {
  67. if (col.ToString() != "ID")
  68. list.Add(table.ToString() + "." + col.ToString());
  69. }
  70. }
  71. list.Sort();
  72. return list;
  73. }
  74. }
  75. }