DatabaseSchema.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Collections.Immutable;
  5. using System.Diagnostics.CodeAnalysis;
  6. using System.Linq;
  7. using System.Linq.Expressions;
  8. using System.Reflection;
  9. namespace InABox.Core
  10. {
  11. public static class DatabaseSchema
  12. {
  13. // {className: {propertyName: property}}
  14. private static ConcurrentDictionary<Type, ImmutableSortedDictionary<string, IProperty>> _properties
  15. = new ConcurrentDictionary<Type, ImmutableSortedDictionary<string, IProperty>>();
  16. private struct SubObject
  17. {
  18. public Type PropertyType { get; set; }
  19. public string Name { get; set; }
  20. public Action<object, object> Setter { get; set; }
  21. public Func<object, object> Getter { get; set; }
  22. public SubObject(Type objectType, Type propertyType, string name)
  23. {
  24. PropertyType = propertyType;
  25. Name = name;
  26. Setter = Expressions.Setter(objectType, name);
  27. Getter = Expressions.Getter(objectType, name);
  28. }
  29. }
  30. private static ConcurrentDictionary<Type, ImmutableList<SubObject>> _subObjects { get; } = new ConcurrentDictionary<Type, ImmutableList<SubObject>>();
  31. private static IReadOnlyCollection<SubObject>? GetSubObjectDefs(Type t)
  32. {
  33. CheckPropertiesInternal(t);
  34. return _subObjects.GetValueOrDefault(t);
  35. }
  36. public static IEnumerable<BaseObject> GetSubObjects(BaseObject obj)
  37. {
  38. var objs = GetSubObjectDefs(obj.GetType());
  39. if(objs is null)
  40. {
  41. yield break;
  42. }
  43. foreach (var subObjectDef in objs)
  44. {
  45. var subObj = subObjectDef.Getter(obj);
  46. if(subObj is BaseObject bObj)
  47. {
  48. yield return bObj;
  49. }
  50. }
  51. }
  52. public static void InitializeSubObjects(BaseObject obj)
  53. {
  54. var objs = GetSubObjectDefs(obj.GetType());
  55. if(objs is null)
  56. {
  57. return;
  58. }
  59. foreach (var subObjectDef in objs)
  60. {
  61. var subObj = (Activator.CreateInstance(subObjectDef.PropertyType) as ISubObject)!;
  62. subObjectDef.Setter(obj, subObj);
  63. subObj.SetLinkedParent(obj);
  64. subObj.SetLinkedPath(subObjectDef.Name);
  65. }
  66. }
  67. // For synchronisation purposes, we register sub objects in bulk, removing the need for nested concurrent dictionaries.
  68. private static void RegisterSubObjects(Type objectType, IEnumerable<Tuple<Type, string>> objects)
  69. {
  70. if (!_subObjects.TryGetValue(objectType, out var subObjects))
  71. {
  72. subObjects = ImmutableList<SubObject>.Empty;
  73. }
  74. // No synchronisation issues, since the original collection is not being modified, just the entry in the concurrent dictionary is updated.
  75. _subObjects[objectType] = subObjects.AddRange(
  76. objects.Where(x => !subObjects.Any(y => x.Item1 == y.PropertyType && x.Item2 == y.Name))
  77. .Select(x => new SubObject(objectType, x.Item1, x.Item2)));
  78. }
  79. public static void Clear()
  80. {
  81. _properties = new ConcurrentDictionary<Type, ImmutableSortedDictionary<string, IProperty>>();
  82. }
  83. /// <summary>
  84. /// Gets the editor for the specified property. If the property has a <see cref="BaseEditor"/> defined, then returns that.<br/>
  85. /// Otherwise, gets a default for the property type. (<see cref="GetEditor(Type)"/>), which can be <see langword="null"/>.
  86. /// </summary>
  87. /// <param name="prop"></param>
  88. /// <returns></returns>
  89. private static BaseEditor? GetEditor(PropertyInfo prop)
  90. {
  91. var attribute = prop.GetCustomAttributes<BaseEditor>(true).FirstOrDefault();
  92. var editor = attribute ?? EditorUtils.GetEditor(prop.PropertyType);
  93. if (editor != null && !prop.CanWrite && !prop.PropertyType.HasInterface<ISubObject>())
  94. {
  95. editor = editor.CloneEditor();
  96. editor.Editable = editor.Editable.Combine(Editable.Disabled);
  97. }
  98. return editor;
  99. }
  100. private static void RegisterProperties(Type master, Type type, string prefix, StandardProperty? parent, Dictionary<string, IProperty> newProperties)
  101. {
  102. try
  103. {
  104. var properties = CoreUtils.PropertyList(
  105. type,
  106. x => !x.PropertyType.IsInterface && x.DeclaringType != typeof(BaseObject)
  107. );
  108. var subObjects = new List<Tuple<Type, string>>();
  109. foreach (var prop in properties)
  110. {
  111. var name = prefix + prop.Name;
  112. if (newProperties.ContainsKey(name)) continue;
  113. var getMethod = prop.GetGetMethod();
  114. if (getMethod is null || !getMethod.IsPublic || getMethod.IsStatic) continue;
  115. BaseEditor? editor;
  116. if (parent != null && parent.HasEditor && parent.Editor is NullEditor)
  117. {
  118. editor = parent.Editor;
  119. }
  120. else
  121. {
  122. editor = GetEditor(prop);
  123. }
  124. if(editor is DataLookupEditor data)
  125. {
  126. data.ParentType = master;
  127. }
  128. var captionAttr = prop.GetCustomAttribute<Caption>();
  129. var subCaption = captionAttr != null ? captionAttr.Text : prop.Name;
  130. var path = captionAttr == null || captionAttr.IncludePath; // If no caption attribute, we should always include the path
  131. var caption = parent?.Caption ?? string.Empty; // We default to the parent caption if subCaption doesn't exist
  132. if (!string.IsNullOrWhiteSpace(subCaption))
  133. {
  134. if (!string.IsNullOrWhiteSpace(caption) && path)
  135. {
  136. caption = $"{caption} {subCaption}";
  137. }
  138. else
  139. {
  140. caption = subCaption;
  141. }
  142. }
  143. // Once the parent page has been found, this property is cemented to that page - it cannot change page to its parent
  144. var page = parent?.Page;
  145. var sequence = parent?.Sequence;
  146. var sequenceAttribute = prop.GetCustomAttribute<EditorSequence>();
  147. if (sequenceAttribute != null)
  148. {
  149. if (string.IsNullOrWhiteSpace(page))
  150. {
  151. page = sequenceAttribute.Page;
  152. }
  153. sequence = sequenceAttribute.Sequence;
  154. }
  155. editor = editor?.Clone() as BaseEditor;
  156. if (editor != null)
  157. {
  158. editor.Page = page;
  159. editor.Caption = caption;
  160. editor.EditorSequence = (int)(sequence ?? 999);
  161. editor.Security = prop.GetCustomAttributes<SecurityAttribute>().ToArray();
  162. }
  163. var comment = prop.GetCustomAttribute<CommentAttribute>()?.Comment;
  164. if(editor != null && editor.ToolTip.IsNullOrWhiteSpace() && !comment.IsNullOrWhiteSpace())
  165. {
  166. editor.ToolTip = comment;
  167. }
  168. bool required = false;
  169. if (parent == null || parent.Required)
  170. {
  171. required = prop.GetCustomAttribute<RequiredColumnAttribute>() != null;
  172. }
  173. LoggablePropertyAttribute? loggable = null;
  174. if (parent == null || parent.Loggable != null)
  175. {
  176. loggable = prop.GetCustomAttribute<LoggablePropertyAttribute>();
  177. }
  178. var newProperty = new StandardProperty
  179. {
  180. _class = master,
  181. Name = name,
  182. PropertyType = prop.PropertyType,
  183. Editor = editor ?? new NullEditor(),
  184. HasEditor = editor != null,
  185. Caption = caption,
  186. Sequence = sequence ?? 999,
  187. Page = page ?? string.Empty,
  188. Required = required,
  189. Loggable = loggable,
  190. Parent = parent,
  191. Property = prop,
  192. Comment = comment ?? ""
  193. };
  194. var parentWithEditable = newProperty.GetOuterParent(x =>
  195. x is StandardProperty st
  196. && st.Property.GetCustomAttribute<EditableAttribute>() != null);
  197. if(parentWithEditable != null)
  198. {
  199. var attr = (parentWithEditable as StandardProperty)!.Property.GetCustomAttribute<EditableAttribute>()!;
  200. newProperty.Editor.Editable = newProperty.Editor.Editable.Combine(attr.Editable);
  201. }
  202. else if(prop.GetCustomAttribute<EditableAttribute>() is EditableAttribute attr)
  203. {
  204. newProperty.Editor.Editable = newProperty.Editor.Editable.Combine(attr.Editable);
  205. }
  206. var isLink = prop.PropertyType.HasInterface<IEntityLink>();
  207. var isEnclosedEntity = prop.PropertyType.HasInterface<IEnclosedEntity>();
  208. var isBaseEditor = prop.PropertyType.HasInterface<IBaseEditor>();
  209. if ((isLink || isEnclosedEntity) && !isBaseEditor)
  210. {
  211. subObjects.Add(new Tuple<Type, string>(prop.PropertyType, prop.Name));
  212. }
  213. if (isLink || isEnclosedEntity || isBaseEditor)
  214. {
  215. RegisterProperties(master, prop.PropertyType, name + ".", newProperty, newProperties);
  216. }
  217. newProperties.Add(newProperty.Name, newProperty);
  218. }
  219. RegisterSubObjects(type, subObjects);
  220. // I don't actually think we need this, since PropertyList gives us properties of our parent.
  221. //if (type.IsSubclassOf(typeof(BaseObject)) && type.BaseType != typeof(BaseObject))
  222. // RegisterProperties(master, type.BaseType, prefix, parent, newProperties);
  223. }
  224. catch (Exception e)
  225. {
  226. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  227. }
  228. }
  229. private static void RegisterProperties(Type type)
  230. {
  231. var properties = new Dictionary<string, IProperty>();
  232. RegisterProperties(type, type, "", null, properties);
  233. if(properties.Count > 0)
  234. {
  235. RegisterProperties(type, properties.Values);
  236. }
  237. }
  238. public static object? DefaultValue(Type type)
  239. {
  240. if (type.IsValueType)
  241. return Activator.CreateInstance(type);
  242. if (type.Equals(typeof(string)))
  243. return "";
  244. return null;
  245. }
  246. private static readonly object _updatelock = new object();
  247. private static void RegisterProperties(Type master, IEnumerable<IProperty> toAdd)
  248. {
  249. if (!_properties.TryGetValue(master, out var properties))
  250. {
  251. properties = ImmutableSortedDictionary<string, IProperty>.Empty;
  252. }
  253. var newDict = properties.ToDictionary(x => x.Key, x => x.Value);
  254. foreach(var prop in toAdd)
  255. {
  256. newDict[prop.Name] = prop;
  257. }
  258. _properties[master] = newDict.ToImmutableSortedDictionary();
  259. }
  260. private static void UnregisterProperties(Type master, IEnumerable<IProperty> toRemove)
  261. {
  262. if (!_properties.TryGetValue(master, out var properties))
  263. {
  264. properties = ImmutableSortedDictionary<string, IProperty>.Empty;
  265. }
  266. var newDict = properties.ToDictionary(x => x.Key, x => x.Value);
  267. foreach(var prop in toRemove)
  268. {
  269. newDict.Remove(prop.Name);
  270. }
  271. _properties[master] = newDict.ToImmutableSortedDictionary();
  272. }
  273. public static void RegisterProperty(IProperty entry)
  274. {
  275. var type = entry.ClassType;
  276. if (type is null) return;
  277. if (!_properties.TryGetValue(type, out var properties))
  278. {
  279. properties = ImmutableSortedDictionary<string, IProperty>.Empty;
  280. }
  281. _properties[type] = properties.Add(entry.Name, entry);
  282. }
  283. public static void Load(CustomProperty[] customproperties)
  284. {
  285. var perType = customproperties.GroupBy(x => x.ClassType);
  286. foreach(var group in perType)
  287. {
  288. if (group.Key is null) continue;
  289. RegisterProperties(group.Key, group);
  290. }
  291. }
  292. public static void Unload(CustomProperty[] customProperties)
  293. {
  294. var perType = customProperties.GroupBy(x => x.ClassType);
  295. foreach(var group in perType)
  296. {
  297. if (group.Key is null) continue;
  298. UnregisterProperties(group.Key, group);
  299. }
  300. }
  301. private static ImmutableSortedDictionary<string, IProperty>? CheckPropertiesInternal(Type type)
  302. {
  303. try
  304. {
  305. var props = _properties.GetValueOrDefault(type);
  306. var hasprops = props?.Any(x => x.Value is StandardProperty) == true;
  307. if (!hasprops)
  308. {
  309. RegisterProperties(type);
  310. return _properties.GetValueOrDefault(type);
  311. }
  312. else
  313. {
  314. return props;
  315. }
  316. }
  317. catch (Exception e)
  318. {
  319. // This seems to be an intermittent error "Collection has been modified" when checking if the Dictionary has been populated already
  320. // I've added a .ToArray() to concretise the list, but who knows?
  321. Logger.Send(LogType.Error,"",$"Error Checking Properties for Type: {type.EntityName()}\n{e.Message}\n{e.StackTrace}");
  322. return null;
  323. }
  324. }
  325. public static void CheckProperties(Type type)
  326. {
  327. CheckPropertiesInternal(type);
  328. }
  329. private static IEnumerable<IProperty> PropertiesInternal(Type type)
  330. => CheckPropertiesInternal(type)?.Values ?? Enumerable.Empty<IProperty>();
  331. /// <summary>
  332. /// Returns every property, both parents and children, for <paramref name="type"/>.
  333. /// </summary>
  334. public static IEnumerable<IProperty> AllProperties(Type type)
  335. => PropertiesInternal(type);
  336. /// <summary>
  337. /// Return the standard property list for <paramref name="type"/>; this includes nested properties.
  338. /// </summary>
  339. /// <param name="type"></param>
  340. /// <returns></returns>
  341. public static IEnumerable<IProperty> Properties(Type type)
  342. => PropertiesInternal(type).Where(x => !x.IsParent);
  343. /// <summary>
  344. /// Return all properties that are defined directly on <paramref name="type"/>, and does not follow sub objects, but rather includes the
  345. /// sub object property itself.
  346. /// </summary>
  347. /// <param name="type"></param>
  348. /// <returns></returns>
  349. public static IEnumerable<IProperty> RootProperties(Type type)
  350. => PropertiesInternal(type).Where(x => x.Parent is null);
  351. /// <summary>
  352. /// Return all properties that are defined locally on <paramref name="type"/>, following sub-objects but not entity links; does not retrieve calculated fields. (On entity links, the ID property is retrieved.)
  353. /// </summary>
  354. /// <param name="type"></param>
  355. /// <returns></returns>
  356. public static IEnumerable<IProperty> LocalProperties(Type type)
  357. => PropertiesInternal(type).Where(
  358. x => !x.IsParent && (!x.HasParentEntityLink() || (x.Parent?.HasParentEntityLink() != true && x.Name.EndsWith(".ID")))
  359. && !x.IsCalculated);
  360. /// <summary>
  361. /// Return the standard property list for <paramref name="type"/>; this includes nested properties.
  362. /// </summary>
  363. /// <param name="type"></param>
  364. /// <returns></returns>
  365. public static IEnumerable<IProperty> Properties<T>() => Properties(typeof(T));
  366. public static IProperty? Property(Type type, string name)
  367. {
  368. var prop = CheckPropertiesInternal(type)?.GetValueOrDefault(name);
  369. // Walk up the inheritance tree, see if an ancestor has this property.
  370. // KENRIC: not sure if this is necessary.
  371. if (prop == null && type.BaseType != null)
  372. prop = Property(type.BaseType, name);
  373. return prop;
  374. }
  375. public static IProperty? Property<T>(Expression<Func<T, object?>> expression) =>
  376. Property(typeof(T), CoreUtils.GetFullPropertyName(expression, "."));
  377. public static IProperty? Property<T, TType>(Expression<Func<T, TType>> expression) =>
  378. Property(typeof(T), CoreUtils.GetFullPropertyName(expression, "."));
  379. public static IProperty PropertyStrict(Type type, string name) =>
  380. Property(type, name) ?? throw new PropertyNotFoundException(type, name);
  381. public static IProperty PropertyStrict<T>(Expression<Func<T, object?>> expression) =>
  382. Property(expression) ?? throw new PropertyNotFoundException(typeof(T), CoreUtils.GetFullPropertyName(expression, "."));
  383. public class PropertyNotFoundException : Exception
  384. {
  385. public Type Type { get; set; }
  386. public string Property { get; set; }
  387. public PropertyNotFoundException(Type T, string property) : base($"Property '{property}' not found on type {T.FullName}")
  388. {
  389. Type = T;
  390. Property = property;
  391. }
  392. }
  393. }
  394. }