/// <summary>
        /// Throws an <see cref="RequiredDependencyConstaintViolationException"/> if the <paramref name="dependencies"/>
        /// collection contains one or more entities with a <see cref="EntityDependencySummary.CanDelete"/>
        /// property value of <see langword="false"/>.
        /// </summary>
        /// <param name="definitionOfEntityBeingDeleted">
        /// The <see cref="IEntityDefinition.EntityDefinitionCode"/> of the entity attempting to be deleted.
        /// </param>
        /// <param name="dependencies">Collection of dependencies to check.</param>
        public static void ThrowIfCannotDelete(IEntityDefinition definitionOfEntityBeingDeleted, ICollection <EntityDependencySummary> dependencies)
        {
            if (definitionOfEntityBeingDeleted == null)
            {
                throw new ArgumentNullException(nameof(definitionOfEntityBeingDeleted));
            }

            var invalidDependencies = EnumerableHelper
                                      .Enumerate(dependencies)
                                      .Where(d => !d.CanDelete);

            var numInvalidDependencies = invalidDependencies.Count();

            if (numInvalidDependencies > 0)
            {
                var    requiredDependency = invalidDependencies.First();
                string message;

                if (numInvalidDependencies == 1)
                {
                    message = string.Format(MESSAGE_TEMPLATE, definitionOfEntityBeingDeleted.Name.ToLower(), requiredDependency.Entity.EntityDefinitionName.ToLower(), requiredDependency.Entity.RootEntityTitle);
                }
                else
                {
                    var numberOfOtherInvalidEntityies = numInvalidDependencies - 1;
                    var numberText = numberOfOtherInvalidEntityies == 2 ? "one other" : numberOfOtherInvalidEntityies + " other entities";
                    message = string.Format(MESSAGE_TEMPLATE_WITH_COUNT, definitionOfEntityBeingDeleted.Name.ToLower(), requiredDependency.Entity.EntityDefinitionName.ToLower(), requiredDependency.Entity.RootEntityTitle, numberText);
                }

                throw new RequiredDependencyConstaintViolationException(message);
            }
        }
        public void ApplyMapping(IEntityDefinition definition, BsonClassMap classMap)
        {
            //Remove invalid maps for the class
            foreach (var map in classMap.DeclaredMemberMaps.ToArray())
            {
                if (map.MemberInfo is PropertyInfo propertyInfo)
                {
                    var getPropertyBaseDefinition = propertyInfo.GetMethod.GetBaseDefinition();
                    if (getPropertyBaseDefinition.DeclaringType != definition.EntityType)
                    {
                        //Remove any member map that just overrides another member
                        classMap.UnmapMember(map.MemberInfo);
                        continue;
                    }
                }
                else
                {
                    //Removes any member map that isn't for a property
                    classMap.UnmapMember(map.MemberInfo);
                }
            }

            definition.Properties = classMap.DeclaredMemberMaps
                                    .Select(m => new EntityProperty
            {
                EntityType   = definition.EntityType,
                IsKey        = m == classMap.IdMemberMap,
                ElementName  = m.ElementName,
                FullPath     = m.ElementName,
                PropertyType = (m.MemberInfo as PropertyInfo).PropertyType,
                PropertyInfo = (m.MemberInfo as PropertyInfo)
            });
        }
        public void ApplyMapping(IEntityDefinition definition, BsonClassMap classMap)
        {
            definition.Relationships = GetEntityRelationships(definition).ToArray();

            var removeProperties = new HashSet <string>();

            foreach (var relationship in definition.Relationships)
            {
                if (relationship.IsCollection)
                {
                    var memberMap            = classMap.MapMember(relationship.NavigationProperty.PropertyInfo);
                    var serializerType       = typeof(EntityNavigationCollectionSerializer <>).MakeGenericType(relationship.EntityType);
                    var collectionSerializer = Activator.CreateInstance(serializerType, relationship.IdProperty) as IBsonSerializer;
                    memberMap.SetSerializer(collectionSerializer);
                }
                else
                {
                    removeProperties.Add(relationship.NavigationProperty.FullPath);
                    classMap.UnmapMember(relationship.NavigationProperty.PropertyInfo);
                }
            }

            //Remove navigation properties
            definition.Properties = definition.Properties.Where(p => !removeProperties.Contains(p.FullPath)).ToArray();
        }
