DatabaseSchema.cs 14 KB

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