public void Apply_RemovesAllPropertiesThatAreNotDataMembers()
        {
            // Arrange
            Mock<Type> clrType = new Mock<Type>();
            clrType.Setup(t => t.GetCustomAttributes(It.IsAny<bool>())).Returns(new[] { new DataContractAttribute() });

            Mock<IStructuralTypeConfiguration> type = new Mock<IStructuralTypeConfiguration>(MockBehavior.Strict);
            type.Setup(t => t.ClrType).Returns(clrType.Object);

            PropertyConfiguration[] mockProperties = new PropertyConfiguration[] 
            { 
                CreateMockProperty(new DataMemberAttribute()),
                CreateMockProperty(new DataMemberAttribute()), 
                CreateMockProperty()
            };
            type.Setup(t => t.Properties).Returns(mockProperties);

            type.Setup(t => t.RemoveProperty(mockProperties[2].PropertyInfo)).Verifiable();

            // Act
            _convention.Apply(type.Object, new Mock<ODataModelBuilder>().Object);

            // Assert
            type.Verify();
        }
Exemplo n.º 2
0
        /// <summary>
        /// Figures out the key properties and marks them as Keys in the EDM model.
        /// </summary>
        /// <param name="entity">The entity type being configured.</param>
        /// <param name="model">The <see cref="ODataModelBuilder"/>.</param>
        public override void Apply(EntityTypeConfiguration entity, ODataConventionModelBuilder model)
        {
            if (entity == null)
            {
                throw Error.ArgumentNull("entity");
            }

            // Suppress the EntityKeyConvention if there is any key in EntityTypeConfiguration.
            if (entity.Keys.Any() || entity.EnumKeys.Any())
            {
                return;
            }

            // Suppress the EntityKeyConvention if base type has any key.
            if (entity.BaseType != null && entity.BaseType.Keys().Any())
            {
                return;
            }

            PropertyConfiguration key = GetKeyProperty(entity);

            if (key != null)
            {
                entity.HasKey(key.PropertyInfo);
            }
        }
Exemplo n.º 3
0
        public override void StartParagraphRendering(PropertyConfiguration textProperty)
        {
            string opt;

            if (PropertyChain.CurrentContextConfiguration != null &&
                PropertyChain.CurrentContextConfiguration.TryGetProperty(MarkdownRenderSetting.MD_REGION, out opt))
            {
                if (opt == MarkdownRenderSetting.MD_REGION_LIST)
                {
                    RenderOut.Append("+ ");
                }
                else if (opt == MarkdownRenderSetting.MD_REGION_LIST_ORDER)
                {
                    RenderOut.Append("1. ");
                }
                else if (opt == MarkdownRenderSetting.MD_REGION_LIST_CB)
                {
                    RenderOut.Append("- [ ] ");
                }
                else if (opt == MarkdownRenderSetting.MD_REGION_QUOTE)
                {
                    RenderOut.Append("> ");
                }
            }
            base.StartParagraphRendering(textProperty);
        }
        public void Apply_RemovesAllPropertiesThatAreNotDataMembers()
        {
            // Arrange
            Mock <Type> clrType = new Mock <Type>();

            clrType.Setup(t => t.GetCustomAttributes(It.IsAny <bool>())).Returns(new[] { new DataContractAttribute() });

            Mock <IStructuralTypeConfiguration> type = new Mock <IStructuralTypeConfiguration>(MockBehavior.Strict);

            type.Setup(t => t.ClrType).Returns(clrType.Object);

            PropertyConfiguration[] mockProperties = new PropertyConfiguration[]
            {
                CreateMockProperty(new DataMemberAttribute()),
                CreateMockProperty(new DataMemberAttribute()),
                CreateMockProperty()
            };
            type.Setup(t => t.Properties).Returns(mockProperties);

            type.Setup(t => t.RemoveProperty(mockProperties[2].PropertyInfo)).Verifiable();

            // Act
            _convention.Apply(type.Object, new Mock <ODataModelBuilder>().Object);

            // Assert
            type.Verify();
        }
        /// <summary>
        /// Set command parameters for each entity in the given entity collection.
        /// </summary>
        /// <param name="setAction">Action that will execute for each entity in the collection.</param>
        /// <param name="idPropertyConfig">Optional property configuration for
        /// entity id property (database generated) that will be populated.</param>
        public void SetParametersForEach <TEntity>(Action <IDbParameterCollection, TEntity> setAction,
                                                   PropertyConfiguration idPropertyConfig = null)
            where TEntity : IEntity
        {
            ThrowIfDisposed();

            _setForEach = new Action <IDbParameterCollection, IEntity>((collection, entity) =>
            {
                setAction(collection, (TEntity)entity);
            });

            // For last inserted id
            if (idPropertyConfig != null)
            {
                if (!idPropertyConfig.IsKey)
                {
                    throw new ArgumentException(
                              "Passed property configuration is not the configuration of a key property");
                }

                _idPropInfo = typeof(TEntity).GetProperty(idPropertyConfig.PropertyName);

                _readLastInsertedId = _command.CommandText.IndexOf("INSERT",
                                                                   StringComparison.OrdinalIgnoreCase) >= 0 &&
                                      idPropertyConfig.IsIntegerKey;
            }
        }
        public void HasOptionalBinding_AddBindindToNavigationSource()
        {
            // Assert
            ODataModelBuilder builder = new ODataModelBuilder();
            var customerType          = builder.EntityType <BindingCustomer>();
            var navigationSource      = builder.EntitySet <BindingCustomer>("Customers");

            StructuralTypeConfiguration addressType = builder.StructuralTypes.FirstOrDefault(c => c.Name == "BindingAddress");

            Assert.Null(addressType);                                                  // Guard
            Assert.Empty(customerType.Properties);                                     // Guard
            Assert.Null(builder.EntitySets.FirstOrDefault(e => e.Name == "Cities_C")); // Guard

            // Act
            new BindingPathConfiguration <BindingCustomer>(builder, customerType, navigationSource.Configuration)
            .HasSinglePath(c => c.Location)
            .HasOptionalBinding(a => a.City, "Cities_C");

            // Assert
            addressType = builder.StructuralTypes.FirstOrDefault(c => c.Name == "BindingAddress");
            Assert.NotNull(addressType);
            PropertyConfiguration citiesProperty = Assert.Single(addressType.Properties);

            Assert.Equal("City", citiesProperty.Name);

            NavigationPropertyConfiguration navigationProperty = Assert.IsType <NavigationPropertyConfiguration>(citiesProperty);

            Assert.Equal(EdmMultiplicity.ZeroOrOne, navigationProperty.Multiplicity);

            var bindings = navigationSource.FindBinding(navigationProperty);
            var binding  = Assert.Single(bindings);

            Assert.Equal("Cities_C", binding.TargetNavigationSource.Name);
            Assert.Equal("Location/City", binding.BindingPath);
        }