Ejemplo n.º 4
0
        public static IEnumerable <IEntityProperty> GetAllProperties(this IEntityDefinition definition)
        {
            var localProperties     = definition.Properties;
            var inheritedProperties = definition.GetInheritedProperties();

            return(localProperties.Concat(inheritedProperties));
        }
Ejemplo n.º 5
0
        public static IEntity Create(this IEntityFactory entityFactory, IEntityDefinition definition)
        {
            entityFactory.NotNull(nameof(entityFactory));
            definition.NotNull(nameof(definition));

            return(entityFactory.Create(definition, CancellationToken.None).GetAwaiter().GetResult());
        }
Ejemplo n.º 6
0
        public Task <bool> Delete(IEntityDefinition entityDefinition, object id, CancellationToken ct)
        {
            entityDefinition.NotNull(nameof(entityDefinition));
            id.NotNull(nameof(id));

            return(entityDefinition.DeleteHandler.Execute(new DeleteExecution(entityDefinition, id), ct));
        }
Ejemplo n.º 7
0
        public IQuery CreateQuery(IEntityDefinition entityDefinition)
        {
            entityDefinition.NotNull(nameof(entityDefinition));

            //TODO: Might allow security/audit interception capability later...
            return(_entityRepository.CreateQuery(entityDefinition));
        }
Ejemplo n.º 8
0
        public static IEntity Hydrate(this IEntityFactory entityFactory, IEntityDefinition definition, PropertyBag values)
        {
            entityFactory.NotNull(nameof(entityFactory));
            definition.NotNull(nameof(definition));

            return(entityFactory.Hydrate(definition, values, CancellationToken.None).GetAwaiter().GetResult());
        }
        public void ApplyMapping(IEntityDefinition definition, BsonClassMap classMap)
        {
            var entityType     = definition.EntityType;
            var collectionName = entityType.Name;

            var tableAttribute = entityType.GetCustomAttribute <TableAttribute>();

            if (tableAttribute == null && entityType.IsGenericType && entityType.GetGenericTypeDefinition() == typeof(EntityBucket <,>))
            {
                var groupType = entityType.GetGenericArguments()[0];
                tableAttribute = groupType.GetCustomAttribute <TableAttribute>();
                if (tableAttribute == null)
                {
                    collectionName = groupType.Name;
                }
            }

            if (tableAttribute != null)
            {
                if (string.IsNullOrEmpty(tableAttribute.Schema))
                {
                    collectionName = tableAttribute.Name;
                }
                else
                {
                    collectionName = tableAttribute.Schema + "." + tableAttribute.Name;
                }
            }

            definition.CollectionName = collectionName;
        }
Ejemplo n.º 10
0
        public void ApplyMapping(IEntityDefinition definition, BsonClassMap classMap)
        {
            var entityType = definition.EntityType;

            //Find the first property with the "Key" attribute to use as the Id
            var properties = entityType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            var idProperty = properties.Where(p => p.GetCustomAttribute <KeyAttribute>() != null).FirstOrDefault();

            if (idProperty != null)
            {
                classMap.MapIdMember(idProperty);
            }

            //If there is no Id generator, set a default based on the member type
            if (classMap.IdMemberMap != null && classMap.IdMemberMap.IdGenerator == null)
            {
                var idMemberMap = classMap.IdMemberMap;
                var memberType  = BsonClassMap.GetMemberInfoType(idMemberMap.MemberInfo);
                if (memberType == typeof(string))
                {
                    idMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance);
                }
                else if (memberType == typeof(Guid))
                {
                    idMemberMap.SetIdGenerator(CombGuidGenerator.Instance);
                }
                else if (memberType == typeof(ObjectId))
                {
                    idMemberMap.SetIdGenerator(ObjectIdGenerator.Instance);
                }
            }
        }
