DatabaseSchema.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. 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 &&
  89. (x.DeclaringType.IsSubclassOf(typeof(BaseObject))
  90. || x.DeclaringType.IsSubclassOf(typeof(BaseEditor)))
  91. );
  92. var subObjects = new List<Tuple<Type, string>>();
  93. foreach (var prop in properties)
  94. {
  95. var name = prefix + prop.Name;
  96. if (newProperties.ContainsKey(name)) continue;
  97. var getMethod = prop.GetGetMethod();
  98. if (getMethod is null || !getMethod.IsPublic || getMethod.IsStatic) continue;
  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. Name = name,
  158. PropertyType = prop.PropertyType,
  159. Editor = editor ?? new NullEditor(),
  160. HasEditor = editor != null,
  161. Caption = caption,
  162. Sequence = sequence ?? 999,
  163. Page = page ?? "",
  164. Required = required,
  165. Loggable = loggable,
  166. Parent = parent,
  167. Property = prop
  168. };
  169. var parentWithEditable = newProperty.GetOuterParent(x =>
  170. x is StandardProperty st
  171. && st.Property.GetCustomAttribute<EditableAttribute>() != null);
  172. if(parentWithEditable != null)
  173. {
  174. var attr = (parentWithEditable as StandardProperty)!.Property.GetCustomAttribute<EditableAttribute>()!;
  175. newProperty.Editor.Editable = newProperty.Editor.Editable.Combine(attr.Editable);
  176. }
  177. else if(prop.GetCustomAttribute<EditableAttribute>() is EditableAttribute attr)
  178. {
  179. newProperty.Editor.Editable = newProperty.Editor.Editable.Combine(attr.Editable);
  180. }
  181. var isLink = prop.PropertyType.HasInterface<IEntityLink>();
  182. var isEnclosedEntity = prop.PropertyType.HasInterface<IEnclosedEntity>();
  183. var isBaseEditor = prop.PropertyType.HasInterface<IBaseEditor>();
  184. if ((isLink || isEnclosedEntity) && !isBaseEditor)
  185. {
  186. subObjects.Add(new Tuple<Type, string>(prop.PropertyType, prop.Name));
  187. }
  188. if (isLink || isEnclosedEntity || isBaseEditor)
  189. {
  190. RegisterProperties(master, prop.PropertyType, name + ".", newProperty, newProperties);
  191. }
  192. else
  193. {
  194. newProperties.Add(newProperty.Name, newProperty);
  195. }
  196. }
  197. RegisterSubObjects(type, subObjects);
  198. // I don't actually think we need this, since PropertyList gives us properties of our parent.
  199. //if (type.IsSubclassOf(typeof(BaseObject)) && type.BaseType != typeof(BaseObject))
  200. // RegisterProperties(master, type.BaseType, prefix, parent, newProperties);
  201. }
  202. catch (Exception e)
  203. {
  204. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  205. }
  206. }
  207. private static void RegisterProperties(Type type)
  208. {
  209. var properties = new Dictionary<string, IProperty>();
  210. RegisterProperties(type, type, "", null, properties);
  211. if(properties.Count > 0)
  212. {
  213. RegisterProperties(type, properties.Values);
  214. }
  215. }
  216. public static object? DefaultValue(Type type)
  217. {
  218. if (type.IsValueType)
  219. return Activator.CreateInstance(type);
  220. if (type.Equals(typeof(string)))
  221. return "";
  222. return null;
  223. }
  224. private static readonly object _updatelock = new object();
  225. private static void RegisterProperties(Type master, IEnumerable<IProperty> toAdd)
  226. {
  227. if (!_properties.TryGetValue(master, out var properties))
  228. {
  229. properties = ImmutableDictionary<string, IProperty>.Empty;
  230. }
  231. var newDict = properties.ToDictionary(x => x.Key, x => x.Value);
  232. foreach(var prop in toAdd)
  233. {
  234. newDict[prop.Name] = prop;
  235. }
  236. _properties[master] = newDict.ToImmutableDictionary();
  237. }
  238. public static void RegisterProperty(IProperty entry)
  239. {
  240. var type = entry.ClassType;
  241. if (type is null) return;
  242. if (!_properties.TryGetValue(type, out var properties))
  243. {
  244. properties = ImmutableDictionary<string, IProperty>.Empty;
  245. }
  246. _properties[type] = properties.Add(entry.Name, entry);
  247. }
  248. public static void Load(CustomProperty[] customproperties)
  249. {
  250. var perType = customproperties.GroupBy(x => x.ClassType);
  251. foreach(var group in perType)
  252. {
  253. if (group.Key is null) continue;
  254. RegisterProperties(group.Key, group);
  255. }
  256. }
  257. private static ImmutableDictionary<string, IProperty>? CheckProperties(Type type)
  258. {
  259. try
  260. {
  261. var props = _properties.GetValueOrDefault(type);
  262. var hasprops = props?.Any(x => x.Value is StandardProperty) == true;
  263. if (!hasprops && type.IsSubclassOf(typeof(BaseObject)))
  264. {
  265. RegisterProperties(type);
  266. return _properties.GetValueOrDefault(type);
  267. }
  268. else
  269. {
  270. return props;
  271. }
  272. }
  273. catch (Exception e)
  274. {
  275. // This seems to be an intermittent error "Collection has been modified" when checking if the Dictionary has been populated already
  276. // I've added a .ToArray() to concretise the list, but who knows?
  277. Logger.Send(LogType.Error,"",$"Error Checking Properties for Type: {type.EntityName()}\n{e.Message}\n{e.StackTrace}");
  278. return null;
  279. }
  280. }
  281. public static IEnumerable<IProperty> Properties(Type type)
  282. {
  283. return CheckProperties(type)?.Select(x => x.Value) ?? Enumerable.Empty<IProperty>();
  284. }
  285. public static IEnumerable<IProperty> Properties<T>() => Properties(typeof(T));
  286. public static IProperty? Property(Type type, string name)
  287. {
  288. var prop = CheckProperties(type)?.GetValueOrDefault(name);
  289. // Walk up the inheritance tree, see if an ancestor has this property
  290. if (prop == null && type.BaseType != null)
  291. prop = Property(type.BaseType, name);
  292. return prop;
  293. }
  294. public static IProperty? Property<T>(Expression<Func<T, object?>> expression) => Property(typeof(T), CoreUtils.GetFullPropertyName(expression, "."));
  295. public static void InitializeObject<TObject>(TObject entity) where TObject : BaseObject
  296. {
  297. entity.UserProperties.Load(Properties(entity.GetType())
  298. .Where(x => x is CustomProperty)
  299. .Select(x => new KeyValuePair<string, object?>(x.Name, DefaultValue(x.PropertyType))));
  300. }
  301. }
  302. }