Exemplo n.º 7
0
        private static object MapValue(object value, Type valueType, PropertyConfiguration configuration)
        {
            var globalHandler   = PatchEngineCore.Config.GlobalMappingHandler;
            var typeHandler     = PatchEngineCore.Config.GetMappingHandlerForType(valueType);
            var propertyHandler = configuration.MappingHandler;

            if (globalHandler != null)
            {
                var globalHandlerResult = globalHandler(value);
                if (!globalHandlerResult.Skipped)
                {
                    value = globalHandlerResult.Value;
                }
            }

            if (typeHandler != null)
            {
                var typeHandlerResult = typeHandler(value);
                if (!typeHandlerResult.Skipped)
                {
                    value = typeHandlerResult.Value;
                }
            }

            if (propertyHandler != null)
            {
                var propertyHandlerResult = propertyHandler(value);
                if (!propertyHandlerResult.Skipped)
                {
                    value = propertyHandlerResult.Value;
                }
            }

            return(value);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Get delete SQL query.
        /// </summary>
        /// <returns>Returns sql query.</returns>
        public virtual string GetDeleteSql()
        {
            StringBuilder sql         = new StringBuilder("DELETE FROM ");
            StringBuilder whereClause = new StringBuilder("WHERE ");

            ReadOnlyCollection <PropertyConfiguration> keyPropConfigs = _configuration.KeyPropertyConfigurations;
            PropertyConfiguration cfg = null;

            sql.Append(GetQuotedIdentifier(_configuration.TableName) + " ");

            for (int i = 0; i < keyPropConfigs.Count; ++i)
            {
                cfg = keyPropConfigs[i];

                if (i != keyPropConfigs.Count - 1)
                {
                    whereClause.Append(GetQuotedIdentifier(cfg.ColumnName) + " = " + "@" + cfg.PropertyName + " AND ");
                }
                else
                {
                    whereClause.Append(GetQuotedIdentifier(cfg.ColumnName) + " = " + "@" + cfg.PropertyName + ";");
                }
            }

            sql.Append(whereClause);

            return(sql.ToString());
        }
Exemplo n.º 9
0
 public PropertyConfigurator(TabConfigurator parent, string @alias)
 {
     this.parent   = parent;
     Configuration = new PropertyConfiguration(alias);
     parent.Properties.Add(alias, this);
     parent.Configuration.Properties.Add(alias, Configuration);
 }
        public override void AddPropertyFacetsConfiguration([NotNull] PropertyConfiguration propertyConfiguration)
        {
            Check.NotNull(propertyConfiguration, nameof(propertyConfiguration));

            base.AddPropertyFacetsConfiguration(propertyConfiguration);
            AddUseIdentityFacetConfiguration(propertyConfiguration);
        }
Exemplo n.º 11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="QueryableRestrictions"/> class.
 /// </summary>
 /// <param name="propertyConfiguration">The PropertyConfiguration containing queryable restrictions.</param>
 public QueryableRestrictions(PropertyConfiguration propertyConfiguration)
 {
     NonFilterable = propertyConfiguration.NonFilterable;
     Unsortable    = propertyConfiguration.Unsortable;
     NotNavigable  = propertyConfiguration.NotNavigable;
     NotExpandable = propertyConfiguration.NotExpandable;
 }
        public virtual void AddValueGeneratedFacetConfiguration(
            [NotNull] PropertyConfiguration propertyConfiguration)
        {
            Check.NotNull(propertyConfiguration, nameof(propertyConfiguration));

            var valueGenerated = propertyConfiguration.Property.ValueGenerated;

            switch (valueGenerated)
            {
            case ValueGenerated.OnAdd:
                // If this property is the single integer primary key on the EntityType then
                // KeyConvention assumes ValueGeneratedOnAdd() so there is no need to add it.
                if (_keyConvention.ValueGeneratedOnAddProperty(
                        new List <Property> {
                    (Property)propertyConfiguration.Property
                },
                        (EntityType)propertyConfiguration.EntityConfiguration.EntityType) == null)
                {
                    propertyConfiguration.AddFacetConfiguration(
                        new FacetConfiguration("ValueGeneratedOnAdd()"));
                }

                break;

            case ValueGenerated.OnAddOrUpdate:
                propertyConfiguration.AddFacetConfiguration(new FacetConfiguration("ValueGeneratedOnAddOrUpdate()"));
                break;
            }
        }
        // remove the base type properties from the derived types.
        internal void RemoveBaseTypeProperties(StructuralTypeConfiguration derivedStructrualType,
                                               StructuralTypeConfiguration baseStructuralType)
        {
            IEnumerable <StructuralTypeConfiguration> typesToLift = new[] { derivedStructrualType }
            .Concat(this.DerivedTypes(derivedStructrualType));

            foreach (PropertyConfiguration property in baseStructuralType.Properties
                     .Concat(baseStructuralType.DerivedProperties()))
            {
                foreach (StructuralTypeConfiguration structuralType in typesToLift)
                {
                    PropertyConfiguration derivedPropertyToRemove = structuralType.Properties.SingleOrDefault(
                        p => p.PropertyInfo.Name == property.PropertyInfo.Name);
                    if (derivedPropertyToRemove != null)
                    {
                        structuralType.RemoveProperty(derivedPropertyToRemove.PropertyInfo);
                    }
                }
            }

            foreach (PropertyInfo ignoredProperty in baseStructuralType.IgnoredProperties())
            {
                foreach (StructuralTypeConfiguration structuralType in typesToLift)
                {
                    PropertyConfiguration derivedPropertyToRemove = structuralType.Properties.SingleOrDefault(
                        p => p.PropertyInfo.Name == ignoredProperty.Name);
                    if (derivedPropertyToRemove != null)
                    {
                        structuralType.RemoveProperty(derivedPropertyToRemove.PropertyInfo);
                    }
                }
            }
        }
    public IPropertyConfigurationQueryOptions <TContext, TEntity, TProperty> ConfigureProperty <TProperty>(Expression <Func <TEntity, TProperty> > propertyExpression)
    {
        var propertyConfiguration = new PropertyConfiguration((MemberExpression)propertyExpression.Body);

        ((List <IPropertyConfiguration>)_dbSetConfiguration.PropertyConfigurations).Add(propertyConfiguration);

        return(new PropertyConfigurationQueryOptions <TContext, TEntity, TProperty>(this, _dbSetConfiguration, propertyConfiguration));
    }
        public void Ignore_SetToTrue(bool ignoreValue)
        {
            PropertyConfiguration pc = new PropertyConfiguration();

            pc.Ignore(ignoreValue);

            Assert.AreEqual(ignoreValue, pc.IsIgnored);
        }
 private void ReapplyPropertyConvention(PropertyConfiguration property,
                                        StructuralTypeConfiguration edmTypeConfiguration)
 {
     foreach (IEdmPropertyConvention propertyConvention in _conventions.OfType <IEdmPropertyConvention>())
     {
         propertyConvention.Apply(property, edmTypeConfiguration, this);
     }
 }
Exemplo n.º 17
0
 protected PonyTextContext(AbstractTextElement textElement, IProcessorFactory processorFactory)
 {
     this.textElement = textElement;
     ProcessorFactory = processorFactory;
     MacroTable       = new MacroTable();
     ContextProperty  = new PropertyConfiguration();
     Metadata         = new ContextMetadata();
 }
        /// <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);
        }
