DatabaseSchema.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. CheckProperties(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. private static void RegisterProperties(Type master, Type type, string prefix, StandardProperty? parent)
  79. {
  80. try
  81. {
  82. var classname = master.EntityName();
  83. var properties = CoreUtils.PropertyList(
  84. type,
  85. x => !x.PropertyType.IsInterface &&
  86. x.GetGetMethod()?.IsPublic == true &&
  87. (x.DeclaringType.IsSubclassOf(typeof(BaseObject))
  88. || x.DeclaringType.IsSubclassOf(typeof(BaseEditor)))
  89. );
  90. var classProps = _properties.GetValueOrDefault(master);
  91. var subObjects = new List<Tuple<Type, string>>();
  92. var newProperties = new List<IProperty>();
  93. foreach (var prop in properties)
  94. {
  95. var name = prefix.IsNullOrWhiteSpace() ? prop.Name : $"{prefix}.{prop.Name}";
  96. var p = classProps?.GetValueOrDefault(name);
  97. if (p == null && !prop.GetAccessors(true)[0].IsStatic)
  98. {
  99. BaseEditor? editor;
  100. if (parent != null && parent.HasEditor && parent.Editor is NullEditor)
  101. {
  102. editor = parent.Editor;
  103. }
  104. else
  105. {
  106. editor = prop.GetEditor();
  107. }
  108. var captionAttr = prop.GetCustomAttribute<Caption>();
  109. var subCaption = captionAttr != null ? captionAttr.Text : prop.Name;
  110. var path = captionAttr == null || captionAttr.IncludePath; // If no caption attribute, we should always include the path
  111. var caption = parent?.Caption ?? ""; // We default to the parent caption if subCaption doesn't exist
  112. if (!string.IsNullOrWhiteSpace(subCaption))
  113. {
  114. if (!string.IsNullOrWhiteSpace(caption) && path)
  115. {
  116. caption = $"{caption} {subCaption}";
  117. }
  118. else
  119. {
  120. caption = subCaption;
  121. }
  122. }
  123. // Once the parent page has been found, this property is cemented to that page - it cannot change page to its parent
  124. // The same goes for sequence
  125. var page = parent?.Page;
  126. var sequence = parent?.Sequence;
  127. if (string.IsNullOrWhiteSpace(page))
  128. {
  129. var sequenceAttribute = prop.GetCustomAttribute<EditorSequence>();
  130. if (sequenceAttribute != null)
  131. {
  132. page = sequenceAttribute.Page;
  133. sequence = sequenceAttribute.Sequence;
  134. }
  135. }
  136. editor = editor?.Clone() as BaseEditor;
  137. if (editor != null)
  138. {
  139. editor.Page = page;
  140. editor.Caption = caption;
  141. editor.EditorSequence = (int)(sequence ?? 999);
  142. editor.Security = prop.GetCustomAttributes<SecurityAttribute>().ToArray();
  143. }
  144. bool required = false;
  145. if (parent == null || parent.Required)
  146. {
  147. required = prop.GetCustomAttribute<RequiredColumnAttribute>() != null;
  148. }
  149. LoggablePropertyAttribute? loggable = null;
  150. if (parent == null || parent.Loggable != null)
  151. {
  152. loggable = prop.GetCustomAttribute<LoggablePropertyAttribute>();
  153. }
  154. var newProperty = new StandardProperty
  155. {
  156. _class = master,
  157. //Class = classname,
  158. Name = name,
  159. PropertyType = prop.PropertyType,
  160. Editor = editor ?? new NullEditor(),
  161. HasEditor = editor != null,
  162. Caption = caption,
  163. Sequence = sequence ?? 999,
  164. Page = page ?? "",
  165. Required = required,
  166. Loggable = loggable,
  167. Parent = parent,
  168. Property = prop
  169. };
  170. var parentWithEditable = newProperty.GetOuterParent(x =>
  171. x is StandardProperty st
  172. && st.Property.GetCustomAttribute<EditableAttribute>() != null);
  173. if(parentWithEditable != null)
  174. {
  175. var attr = (parentWithEditable as StandardProperty)!.Property.GetCustomAttribute<EditableAttribute>()!;
  176. newProperty.Editor.Editable = newProperty.Editor.Editable.Combine(attr.Editable);
  177. }
  178. else if(prop.GetCustomAttribute<EditableAttribute>() is EditableAttribute attr)
  179. {
  180. newProperty.Editor.Editable = newProperty.Editor.Editable.Combine(attr.Editable);
  181. }
  182. var isLink = typeof(IEntityLink).IsAssignableFrom(prop.PropertyType);
  183. var isEnclosedEntity = typeof(IEnclosedEntity).IsAssignableFrom(prop.PropertyType);
  184. var isBaseEditor = prop.PropertyType.Equals(typeof(BaseEditor)) ||
  185. prop.PropertyType.IsSubclassOf(typeof(BaseEditor));
  186. if ((isLink || isEnclosedEntity) && !isBaseEditor)
  187. {
  188. subObjects.Add(new Tuple<Type, string>(prop.PropertyType, prop.Name));
  189. }
  190. if (isLink || isEnclosedEntity || isBaseEditor)
  191. {
  192. RegisterProperties(master, prop.PropertyType, name, newProperty);
  193. }
  194. else
  195. {
  196. newProperties.Add(newProperty);
  197. }
  198. }
  199. }
  200. RegisterProperties(master, newProperties);
  201. RegisterSubObjects(type, subObjects);
  202. if (type.IsSubclassOf(typeof(BaseObject)))
  203. RegisterProperties(master, type.BaseType, prefix, parent);
  204. }
  205. catch (Exception e)
  206. {
  207. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  208. }
  209. }
  210. private static void RegisterProperties(Type type)
  211. {
  212. RegisterProperties(type, type, "", null);
  213. }
  214. public static object? DefaultValue(Type type)
  215. {
  216. if (type.IsValueType)
  217. return Activator.CreateInstance(type);
  218. if (type.Equals(typeof(string)))
  219. return "";
  220. return null;
  221. }
  222. private static readonly object _updatelock = new object();
  223. private static void RegisterProperties(Type master, IEnumerable<IProperty> toAdd)
  224. {
  225. if (!_properties.TryGetValue(master, out var properties))
  226. {
  227. properties = ImmutableDictionary<string, IProperty>.Empty;
  228. }
  229. var newDict = properties.ToDictionary(x => x.Key, x => x.Value);
  230. foreach(var prop in toAdd)
  231. {
  232. newDict[prop.Name] = prop;
  233. }
  234. _properties[master] = newDict.ToImmutableDictionary();
  235. }
  236. public static void RegisterProperty(IProperty entry)
  237. {
  238. var type = entry.ClassType;
  239. if (type is null) return;
  240. if (!_properties.TryGetValue(type, out var properties))
  241. {
  242. properties = ImmutableDictionary<string, IProperty>.Empty;
  243. }
  244. _properties[type] = properties.Add(entry.Name, entry);
  245. }
  246. public static void Load(CustomProperty[] customproperties)
  247. {
  248. var perType = customproperties.GroupBy(x => x.ClassType);
  249. foreach(var group in perType)
  250. {
  251. if (group.Key is null) continue;
  252. RegisterProperties(group.Key, group);
  253. }
  254. }
  255. private static ImmutableDictionary<string, IProperty>? CheckProperties(Type type)
  256. {
  257. try
  258. {
  259. var props = _properties.GetValueOrDefault(type);
  260. var hasprops = props?.Any(x => x.Value is StandardProperty) == true;
  261. if (!hasprops && type.IsSubclassOf(typeof(BaseObject)))
  262. {
  263. RegisterProperties(type);
  264. return _properties.GetValueOrDefault(type);
  265. }
  266. else
  267. {
  268. return props;
  269. }
  270. }
  271. catch (Exception e)
  272. {
  273. // This seems to be an intermittent error "Collection has been modified" when checking if the Dictionary has been populated already
  274. // I've added a .ToArray() to concretise the list, but who knows?
  275. Logger.Send(LogType.Error,"",$"Error Checking Properties for Type: {type.EntityName()}\n{e.Message}\n{e.StackTrace}");
  276. return null;
  277. }
  278. }
  279. public static IEnumerable<IProperty> Properties(Type type)
  280. {
  281. return CheckProperties(type)?.Select(x => x.Value) ?? Enumerable.Empty<IProperty>();
  282. }
  283. public static IProperty? Property(Type type, string name)
  284. {
  285. var prop = CheckProperties(type)?.GetValueOrDefault(name);
  286. // Walk up the inheritance tree, see if an ancestor has this property
  287. if (prop == null && type.BaseType != null)
  288. prop = Property(type.BaseType, name);
  289. return prop;
  290. }
  291. public static IProperty? Property<T>(Expression<Func<T, object?>> expression) => Property(typeof(T), CoreUtils.GetFullPropertyName(expression, "."));
  292. public static void InitializeObject<TObject>(TObject entity) where TObject : BaseObject
  293. {
  294. entity.UserProperties.Load(Properties(entity.GetType())
  295. .Where(x => x is CustomProperty)
  296. .Select(x => new KeyValuePair<string, object?>(x.Name, x.PropertyType)));
  297. }
  298. }
  299. }