DatabaseSchema.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Linq.Expressions;
  6. using System.Reflection;
  7. namespace InABox.Core
  8. {
  9. public static class DatabaseSchema
  10. {
  11. // {className: {propertyName: property}}
  12. private static Dictionary<string, Dictionary<string, IProperty>> _properties
  13. = new Dictionary<string, Dictionary<string, IProperty>>();
  14. private struct SubObject
  15. {
  16. public Type PropertyType { get; set; }
  17. public string Name { get; set; }
  18. public Action<object, object> Setter { get; set; }
  19. public SubObject(Type objectType, Type propertyType, string name)
  20. {
  21. PropertyType = propertyType;
  22. Name = name;
  23. Setter = Expressions.Setter(objectType, name);
  24. }
  25. }
  26. private static Dictionary<Type, List<SubObject>> _subObjects { get; } = new Dictionary<Type, List<SubObject>>();
  27. private static List<SubObject>? GetSubObjects(Type t)
  28. {
  29. CheckProperties(t);
  30. return _subObjects.GetValueOrDefault(t);
  31. }
  32. public static void InitializeSubObjects(BaseObject obj)
  33. {
  34. var objs = GetSubObjects(obj.GetType());
  35. if(objs is null)
  36. {
  37. return;
  38. }
  39. foreach (var subObjectDef in objs)
  40. {
  41. var subObj = (Activator.CreateInstance(subObjectDef.PropertyType) as ISubObject)!;
  42. subObjectDef.Setter(obj, subObj);
  43. subObj.SetLinkedParent(obj);
  44. subObj.SetLinkedPath(subObjectDef.Name);
  45. }
  46. }
  47. private static void RegisterSubObject(Type objectType, Type propertyType, string name)
  48. {
  49. lock (_updatelock)
  50. {
  51. if (!_subObjects.TryGetValue(objectType, out var properties))
  52. {
  53. properties = new List<SubObject>();
  54. _subObjects[objectType] = properties;
  55. }
  56. if (!properties.Any(x => x.Name == name && x.PropertyType == propertyType))
  57. {
  58. properties.Add(new SubObject(objectType, propertyType, name));
  59. }
  60. }
  61. }
  62. private static void RegisterProperties(Type master, Type type, string prefix, StandardProperty? parent)
  63. {
  64. try
  65. {
  66. var classname = master.EntityName();
  67. var properties = CoreUtils.PropertyList(
  68. type,
  69. x => !x.PropertyType.IsInterface &&
  70. x.GetGetMethod()?.IsPublic == true &&
  71. (x.DeclaringType.IsSubclassOf(typeof(BaseObject))
  72. || x.DeclaringType.IsSubclassOf(typeof(BaseEditor)))
  73. );
  74. var classProps = _properties.GetValueOrDefault(classname);
  75. foreach (var prop in properties)
  76. {
  77. var name = string.IsNullOrWhiteSpace(prefix) ? prop.Name : string.Format("{0}.{1}", prefix, prop.Name);
  78. var p = classProps?.GetValueOrDefault(name);
  79. if (p == null)
  80. {
  81. var isstatic = prop.GetAccessors(true)[0].IsStatic;
  82. if (!isstatic)
  83. {
  84. BaseEditor? editor;
  85. if (parent != null && parent.HasEditor && parent.Editor is NullEditor)
  86. {
  87. editor = parent.Editor;
  88. }
  89. else
  90. {
  91. editor = prop.GetEditor();
  92. }
  93. var captionAttr = prop.GetCustomAttribute<Caption>();
  94. var subCaption = captionAttr != null ? captionAttr.Text : prop.Name;
  95. var path = captionAttr == null || captionAttr.IncludePath; // If no caption attribute, we should always include the path
  96. var caption = parent?.Caption ?? ""; // We default to the parent caption if subCaption doesn't exist
  97. if (!string.IsNullOrWhiteSpace(subCaption))
  98. {
  99. if (!string.IsNullOrWhiteSpace(caption) && path)
  100. {
  101. caption = $"{caption} {subCaption}";
  102. }
  103. else
  104. {
  105. caption = subCaption;
  106. }
  107. }
  108. // Once the parent page has been found, this property is cemented to that page - it cannot change page to its parent
  109. // The same goes for sequence
  110. var page = parent?.Page;
  111. var sequence = parent?.Sequence;
  112. if (string.IsNullOrWhiteSpace(page))
  113. {
  114. var sequenceAttribute = prop.GetCustomAttribute<EditorSequence>();
  115. if (sequenceAttribute != null)
  116. {
  117. page = sequenceAttribute.Page;
  118. sequence = sequenceAttribute.Sequence;
  119. }
  120. }
  121. editor = editor?.Clone() as BaseEditor;
  122. if (editor != null)
  123. {
  124. editor.Page = page;
  125. editor.Caption = caption;
  126. editor.EditorSequence = (int)(sequence ?? 999);
  127. editor.Security = prop.GetCustomAttributes<SecurityAttribute>().ToArray();
  128. }
  129. bool required = false;
  130. if (parent == null || parent.Required)
  131. {
  132. required = prop.GetCustomAttribute<RequiredColumnAttribute>() != null;
  133. }
  134. LoggablePropertyAttribute? loggable = null;
  135. if (parent == null || parent.Loggable != null)
  136. {
  137. loggable = prop.GetCustomAttribute<LoggablePropertyAttribute>();
  138. }
  139. var newProperty = new StandardProperty
  140. {
  141. _class = master,
  142. //Class = classname,
  143. Name = name,
  144. PropertyType = prop.PropertyType,
  145. Editor = editor ?? new NullEditor(),
  146. HasEditor = editor != null,
  147. Caption = caption,
  148. Sequence = sequence ?? 999,
  149. Page = page ?? "",
  150. Required = required,
  151. Loggable = loggable,
  152. Parent = parent,
  153. Property = prop
  154. };
  155. var parentWithEditable = newProperty.GetOuterParent(x =>
  156. x is StandardProperty st
  157. && st.Property.GetCustomAttribute<EditableAttribute>() != null);
  158. if(parentWithEditable != null)
  159. {
  160. var attr = (parentWithEditable as StandardProperty)!.Property.GetCustomAttribute<EditableAttribute>()!;
  161. newProperty.Editor.Editable = newProperty.Editor.Editable.Combine(attr.Editable);
  162. }
  163. else if(prop.GetCustomAttribute<EditableAttribute>() is EditableAttribute attr)
  164. {
  165. newProperty.Editor.Editable = newProperty.Editor.Editable.Combine(attr.Editable);
  166. }
  167. var isLink = prop.PropertyType.GetInterfaces().Contains(typeof(IEntityLink));
  168. var isEnclosedEntity = prop.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity));
  169. var isBaseEditor = prop.PropertyType.Equals(typeof(BaseEditor)) ||
  170. prop.PropertyType.IsSubclassOf(typeof(BaseEditor));
  171. if ((isLink || isEnclosedEntity) && !isBaseEditor)
  172. {
  173. RegisterSubObject(type, prop.PropertyType, prop.Name);
  174. }
  175. if (isLink || isEnclosedEntity || isBaseEditor)
  176. {
  177. RegisterProperties(master, prop.PropertyType, name, newProperty);
  178. }
  179. else
  180. {
  181. RegisterProperty(newProperty);
  182. }
  183. }
  184. }
  185. }
  186. if (type.IsSubclassOf(typeof(BaseObject)))
  187. RegisterProperties(master, type.BaseType, prefix, parent);
  188. }
  189. catch (Exception e)
  190. {
  191. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  192. }
  193. }
  194. private static void RegisterProperties(Type type)
  195. {
  196. RegisterProperties(type, type, "", null);
  197. }
  198. public static object? DefaultValue(Type type)
  199. {
  200. if (type.IsValueType)
  201. return Activator.CreateInstance(type);
  202. if (type.Equals(typeof(string)))
  203. return "";
  204. return null;
  205. }
  206. private static readonly object _updatelock = new object();
  207. public static void RegisterProperty(IProperty entry)
  208. {
  209. lock (_updatelock)
  210. {
  211. if (!_properties.ContainsKey(entry.Class))
  212. _properties[entry.Class] = new Dictionary<string, IProperty>();
  213. _properties[entry.Class][entry.Name] = entry;
  214. }
  215. }
  216. public static void Load(CustomProperty[] customproperties)
  217. {
  218. foreach (var prop in customproperties)
  219. RegisterProperty(prop);
  220. }
  221. private static void CheckProperties(Type type)
  222. {
  223. var entityName = type.EntityName();
  224. try
  225. {
  226. var props = _properties.GetValueOrDefault(entityName);
  227. var hasprops = props?.Any(x => x.Value is StandardProperty) == true;
  228. if (type.IsSubclassOf(typeof(BaseObject)) && !hasprops)
  229. RegisterProperties(type);
  230. }
  231. catch (Exception e)
  232. {
  233. // This seems to be an intermittent error "Collection has been modified" when checking if the Dictionary has been populated already
  234. // I've added a .ToArray() to concretise the list, but who knows?
  235. Logger.Send(LogType.Error,"",$"Error Checking Properties for Type: {entityName}\n{e.Message}\n{e.StackTrace}");
  236. }
  237. }
  238. public static IEnumerable<IProperty> Properties(Type type)
  239. {
  240. CheckProperties(type);
  241. var entityName = type.EntityName();
  242. return _properties.GetValueOrDefault(entityName)?.Select(x => x.Value) ?? Array.Empty<IProperty>();
  243. }
  244. public static IProperty? Property(Type type, string name)
  245. {
  246. CheckProperties(type);
  247. var entityName = type.EntityName();
  248. var prop = _properties.GetValueOrDefault(entityName)?.GetValueOrDefault(name);
  249. // Walk up the inheritance tree, see if an ancestor has this property
  250. if (prop == null && type.BaseType != null)
  251. prop = Property(type.BaseType, name);
  252. return prop;
  253. }
  254. public static IProperty? Property<T>(Expression<Func<T, object?>> expression) => Property(typeof(T), CoreUtils.GetFullPropertyName(expression, "."));
  255. public static void InitializeObject<TObject>(TObject entity) where TObject : BaseObject
  256. {
  257. entity.UserProperties.Clear();
  258. var props = Properties(entity.GetType()).Where(x => x is CustomProperty).ToArray();
  259. foreach (var field in props) entity.UserProperties[field.Name] = DefaultValue(field.PropertyType);
  260. }
  261. }
  262. }