DatabaseSchema.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. newProperties.Add(newProperty.Name, newProperty);
  192. }
  193. RegisterSubObjects(type, subObjects);
  194. // I don't actually think we need this, since PropertyList gives us properties of our parent.
  195. //if (type.IsSubclassOf(typeof(BaseObject)) && type.BaseType != typeof(BaseObject))
  196. // RegisterProperties(master, type.BaseType, prefix, parent, newProperties);
  197. }
  198. catch (Exception e)
  199. {
  200. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  201. }
  202. }
  203. private static void RegisterProperties(Type type)
  204. {
  205. var properties = new Dictionary<string, IProperty>();
  206. RegisterProperties(type, type, "", null, properties);
  207. if(properties.Count > 0)
  208. {
  209. RegisterProperties(type, properties.Values);
  210. }
  211. }
  212. public static object? DefaultValue(Type type)
  213. {
  214. if (type.IsValueType)
  215. return Activator.CreateInstance(type);
  216. if (type.Equals(typeof(string)))
  217. return "";
  218. return null;
  219. }
  220. private static readonly object _updatelock = new object();
  221. private static void RegisterProperties(Type master, IEnumerable<IProperty> toAdd)
  222. {
  223. if (!_properties.TryGetValue(master, out var properties))
  224. {
  225. properties = ImmutableDictionary<string, IProperty>.Empty;
  226. }
  227. var newDict = properties.ToDictionary(x => x.Key, x => x.Value);
  228. foreach(var prop in toAdd)
  229. {
  230. newDict[prop.Name] = prop;
  231. }
  232. _properties[master] = newDict.ToImmutableDictionary();
  233. }
  234. public static void RegisterProperty(IProperty entry)
  235. {
  236. var type = entry.ClassType;
  237. if (type is null) return;
  238. if (!_properties.TryGetValue(type, out var properties))
  239. {
  240. properties = ImmutableDictionary<string, IProperty>.Empty;
  241. }
  242. _properties[type] = properties.Add(entry.Name, entry);
  243. }
  244. public static void Load(CustomProperty[] customproperties)
  245. {
  246. var perType = customproperties.GroupBy(x => x.ClassType);
  247. foreach(var group in perType)
  248. {
  249. if (group.Key is null) continue;
  250. RegisterProperties(group.Key, group);
  251. }
  252. }
  253. private static ImmutableDictionary<string, IProperty>? CheckProperties(Type type)
  254. {
  255. try
  256. {
  257. var props = _properties.GetValueOrDefault(type);
  258. var hasprops = props?.Any(x => x.Value is StandardProperty) == true;
  259. if (!hasprops && type.IsSubclassOf(typeof(BaseObject)))
  260. {
  261. RegisterProperties(type);
  262. return _properties.GetValueOrDefault(type);
  263. }
  264. else
  265. {
  266. return props;
  267. }
  268. }
  269. catch (Exception e)
  270. {
  271. // This seems to be an intermittent error "Collection has been modified" when checking if the Dictionary has been populated already
  272. // I've added a .ToArray() to concretise the list, but who knows?
  273. Logger.Send(LogType.Error,"",$"Error Checking Properties for Type: {type.EntityName()}\n{e.Message}\n{e.StackTrace}");
  274. return null;
  275. }
  276. }
  277. private static IEnumerable<IProperty> PropertiesInternal(Type type)
  278. => CheckProperties(type)?.Select(x => x.Value) ?? Enumerable.Empty<IProperty>();
  279. /// <summary>
  280. /// Return the standard property list for <paramref name="type"/>; this includes nested properties.
  281. /// </summary>
  282. /// <param name="type"></param>
  283. /// <returns></returns>
  284. public static IEnumerable<IProperty> Properties(Type type)
  285. => PropertiesInternal(type).Where(x => !x.IsParent);
  286. /// <summary>
  287. /// Return all properties that are defined directly on <paramref name="type"/>, and does not follow sub objects, but rather includes the
  288. /// sub object property itself.
  289. /// </summary>
  290. /// <param name="type"></param>
  291. /// <returns></returns>
  292. public static IEnumerable<IProperty> RootProperties(Type type)
  293. => PropertiesInternal(type).Where(x => x.Parent is null);
  294. /// <summary>
  295. /// Return the standard property list for <paramref name="type"/>; this includes nested properties.
  296. /// </summary>
  297. /// <param name="type"></param>
  298. /// <returns></returns>
  299. public static IEnumerable<IProperty> Properties<T>() => Properties(typeof(T));
  300. public static IProperty? Property(Type type, string name)
  301. {
  302. var prop = CheckProperties(type)?.GetValueOrDefault(name);
  303. // Walk up the inheritance tree, see if an ancestor has this property
  304. if (prop == null && type.BaseType != null)
  305. prop = Property(type.BaseType, name);
  306. return prop;
  307. }
  308. public static IProperty? Property<T>(Expression<Func<T, object?>> expression) => Property(typeof(T), CoreUtils.GetFullPropertyName(expression, "."));
  309. public static void InitializeObject<TObject>(TObject entity) where TObject : BaseObject
  310. {
  311. entity.UserProperties.Load(Properties(entity.GetType())
  312. .Where(x => x is CustomProperty)
  313. .Select(x => new KeyValuePair<string, object?>(x.Name, DefaultValue(x.PropertyType))));
  314. }
  315. }
  316. }