DatabaseSchema.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. bool required = false;
  143. if (parent == null || parent.Required)
  144. {
  145. required = prop.GetCustomAttribute<RequiredColumnAttribute>() != null;
  146. }
  147. LoggablePropertyAttribute? loggable = null;
  148. if (parent == null || parent.Loggable != null)
  149. {
  150. loggable = prop.GetCustomAttribute<LoggablePropertyAttribute>();
  151. }
  152. var newProperty = new StandardProperty
  153. {
  154. _class = master,
  155. Name = name,
  156. PropertyType = prop.PropertyType,
  157. Editor = editor ?? new NullEditor(),
  158. HasEditor = editor != null,
  159. Caption = caption,
  160. Sequence = sequence ?? 999,
  161. Page = page ?? string.Empty,
  162. Required = required,
  163. Loggable = loggable,
  164. Parent = parent,
  165. Property = prop
  166. };
  167. var parentWithEditable = newProperty.GetOuterParent(x =>
  168. x is StandardProperty st
  169. && st.Property.GetCustomAttribute<EditableAttribute>() != null);
  170. if(parentWithEditable != null)
  171. {
  172. var attr = (parentWithEditable as StandardProperty)!.Property.GetCustomAttribute<EditableAttribute>()!;
  173. newProperty.Editor.Editable = newProperty.Editor.Editable.Combine(attr.Editable);
  174. }
  175. else if(prop.GetCustomAttribute<EditableAttribute>() is EditableAttribute attr)
  176. {
  177. newProperty.Editor.Editable = newProperty.Editor.Editable.Combine(attr.Editable);
  178. }
  179. var isLink = prop.PropertyType.HasInterface<IEntityLink>();
  180. var isEnclosedEntity = prop.PropertyType.HasInterface<IEnclosedEntity>();
  181. var isBaseEditor = prop.PropertyType.HasInterface<IBaseEditor>();
  182. if ((isLink || isEnclosedEntity) && !isBaseEditor)
  183. {
  184. subObjects.Add(new Tuple<Type, string>(prop.PropertyType, prop.Name));
  185. }
  186. if (isLink || isEnclosedEntity || isBaseEditor)
  187. {
  188. RegisterProperties(master, prop.PropertyType, name + ".", newProperty, newProperties);
  189. }
  190. newProperties.Add(newProperty.Name, newProperty);
  191. }
  192. RegisterSubObjects(type, subObjects);
  193. // I don't actually think we need this, since PropertyList gives us properties of our parent.
  194. //if (type.IsSubclassOf(typeof(BaseObject)) && type.BaseType != typeof(BaseObject))
  195. // RegisterProperties(master, type.BaseType, prefix, parent, newProperties);
  196. }
  197. catch (Exception e)
  198. {
  199. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  200. }
  201. }
  202. private static void RegisterProperties(Type type)
  203. {
  204. var properties = new Dictionary<string, IProperty>();
  205. RegisterProperties(type, type, "", null, properties);
  206. if(properties.Count > 0)
  207. {
  208. RegisterProperties(type, properties.Values);
  209. }
  210. }
  211. public static object? DefaultValue(Type type)
  212. {
  213. if (type.IsValueType)
  214. return Activator.CreateInstance(type);
  215. if (type.Equals(typeof(string)))
  216. return "";
  217. return null;
  218. }
  219. private static readonly object _updatelock = new object();
  220. private static void RegisterProperties(Type master, IEnumerable<IProperty> toAdd)
  221. {
  222. if (!_properties.TryGetValue(master, out var properties))
  223. {
  224. properties = ImmutableSortedDictionary<string, IProperty>.Empty;
  225. }
  226. var newDict = properties.ToDictionary(x => x.Key, x => x.Value);
  227. foreach(var prop in toAdd)
  228. {
  229. newDict[prop.Name] = prop;
  230. }
  231. _properties[master] = newDict.ToImmutableSortedDictionary();
  232. }
  233. public static void RegisterProperty(IProperty entry)
  234. {
  235. var type = entry.ClassType;
  236. if (type is null) return;
  237. if (!_properties.TryGetValue(type, out var properties))
  238. {
  239. properties = ImmutableSortedDictionary<string, IProperty>.Empty;
  240. }
  241. _properties[type] = properties.Add(entry.Name, entry);
  242. }
  243. public static void Load(CustomProperty[] customproperties)
  244. {
  245. var perType = customproperties.GroupBy(x => x.ClassType);
  246. foreach(var group in perType)
  247. {
  248. if (group.Key is null) continue;
  249. RegisterProperties(group.Key, group);
  250. }
  251. }
  252. private static ImmutableSortedDictionary<string, IProperty>? CheckPropertiesInternal(Type type)
  253. {
  254. try
  255. {
  256. var props = _properties.GetValueOrDefault(type);
  257. var hasprops = props?.Any(x => x.Value is StandardProperty) == true;
  258. if (!hasprops)
  259. {
  260. RegisterProperties(type);
  261. return _properties.GetValueOrDefault(type);
  262. }
  263. else
  264. {
  265. return props;
  266. }
  267. }
  268. catch (Exception e)
  269. {
  270. // This seems to be an intermittent error "Collection has been modified" when checking if the Dictionary has been populated already
  271. // I've added a .ToArray() to concretise the list, but who knows?
  272. Logger.Send(LogType.Error,"",$"Error Checking Properties for Type: {type.EntityName()}\n{e.Message}\n{e.StackTrace}");
  273. return null;
  274. }
  275. }
  276. public static void CheckProperties(Type type)
  277. {
  278. CheckPropertiesInternal(type);
  279. }
  280. private static IEnumerable<IProperty> PropertiesInternal(Type type)
  281. => CheckPropertiesInternal(type)?.Values ?? Enumerable.Empty<IProperty>();
  282. /// <summary>
  283. /// Return the standard property list for <paramref name="type"/>; this includes nested properties.
  284. /// </summary>
  285. /// <param name="type"></param>
  286. /// <returns></returns>
  287. public static IEnumerable<IProperty> Properties(Type type)
  288. => PropertiesInternal(type).Where(x => !x.IsParent);
  289. /// <summary>
  290. /// Return all properties that are defined directly on <paramref name="type"/>, and does not follow sub objects, but rather includes the
  291. /// sub object property itself.
  292. /// </summary>
  293. /// <param name="type"></param>
  294. /// <returns></returns>
  295. public static IEnumerable<IProperty> RootProperties(Type type)
  296. => PropertiesInternal(type).Where(x => x.Parent is null);
  297. /// <summary>
  298. /// 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.)
  299. /// </summary>
  300. /// <param name="type"></param>
  301. /// <returns></returns>
  302. public static IEnumerable<IProperty> LocalProperties(Type type)
  303. => PropertiesInternal(type).Where(
  304. x => !x.IsParent && (!x.HasParentEntityLink() || (x.Parent?.HasParentEntityLink() != true && x.Name.EndsWith(".ID")))
  305. && !x.IsCalculated);
  306. /// <summary>
  307. /// Return the standard property list for <paramref name="type"/>; this includes nested properties.
  308. /// </summary>
  309. /// <param name="type"></param>
  310. /// <returns></returns>
  311. public static IEnumerable<IProperty> Properties<T>() => Properties(typeof(T));
  312. public static IProperty? Property(Type type, string name)
  313. {
  314. var prop = CheckPropertiesInternal(type)?.GetValueOrDefault(name);
  315. // Walk up the inheritance tree, see if an ancestor has this property.
  316. // KENRIC: not sure if this is necessary.
  317. if (prop == null && type.BaseType != null)
  318. prop = Property(type.BaseType, name);
  319. return prop;
  320. }
  321. public static IProperty? Property<T>(Expression<Func<T, object?>> expression) => Property(typeof(T), CoreUtils.GetFullPropertyName(expression, "."));
  322. public static IProperty? Property<T, TType>(Expression<Func<T, TType>> expression) => Property(typeof(T), CoreUtils.GetFullPropertyName(expression, "."));
  323. public static IProperty PropertyStrict(Type type, string name) => Property(type, name) ?? throw new PropertyNotFoundException(type, name);
  324. public class PropertyNotFoundException : Exception
  325. {
  326. public Type Type { get; set; }
  327. public string Property { get; set; }
  328. public PropertyNotFoundException(Type T, string property) : base($"Property '{property}' not found on type {T.FullName}")
  329. {
  330. Type = T;
  331. Property = property;
  332. }
  333. }
  334. }
  335. }