public void TestDeserializationFromAttributeTable()
        {
            IAttributeTable attributeTable       = new AttributeTable();
            AttributeTable  entityAttributeTable = new AttributeTable();
            const string    TestValueString      = "Test";

            entityAttributeTable.SetValue(TestComponent.AttributeTestString, TestValueString);
            EntityConfiguration entityConfiguration = new EntityConfiguration
            {
                BlueprintId   = TestBlueprintId,
                Configuration = entityAttributeTable
            };

            attributeTable.SetValue(TestData.AttributeTestEntity, entityConfiguration);

            TestData testData = InspectorUtils.CreateFromAttributeTable <TestData>(
                this.testGame.EntityManager, InspectorType.GetInspectorType(typeof(TestData)), attributeTable);

            Assert.AreNotEqual(testData.TestEntity, 0);
            Assert.AreNotEqual(testData.TestEntity, -1);

            // Check entity.
            TestComponent testComponent = this.testGame.EntityManager.GetComponent <TestComponent>(testData.TestEntity);

            Assert.NotNull(testComponent);
            Assert.AreEqual(testComponent.TestString, TestValueString);
        }
Example #2
0
        private void OnPropertyControlValueChanged(InspectorPropertyAttribute inspectorProperty, object newValue)
        {
            EntityConfiguration entityConfiguration = (EntityConfiguration)this.Value ?? new EntityConfiguration();

            // Remove value if default value or inherited from blueprint. Otherwise set it.
            object defaultValue = this.GetDefaultValue(inspectorProperty);

            var defaultList = defaultValue as IList;
            var newList     = newValue as IList;

            if (defaultList != null && newList != null && CollectionUtils.ListEqual(defaultList, newList))
            {
                entityConfiguration.Configuration.RemoveValue(inspectorProperty.Name);
            }
            else if (Equals(newValue, defaultValue))
            {
                entityConfiguration.Configuration.RemoveValue(inspectorProperty.Name);
            }
            else
            {
                entityConfiguration.Configuration.SetValue(inspectorProperty.Name, newValue);
            }

            this.OnValueChanged();
        }
 public EntityTypeBuilderTests()
 {
     this.contextOptionsMock = new Mock <IDynamoContextOptions>();
     this.entityConfig       = new EntityConfigurationFake();
     this.builder            = new EntityTypeBuilderFake(
         this.entityConfig, this.contextOptionsMock.Object);
 }
Example #4
0
        public ModelViewConfiguration Insert(string fileUpload, ModelViewConfiguration data, string path, int[] Usuarios)
        {
            string fileName    = data.Url;
            string combinePath = path + fileName;

            System.IO.File.Copy(fileUpload, combinePath, true);
            System.IO.File.Delete(fileUpload);
            var objRepository          = new RepositoryConfiguration();
            var objRepositoryMsj       = new RepositoryReceivers();
            EntityConfiguration config = new EntityConfiguration()
            {
                ConfigurationID = data.ConfigurationID,
                Title           = data.Title,
                Message         = data.Message,
                Url             = GlobalConfiguration.urlRequest + "Content/Notification/" + fileName,
                Status          = true,
                CreateDate      = DateTime.Now,
                ModifyDate      = DateTime.UtcNow
            };

            config = objRepository.Insert(config);
            foreach (var item in Usuarios)
            {
                EntityReceivers receivers = new EntityReceivers()
                {
                    ConfigurationID = config.ConfigurationID,
                    UserID          = item,
                    MessageCreate   = true,
                    CreateDate      = DateTime.Now,
                    ModifyDate      = DateTime.UtcNow
                };
                receivers = objRepositoryMsj.Insert(receivers);
            }
            return(data);
        }
        private Triple<XmlElement, IExtendedPropertyMapper, String> GenerateInheritanceMappingData(
                PersistentClass pc, EntityXmlMappingData xmlMappingData, AuditTableData auditTableData,
                String inheritanceMappingType)
        {
            String extendsEntityName = VerEntCfg.GetAuditEntityName(pc.Superclass.EntityName);
            XmlElement class_mapping = MetadataTools.CreateSubclassEntity(xmlMappingData.MainXmlMapping,
                    inheritanceMappingType, auditTableData, extendsEntityName, pc.DiscriminatorValue);

            // The id and revision type is already mapped in the parent

            // Getting the property mapper of the parent - when mapping properties, they need to be included
            String parentEntityName = pc.Superclass.EntityName;

            EntityConfiguration parentConfiguration = EntitiesConfigurations[parentEntityName];
            if (parentConfiguration == null)
            {
                throw new MappingException("Entity '" + pc.EntityName + "' is audited, but its superclass: '" +
                        parentEntityName + "' is not.");
            }

            IExtendedPropertyMapper parentPropertyMapper = parentConfiguration.PropertyMapper;
            IExtendedPropertyMapper propertyMapper = new SubclassPropertyMapper(new MultiPropertyMapper(), parentPropertyMapper);

            return Triple<XmlElement, IExtendedPropertyMapper, String>.Make<XmlElement, IExtendedPropertyMapper, String>(class_mapping, propertyMapper, parentEntityName);
        }