Ejemplo n.º 11
0
        public void CreateDiagram()
        {
            Table t = new Table();

            t.Name = manager.GetName();
            IEntityDefinition definition = SystemDefinitionsManager.DefinitionsManager.GetValidationDefinition(EntityTypesDefinition.Table);

            if (!(definition is TableDefinition))
            {
                return;
            }
            TableDefinition      tabledefinition = definition as TableDefinition;
            List <EntityElement> e = manager.GetEntityElements(tabledefinition.TablePropertyTag);

            t.Properties = new System.Collections.ObjectModel.ObservableCollection <Properties>();
            foreach (EntityElement ee in e)
            {
                var  type      = ee.attributes.Where(x => x.Key == tabledefinition.TablePropertyType).First();
                var  name      = ee.attributes.Where(x => x.Key == tabledefinition.TablePropertyName).First();
                var  isprimary = ee.attributes.Where(x => x.Key == tabledefinition.TablePropertyPrimary);
                bool iskey     = (isprimary.Count() > 0 && isprimary.First().Value.ToUpper() == "TRUE");
                if (string.IsNullOrEmpty(name.Value) || string.IsNullOrEmpty(type.Value))
                {
                    continue;
                }
                t.Properties.Add(new Properties()
                {
                    Name = name.Value, Type = type.Value, IsPrimaryKey = iskey
                });
            }
            var m = Structure.Struct.model;

            m.tables.Add(t);
        }
 private static void ValidateDefinitionExists(IEntityDefinition definition, string identifier)
 {
     if (definition == null)
     {
         throw new EntityNotFoundException <IEntityDefinition>($"IEntityDefinition '{identifier}' is not registered, but has been requested.", identifier);
     }
 }
Ejemplo n.º 13
0
        private bool CheckValidCriterion(IEntityDefinition entityDefinition, string propertyName)
        {
            string remaining          = null;
            var    leading            = propertyName.SplitFirst('.', out remaining);
            var    propertyDefinition = entityDefinition.Properties.SafeGet(leading);

            if ((propertyDefinition == null) ||
                ((propertyDefinition.PropertyType.DataTypeType == DataTypeType.Relation) && !remaining.SafeOrdinalEquals(MetaConstants.IdProperty)))
            {
                return(false);
            }

            if (remaining == null)
            {
                return(true);
            }

            var targetDataType = propertyDefinition.PropertyType;
            var indirectTargetEntityDefinition =
                targetDataType.GetTargetValueType(propertyDefinition);
            IEntityDefinition targetEntityDefinition;

            if (indirectTargetEntityDefinition != null)
            {
                targetEntityDefinition = indirectTargetEntityDefinition as IEntityDefinition;
            }
            else
            {
                targetEntityDefinition = targetDataType as IEntityDefinition;
            }
            return(targetEntityDefinition != null && CheckValidCriterion(targetEntityDefinition, remaining));
        }
