DatabaseSchema.cs 13 KB

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