DatabaseSchema.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. public static void RegisterProperty(IProperty entry)
  240. {
  241. var type = entry.ClassType;
  242. if (type is null) return;
  243. if (!_properties.TryGetValue(type, out var properties))
  244. {
  245. properties = ImmutableSortedDictionary<string, IProperty>.Empty;
  246. }
  247. _properties[type] = properties.Add(entry.Name, entry);
  248. }
  249. public static void Load(CustomProperty[] customproperties)
  250. {
  251. var perType = customproperties.GroupBy(x => x.ClassType);
  252. foreach(var group in perType)
  253. {
  254. if (group.Key is null) continue;
  255. RegisterProperties(group.Key, group);
  256. }
  257. }
  258. private static ImmutableSortedDictionary<string, IProperty>? CheckPropertiesInternal(Type type)
  259. {
  260. try
  261. {
  262. var props = _properties.GetValueOrDefault(type);
  263. var hasprops = props?.Any(x => x.Value is StandardProperty) == true;
  264. if (!hasprops)
  265. {
  266. RegisterProperties(type);
  267. return _properties.GetValueOrDefault(type);
  268. }
  269. else
  270. {
  271. return props;
  272. }
  273. }
  274. catch (Exception e)
  275. {
  276. // This seems to be an intermittent error "Collection has been modified" when checking if the Dictionary has been populated already
  277. // I've added a .ToArray() to concretise the list, but who knows?
  278. Logger.Send(LogType.Error,"",$"Error Checking Properties for Type: {type.EntityName()}\n{e.Message}\n{e.StackTrace}");
  279. return null;
  280. }
  281. }
  282. public static void CheckProperties(Type type)
  283. {
  284. CheckPropertiesInternal(type);
  285. }
  286. private static IEnumerable<IProperty> PropertiesInternal(Type type)
  287. => CheckPropertiesInternal(type)?.Values ?? Enumerable.Empty<IProperty>();
  288. /// <summary>
  289. /// Return the standard property list for <paramref name="type"/>; this includes nested properties.
  290. /// </summary>
  291. /// <param name="type"></param>
  292. /// <returns></returns>
  293. public static IEnumerable<IProperty> Properties(Type type)
  294. => PropertiesInternal(type).Where(x => !x.IsParent);
  295. /// <summary>
  296. /// Return all properties that are defined directly on <paramref name="type"/>, and does not follow sub objects, but rather includes the
  297. /// sub object property itself.
  298. /// </summary>
  299. /// <param name="type"></param>
  300. /// <returns></returns>
  301. public static IEnumerable<IProperty> RootProperties(Type type)
  302. => PropertiesInternal(type).Where(x => x.Parent is null);
  303. /// <summary>
  304. /// 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.)
  305. /// </summary>
  306. /// <param name="type"></param>
  307. /// <returns></returns>
  308. public static IEnumerable<IProperty> LocalProperties(Type type)
  309. => PropertiesInternal(type).Where(
  310. x => !x.IsParent && (!x.HasParentEntityLink() || (x.Parent?.HasParentEntityLink() != true && x.Name.EndsWith(".ID")))
  311. && !x.IsCalculated);
  312. /// <summary>
  313. /// Return the standard property list for <paramref name="type"/>; this includes nested properties.
  314. /// </summary>
  315. /// <param name="type"></param>
  316. /// <returns></returns>
  317. public static IEnumerable<IProperty> Properties<T>() => Properties(typeof(T));
  318. public static IProperty? Property(Type type, string name)
  319. {
  320. var prop = CheckPropertiesInternal(type)?.GetValueOrDefault(name);
  321. // Walk up the inheritance tree, see if an ancestor has this property.
  322. // KENRIC: not sure if this is necessary.
  323. if (prop == null && type.BaseType != null)
  324. prop = Property(type.BaseType, name);
  325. return prop;
  326. }
  327. public static IProperty? Property<T>(Expression<Func<T, object?>> expression) => Property(typeof(T), CoreUtils.GetFullPropertyName(expression, "."));
  328. public static IProperty? Property<T, TType>(Expression<Func<T, TType>> expression) => Property(typeof(T), CoreUtils.GetFullPropertyName(expression, "."));
  329. public static IProperty PropertyStrict(Type type, string name) => Property(type, name) ?? throw new PropertyNotFoundException(type, name);
  330. public class PropertyNotFoundException : Exception
  331. {
  332. public Type Type { get; set; }
  333. public string Property { get; set; }
  334. public PropertyNotFoundException(Type T, string property) : base($"Property '{property}' not found on type {T.FullName}")
  335. {
  336. Type = T;
  337. Property = property;
  338. }
  339. }
  340. }
  341. }