123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363 |
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Collections.Immutable;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Reflection;
- namespace InABox.Core
- {
- public static class DatabaseSchema
- {
- // {className: {propertyName: property}}
- private static ConcurrentDictionary<Type, ImmutableDictionary<string, IProperty>> _properties
- = new ConcurrentDictionary<Type, ImmutableDictionary<string, IProperty>>();
- private struct SubObject
- {
- public Type PropertyType { get; set; }
- public string Name { get; set; }
- public Action<object, object> Setter { get; set; }
- public Func<object, object> Getter { get; set; }
- public SubObject(Type objectType, Type propertyType, string name)
- {
- PropertyType = propertyType;
- Name = name;
- Setter = Expressions.Setter(objectType, name);
- Getter = Expressions.Getter(objectType, name);
- }
- }
- private static ConcurrentDictionary<Type, ImmutableList<SubObject>> _subObjects { get; } = new ConcurrentDictionary<Type, ImmutableList<SubObject>>();
- private static IReadOnlyCollection<SubObject>? GetSubObjectDefs(Type t)
- {
- CheckProperties(t);
- return _subObjects.GetValueOrDefault(t);
- }
- public static IEnumerable<BaseObject> GetSubObjects(BaseObject obj)
- {
- var objs = GetSubObjectDefs(obj.GetType());
- if(objs is null)
- {
- yield break;
- }
- foreach (var subObjectDef in objs)
- {
- var subObj = subObjectDef.Getter(obj);
- if(subObj is BaseObject bObj)
- {
- yield return bObj;
- }
- }
- }
- public static void InitializeSubObjects(BaseObject obj)
- {
- var objs = GetSubObjectDefs(obj.GetType());
- if(objs is null)
- {
- return;
- }
- foreach (var subObjectDef in objs)
- {
- var subObj = (Activator.CreateInstance(subObjectDef.PropertyType) as ISubObject)!;
- subObjectDef.Setter(obj, subObj);
- subObj.SetLinkedParent(obj);
- subObj.SetLinkedPath(subObjectDef.Name);
- }
- }
- // For synchronisation purposes, we register sub objects in bulk, removing the need for nested concurrent dictionaries.
- private static void RegisterSubObjects(Type objectType, IEnumerable<Tuple<Type, string>> objects)
- {
- if (!_subObjects.TryGetValue(objectType, out var subObjects))
- {
- subObjects = ImmutableList<SubObject>.Empty;
- }
- // No synchronisation issues, since the original collection is not being modified, just the entry in the concurrent dictionary is updated.
- _subObjects[objectType] = subObjects.AddRange(
- objects.Where(x => !subObjects.Any(y => x.Item1 == y.PropertyType && x.Item2 == y.Name))
- .Select(x => new SubObject(objectType, x.Item1, x.Item2)));
- }
- public static void Clear()
- {
- _properties = new ConcurrentDictionary<Type, ImmutableDictionary<string, IProperty>>();
- }
- private static void RegisterProperties(Type master, Type type, string prefix, StandardProperty? parent, Dictionary<string, IProperty> newProperties)
- {
- try
- {
- var properties = CoreUtils.PropertyList(
- type,
- x => !x.PropertyType.IsInterface &&
- (x.DeclaringType.IsSubclassOf(typeof(BaseObject))
- || x.DeclaringType.IsSubclassOf(typeof(BaseEditor)))
- );
- var subObjects = new List<Tuple<Type, string>>();
- foreach (var prop in properties)
- {
- var name = prefix + prop.Name;
- if (newProperties.ContainsKey(name)) continue;
- var getMethod = prop.GetGetMethod();
- if (getMethod is null || !getMethod.IsPublic || getMethod.IsStatic) continue;
- BaseEditor? editor;
- if (parent != null && parent.HasEditor && parent.Editor is NullEditor)
- {
- editor = parent.Editor;
- }
- else
- {
- editor = prop.GetEditor();
- }
- var captionAttr = prop.GetCustomAttribute<Caption>();
- var subCaption = captionAttr != null ? captionAttr.Text : prop.Name;
- var path = captionAttr == null || captionAttr.IncludePath; // If no caption attribute, we should always include the path
- var caption = parent?.Caption ?? ""; // We default to the parent caption if subCaption doesn't exist
- if (!string.IsNullOrWhiteSpace(subCaption))
- {
- if (!string.IsNullOrWhiteSpace(caption) && path)
- {
- caption = $"{caption} {subCaption}";
- }
- else
- {
- caption = subCaption;
- }
- }
- // Once the parent page has been found, this property is cemented to that page - it cannot change page to its parent
- var page = parent?.Page;
- var sequence = parent?.Sequence;
- var sequenceAttribute = prop.GetCustomAttribute<EditorSequence>();
- if (sequenceAttribute != null)
- {
- if (string.IsNullOrWhiteSpace(page))
- {
- page = sequenceAttribute.Page;
- }
- sequence = sequenceAttribute.Sequence;
- }
- editor = editor?.Clone() as BaseEditor;
- if (editor != null)
- {
- editor.Page = page;
- editor.Caption = caption;
- editor.EditorSequence = (int)(sequence ?? 999);
- editor.Security = prop.GetCustomAttributes<SecurityAttribute>().ToArray();
- }
- bool required = false;
- if (parent == null || parent.Required)
- {
- required = prop.GetCustomAttribute<RequiredColumnAttribute>() != null;
- }
- LoggablePropertyAttribute? loggable = null;
- if (parent == null || parent.Loggable != null)
- {
- loggable = prop.GetCustomAttribute<LoggablePropertyAttribute>();
- }
- var newProperty = new StandardProperty
- {
- _class = master,
- Name = name,
- PropertyType = prop.PropertyType,
- Editor = editor ?? new NullEditor(),
- HasEditor = editor != null,
- Caption = caption,
- Sequence = sequence ?? 999,
- Page = page ?? "",
- Required = required,
- Loggable = loggable,
- Parent = parent,
- Property = prop
- };
- var parentWithEditable = newProperty.GetOuterParent(x =>
- x is StandardProperty st
- && st.Property.GetCustomAttribute<EditableAttribute>() != null);
- if(parentWithEditable != null)
- {
- var attr = (parentWithEditable as StandardProperty)!.Property.GetCustomAttribute<EditableAttribute>()!;
- newProperty.Editor.Editable = newProperty.Editor.Editable.Combine(attr.Editable);
- }
- else if(prop.GetCustomAttribute<EditableAttribute>() is EditableAttribute attr)
- {
- newProperty.Editor.Editable = newProperty.Editor.Editable.Combine(attr.Editable);
- }
- var isLink = prop.PropertyType.HasInterface<IEntityLink>();
- var isEnclosedEntity = prop.PropertyType.HasInterface<IEnclosedEntity>();
- var isBaseEditor = prop.PropertyType.HasInterface<IBaseEditor>();
- if ((isLink || isEnclosedEntity) && !isBaseEditor)
- {
- subObjects.Add(new Tuple<Type, string>(prop.PropertyType, prop.Name));
- }
- if (isLink || isEnclosedEntity || isBaseEditor)
- {
- RegisterProperties(master, prop.PropertyType, name + ".", newProperty, newProperties);
- }
- newProperties.Add(newProperty.Name, newProperty);
- }
- RegisterSubObjects(type, subObjects);
- // I don't actually think we need this, since PropertyList gives us properties of our parent.
- //if (type.IsSubclassOf(typeof(BaseObject)) && type.BaseType != typeof(BaseObject))
- // RegisterProperties(master, type.BaseType, prefix, parent, newProperties);
- }
- catch (Exception e)
- {
- Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
- }
- }
- private static void RegisterProperties(Type type)
- {
- var properties = new Dictionary<string, IProperty>();
- RegisterProperties(type, type, "", null, properties);
- if(properties.Count > 0)
- {
- RegisterProperties(type, properties.Values);
- }
- }
- public static object? DefaultValue(Type type)
- {
- if (type.IsValueType)
- return Activator.CreateInstance(type);
- if (type.Equals(typeof(string)))
- return "";
- return null;
- }
-
- private static readonly object _updatelock = new object();
- private static void RegisterProperties(Type master, IEnumerable<IProperty> toAdd)
- {
- if (!_properties.TryGetValue(master, out var properties))
- {
- properties = ImmutableDictionary<string, IProperty>.Empty;
- }
- var newDict = properties.ToDictionary(x => x.Key, x => x.Value);
- foreach(var prop in toAdd)
- {
- newDict[prop.Name] = prop;
- }
- _properties[master] = newDict.ToImmutableDictionary();
- }
-
- public static void RegisterProperty(IProperty entry)
- {
- var type = entry.ClassType;
- if (type is null) return;
- if (!_properties.TryGetValue(type, out var properties))
- {
- properties = ImmutableDictionary<string, IProperty>.Empty;
- }
- _properties[type] = properties.Add(entry.Name, entry);
- }
- public static void Load(CustomProperty[] customproperties)
- {
- var perType = customproperties.GroupBy(x => x.ClassType);
- foreach(var group in perType)
- {
- if (group.Key is null) continue;
- RegisterProperties(group.Key, group);
- }
- }
- private static ImmutableDictionary<string, IProperty>? CheckProperties(Type type)
- {
- try
- {
- var props = _properties.GetValueOrDefault(type);
- var hasprops = props?.Any(x => x.Value is StandardProperty) == true;
- if (!hasprops && type.IsSubclassOf(typeof(BaseObject)))
- {
- RegisterProperties(type);
- return _properties.GetValueOrDefault(type);
- }
- else
- {
- return props;
- }
- }
- catch (Exception e)
- {
- // This seems to be an intermittent error "Collection has been modified" when checking if the Dictionary has been populated already
- // I've added a .ToArray() to concretise the list, but who knows?
- Logger.Send(LogType.Error,"",$"Error Checking Properties for Type: {type.EntityName()}\n{e.Message}\n{e.StackTrace}");
- return null;
- }
- }
- private static IEnumerable<IProperty> PropertiesInternal(Type type)
- => CheckProperties(type)?.Select(x => x.Value) ?? Enumerable.Empty<IProperty>();
- /// <summary>
- /// Return the standard property list for <paramref name="type"/>; this includes nested properties.
- /// </summary>
- /// <param name="type"></param>
- /// <returns></returns>
- public static IEnumerable<IProperty> Properties(Type type)
- => PropertiesInternal(type).Where(x => !x.IsParent);
- /// <summary>
- /// Return all properties that are defined directly on <paramref name="type"/>, and does not follow sub objects, but rather includes the
- /// sub object property itself.
- /// </summary>
- /// <param name="type"></param>
- /// <returns></returns>
- public static IEnumerable<IProperty> RootProperties(Type type)
- => PropertiesInternal(type).Where(x => x.Parent is null);
- /// <summary>
- /// Return the standard property list for <paramref name="type"/>; this includes nested properties.
- /// </summary>
- /// <param name="type"></param>
- /// <returns></returns>
- public static IEnumerable<IProperty> Properties<T>() => Properties(typeof(T));
-
- public static IProperty? Property(Type type, string name)
- {
- var prop = CheckProperties(type)?.GetValueOrDefault(name);
- // Walk up the inheritance tree, see if an ancestor has this property
- if (prop == null && type.BaseType != null)
- prop = Property(type.BaseType, name);
- return prop;
- }
- public static IProperty? Property<T>(Expression<Func<T, object?>> expression) => Property(typeof(T), CoreUtils.GetFullPropertyName(expression, "."));
- public static void InitializeObject<TObject>(TObject entity) where TObject : BaseObject
- {
- entity.UserProperties.Load(Properties(entity.GetType())
- .Where(x => x is CustomProperty)
- .Select(x => new KeyValuePair<string, object?>(x.Name, DefaultValue(x.PropertyType))));
- }
- }
- }
|