Exemplo n.º 19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="QueryableRestrictions"/> class.
 /// </summary>
 /// <param name="propertyConfiguration">The PropertyConfiguration containing queryable restrictions.</param>
 public QueryableRestrictions(PropertyConfiguration propertyConfiguration)
 {
     NotFilterable = propertyConfiguration.NotFilterable;
     NotSortable   = propertyConfiguration.NotSortable;
     NotNavigable  = propertyConfiguration.NotNavigable;
     NotExpandable = propertyConfiguration.NotExpandable;
     NotCountable  = propertyConfiguration.NotCountable;
     _autoExpand   = propertyConfiguration.AutoExpand;
 }
        public void HasName_NameAccepted()
        {
            string mappedName        = "test";
            PropertyConfiguration pc = new PropertyConfiguration();

            pc.HasName(mappedName);

            Assert.AreEqual(mappedName, pc.Name);
        }
        private PropertyConfiguration ParsePropertyConfig(XElement propertyElement)
        {
            var property = new PropertyConfiguration();

            property.Name = GetAttributeValue(propertyElement, "name");
            property.Selector = GetAttributeValue(propertyElement, "selector");
            
            return property;
        }
Exemplo n.º 22
0
 /// <summary>
 /// Create the default ABI set.
 /// </summary>
 public AndroidAbis()
 {
     lock (typeof(AndroidAbis)) {
         if (propertyConfiguration == null)
         {
             propertyConfiguration = new PropertyConfiguration();
         }
     }
     abis = new HashSet <string>(Supported);
 }