Ejemplo n.º 14
0
        public void ApplyMapping(IEntityDefinition definition, BsonClassMap classMap)
        {
            var entityType     = definition.EntityType;
            var collectionName = entityType.Name;

            var tableAttribute = entityType.GetCustomAttribute <TableAttribute>();

            if (tableAttribute == null && entityType.IsGenericType && entityType.GetGenericTypeDefinition() == typeof(EntityBucket <,>))
            {
                var groupProperty = entityType.GetProperty("Group", BindingFlags.Public | BindingFlags.Instance);
                tableAttribute = groupProperty.GetCustomAttribute <TableAttribute>();
                if (tableAttribute == null)
                {
                    collectionName = groupProperty.PropertyType.Name;
                }
            }

            if (tableAttribute != null)
            {
                if (string.IsNullOrEmpty(tableAttribute.Schema))
                {
                    collectionName = tableAttribute.Name;
                }
                else
                {
                    collectionName = tableAttribute.Schema + "." + tableAttribute.Name;
                }
            }

            definition.CollectionName = collectionName;
        }
        public void ApplyMapping(IEntityDefinition definition, BsonClassMap classMap)
        {
            var entityType = definition.EntityType;

            //Ignore extra elements when the "IgnoreExtraElementsAttribute" is on the Entity
            var ignoreExtraElements = entityType.GetCustomAttribute <IgnoreExtraElementsAttribute>();

            if (ignoreExtraElements != null)
            {
                classMap.SetIgnoreExtraElements(true);
                classMap.SetIgnoreExtraElementsIsInherited(ignoreExtraElements.IgnoreInherited);
            }
            else
            {
                //If any of the Entity's properties have the "ExtraElementsAttribute", assign that against the BsonClassMap
                var extraElementsProperty = entityType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
                                            .Select(p => new
                {
                    PropertyInfo           = p,
                    ExtraElementsAttribute = p.GetCustomAttribute <ExtraElementsAttribute>()
                }).Where(p => p.ExtraElementsAttribute != null).FirstOrDefault();

                if (extraElementsProperty != null && typeof(IDictionary <string, object>).IsAssignableFrom(extraElementsProperty.PropertyInfo.PropertyType))
                {
                    var memberMap = classMap.DeclaredMemberMaps
                                    .Where(m => m.MemberInfo == extraElementsProperty.PropertyInfo)
                                    .FirstOrDefault();
                    classMap.SetExtraElementsMember(memberMap);
                }
            }
        }
Ejemplo n.º 16
0
 public static IEntityDefinition SetEntityDefinition(IEntityDefinition definition)
 {
     return(EntityDefinitions.AddOrUpdate(definition.EntityType, definition, (entityType, existingValue) =>
     {
         return definition;
     }));
 }
