DatabaseSchema.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Linq.Expressions;
  6. using System.Reflection;
  7. namespace InABox.Core
  8. {
  9. public static class DatabaseSchema
  10. {
  11. // {className: {propertyName: property}}
  12. private static Dictionary<string, Dictionary<string, IProperty>> _properties
  13. = new Dictionary<string, Dictionary<string, IProperty>>();
  14. private struct SubObject
  15. {
  16. public Type PropertyType { get; set; }
  17. public string Name { get; set; }
  18. public Action<object, object> Setter { get; set; }
  19. public Func<object, object> Getter { get; set; }
  20. public SubObject(Type objectType, Type propertyType, string name)
  21. {
  22. PropertyType = propertyType;
  23. Name = name;
  24. Setter = Expressions.Setter(objectType, name);
  25. Getter = Expressions.Getter(objectType, name);
  26. }
  27. }
  28. private static Dictionary<Type, List<SubObject>> _subObjects { get; } = new Dictionary<Type, List<SubObject>>();
  29. private static List<SubObject>? GetSubObjectDefs(Type t)
  30. {
  31. CheckProperties(t);
  32. return _subObjects.GetValueOrDefault(t);
  33. }
  34. public static IEnumerable<BaseObject> GetSubObjects(BaseObject obj)
  35. {
  36. var objs = GetSubObjectDefs(obj.GetType());
  37. if(objs is null)
  38. {
  39. yield break;
  40. }
  41. foreach (var subObjectDef in objs)
  42. {
  43. var subObj = subObjectDef.Getter(obj);
  44. if(subObj is BaseObject bObj)
  45. {
  46. yield return bObj;
  47. }
  48. }
  49. }
  50. public static void InitializeSubObjects(BaseObject obj)
  51. {
  52. var objs = GetSubObjectDefs(obj.GetType());
  53. if(objs is null)
  54. {
  55. return;
  56. }
  57. foreach (var subObjectDef in objs)
  58. {
  59. var subObj = (Activator.CreateInstance(subObjectDef.PropertyType) as ISubObject)!;
  60. subObjectDef.Setter(obj, subObj);
  61. subObj.SetLinkedParent(obj);
  62. subObj.SetLinkedPath(subObjectDef.Name);
  63. }
  64. }
  65. private static void RegisterSubObject(Type objectType, Type propertyType, string name)
  66. {
  67. lock (_updatelock)
  68. {
  69. if (!_subObjects.TryGetValue(objectType, out var properties))
  70. {
  71. properties = new List<SubObject>();
  72. _subObjects[objectType] = properties;
  73. }
  74. if (!properties.Any(x => x.Name == name && x.PropertyType == propertyType))
  75. {
  76. properties.Add(new SubObject(objectType, propertyType, name));
  77. }
  78. }
  79. }
  80. private static void RegisterProperties(Type master, Type type, string prefix, StandardProperty? parent)
  81. {
  82. try
  83. {
  84. var classname = master.EntityName();
  85. var properties = CoreUtils.PropertyList(
  86. type,
  87. x => !x.PropertyType.IsInterface &&
  88. x.GetGetMethod()?.IsPublic == true &&
  89. (x.DeclaringType.IsSubclassOf(typeof(BaseObject))
  90. || x.DeclaringType.IsSubclassOf(typeof(BaseEditor)))
  91. );
  92. var classProps = _properties.GetValueOrDefault(classname);
  93. foreach (var prop in properties)
  94. {
  95. var name = string.IsNullOrWhiteSpace(prefix) ? prop.Name : string.Format("{0}.{1}", prefix, prop.Name);
  96. var p = classProps?.GetValueOrDefault(name);
  97. if (p == null)
  98. {
  99. var isstatic = prop.GetAccessors(true)[0].IsStatic;
  100. if (!isstatic)
  101. {
  102. BaseEditor? editor;
  103. if (parent != null && parent.HasEditor && parent.Editor is NullEditor)
  104. {
  105. editor = parent.Editor;
  106. }
  107. else
  108. {
  109. editor = prop.GetEditor();
  110. }
  111. var captionAttr = prop.GetCustomAttribute<Caption>();
  112. var subCaption = captionAttr != null ? captionAttr.Text : prop.Name;
  113. var path = captionAttr == null || captionAttr.IncludePath; // If no caption attribute, we should always include the path
  114. var caption = parent?.Caption ?? ""; // We default to the parent caption if subCaption doesn't exist
  115. if (!string.IsNullOrWhiteSpace(subCaption))
  116. {
  117. if (!string.IsNullOrWhiteSpace(caption) && path)
  118. {
  119. caption = $"{caption} {subCaption}";
  120. }
  121. else
  122. {
  123. caption = subCaption;
  124. }
  125. }
  126. // Once the parent page has been found, this property is cemented to that page - it cannot change page to its parent
  127. // The same goes for sequence
  128. var page = parent?.Page;
  129. var sequence = parent?.Sequence;
  130. if (string.IsNullOrWhiteSpace(page))
  131. {
  132. var sequenceAttribute = prop.GetCustomAttribute<EditorSequence>();
  133. if (sequenceAttribute != null)
  134. {
  135. page = sequenceAttribute.Page;
  136. sequence = sequenceAttribute.Sequence;
  137. }
  138. }
  139. editor = editor?.Clone() as BaseEditor;
  140. if (editor != null)
  141. {
  142. editor.Page = page;
  143. editor.Caption = caption;
  144. editor.EditorSequence = (int)(sequence ?? 999);
  145. editor.Security = prop.GetCustomAttributes<SecurityAttribute>().ToArray();
  146. }
  147. bool required = false;
  148. if (parent == null || parent.Required)
  149. {
  150. required = prop.GetCustomAttribute<RequiredColumnAttribute>() != null;
  151. }
  152. LoggablePropertyAttribute? loggable = null;
  153. if (parent == null || parent.Loggable != null)
  154. {
  155. loggable = prop.GetCustomAttribute<LoggablePropertyAttribute>();
  156. }
  157. var newProperty = new StandardProperty
  158. {
  159. _class = master,
  160. //Class = classname,
  161. Name = name,
  162. PropertyType = prop.PropertyType,
  163. Editor = editor ?? new NullEditor(),
  164. HasEditor = editor != null,
  165. Caption = caption,
  166. Sequence = sequence ?? 999,
  167. Page = page ?? "",
  168. Required = required,
  169. Loggable = loggable,
  170. Parent = parent,
  171. Property = prop
  172. };
  173. var parentWithEditable = newProperty.GetOuterParent(x =>
  174. x is StandardProperty st
  175. && st.Property.GetCustomAttribute<EditableAttribute>() != null);
  176. if(parentWithEditable != null)
  177. {
  178. var attr = (parentWithEditable as StandardProperty)!.Property.GetCustomAttribute<EditableAttribute>()!;
  179. newProperty.Editor.Editable = newProperty.Editor.Editable.Combine(attr.Editable);
  180. }
  181. else if(prop.GetCustomAttribute<EditableAttribute>() is EditableAttribute attr)
  182. {
  183. newProperty.Editor.Editable = newProperty.Editor.Editable.Combine(attr.Editable);
  184. }
  185. var isLink = prop.PropertyType.GetInterfaces().Contains(typeof(IEntityLink));
  186. var isEnclosedEntity = prop.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity));
  187. var isBaseEditor = prop.PropertyType.Equals(typeof(BaseEditor)) ||
  188. prop.PropertyType.IsSubclassOf(typeof(BaseEditor));
  189. if ((isLink || isEnclosedEntity) && !isBaseEditor)
  190. {
  191. RegisterSubObject(type, prop.PropertyType, prop.Name);
  192. }
  193. if (isLink || isEnclosedEntity || isBaseEditor)
  194. {
  195. RegisterProperties(master, prop.PropertyType, name, newProperty);
  196. }
  197. else
  198. {
  199. RegisterProperty(newProperty);
  200. }
  201. }
  202. }
  203. }
  204. if (type.IsSubclassOf(typeof(BaseObject)))
  205. RegisterProperties(master, type.BaseType, prefix, parent);
  206. }
  207. catch (Exception e)
  208. {
  209. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  210. }
  211. }
  212. private static void RegisterProperties(Type type)
  213. {
  214. RegisterProperties(type, type, "", null);
  215. }
  216. public static object? DefaultValue(Type type)
  217. {
  218. if (type.IsValueType)
  219. return Activator.CreateInstance(type);
  220. if (type.Equals(typeof(string)))
  221. return "";
  222. return null;
  223. }
  224. private static readonly object _updatelock = new object();
  225. public static void RegisterProperty(IProperty entry)
  226. {
  227. lock (_updatelock)
  228. {
  229. if (!_properties.ContainsKey(entry.Class))
  230. _properties[entry.Class] = new Dictionary<string, IProperty>();
  231. _properties[entry.Class][entry.Name] = entry;
  232. }
  233. }
  234. public static void Load(CustomProperty[] customproperties)
  235. {
  236. foreach (var prop in customproperties)
  237. RegisterProperty(prop);
  238. }
  239. private static void CheckProperties(Type type)
  240. {
  241. var entityName = type.EntityName();
  242. try
  243. {
  244. var props = _properties.GetValueOrDefault(entityName);
  245. var hasprops = props?.Any(x => x.Value is StandardProperty) == true;
  246. if (!hasprops && type.IsSubclassOf(typeof(BaseObject)))
  247. RegisterProperties(type);
  248. }
  249. catch (Exception e)
  250. {
  251. // This seems to be an intermittent error "Collection has been modified" when checking if the Dictionary has been populated already
  252. // I've added a .ToArray() to concretise the list, but who knows?
  253. Logger.Send(LogType.Error,"",$"Error Checking Properties for Type: {entityName}\n{e.Message}\n{e.StackTrace}");
  254. }
  255. }
  256. public static IEnumerable<IProperty> Properties(Type type)
  257. {
  258. CheckProperties(type);
  259. var entityName = type.EntityName();
  260. return _properties.GetValueOrDefault(entityName)?.Select(x => x.Value) ?? Array.Empty<IProperty>();
  261. }
  262. public static IProperty? Property(Type type, string name)
  263. {
  264. CheckProperties(type);
  265. var entityName = type.EntityName();
  266. var prop = _properties.GetValueOrDefault(entityName)?.GetValueOrDefault(name);
  267. // Walk up the inheritance tree, see if an ancestor has this property
  268. if (prop == null && type.BaseType != null)
  269. prop = Property(type.BaseType, name);
  270. return prop;
  271. }
  272. public static IProperty? Property<T>(Expression<Func<T, object?>> expression) => Property(typeof(T), CoreUtils.GetFullPropertyName(expression, "."));
  273. public static void InitializeObject<TObject>(TObject entity) where TObject : BaseObject
  274. {
  275. entity.UserProperties.Load(Properties(entity.GetType())
  276. .Where(x => x is CustomProperty)
  277. .Select(x => new KeyValuePair<string, object?>(x.Name, x.PropertyType)));
  278. }
  279. }
  280. }