Exemplo n.º 23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="QueryableRestrictions"/> class.
 /// </summary>
 /// <param name="propertyConfiguration">The PropertyConfiguration containing queryable restrictions.</param>
 public QueryableRestrictions(PropertyConfiguration propertyConfiguration)
 {
     this.NotFilterable = propertyConfiguration.NotFilterable;
     this.NotSortable   = propertyConfiguration.NotSortable;
     this.NotNavigable  = propertyConfiguration.NotNavigable;
     this.NotExpandable = propertyConfiguration.NotExpandable;
     this.NotCountable  = propertyConfiguration.NotCountable;
     this.DisableAutoExpandWhenSelectIsPresent = propertyConfiguration.DisableAutoExpandWhenSelectIsPresent;
     this._autoExpand = propertyConfiguration.AutoExpand;
 }
        public void HasSinglePath_AddBindindPath(bool required, bool contained)
        {
            // Assert
            ODataModelBuilder builder = new ODataModelBuilder();
            var customerType          = builder.EntityType <BindingCustomer>();
            var navigationSource      = builder.EntitySet <BindingCustomer>("Customers");

            StructuralTypeConfiguration addressType = builder.StructuralTypes.FirstOrDefault(c => c.Name == "BindingAddress");

            Assert.Null(addressType);              // Guard
            Assert.Empty(customerType.Properties); // Guard

            // Act
            var binding    = new BindingPathConfiguration <BindingCustomer>(builder, customerType, navigationSource.Configuration);
            var newBinding = binding.HasSinglePath(c => c.Location, required, contained);

            // Assert
            addressType = builder.StructuralTypes.FirstOrDefault(c => c.Name == "BindingAddress");
            Assert.NotNull(addressType);
            PropertyConfiguration locationProperty = Assert.Single(customerType.Properties);

            Assert.Equal("Location", locationProperty.Name);

            if (contained)
            {
                Assert.Equal(EdmTypeKind.Entity, addressType.Kind);
                Assert.Equal(PropertyKind.Navigation, locationProperty.Kind);
                NavigationPropertyConfiguration navigationProperty = Assert.IsType <NavigationPropertyConfiguration>(locationProperty);
                if (required)
                {
                    Assert.Equal(EdmMultiplicity.One, navigationProperty.Multiplicity);
                }
                else
                {
                    Assert.Equal(EdmMultiplicity.ZeroOrOne, navigationProperty.Multiplicity);
                }

                Assert.True(navigationProperty.ContainsTarget);
            }
            else
            {
                Assert.Equal(EdmTypeKind.Complex, addressType.Kind);
                Assert.Equal(PropertyKind.Complex, locationProperty.Kind);
                ComplexPropertyConfiguration complexProperty = Assert.IsType <ComplexPropertyConfiguration>(locationProperty);
                Assert.Equal(!required, complexProperty.OptionalProperty);
                Assert.Equal(typeof(BindingAddress), complexProperty.RelatedClrType);
            }

            // different bindings
            Assert.NotSame(binding, newBinding);
            Assert.Equal("", binding.BindingPath);

            Assert.IsType <BindingPathConfiguration <BindingAddress> >(newBinding);
            Assert.Equal("Location", newBinding.BindingPath);
        }
        public void Convert(Metadata data, PropertyConfiguration configuration)
        {
            if (data == null) throw new ArgumentNullException("data");
            if (configuration == null) throw new ArgumentNullException("configuration");

            Configuration = configuration;
            ConvertToConfiguration(data);
            if (adapter != null)
            {
                adapter.Convert(data, configuration);
            }
        }
Exemplo n.º 26
0
        protected PropertyConfiguration AddOrGetPropertyConfiguration(MemberInfo memberInfo)
        {
            if (this.propertiesMapping.TryGetValue(memberInfo, out var pc))
            {
                return(pc);
            }

            pc = new PropertyConfiguration();
            this.propertiesMapping.Add(memberInfo, pc);

            return(pc);
        }