Ejemplo n.º 17
0
        public static IPropertyDefinition Create(
            IEntityDefinition entityDefinition,
            IDataType dataType      = null,
            PropertyBag propertyBag = null)
        {
            entityDefinition.NotNull(nameof(entityDefinition));

            var result = new PropertyDefinition
            {
                EntityDefinition = entityDefinition,
                PropertyType     = dataType,
                PropertyBag      = propertyBag,
                Name             = propertyBag?["name"] as string,
                Description      = propertyBag?["description"] as string,
                DefaultValue     = propertyBag?["default"]
            };

            var validatorsData = propertyBag?["validators"] as PropertyBag[];

            if (validatorsData != null)
            {
                result.ValidatorDefinitions = CreateValidatorDefinitions(result, validatorsData);
            }

            return(result);
        }
        public void ApplyMapping(IEntityDefinition definition, BsonClassMap classMap)
        {
            var entityType = definition.EntityType;

            //Ignore extra elements when the "IgnoreExtraElementsAttribute" is on the Entity
            var ignoreExtraElements = entityType.GetCustomAttribute <IgnoreExtraElementsAttribute>();

            if (ignoreExtraElements != null)
            {
                classMap.SetIgnoreExtraElements(true);
                classMap.SetIgnoreExtraElementsIsInherited(ignoreExtraElements.IgnoreInherited);
            }
            else
            {
                classMap.SetIgnoreExtraElements(false);

                //If any of the Entity's properties have the "ExtraElementsAttribute", assign that against the BsonClassMap

                foreach (var property in definition.Properties)
                {
                    var extraElementsAttribute = property.PropertyInfo.GetCustomAttribute <ExtraElementsAttribute>();
                    if (extraElementsAttribute != null && typeof(IDictionary <string, object>).IsAssignableFrom(property.PropertyType))
                    {
                        foreach (var memberMap in classMap.DeclaredMemberMaps)
                        {
                            if (memberMap.ElementName == property.ElementName)
                            {
                                classMap.SetExtraElementsMember(memberMap);
                                return;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Root constructor
 /// </summary>
 /// <param name="definition">Entity definition that determines identity parameters</param>
 /// <param name="rootItem">Item contained by root</param>
 /// <param name="checkOptions">Options governing how uniqueness is enforced</param>
 protected MutableEntityTreeNode(IEntityDefinition <TId, TName, TItem> definition,
                                 TItem rootItem,
                                 ErrorCheckOptions checkOptions = ErrorCheckOptions.Default)
     : base(definition, rootItem, checkOptions)
 {
     _getName = definition.GetName;
 }
Ejemplo n.º 20
0
        public void ApplyMapping(IEntityDefinition definition, BsonClassMap classMap)
        {
            var entityType = definition.EntityType;
            var properties = entityType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

            foreach (var property in properties)
            {
                var propertyType = property.PropertyType;

                //Maps the property type for handling property nesting
                if (propertyType.IsClass && propertyType != entityType)
                {
                    if (!EntityMapping.IsRegistered(propertyType))
                    {
                        EntityMapping.RegisterType(propertyType);
                    }
                }
                else if (
                    propertyType.IsGenericType && propertyType.GetGenericArguments().Count() == 1 &&
                    (
                        propertyType.GetGenericTypeDefinition() == typeof(IEnumerable <>) ||
                        propertyType.GetInterfaces().Where(i => i.IsGenericType).Any(i => i.GetGenericTypeDefinition() == typeof(IEnumerable <>))
                    )
                    )
                {
                    var genericType = propertyType.GetGenericArguments()[0];
                    if (!EntityMapping.IsRegistered(genericType))
                    {
                        EntityMapping.RegisterType(genericType);
                    }
                }
            }
        }
        public void ApplyMapping(IEntityDefinition definition, BsonClassMap classMap)
        {
            var entityType = definition.EntityType;
            var properties = entityType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

            foreach (var property in properties)
            {
                //Unmap fields with the "NotMappedAttribute"
                var notMappedAttribute = property.GetCustomAttribute <NotMappedAttribute>();
                if (notMappedAttribute != null)
                {
                    classMap.UnmapProperty(property.Name);
                    continue;
                }

                //Remap fields with the "ColumnAttribute"
                var columnAttribute = property.GetCustomAttribute <ColumnAttribute>();
                if (columnAttribute != null)
                {
                    var mappedName = columnAttribute.Name;
                    var memberMap  = classMap.GetMemberMap(property.Name);
                    memberMap?.SetElementName(mappedName);
                }
            }
        }
Ejemplo n.º 22
0
 protected Query(IEntityDefinition entityDefinition)
 {
     EntityDefinition = entityDefinition.NotNull(nameof(entityDefinition));
     Criterions       = new List <ICriterion>();
     Orders           = new List <Order>();
     SubQueries       = new Dictionary <string, IQuery>(StringComparer.OrdinalIgnoreCase);
     Includes         = new HashSet <IPropertyDefinition>();
 }
 public void ApplyMapping(IEntityDefinition definition, BsonClassMap classMap)
 {
     if (!ProviderAdded)
     {
         ProviderAdded = true;
         BsonSerializer.RegisterSerializationProvider(TypeDiscoverySerializationProvider.Instance);
     }
 }
Ejemplo n.º 24
0
        public static Task <IEntity> GetById(this IEntityService entityService, IEntityDefinition entityDefinition, object id, CancellationToken ct)
        {
            entityService.NotNull(nameof(entityService));
            entityDefinition.NotNull(nameof(entityDefinition));
            id.NotNull(nameof(id));

            return(entityService.CreateQuery(entityDefinition).Add(Criterion.IdEq(id)).UniqueResult <IEntity>(ct));
        }
 /// <summary>
 /// Root constructor
 /// </summary>
 /// <param name="definition">Entity definition that determines identity parameters</param>
 /// <param name="rootItem">Item contained by root</param>
 /// <param name="checkOptions">Options governing how uniqueness is enforced</param>
 protected ReadOnlyEntityTreeNode(IEntityDefinition <TId, TItem> definition,
                                  TItem rootItem,
                                  ErrorCheckOptions checkOptions = ErrorCheckOptions.Default)
     : base(definition,
            checkOptions,
            rootItem)
 {
 }
 /// <summary>
 /// Root constructor
 /// </summary>
 /// <param name="definition">Entity definition that determines identity parameters</param>
 /// <param name="setItemName">Function specifying how entity name is set</param>
 /// <param name="rootItem">Item contained by root</param>
 /// <param name="checkOptions">Options governing how uniqueness is enforced</param>
 public NamedMutableEntityTreeNode(IEntityDefinition <TId, string, TItem> definition,
                                   Action <TItem, string> setItemName,
                                   TItem rootItem,
                                   ErrorCheckOptions checkOptions = ErrorCheckOptions.Default)
     : base(definition, rootItem, checkOptions)
 {
     _setItemName = setItemName;
 }
Ejemplo n.º 27
0
 public IPermission GetByEntityAndPermissionType(IEntityDefinition entityDefinition, PermissionType permissionType)
 {
     if (entityDefinition == null || permissionType == null)
     {
         return(null);
     }
     return(GetByEntityAndPermissionType(entityDefinition.EntityDefinitionCode, permissionType.Code));
 }
Ejemplo n.º 28
0
 protected override IEnumerable <IFieldDefinition> EvaluateFields(IEntityDefinition entityDefinition)
 {
     return(_fields.Join(entityDefinition.FieldDefinitions,
                         field => field,
                         definition => definition.Name,
                         (s, definition) => definition,
                         StringComparer.CurrentCultureIgnoreCase));
 }
Ejemplo n.º 29
0
 public DefaultIdPropertyDefinition(IEntityDefinition entityDefinition, IDataType guidDataType)
 {
     Name             = MetaConstants.IdProperty;
     EntityDefinition = entityDefinition;
     PropertyType     = guidDataType;
     DefaultValue     = GuidValueType.NewGuidDefaultValue;
     Description      = $"Id for {entityDefinition}";
 }
Ejemplo n.º 30
0
        public void ApplyMapping(IEntityDefinition definition, BsonClassMap classMap)
        {
            var entityType = definition.EntityType;
            var properties = entityType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

            var definitionProperties = new List <IEntityProperty>();

            foreach (var property in properties)
            {
                if (!property.CanRead || !property.CanWrite)
                {
                    continue;
                }

                //Skip overridden properties
                var getMethod = property.GetMethod;
                if (property.GetMethod.IsVirtual && getMethod.GetBaseDefinition().DeclaringType != entityType)
                {
                    continue;
                }

                //Skip indexer properties (eg. "this[int index]")
                if (property.GetIndexParameters().Length > 0)
                {
                    continue;
                }

                //Skip properties with the "NotMappedAttribute"
                var notMappedAttribute = property.GetCustomAttribute <NotMappedAttribute>();
                if (notMappedAttribute != null)
                {
                    continue;
                }

                //Do the mapping
                var memberMap = classMap.MapMember(property);

                //Set custom element name with the "ColumnAttribute"
                var columnAttribute = property.GetCustomAttribute <ColumnAttribute>();
                if (columnAttribute != null)
                {
                    var mappedName = columnAttribute.Name;
                    memberMap.SetElementName(mappedName);
                }

                definitionProperties.Add(new EntityProperty
                {
                    EntityType   = definition.EntityType,
                    ElementName  = memberMap.ElementName,
                    FullPath     = memberMap.ElementName,
                    PropertyType = property.PropertyType,
                    PropertyInfo = property
                });
            }

            definition.Properties = definitionProperties;
        }