Example #6
0
        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="metaDataStore"></param>
        /// <param name="mainGenerator">Main generator, giving access to configuration and the basic mapper.</param>
        /// <param name="propertyValue">Value of the collection, as mapped by Hibernate.</param>
        /// <param name="currentMapper">Mapper, to which the appropriate {@link org.hibernate.envers.entities.mapper.PropertyMapper} will be added.</param>
        /// <param name="referencingEntityName">Name of the entity that owns this collection.</param>
        /// <param name="xmlMappingData">In case this collection requires a middle table, additional mapping documents will be created using this object.</param>
        /// <param name="propertyAuditingData">
        /// Property auditing (meta-)data. Among other things, holds the name of the
        /// property that references the collection in the referencing entity, the user data for middle (join)
        /// table and the value of the <code>@MapKey</code> annotation, if there was one.
        /// </param>
        public CollectionMetadataGenerator(IMetaDataStore metaDataStore,
                                           AuditMetadataGenerator mainGenerator,
                                           Mapping.Collection propertyValue,
                                           ICompositeMapperBuilder currentMapper,
                                           string referencingEntityName,
                                           EntityXmlMappingData xmlMappingData,
                                           PropertyAuditingData propertyAuditingData)
        {
            _metaDataStore         = metaDataStore;
            _mainGenerator         = mainGenerator;
            _propertyValue         = propertyValue;
            _currentMapper         = currentMapper;
            _referencingEntityName = referencingEntityName;
            _xmlMappingData        = xmlMappingData;
            _propertyAuditingData  = propertyAuditingData;

            _propertyName = propertyAuditingData.Name;

            _referencingEntityConfiguration = mainGenerator.EntitiesConfigurations[referencingEntityName];
            if (_referencingEntityConfiguration == null)
            {
                throw new MappingException("Unable to read auditing configuration for " + referencingEntityName + "!");
            }

            _referencedEntityName = MappingTools.ReferencedEntityName(propertyValue.Element);
        }
Example #7
0
        public void TestDeinitRemovesChildEntity()
        {
            var              entityManager   = this.testGame.EntityManager;
            const string     TestBlueprintId = "TestBlueprint";
            BlueprintManager blueprintManager;

            this.testGame.BlueprintManager = blueprintManager = new BlueprintManager();
            blueprintManager.AddBlueprint(TestBlueprintId, new Blueprint());

            TestInspectorTypeWithEntityProperty testType = new TestInspectorTypeWithEntityProperty();
            var                 testInspectorType        = InspectorType.GetInspectorType(typeof(TestInspectorTypeWithEntityProperty));
            IAttributeTable     configuration            = new AttributeTable();
            EntityConfiguration childConfiguration       = new EntityConfiguration {
                BlueprintId = TestBlueprintId
            };

            configuration.SetValue(TestInspectorTypeWithEntityProperty.AttributeMember1, childConfiguration);

            // Init.
            InspectorUtils.InitFromAttributeTable(entityManager, testInspectorType, testType, configuration);

            // Check that child entity was created.
            Assert.AreNotEqual(0, testType.EntityMember);

            // Deinit.
            InspectorUtils.Deinit(entityManager, testInspectorType, testType);

            // Check that child entity was removed.
            Assert.IsTrue(entityManager.EntityIsBeingRemoved(testType.EntityMember));
        }