Exemplo n.º 27
0
        public virtual void AddPropertyFacetsConfiguration([NotNull] PropertyConfiguration propertyConfiguration)
        {
            Check.NotNull(propertyConfiguration, nameof(propertyConfiguration));

            AddRequiredFacetConfiguration(propertyConfiguration);
            AddMaxLengthFacetConfiguration(propertyConfiguration);
            AddStoreGeneratedPatternFacetConfiguration(propertyConfiguration);
            AddColumnNameFacetConfiguration(propertyConfiguration);
            AddColumnTypeFacetConfiguration(propertyConfiguration);
            AddDefaultValueFacetConfiguration(propertyConfiguration);
            AddDefaultExpressionFacetConfiguration(propertyConfiguration);
        }
        /// <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);
        }
        /// <summary>
        /// Find all user claims by user id and the given claim.
        /// </summary>
        /// <param name="userId">Target user id.</param>
        /// <param name="claim">Target claim.</param>
        /// <returns>Returns a list of user claims if found; otherwise, returns empty list.</returns>
        public ICollection <TUserClaim> FindAllByUserId(TKey userId, Claim claim)
        {
            PropertyConfiguration userIdPropCfg     = Configuration.Property(p => p.UserId);
            PropertyConfiguration claimTypePropCfg  = Configuration.Property(p => p.ClaimType);
            PropertyConfiguration claimValuePropCfg = Configuration.Property(p => p.ClaimValue);
            DbCommand             command           = StorageContext.CreateCommand();

            command.CommandText = String.Format(
                @"SELECT * FROM {0} WHERE {1} = @{4} AND {2} = @{5} AND {3} = @{6};",
                QueryBuilder.GetQuotedIdentifier(Configuration.TableName),
                // Configured field names
                QueryBuilder.GetQuotedIdentifier(userIdPropCfg.ColumnName),
                QueryBuilder.GetQuotedIdentifier(claimTypePropCfg.ColumnName),
                QueryBuilder.GetQuotedIdentifier(claimValuePropCfg.ColumnName),
                // Parameter names
                userIdPropCfg.PropertyName,
                claimTypePropCfg.PropertyName,
                claimValuePropCfg.PropertyName);

            DbCommandContext cmdContext = new DbCommandContext(command);

            cmdContext.Parameters[userIdPropCfg.PropertyName].Value     = userId;
            cmdContext.Parameters[claimTypePropCfg.PropertyName].Value  = claim.Type;
            cmdContext.Parameters[claimValuePropCfg.PropertyName].Value = claim.Value;

            DbDataReader             reader = null;
            ICollection <TUserClaim> list   = null;

            StorageContext.Open();

            try
            {
                reader = cmdContext.ExecuteReader();
                list   = EntityBuilder.BuildAll(reader);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

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

            return(list);
        }
Exemplo n.º 30
0
        public SqlGenerator()
        {
            Type t = typeof(T);

            CrudAccessTableNameAttribute atrTableName = t.GetCustomAttribute <CrudAccessTableNameAttribute>(false);     //get the table name attribute for the DTO

            if (atrTableName == null || string.IsNullOrWhiteSpace(atrTableName.Name))                                   //if there is no table name for DTO
            {
                throw new DbAccessException($"There is no CrudAccessTableName attribute set for '{typeof(T).Name}'");   //throw an exception
            }
            //else get the table name
            else
            {
                _TableName = atrTableName.Name;
            }

            //get the property names for this DTO
            PropertyInfo[] props = t.GetProperties();
            //_PropertyNameList = new List<string>();
            _PropertyConfiguration = new List <PropertyConfiguration>();

            foreach (PropertyInfo pi in props)
            {
                CrudAccessKeyAttribute keyAtr = pi.GetCustomAttribute <CrudAccessKeyAttribute>();
                CrudAccessPropertySettingsAttribute settingAtr = pi.GetCustomAttribute <CrudAccessPropertySettingsAttribute>();

                PropertyConfiguration cfg = new PropertyConfiguration();
                cfg.Name = pi.Name;

                if (keyAtr != null)
                {
                    //TODO: create support for multiple (composite) keys?
                    if (_PropertyConfiguration.Where(x => x.isKey).SingleOrDefault() != null)
                    {
                        throw new DbAccessException($"Multiple keys specified on crud model. ");
                    }

                    cfg.isKey  = true;
                    cfg.Insert = keyAtr.Insert;
                    cfg.Update = keyAtr.Update;
                }
                if (settingAtr != null)
                {
                    //settings attribute overrides key attribute (wouldn't usually expect these on the same property!)
                    cfg.Insert = settingAtr.Insert;
                    cfg.Update = settingAtr.Update;
                    cfg.Select = settingAtr.Select;
                    cfg.DoBy   = settingAtr.DoBy;
                }
                _PropertyConfiguration.Add(cfg);
            }
        }
        /// <summary>
        /// Find user login by login information and user id.
        /// </summary>
        /// <param name="userId">Target user.</param>
        /// <param name="loginInfo">User login information.</param>
        /// <returns>Returns the user login if found; otherwise, returns null.</returns>
        public TUserLogin Find(TKey userId, UserLoginInfo loginInfo)
        {
            PropertyConfiguration loginProviderPropCfg = Configuration.Property(p => p.LoginProvider);
            PropertyConfiguration providerKeyPropCfg   = Configuration.Property(p => p.ProviderKey);
            PropertyConfiguration userIdPropCfg        = Configuration.Property(p => p.UserId);
            DbCommand             command = StorageContext.CreateCommand();

            command.CommandText = String.Format(
                @"SELECT * FROM {0} WHERE {1} = @{4} AND {2} = @{5} AND {3} = @{6};",
                QueryBuilder.GetQuotedIdentifier(Configuration.TableName),
                // Configured field names
                QueryBuilder.GetQuotedIdentifier(loginProviderPropCfg.ColumnName),
                QueryBuilder.GetQuotedIdentifier(providerKeyPropCfg.ColumnName),
                QueryBuilder.GetQuotedIdentifier(userIdPropCfg.ColumnName),
                // Parameter names
                loginProviderPropCfg.PropertyName,
                providerKeyPropCfg.PropertyName,
                userIdPropCfg.PropertyName);

            DbCommandContext cmdContext = new DbCommandContext(command);

            cmdContext.Parameters[loginProviderPropCfg.PropertyName].Value = loginInfo.LoginProvider;
            cmdContext.Parameters[providerKeyPropCfg.PropertyName].Value   = loginInfo.ProviderKey;
            cmdContext.Parameters[userIdPropCfg.PropertyName].Value        = userId;

            DbDataReader reader    = null;
            TUserLogin   userLogin = default(TUserLogin);

            StorageContext.Open();

            try
            {
                reader    = cmdContext.ExecuteReader();
                userLogin = EntityBuilder.Build(reader);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

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

            return(userLogin);
        }
Exemplo n.º 32
0
 public override void RenderText(string text, PropertyConfiguration textProperty)
 {
     if (textProperty == null)
     {
         RenderOut.Append(text);
     }
     else
     {
         EnterRenderContext(textProperty);
         renderStrategyChain.TryRenderFromStart(text, this);
         LeaveRenderContext();
     }
 }
Exemplo n.º 33
0
        public static MapBuilder <TSource, TResult> MapField <TSource, TResult>(
            this MapBuilder <TSource, TResult> builder,
            string from)
        {
            var prop = new PropertyConfiguration <TSource, TResult>
            {
                SourcePropertyName = from,
                TargetPropertyName = from
            };

            builder.AddProperty(prop);
            return(builder);
        }
        public ConfigurationAdapter Create(PropertyConfiguration configuration)
        {
            Type type = configuration.GetType();
            do
            {
                if (adapters.ContainsKey(type))
                {
                    return (ConfigurationAdapter) Activator.CreateInstance(adapters[type]);
                }
                type = type.BaseType;
            } while (type != null && type != typeof (object));

            throw new InvalidOperationException("unknown configuration " + configuration.GetType().Name);
        }
Exemplo n.º 35
0
        public static List<ModelConfiguration> GetModelConfigurationData()
        {
            List<ModelConfiguration> dataList = new List<ModelConfiguration>();
            Dictionary<string, PropertyConfiguration> properties = new Dictionary<string, PropertyConfiguration>();


            //Property Configuration
            List<ValidationBase> validators1 = new List<ValidationBase>();
            validators1.Add(new RequiredValidator(new Dictionary<string, string>() { { "Validate", "true" }, { "MessageKey", "LoginInputView_UserName_Required" } }));
            PropertyConfiguration usernameProperty = new PropertyConfiguration("UserName", validators1, accessPolicyCode: "UN_ACCESS_POLICY");

            List<ValidationBase> validators2 = new List<ValidationBase>();
            validators2.Add(new RequiredValidator(new Dictionary<string, string>() { { "Validate", "true" }, { "MessageKey", "LoginInputView_Password_Required" } }));
            PropertyConfiguration passwordProperty = new PropertyConfiguration("Password", validators2, accessPolicyCode: "PWD_ACCESS_POLICY");

            List<ValidationBase> validators3 = new List<ValidationBase>();
            validators3.Add(new RequiredValidator(new Dictionary<string, string>() { { "Validate", "true" }, { "MessageKey", "AddPlayerModel_PostalCode_Required" } }));

            properties.Add(usernameProperty.Key, usernameProperty);
            properties.Add(passwordProperty.Key, passwordProperty);

            
            //Model Property Configuration
            List<IModelPropertyConfiguration> mlist = new List<IModelPropertyConfiguration>();
            mlist.Add(new ModelPropertyConfiguration("UserName", "UserName", "LoginInputView_UserName", properties["UserName"]));
            mlist.Add(new ModelPropertyConfiguration("Password", "Password", "LoginInputView_Password", properties["Password"]));

            ModelConfiguration mConfig = new ModelConfiguration("LoginInputView", mlist);

            dataList.Add(mConfig);

            //**************************************************** Add player Model Configuration ************************************************************************
            List<IModelPropertyConfiguration> playerModelPropertyList = new List<IModelPropertyConfiguration>();

            Dictionary<string, string> adb = new Dictionary<string, string>() { { "ActionName", "process" }, { "ControllerName", "ControlLibrary_PostalCode_Get" }, { "ActionURL", "ControlLibrary_PostalCode_Get/process" } };
            AutoCompleteBehaviourPropertyBag abag = new AutoCompleteBehaviourPropertyBag(adb);
            Dictionary<string, object> bd = new Dictionary<string, object>() { { "AutoCompleteBehaviourPropertyBag", abag } };

            playerModelPropertyList.Add(new ModelPropertyConfiguration("PostalCode", "HomeAddress.PostalCode", "AddPlayerModel_HomeAddress_PostalCode",
                    new PropertyConfiguration("PostalCode", new List<ValidationBase>() {
                                new RequiredValidator(new Dictionary<string, string>() { { "Validate", "true" }, { "MessageKey", "AddPlayerModel_PostalCode_Required" } })
            }, behaviourDtls: bd)));

            playerModelPropertyList.Add(new ModelPropertyConfiguration("AccountNumber", "AccountNumber", "AddPlayerModel_AccountNumber",
                    new PropertyConfiguration("AccountNumber", new List<ValidationBase>() {
                                new RequiredValidator(new Dictionary<string, string>() { { "Validate", "true" }, { "MessageKey", "AddPlayerModel_AccountNumber_Required" } })
            })));

            playerModelPropertyList.Add(new ModelPropertyConfiguration("FirstName", "FirstName", "AddPlayerModel_FirstName",
                    new PropertyConfiguration("FirstName", new List<ValidationBase>() {
                                new RequiredValidator(new Dictionary<string, string>() { { "Validate", "true" }, { "MessageKey", "AddPlayerModel_FirstName_Required" } })
            })));

            playerModelPropertyList.Add(new ModelPropertyConfiguration("LastName", "LastName", "AddPlayerModel_LastName",
                    new PropertyConfiguration("LastName", new List<ValidationBase>() {
                                new RequiredValidator(new Dictionary<string, string>() { { "Validate", "true" }, { "MessageKey", "AddPlayerModel_LastName_Required" } })
            })));

            playerModelPropertyList.Add(new ModelPropertyConfiguration("PhoneNumber", "PhoneNumber", "AddPlayerModel_PhoneNumber",
                    new PropertyConfiguration("PhoneNumber", new List<ValidationBase>() {
                                new RequiredValidator(new Dictionary<string, string>() { { "Validate", "true" }, { "MessageKey", "AddPlayerModel_PhoneNumber_Required" } }),
                                new CustomValidators(new Dictionary<string, string>() { { "Validate", "true" }, { "MessageKey", "AddPlayerModel_PhoneNumber_Invalid" },{"ValidationType","Phone"} })
            })));

            playerModelPropertyList.Add(new ModelPropertyConfiguration("SSN", "SSN", "AddPlayerModel_SSN",
                    new PropertyConfiguration("SSN", new List<ValidationBase>() {
                                new RequiredValidator(new Dictionary<string, string>() { { "Validate", "true" }, { "MessageKey", "AddPlayerModel_SSN_Required" } }),
                                //new SpecialCharValidator(new Dictionary<string, string>() { { "Validate", "true" }, { "MessageKey", "AddPlayerModel_SSN_SpecialCharNotAllowed" },{"Expression",""},{"Restriction","Allow"} })
                                new CustomValidators(new Dictionary<string, string>() { { "Validate", "true" }, { "MessageKey", "AddPlayerModel_SSN_Invalid" },{"ValidationType","SSN"} })
            })));

            ModelConfiguration playerAddConfig = new ModelConfiguration("AddPlayerModel", playerModelPropertyList);
            dataList.Add(playerAddConfig);

            //**************************************************** END of Add player Model Configuration ************************************************************************

            /*Control Library Controls Test Validators*/
            List<ValidationBase> fn_ReqValidator = new List<ValidationBase>();
            fn_ReqValidator.Add(new RequiredValidator(new Dictionary<string, string>() { { "Validate", "true" }, { "MessageKey", "AllControlModel_UserName_Required" } }));
            fn_ReqValidator.Add(new LengthValidator(new Dictionary<string, string>() { { "MinLength", "2" }, { "MaxLength", "18" }, { "Validate", "true" }, { "MessageKey", "AllControlModel_UserName_Length" } }));
            fn_ReqValidator.Add(new SpecialCharValidator(new Dictionary<string, string>() { { "Expression", "#$" }, { "Restriction", RestrictionType.Restrict.ToString() }, { "Validate", "true" }, { "MessageKey", "AllControlModel_UserName_SpecialChar" } }));
            //fn_ReqValidator.Add(new RangeValidator(new Dictionary<string, string>() { { "MinLength", "2" }, { "MaxLength", "5" }, { "Validate", "true" }, { "MessageKey", "AllControlModel_UserName_Range" } }));


            //PropertyConfiguration firstNameProperty = new PropertyConfiguration("FirstName", fn_ReqValidator, accessPolicyCode: "UN_ACCESS_POLICY");

            //PropertyConfiguration firstNameProperty = new PropertyConfiguration("FirstName", fn_ReqValidator, accessPolicyCode: "UN_ACCESS_POLICY",);

            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("ActionURL", @"ControlLibrary_AutoComplete_load");
            AutoCompleteBehaviourPropertyBag autoCompleteBhBag = new AutoCompleteBehaviourPropertyBag(dic);
            Dictionary<string, object> behaviourDtls = new Dictionary<string, object>();
            behaviourDtls.Add("AutoCompleteBehaviourPropertyBag", autoCompleteBhBag);

            /*Masking Property Configuration*/
            Dictionary<string, string> Maskingdic = new Dictionary<string, string>();
            Maskingdic.Add("MaskingChar", "X");
            Maskingdic.Add("MaskingType", MaskingType.Partial.ToString());
            Maskingdic.Add("MaskCharLength", 4.ToString());
            Maskingdic.Add("MaskingPosition", MaskingPosition.Last.ToString());
            MaskingBehaviourPropertyBag maskingBag = new MaskingBehaviourPropertyBag(Maskingdic);
            behaviourDtls.Add("MaskingBehaviourPropertyBag", maskingBag);

            PropertyConfiguration firstNameProperty = new PropertyConfiguration("FirstName", fn_ReqValidator, accessPolicyCode: "FN_ACCESS_POLICY",
                behaviourDtls: behaviourDtls);
            properties.Add(firstNameProperty.Key, firstNameProperty);

            List<IModelPropertyConfiguration> modelList = new List<IModelPropertyConfiguration>();

            modelList.Add(new ModelPropertyConfiguration("FirstName", "FirstName", "AllControlModel_FirstName", properties["FirstName"]));

            ModelConfiguration modelConfig = new ModelConfiguration("AllControlModel", modelList);

            dataList.Add(modelConfig);

            return dataList;

        }
        private IObjectConfiguration ConfigureObject(XmlNode configNode, IContainer container)
        {
            string objectName = configNode.Attributes["name"].Value;
            IObjectConfiguration objectConfig = GetObjectConfiguration(objectName, container);
            objectConfig.Name = objectName;

            if (configNode.Attributes["aop-config"] != null)
            {
                string sectionName = configNode.Attributes["aop-config"].Value;
                IEngine engine = NAspect.Framework.ApplicationContext.ConfigureFromSection(sectionName);
                objectConfig.AopEngine = engine;
            }

            if (configNode.Attributes["type"] != null)
            {
                string objectTypeString = configNode.Attributes["type"].Value;
                Type objectType = ResolveType(objectTypeString);
                objectConfig.Type = objectType;
            }

            if (configNode.Attributes["factory"] != null)
            {
                string factoryName = configNode.Attributes["factory"].Value;
                IFactoryConfiguration factoryConfig = GetFactoryConfiguration(factoryName, container);
                objectConfig.InstanceValue = factoryConfig;
            }

            //done
            if (configNode.Attributes["instance-mode"] != null)
            {
                string instanceModeString = configNode.Attributes["instance-mode"].Value;
                objectConfig.InstanceMode = (InstanceMode) InstanceMode.Parse(typeof (InstanceMode), instanceModeString);
            }

            container.Configuration.AddObjectConfiguration(objectConfig);

            foreach (XmlNode objectNode in configNode)
            {
                #region property

                if (objectNode.Name == "property")
                {
                    PropertyConfiguration propertyConfig = new PropertyConfiguration();
                    propertyConfig.Name = objectNode.Attributes["name"].Value;
                    ConfigureElement(objectNode, propertyConfig, container, null);
                    if (objectNode.Attributes["action"] != null)
                    {
                        string action = objectNode.Attributes["action"].Value;
                        if (action == "Add")
                            propertyConfig.ListAction = ListAction.Add;

                        if (action == "Replace")
                            propertyConfig.ListAction = ListAction.Replace;

                    }

                    objectConfig.PropertyConfigurations.Add(propertyConfig);
                }

                #endregion

                #region Ctor Parameter

                if (objectNode.Name == "ctor-parameter")
                {
                    ParameterConfiguration parameterConfig = new ParameterConfiguration();
                    parameterConfig.Index = Convert.ToInt32(objectNode.Attributes["index"].Value);
                    ConfigureElement(objectNode, parameterConfig, container, null);
                    objectConfig.CtorParameterConfigurations.Add(parameterConfig);
                }

                #endregion
            }
            return objectConfig;
        }