DatabaseSchema.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. private static void RegisterProperties(Type master, Type type, string prefix, StandardProperty? parent, Dictionary<string, IProperty> newProperties)
  84. {
  85. try
  86. {
  87. var properties = CoreUtils.PropertyList(
  88. type,
  89. x => !x.PropertyType.IsInterface && x.DeclaringType != typeof(BaseObject)
  90. );
  91. var subObjects = new List<Tuple<Type, string>>();
  92. foreach (var prop in properties)
  93. {
  94. var name = prefix + prop.Name;
  95. if (newProperties.ContainsKey(name)) continue;
  96. var getMethod = prop.GetGetMethod();
  97. if (getMethod is null || !getMethod.IsPublic || getMethod.IsStatic) continue;
  98. BaseEditor? editor;
  99. if (parent != null && parent.HasEditor && parent.Editor is NullEditor)
  100. {
  101. editor = parent.Editor;
  102. }
  103. else
  104. {
  105. editor = prop.GetEditor();
  106. }
  107. var captionAttr = prop.GetCustomAttribute<Caption>();
  108. var subCaption = captionAttr != null ? captionAttr.Text : prop.Name;
  109. var path = captionAttr == null || captionAttr.IncludePath; // If no caption attribute, we should always include the path
  110. var caption = parent?.Caption ?? string.Empty; // We default to the parent caption if subCaption doesn't exist
  111. if (!string.IsNullOrWhiteSpace(subCaption))
  112. {
  113. if (!string.IsNullOrWhiteSpace(caption) && path)
  114. {
  115. caption = $"{caption} {subCaption}";
  116. }
  117. else
  118. {
  119. caption = subCaption;
  120. }
  121. }
  122. // Once the parent page has been found, this property is cemented to that page - it cannot change page to its parent
  123. var page = parent?.Page;
  124. var sequence = parent?.Sequence;
  125. var sequenceAttribute = prop.GetCustomAttribute<EditorSequence>();
  126. if (sequenceAttribute != null)
  127. {
  128. if (string.IsNullOrWhiteSpace(page))
  129. {
  130. page = sequenceAttribute.Page;
  131. }
  132. sequence = sequenceAttribute.Sequence;
  133. }
  134. editor = editor?.Clone() as BaseEditor;
  135. if (editor != null)
  136. {
  137. editor.Page = page;
  138. editor.Caption = caption;
  139. editor.EditorSequence = (int)(sequence ?? 999);
  140. editor.Security = prop.GetCustomAttributes<SecurityAttribute>().ToArray();
  141. }
  142. var comment = prop.GetCustomAttribute<CommentAttribute>()?.Comment;
  143. if(editor != null && editor.ToolTip.IsNullOrWhiteSpace() && !comment.IsNullOrWhiteSpace())
  144. {
  145. editor.ToolTip = comment;
  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. Name = name,
  161. PropertyType = prop.PropertyType,
  162. Editor = editor ?? new NullEditor(),
  163. HasEditor = editor != null,
  164. Caption = caption,
  165. Sequence = sequence ?? 999,
  166. Page = page ?? string.Empty,
  167. Required = required,
  168. Loggable = loggable,
  169. Parent = parent,
  170. Property = prop,
  171. Comment = comment ?? ""
  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.HasInterface<IEntityLink>();
  186. var isEnclosedEntity = prop.PropertyType.HasInterface<IEnclosedEntity>();
  187. var isBaseEditor = prop.PropertyType.HasInterface<IBaseEditor>();
  188. if ((isLink || isEnclosedEntity) && !isBaseEditor)
  189. {
  190. subObjects.Add(new Tuple<Type, string>(prop.PropertyType, prop.Name));
  191. }
  192. if (isLink || isEnclosedEntity || isBaseEditor)
  193. {
  194. RegisterProperties(master, prop.PropertyType, name + ".", newProperty, newProperties);
  195. }
  196. newProperties.Add(newProperty.Name, newProperty);
  197. }
  198. RegisterSubObjects(type, subObjects);
  199. // I don't actually think we need this, since PropertyList gives us properties of our parent.
  200. //if (type.IsSubclassOf(typeof(BaseObject)) && type.BaseType != typeof(BaseObject))
  201. // RegisterProperties(master, type.BaseType, prefix, parent, newProperties);
  202. }
  203. catch (Exception e)
  204. {
  205. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  206. }
  207. }
  208. private static void RegisterProperties(Type type)
  209. {
  210. var properties = new Dictionary<string, IProperty>();
  211. RegisterProperties(type, type, "", null, properties);
  212. if(properties.Count > 0)
  213. {
  214. RegisterProperties(type, properties.Values);
  215. }
  216. }
  217. public static object? DefaultValue(Type type)
  218. {
  219. if (type.IsValueType)
  220. return Activator.CreateInstance(type);
  221. if (type.Equals(typeof(string)))
  222. return "";
  223. return null;
  224. }
  225. private static readonly object _updatelock = new object();
  226. private static void RegisterProperties(Type master, IEnumerable<IProperty> toAdd)
  227. {
  228. if (!_properties.TryGetValue(master, out var properties))
  229. {
  230. properties = ImmutableSortedDictionary<string, IProperty>.Empty;
  231. }
  232. var newDict = properties.ToDictionary(x => x.Key, x => x.Value);
  233. foreach(var prop in toAdd)
  234. {
  235. newDict[prop.Name] = prop;
  236. }
  237. _properties[master] = newDict.ToImmutableSortedDictionary();
  238. }
  239. private static void UnregisterProperties(Type master, IEnumerable<IProperty> toRemove)
  240. {
  241. if (!_properties.TryGetValue(master, out var properties))
  242. {
  243. properties = ImmutableSortedDictionary<string, IProperty>.Empty;
  244. }
  245. var newDict = properties.ToDictionary(x => x.Key, x => x.Value);
  246. foreach(var prop in toRemove)
  247. {
  248. newDict.Remove(prop.Name);
  249. }
  250. _properties[master] = newDict.ToImmutableSortedDictionary();
  251. }
  252. public static void RegisterProperty(IProperty entry)
  253. {
  254. var type = entry.ClassType;
  255. if (type is null) return;
  256. if (!_properties.TryGetValue(type, out var properties))
  257. {
  258. properties = ImmutableSortedDictionary<string, IProperty>.Empty;
  259. }
  260. _properties[type] = properties.Add(entry.Name, entry);
  261. }
  262. public static void Load(CustomProperty[] customproperties)
  263. {
  264. var perType = customproperties.GroupBy(x => x.ClassType);
  265. foreach(var group in perType)
  266. {
  267. if (group.Key is null) continue;
  268. RegisterProperties(group.Key, group);
  269. }
  270. }
  271. public static void Unload(CustomProperty[] customProperties)
  272. {
  273. var perType = customProperties.GroupBy(x => x.ClassType);
  274. foreach(var group in perType)
  275. {
  276. if (group.Key is null) continue;
  277. UnregisterProperties(group.Key, group);
  278. }
  279. }
  280. private static ImmutableSortedDictionary<string, IProperty>? CheckPropertiesInternal(Type type)
  281. {
  282. try
  283. {
  284. var props = _properties.GetValueOrDefault(type);
  285. var hasprops = props?.Any(x => x.Value is StandardProperty) == true;
  286. if (!hasprops)
  287. {
  288. RegisterProperties(type);
  289. return _properties.GetValueOrDefault(type);
  290. }
  291. else
  292. {
  293. return props;
  294. }
  295. }
  296. catch (Exception e)
  297. {
  298. // This seems to be an intermittent error "Collection has been modified" when checking if the Dictionary has been populated already
  299. // I've added a .ToArray() to concretise the list, but who knows?
  300. Logger.Send(LogType.Error,"",$"Error Checking Properties for Type: {type.EntityName()}\n{e.Message}\n{e.StackTrace}");
  301. return null;
  302. }
  303. }
  304. public static void CheckProperties(Type type)
  305. {
  306. CheckPropertiesInternal(type);
  307. }
  308. private static IEnumerable<IProperty> PropertiesInternal(Type type)
  309. => CheckPropertiesInternal(type)?.Values ?? Enumerable.Empty<IProperty>();
  310. /// <summary>
  311. /// Return the standard property list for <paramref name="type"/>; this includes nested properties.
  312. /// </summary>
  313. /// <param name="type"></param>
  314. /// <returns></returns>
  315. public static IEnumerable<IProperty> Properties(Type type)
  316. => PropertiesInternal(type).Where(x => !x.IsParent);
  317. /// <summary>
  318. /// Return all properties that are defined directly on <paramref name="type"/>, and does not follow sub objects, but rather includes the
  319. /// sub object property itself.
  320. /// </summary>
  321. /// <param name="type"></param>
  322. /// <returns></returns>
  323. public static IEnumerable<IProperty> RootProperties(Type type)
  324. => PropertiesInternal(type).Where(x => x.Parent is null);
  325. /// <summary>
  326. /// 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.)
  327. /// </summary>
  328. /// <param name="type"></param>
  329. /// <returns></returns>
  330. public static IEnumerable<IProperty> LocalProperties(Type type)
  331. => PropertiesInternal(type).Where(
  332. x => !x.IsParent && (!x.HasParentEntityLink() || (x.Parent?.HasParentEntityLink() != true && x.Name.EndsWith(".ID")))
  333. && !x.IsCalculated);
  334. /// <summary>
  335. /// Return the standard property list for <paramref name="type"/>; this includes nested properties.
  336. /// </summary>
  337. /// <param name="type"></param>
  338. /// <returns></returns>
  339. public static IEnumerable<IProperty> Properties<T>() => Properties(typeof(T));
  340. public static IProperty? Property(Type type, string name)
  341. {
  342. var prop = CheckPropertiesInternal(type)?.GetValueOrDefault(name);
  343. // Walk up the inheritance tree, see if an ancestor has this property.
  344. // KENRIC: not sure if this is necessary.
  345. if (prop == null && type.BaseType != null)
  346. prop = Property(type.BaseType, name);
  347. return prop;
  348. }
  349. public static IProperty? Property<T>(Expression<Func<T, object?>> expression) => Property(typeof(T), CoreUtils.GetFullPropertyName(expression, "."));
  350. public static IProperty? Property<T, TType>(Expression<Func<T, TType>> expression) => Property(typeof(T), CoreUtils.GetFullPropertyName(expression, "."));
  351. public static IProperty PropertyStrict(Type type, string name) => Property(type, name) ?? throw new PropertyNotFoundException(type, name);
  352. public class PropertyNotFoundException : Exception
  353. {
  354. public Type Type { get; set; }
  355. public string Property { get; set; }
  356. public PropertyNotFoundException(Type T, string property) : base($"Property '{property}' not found on type {T.FullName}")
  357. {
  358. Type = T;
  359. Property = property;
  360. }
  361. }
  362. }
  363. }