Example #8
0
        public virtual void AddEntityFacetsConfiguration([NotNull] EntityConfiguration entityConfiguration)
        {
            Check.NotNull(entityConfiguration, nameof(entityConfiguration));

            AddEntityKeyConfiguration(entityConfiguration);
            AddTableNameFacetConfiguration(entityConfiguration);
        }
 protected internal EntityTypeBuilder(
     EntityConfiguration <TContext, TEntity> entityConfig,
     IDynamoContextOptions contextOptions)
 {
     this.entityConfig   = entityConfig;
     this.contextOptions = contextOptions;
 }
Example #10
0
        public virtual string WriteCode(
            [NotNull] EntityConfiguration entityConfiguration)
        {
            Check.NotNull(entityConfiguration, nameof(entityConfiguration));

            _entity = entityConfiguration;
            _sb     = new IndentedStringBuilder();

            _sb.AppendLine("using System;");
            _sb.AppendLine("using System.Collections.Generic;");
            if (!_entity.ModelConfiguration.CustomConfiguration.UseFluentApiOnly)
            {
                _sb.AppendLine("using System.ComponentModel.DataAnnotations;");
                _sb.AppendLine("using System.ComponentModel.DataAnnotations.Schema;");
            }

            _sb.AppendLine();
            _sb.AppendLine("namespace " + _entity.ModelConfiguration.Namespace());
            _sb.AppendLine("{");
            using (_sb.Indent())
            {
                AddClass();
            }
            _sb.AppendLine("}");

            return(_sb.ToString());
        }
Example #11
0
        public virtual void AddEntityKeyConfiguration([NotNull] EntityConfiguration entityConfiguration)
        {
            Check.NotNull(entityConfiguration, nameof(entityConfiguration));

            var entityType = (EntityType)entityConfiguration.EntityType;
            var key        = entityType.FindPrimaryKey();

            if (key == null || key.Properties.Count == 0)
            {
                return;
            }

            var conventionKeyProperties =
                _keyDiscoveryConvention.DiscoverKeyProperties(entityType);

            if (conventionKeyProperties != null &&
                Enumerable.SequenceEqual(
                    key.Properties.OrderBy(p => p.Name),
                    conventionKeyProperties.OrderBy(p => p.Name)))
            {
                return;
            }

            entityConfiguration.FacetConfigurations.Add(
                new FacetConfiguration(
                    "Key(e => "
                    + GeneratorModel.Generator.ModelUtilities.GenerateLambdaToKey(key.Properties, "e")
                    + ")"));
        }
Example #12
0
 public void SetConfig()
 {
     EntityConfiguration.GetDefaultEntityMapping <Domain.DataModel.TestModel>()
     .SetTableName(testAppDataContext.DbPrefix + "Tests")
     .SetProperty(test => test.ID, prop => prop.SetPrimaryKey().SetDatabaseGenerated(DatabaseGeneratedOption.Identity))                                                                                             // Call SetProperty once per each property!
     .SetProperty(test => test.Title);
 }
