DatabaseSchema.cs 16 KB

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