Example #13
0
        public ModelViewConfiguration InsertURLY(ModelViewConfiguration data, int[] Usuarios)
        {
            var objRepository          = new RepositoryConfiguration();
            var objRepositoryMsj       = new RepositoryReceivers();
            EntityConfiguration config = new EntityConfiguration()
            {
                ConfigurationID = data.ConfigurationID,
                Title           = data.Title,
                Message         = data.Message,
                Url             = data.Url,
                Status          = true,
                CreateDate      = DateTime.Now,
                ModifyDate      = DateTime.UtcNow
            };

            config = objRepository.Insert(config);
            foreach (var item in Usuarios)
            {
                EntityReceivers receivers = new EntityReceivers()
                {
                    ConfigurationID = config.ConfigurationID,
                    UserID          = item,
                    MessageCreate   = true,
                    CreateDate      = DateTime.Now,
                    ModifyDate      = DateTime.UtcNow
                };
                receivers = objRepositoryMsj.Insert(receivers);
            }

            return(data);
        }
        private static QueryExpression ParseRelation(EntityConfiguration configuration, Tokenizer tokenizer)
        {
            if (tokenizer.Current == null)
            {
                throw new InvalidOperationException("Invalid expression!");
            }

            // Parse the left side literal in the relation.
            var expression = ParseLiteral(configuration, tokenizer);

            if (tokenizer.Current?.IsRelationalOperator() == true)
            {
                var @operator = tokenizer.Current.GetRelationalOperator();
                tokenizer.MoveNext(); // Consume operator.

                // Parse the right side literal in the relation.
                var right = ParseLiteral(configuration, tokenizer);

                return(new RelationalExpression(
                           expression,
                           right,
                           @operator));
            }

            return(expression);
        }
Example #15
0
 public void SetConfig()
 {
     EntityConfiguration.GetDefaultEntityMapping <Domain.DataModel.RoleModel>()
     .SetTableName(roleAppDataContext.DbPrefix + "Roles")
     .SetProperty(role => role.Id, prop => prop.SetPrimaryKey().SetDatabaseGenerated(DatabaseGeneratedOption.Identity))
     .SetProperty(role => role.Title)
     .SetProperty(role => role.IsActive);
 }
 private EntityConfiguration <T> ContentConfiguration <T>(EntityConfiguration <T> configuration) where T : Content
 {
     configuration.Property(e => e.Title).IsRequired();
     configuration.HasMany(e => e.Comments);
     configuration.HasMany(e => e.Tags).WithMany();
     configuration.HasRequired(e => e.WebSite);
     return(configuration);
 }
Example #17
0
        public EntityConfiguration <T> Entity <T>()
        {
            var configuration = new EntityConfiguration <T>();

            _entityConfigurations[typeof(T)] = configuration;

            return(configuration);
        }
Example #18
0
 /// <summary>
 /// Dispose unmanaged resources and/or set large fields
 /// (managed/unmanaged) to null. This method will be called whether
 /// the <see cref="Disposable.Dispose()"/> method is called by the
 /// finalizer or your code.
 /// </summary>
 protected override void DisposeExtra()
 {
     base.DisposeExtra();
     _storageContext = null;
     _configuration  = null;
     _queryBuilder   = null;
     _cmdBuilder     = null;
     _entityBuilder  = null;
 }
        /// <summary>
        /// Find a list of role names by user id.
        /// </summary>
        /// <param name="userId">Target user id.</param>
        /// <returns>Returns a list of roles if found; otherwise, returns empty list.</returns>
        public IList <string> FindRoleNamesByUserId(TKey userId)
        {
            EntityConfiguration <TUserRole> userRoleCfg     = StorageContext.GetEntityConfiguration <TUserRole>();
            PropertyConfiguration           userIdPropCfg   = userRoleCfg.Property(p => p.UserId);
            PropertyConfiguration           roleNamePropCfg = Configuration.Property(p => p.Name);
            DbCommand command = StorageContext.CreateCommand();

            command.CommandText = String.Format(
                @"SELECT {2} FROM {0} INNER JOIN {1} ON ({0}.{3} = {1}.{4}) WHERE {5} = @{6};",
                QueryBuilder.GetQuotedIdentifier(Configuration.TableName),
                QueryBuilder.GetQuotedIdentifier(userRoleCfg.TableName),
                // Configured field names
                QueryBuilder.GetQuotedIdentifier(roleNamePropCfg.ColumnName),
                QueryBuilder.GetQuotedIdentifier(Configuration.Property(p => p.Id).ColumnName),
                QueryBuilder.GetQuotedIdentifier(userRoleCfg.Property(p => p.RoleId).ColumnName),
                QueryBuilder.GetQuotedIdentifier(userIdPropCfg.ColumnName),
                // Parameter names
                userIdPropCfg.PropertyName);

            DbCommandContext cmdContext = new DbCommandContext(command);

            cmdContext.Parameters[userIdPropCfg.PropertyName].Value = userId;

            DbDataReader  reader   = null;
            List <string> list     = new List <string>();
            string        roleName = null;

            StorageContext.Open();

            try
            {
                reader = cmdContext.ExecuteReader();

                while (reader.Read())
                {
                    roleName = reader.GetSafeString(roleNamePropCfg.ColumnName);

                    list.Add(roleName);
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                cmdContext.Dispose();
                StorageContext.Close();
            }

            return(list);
        }
        private static QueryExpression ParseScope(EntityConfiguration configuration, Tokenizer tokenizer)
        {
            tokenizer.Consume(TokenType.OpeningParenthesis);
            var expression = Parse(configuration, tokenizer);

            tokenizer.Consume(TokenType.ClosingParenthesis);

            return(new ScopeExpression(expression));
        }
Example #21
0
        /// <summary>
        /// Initialize a new instance of the class.
        /// </summary>
        /// <param name="configuration">Entity configuration.</param>
        protected DbQueryBuilder(EntityConfiguration <TEntity> configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("Entity configuration null");
            }

            _configuration = configuration;
        }
        /// <summary>
        /// Initialize a new instance of the class.
        /// </summary>
        /// <param name="configuration">Entity configuration.</param>
        public DbEntityBuilder(EntityConfiguration <TEntity> configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("Entity configuration null");
            }

            _configuration = configuration;
        }
        // Write Code returns generated code for class and you can raplec it with your base class
        public override string WriteCode([NotNull] EntityConfiguration entityConfiguration)
        {
            var classStr   = base.WriteCode(entityConfiguration);
            var defaultStr = "public partial class " + entityConfiguration.EntityType.Name;
            var baseStr    = "public partial class " + entityConfiguration.EntityType.Name + " : EntityBase";

            classStr = classStr.Replace(defaultStr, baseStr);
            return(classStr);
        }
Example #24
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public virtual PropertyConfiguration CreatePropertyConfiguration(
            [NotNull] EntityConfiguration entityConfiguration,
            [NotNull] IProperty property)
        {
            Check.NotNull(entityConfiguration, nameof(entityConfiguration));
            Check.NotNull(property, nameof(property));

            return(new PropertyConfiguration(entityConfiguration, property));
        }
        internal static void SetEntityConfig <TEntity>(Action <IEntityConfiguration <TEntity> > config)
        {
            var entitySettings = new EntityConfiguration <TEntity>();

            config.Invoke(entitySettings);

            var entityConfig = EnsureConfigForEntity <TEntity>();

            entityConfig.IgnoredProperties  = entitySettings.IgnoredProperties;
            entityConfig.OverrideProperties = entitySettings.OverrideProperties;
            entityConfig.FormatProperties   = entitySettings.FormatProperties;
        }
        /// <summary>
        /// Check whether the user belongs to the given role.
        /// </summary>
        /// <param name="userId">Target user id.</param>
        /// <param name="roleName">Target role name.</param>
        /// <returns>Returns true if belongs; otherwise, returns false.</returns>
        public bool IsInRole(TKey userId, string roleName)
        {
            EntityConfiguration <TUserRole> userRoleCfg     = StorageContext.GetEntityConfiguration <TUserRole>();
            PropertyConfiguration           userIdPropCfg   = userRoleCfg.Property(p => p.UserId);
            PropertyConfiguration           roleNamePropCfg = Configuration.Property(p => p.Name);
            DbCommand command = StorageContext.CreateCommand();

            command.CommandText = String.Format(
                @"SELECT {2} FROM {0} INNER JOIN {1} ON ({0}.{2} = {1}.{3}) 
                    WHERE {4} = @{6} AND LOWER({5}) = LOWER(@{7});",
                QueryBuilder.GetQuotedIdentifier(Configuration.TableName),
                QueryBuilder.GetQuotedIdentifier(userRoleCfg.TableName),
                // Configured field names
                QueryBuilder.GetQuotedIdentifier(Configuration.Property(p => p.Id).ColumnName),
                QueryBuilder.GetQuotedIdentifier(userRoleCfg.Property(p => p.RoleId).ColumnName),
                QueryBuilder.GetQuotedIdentifier(userIdPropCfg.ColumnName),
                QueryBuilder.GetQuotedIdentifier(roleNamePropCfg.ColumnName),
                // Parameter names
                userIdPropCfg.PropertyName,
                roleNamePropCfg.PropertyName);

            DbCommandContext cmdContext = new DbCommandContext(command);

            cmdContext.Parameters[userIdPropCfg.PropertyName].Value   = userId;
            cmdContext.Parameters[roleNamePropCfg.PropertyName].Value = roleName;

            DbDataReader reader = null;
            bool         inRole = false;

            StorageContext.Open();

            try
            {
                reader = cmdContext.ExecuteReader();

                inRole = reader.Read();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                StorageContext.Close();
            }

            return(inRole);
        }
        private static QueryExpression ParseLiteral(EntityConfiguration configuration, Tokenizer tokenizer)
        {
            var result = (QueryExpression)null;

            if (tokenizer.Current != null)
            {
                // ReSharper disable once SwitchStatementMissingSomeCases
                switch (tokenizer.Current.Type)
                {
                case TokenType.Integer:
                    result = ParseConstant(tokenizer, value => int.Parse(value, CultureInfo.InvariantCulture));
                    break;

                case TokenType.Decimal:
                    result = ParseConstant(tokenizer, value => decimal.Parse(value, CultureInfo.InvariantCulture));
                    break;

                case TokenType.String:
                    result = ParseConstant(tokenizer, value => value);
                    break;

                case TokenType.True:
                    result = ParseConstant(tokenizer, _ => true);
                    break;

                case TokenType.False:
                    result = ParseConstant(tokenizer, _ => false);
                    break;

                case TokenType.Null:
                    result = ParseConstant(tokenizer, _ => null);
                    break;

                case TokenType.OpeningParenthesis:
                    result = ParseScope(configuration, tokenizer);
                    break;

                case TokenType.Word:
                    result = ParseProperty(configuration, tokenizer);
                    break;

                default:
                    throw new InvalidOperationException($"Could not parse literal expression ({tokenizer.Current.Type}).");
                }
            }

            if (result != null)
            {
                return(result);
            }

            throw new InvalidOperationException("Unexpected end of expression.");
        }
        private static QueryExpression ParseProperty(EntityConfiguration configuration, Tokenizer tokenizer)
        {
            var name = tokenizer.Consume(TokenType.Word).Value;

            var property = configuration.GetProperty(name);

            if (property == null)
            {
                throw new InvalidOperationException("Could not find property.");
            }

            return(new PropertyExpression(property.PropertyInfo));
        }
        public static QueryExpression Parse(EntityConfiguration configuration, string expression)
        {
            if (string.IsNullOrWhiteSpace(expression))
            {
                return(null);
            }

            var tokenizer = new Tokenizer(expression);

            tokenizer.MoveNext();

            return(Parse(configuration, tokenizer));
        }
 public ToOneDelegateSessionImplementor(IAuditReaderImplementor versionsReader,
     System.Type entityClass,
     Object entityId, long revision,
     AuditConfiguration verCfg)
     : base(versionsReader.SessionImplementor)
 {
     this.versionsReader = versionsReader;
     this.entityClass = entityClass;
     this.entityId = entityId;
     this.revision = revision;
     EntitiesConfigurations entCfg = verCfg.EntCfg;
     notVersionedEntityConfiguration = entCfg.GetNotVersionEntityConfiguration(entityClass.FullName);
 }
        /// <summary>
        /// Initialize a new instance of the class.
        /// </summary>
        /// <param name="configuration">Entity configuration.</param>
        protected EntityMap(EntityConfiguration <TEntity> configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("Configuration parameter null");
            }

            _configuration = configuration;
            ToTable(_configuration.TableName);
            MapPrimaryKey();
            MapFields();
            MapRelationships();
        }