Esempio n. 1
0
        /// <summary>
        /// 通过实体类型获取实体信息
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public EntityInfo GetEntity(Type type)
        {
            EntityInfo entityInfo = null;

            if (!_entityInfos.TryGetValue(type, out entityInfo))
            {
                lock (_entityLocker)
                {
                    entityInfo           = new EntityInfo();
                    entityInfo.TableName = ExpressionUtil.GetEntityTableName(type);
                    if (string.IsNullOrWhiteSpace(entityInfo.TableName))
                    {
                        throw new Exception("实体必须标明TableAttribute");
                    }
                    entityInfo.EntityType = type;

                    var pis = ExpressionReflector.GetProperties(type).Values;
                    foreach (var property in pis)
                    {
                        var foreignKeyAttr = AttributeHelper.GetAttribute <ForeignKeyAttribute>(property);
                        if (foreignKeyAttr != null)
                        {
                            entityInfo.ForeignKeys.Add(property);
                        }
                        entityInfo.Properties.Add(property);
                    }

                    _entityInfos.Add(type, entityInfo);
                }
            }

            return(entityInfo);
        }
Esempio n. 2
0
 protected override Expression ParseRawValue(Expression rawValue)
 {
     return(Expression.Call(
                ExpressionReflector.GetMethodInfo(() => Convert.ToInt32("", null)),
                rawValue,
                Expression.Constant(CultureInfo.InvariantCulture)));
 }
Esempio n. 3
0
        public void TestDelegate()
        {
            var models = new List <Model>();

            for (int i = 0; i < 10000000; i++)
            {
                models.Add(new Model()
                {
                    Id   = 1,
                    Id1  = 1,
                    Name = "1",
                    P1   = DateTime.Now,
                    P2   = DateTime.Now,
                    P3   = 1,
                    P4   = 1,
                    P5   = 1,
                    P6   = 1
                });
            }
            var properties = typeof(Model).GetProperties();

            foreach (var model in models)
            {
                foreach (var property in properties)
                {
                    var getters = ExpressionReflector.GetValue(model, property.Name);
                }
            }
        }
Esempio n. 4
0
        protected override Expression VisitLambda <T>(Expression <T> node)
        {
            if (node.Body is NewExpression)
            {
                //此处一般是在Select方法中new了匿名对象,例如users.Select(x=>new {x.Id})
                return(base.VisitLambda <T>(node));
            }

            //此处一般是在Select方法中直接选择了参数,例如users.Select(x=>x),这种情况下直接把x的所有列转换出来
            var properties = ExpressionReflector.GetProperties(node.Body.Type).Values;

            foreach (var item in properties)
            {
                if (!ExpressionUtil.IsEntityPropertyType(item.PropertyType))
                {
                    continue;
                    ////是否.Net自带的String、DateTime,如果不是则跳过
                    //if (!((item.PropertyType.FullName == "System.String" || item.PropertyType.FullName == "System.DateTime") && item.PropertyType.Assembly.GlobalAssemblyCache))
                    //{
                    //    continue;
                    //}
                    ////是否可空,如果不是则跳过
                    //var type = Nullable.GetUnderlyingType(item.PropertyType);
                    //if (type == null)
                    //{
                    //    continue;
                    //}
                }
                _columnInfos.Add(item.Name, new KeyValuePair <string, string>(_masterTableName, item.Name));
            }
            return(node);
        }
Esempio n. 5
0
        protected override Expression ListToResult(Expression list)
        {
            var method = ExpressionReflector.GetMethodInfo(() => Enumerable.ToArray <object>(null), true)
                         .MakeGenericMethod(ElementType);

            return(Expression.Call(method, list));
        }
Esempio n. 6
0
        /// <summary>
        /// Registers that a writable property or field should be assigned a
        /// specific value as part of specimen post-processing.
        /// </summary>
        /// <typeparam name="TProperty">
        /// The type of the property of field.
        /// </typeparam>
        /// <param name="propertyPicker">
        /// An expression that identifies the property or field that will have
        /// <paramref name="value"/> assigned.
        /// </param>
        /// <param name="value">
        /// The value to assign to the property or field identified by
        /// <paramref name="propertyPicker"/>.
        /// </param>
        /// <returns>
        /// An <see cref="IPostprocessComposer{T}"/> which can be used to
        /// further customize the post-processing of created specimens.
        /// </returns>
        public IPostprocessComposer <T> With <TProperty>(
            Expression <Func <T, TProperty> > propertyPicker, TProperty value)
        {
            ExpressionReflector.VerifyIsNonNestedWritableMemberExpression(propertyPicker);

            var graphWithAutoPropertiesNode   = this.GetGraphWithAutoPropertiesNode();
            var graphWithoutSeedIgnoringRelay = WithoutSeedIgnoringRelay(graphWithAutoPropertiesNode);

            var container = FindContainer(graphWithoutSeedIgnoringRelay);

            var graphWithProperty = graphWithoutSeedIgnoringRelay.ReplaceNodes(
                with: n => n.Compose(
                    new ISpecimenBuilder[]
            {
                new Postprocessor(
                    CompositeSpecimenBuilder.ComposeIfMultiple(n),
                    new BindingCommand <T, TProperty>(propertyPicker, value),
                    CreateSpecification()),
                new SeedIgnoringRelay()
            }),
                when: container.Equals);

            var member = propertyPicker.GetWritableMember().Member;

            return((NodeComposer <T>)ExcludeMemberFromAutoProperties(member, graphWithProperty));
        }
Esempio n. 7
0
        public static IList Map(Type objectType, DataSet ds)
        {
            var list = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(objectType));
            Dictionary <string, Action <object, object> > propertySetters = ExpressionReflector.GetSetters(objectType);
            var       properties = ExpressionReflector.GetProperties(objectType);
            DataTable table      = ds.Tables[0];

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                object local = null;
                if (objectType.IsSealed)
                {
                    var parameterObjects = new List <object>();
                    foreach (DataColumn column in ds.Tables[0].Columns)
                    {
                        var obj = row[column];
                        if (obj == DBNull.Value)
                        {
                            obj = null;
                        }
                        parameterObjects.Add(obj);
                    }
                    local = ExpressionReflector.CreateInstance(objectType, parameterObjects.ToArray());
                }
                else
                {
                    local = ExpressionReflector.CreateInstance(objectType);
                    foreach (DataColumn column in ds.Tables[0].Columns)
                    {
                        object obj2 = row[column];
                        if (obj2 != DBNull.Value)
                        {
                            var property = properties.Get(column.ColumnName);
                            if (property == null)
                            {
                                continue;
                            }
                            Type propertyType   = property.PropertyType;
                            Type underlyingType = Nullable.GetUnderlyingType(propertyType);
                            if (underlyingType == null)
                            {
                                underlyingType = propertyType;
                            }
                            if (underlyingType.IsEnum)
                            {
                                obj2 = Enum.Parse(underlyingType, Convert.ToString(obj2));
                            }
                            else
                            {
                                obj2 = Convert.ChangeType(obj2, underlyingType);
                            }
                            propertySetters.Get(column.ColumnName)(local, obj2);
                        }
                    }
                }
                list.Add(local);
            }
            return(list);
        }
Esempio n. 8
0
 internal override Expression GetDeserializerExpression(ParameterExpression jsonReader, ParameterExpression settings)
 {
     return(Expression.Call(
                ExpressionReflector.GetMethodInfo(() => Enums.Parse <StringComparison>(""), true).MakeGenericMethod(Type),
                Expression.Call(
                    jsonReader,
                    ExpressionReflector.GetMethodInfo((JsonReader r) => r.ReadUnquoted()))));
 }
Esempio n. 9
0
        /// <summary>
        /// Registers that a writable property should not be assigned an
        /// automatic value as part of specimen post-processing.
        /// </summary>
        /// <typeparam name="TProperty">
        /// The type of the property or field to ignore.
        /// </typeparam>
        /// <param name="propertyPicker">
        /// An expression that identifies the property or field to be ignored.
        /// </param>
        /// <returns>
        /// An <see cref="IPostprocessComposer{T}"/> which can be used to
        /// further customize the post-processing of created specimens.
        /// </returns>
        public IPostprocessComposer <T> Without <TProperty>(
            Expression <Func <T, TProperty> > propertyPicker)
        {
            ExpressionReflector.VerifyIsNonNestedWritableMemberExpression(propertyPicker);

            var member = propertyPicker.GetWritableMember().Member;
            var graphWithAutoPropertiesNode = this.GetGraphWithAutoPropertiesNode();

            return((NodeComposer <T>)ExcludeMemberFromAutoProperties(member, graphWithAutoPropertiesNode));
        }
Esempio n. 10
0
        //private static Dictionary<Type, Dictionary<string, Func<object, object>>> _objectGetters = new Dictionary<Type, Dictionary<string, Func<object, object>>>();
        //private static Dictionary<Type, Dictionary<string, Action<object, object[]>>> _objectMethods = new Dictionary<Type, Dictionary<string, Action<object, object[]>>>();
        //private static Dictionary<Type, Dictionary<string, PropertyInfo>> _objectProperties = new Dictionary<Type, Dictionary<string, PropertyInfo>>();
        //private static Dictionary<Type, Dictionary<string, Action<object, object>>> _objectSetters = new Dictionary<Type, Dictionary<string, Action<object, object>>>();
        //private static Type _objectType = typeof(object);


        //public static Dictionary<string, PropertyInfo> GetProperties(Type type)
        //{
        //    if (_objectProperties.ContainsKey(type))
        //    {
        //        return _objectProperties[type];
        //    }
        //    PropertyInfo[] properties = type.GetProperties(BindingFlags.SetProperty | BindingFlags.GetProperty | BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance);
        //    Dictionary<string, PropertyInfo> dictionary = new Dictionary<string, PropertyInfo>();
        //    foreach (PropertyInfo info in properties)
        //    {
        //        dictionary.Add(info.Name, info);
        //    }
        //    _objectProperties.Add(type, dictionary);
        //    return dictionary;
        //}

        //public static Dictionary<string, Func<object, object>> GetPropertyGetters(Type objectType)
        //{
        //    Type key = objectType;
        //    if (_objectGetters.ContainsKey(key))
        //    {
        //        return _objectGetters[key];
        //    }
        //    Dictionary<string, Func<object, object>> dictionary = new Dictionary<string, Func<object, object>>();
        //    foreach (PropertyInfo info in GetProperties(key).Values)
        //    {
        //        ParameterExpression expression = Expression.Parameter(_objectType);
        //        dictionary.Add(info.Name, Expression.Lambda<Func<object, object>>(Expression.Convert(Expression.MakeMemberAccess(Expression.Convert(expression, info.DeclaringType), info), _objectType), new ParameterExpression[] { expression }).Compile());
        //    }
        //    _objectGetters.Add(key, dictionary);
        //    return dictionary;
        //}

        //public static Dictionary<string, Action<object, object>> GetPropertySetters(Type objectType)
        //{
        //    if (_objectSetters.ContainsKey(objectType))
        //    {
        //        return _objectSetters[objectType];
        //    }
        //    Dictionary<string, Action<object, object>> dictionary = new Dictionary<string, Action<object, object>>();
        //    foreach (PropertyInfo info in GetProperties(objectType).Values)
        //    {
        //        ParameterExpression expression = Expression.Parameter(_objectType);
        //        Expression instance = Expression.Convert(expression, objectType);
        //        ParameterExpression expression3 = Expression.Parameter(_objectType);
        //        UnaryExpression expression4 = Expression.Convert(expression3, info.PropertyType);
        //        Action<object, object> action = Expression.Lambda<Action<object, object>>(Expression.Call(instance, info.GetSetMethod(), new Expression[] { expression4 }), new ParameterExpression[] { expression, expression3 }).Compile();
        //        dictionary.Add(info.Name, action);
        //    }
        //    lock (_objectSetters)
        //    {
        //        _objectSetters.Add(objectType, dictionary);
        //    }
        //    return dictionary;
        //}

        public static Dictionary <string, object> GetPropertyValues(object entity)
        {
            Dictionary <string, object> dictionary = new Dictionary <string, object>();
            Dictionary <string, Func <object, object> > propertyGetters = ExpressionReflector.GetGetters(entity.GetType());

            foreach (KeyValuePair <string, Func <object, object> > pair in propertyGetters)
            {
                dictionary.Add(pair.Key, pair.Value(entity));
            }
            return(dictionary);
        }
Esempio n. 11
0
 protected ConditionalExpression MakeSureBlockStartsWith(ParameterExpression jsonReaderParam, char c)
 {
     return(Expression.IfThen(
                Expression.NotEqual(
                    Expression.Call(jsonReaderParam, ExpressionReflector.GetMethodInfo <JsonReader>(r => r.CurrentChar())),
                    Expression.Constant(c)),
                Expression.Throw(
                    Expression.New(
                        ExpressionReflector.GetConstructorInfo(() => new JsonReadException(null, null)),
                        Expression.Constant($"Input is not a valid Json: '{c}' expected."),
                        Expression.Default(typeof(Exception))))));
 }
Esempio n. 12
0
        private Expression CreateParameterLessFactory()
        {
            var constructor = Type.GetConstructor(BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);

            return(constructor != null ?
                   (Expression)Expression.New(constructor) :
                   Expression.Convert(
                       Expression.Call(
                           ExpressionReflector.GetMethodInfo(() => FormatterServices.GetUninitializedObject(null)),
                           Expression.Constant(Type)),
                       Type));
        }
Esempio n. 13
0
        internal override Expression GetDeserializerExpression(ParameterExpression jsonReaderParam, ParameterExpression settingsParam)
        {
            var resultVar = Expression.Variable(typeof(Dictionary <,>).MakeGenericType(KeyType, ValueType), "result");

            return(Expression.Block(
                       new[] { resultVar },
                       MakeSureBlockStartsWith(jsonReaderParam, '{'),
                       Expression.Call(jsonReaderParam, ExpressionReflector.GetMethodInfo <JsonReader>(r => r.ReadNextChar())),
                       Expression.Assign(resultVar, Expression.New(resultVar.Type)),
                       CreateValueLoop(jsonReaderParam, settingsParam, resultVar),
                       DictionaryToResult(resultVar)));
        }
Esempio n. 14
0
 public BuilderFactory CreateSqlBuilderFactory()
 {
     if (!string.IsNullOrWhiteSpace(ConfigManager.SqlBuilder))
     {
         if (_type == null)
         {
             var assInfos = ConfigManager.SqlBuilder.Split(',');
             _type = Assembly.Load(assInfos[1]).GetTypes().FirstOrDefault(x => x.FullName == assInfos[0]);
         }
         return((BuilderFactory)ExpressionReflector.CreateInstance(_type));
     }
     return(new BuilderFactory(DatabaseType));
 }
Esempio n. 15
0
        /// <summary>
        /// Registers that a writable property or field should be assigned an
        /// anonymous value as part of specimen post-processing.
        /// </summary>
        /// <typeparam name="TProperty">
        /// The type of the property of field.
        /// </typeparam>
        /// <param name="propertyPicker">
        /// An expression that identifies the property or field that will
        /// should have a value
        /// assigned.
        /// </param>
        /// <returns>
        /// An <see cref="IPostprocessComposer{T}"/> which can be used to
        /// further customize the post-processing of created specimens.
        /// </returns>
        public IPostprocessComposer <T> With <TProperty>(
            Expression <Func <T, TProperty> > propertyPicker)
        {
            ExpressionReflector.VerifyIsNonNestedWritableMemberExpression(propertyPicker);

            var targetToDecorate = this.FindFirstNode(n => n is NoSpecimenOutputGuard);

            return((NodeComposer <T>) this.ReplaceNodes(
                       with: n => new Postprocessor(
                           n,
                           new BindingCommand <T, TProperty>(propertyPicker),
                           CreateSpecification()),
                       when: targetToDecorate.Equals));
        }
Esempio n. 16
0
        public static void Map <TSource, TTarget>(TSource source, TTarget target)
        {
            Type objectType = typeof(TSource);
            Type type2      = typeof(TTarget);
            Dictionary <string, Func <object, object> >   propertyGetters = ExpressionReflector.GetGetters(objectType);
            Dictionary <string, Action <object, object> > propertySetters = ExpressionReflector.GetSetters(type2);

            foreach (string str in propertyGetters.Keys)
            {
                if (propertySetters.ContainsKey(str))
                {
                    propertySetters[str](target, propertyGetters[str](source));
                }
            }
        }
Esempio n. 17
0
        protected Expression ManageEndOfBlockOrNextElement(ParameterExpression jsonReaderVar, LabelTarget breakTarget, LabelTarget continueTarget, char endOfBlock)
        {
            var nextCharVar = Expression.Variable(typeof(char), "nextChar");

            return(Expression.Block(
                       new[] { nextCharVar },
                       Expression.Assign(nextCharVar, Expression.Call(jsonReaderVar, nameof(JsonReader.CurrentChar), Type.EmptyTypes)),
                       Expression.Call(jsonReaderVar, ExpressionReflector.GetMethodInfo <JsonReader>(r => r.ReadNextChar())),
                       Expression.IfThen(
                           Expression.Equal(nextCharVar, Expression.Constant(',')),
                           Expression.Goto(continueTarget)),
                       Expression.IfThen(
                           Expression.Equal(nextCharVar, Expression.Constant(endOfBlock)),
                           Expression.Goto(breakTarget)),
                       Expression.Call(
                           jsonReaderVar,
                           ExpressionReflector.GetMethodInfo <JsonReader>(r => r.ThrowError("")),
                           Expression.Constant("Input is not a valid Json: ',' or '}' expected at position {0}."))));
        }
Esempio n. 18
0
        private BlockExpression GetMemberExpressionLoopBlock(ParameterExpression jsonReaderParam, ParameterExpression jsonReaderVar, ParameterExpression resultVar, ParameterExpression memberNameVar, ParameterExpression comparerVar, ParameterExpression settingsParam, LabelTarget breakTarget, LabelTarget continueTarget)
        {
            var expressions = new List <Expression>();

            expressions.Add(Expression.Assign(
                                memberNameVar,
                                Expression.Call(
                                    jsonReaderParam,
                                    ExpressionReflector.GetMethodInfo <JsonReader>(r => r.ReadMemberName()))));
            expressions.Add(Expression.Call(jsonReaderVar, nameof(JsonReader.ReadAssignment), Type.EmptyTypes));
            var properties = Type.GetProperties().Where(p => p.GetSetMethod(true) != null);

            using (var enumerator = properties.GetEnumerator())
            {
                var updates = GenerateMemberSetters(jsonReaderParam, resultVar, memberNameVar, comparerVar, settingsParam, enumerator);
                expressions.Add(updates);
            }
            expressions.Add(ManageEndOfBlockOrNextElement(jsonReaderVar, breakTarget, continueTarget, '}'));
            return(Expression.Block(expressions));
        }
Esempio n. 19
0
        internal override Expression GetDeserializerExpression(ParameterExpression jsonReader, ParameterExpression settings)
        {
            var rawValue = GetRawStringValue(jsonReader);

            if (!Type.IsGenericType || Type.GetGenericTypeDefinition() != typeof(Nullable <>))
            {
                return(ParseRawValue(rawValue));
            }
            else
            {
                var stringValue = Expression.Variable(typeof(string));
                return(Expression.Block(
                           new[] { stringValue },
                           Expression.Assign(stringValue, rawValue),
                           Expression.Condition(
                               Expression.Call(
                                   ExpressionReflector.GetMethodInfo(() => string.IsNullOrWhiteSpace("")),
                                   stringValue),
                               Expression.Default(Type),
                               Expression.Convert(ParseRawValue(stringValue), Type))));
            }
        }
Esempio n. 20
0
        //public static void Invoke(object entity, string methodName, params object[] args)
        //{
        //    Type key = entity.GetType();
        //    Action<object, object[]> action = null;
        //    if (_objectMethods.ContainsKey(key))
        //    {
        //        Dictionary<string, Action<object, object[]>> dictionary = _objectMethods[key];
        //        if (dictionary.ContainsKey(methodName))
        //        {
        //            action = dictionary[methodName];
        //        }
        //    }
        //    else
        //    {
        //        Dictionary<string, Action<object, object[]>> dictionary2 = new Dictionary<string, Action<object, object[]>>();
        //        _objectMethods.Add(key, dictionary2);
        //    }
        //    if (action == null)
        //    {
        //        ParameterExpression expression = Expression.Parameter(_objectType);
        //        UnaryExpression expression2 = Expression.Convert(expression, key);
        //        ParameterExpression array = Expression.Parameter(typeof(object[]));
        //        List<Expression> list = new List<Expression>();
        //        MethodInfo method = key.GetMethod(methodName);
        //        ParameterInfo[] parameters = method.GetParameters();
        //        for (int i = 0; i < parameters.Length; i++)
        //        {
        //            ParameterInfo info2 = parameters[i];
        //            UnaryExpression item = Expression.Convert(Expression.ArrayIndex(array, Expression.Constant(i)), parameters[i].ParameterType);
        //            list.Add(item);
        //        }
        //        Expression instance = method.IsStatic ? null : Expression.Convert(expression, method.ReflectedType);
        //        action = Expression.Lambda<Action<object, object[]>>(Expression.Call(instance, method, list.ToArray()), new ParameterExpression[] { expression, array }).Compile();
        //        _objectMethods[key].Add(methodName, action);
        //    }
        //    action(entity, args);
        //}

        public static List <TObject> Map <TObject>(DataSet ds) where TObject : class, new()
        {
            List <TObject> list       = new List <TObject>();
            Type           objectType = typeof(TObject);
            Dictionary <string, Action <object, object> > propertySetters = ExpressionReflector.GetSetters(objectType);
            var       properties = ExpressionReflector.GetProperties(objectType);
            DataTable table      = ds.Tables[0];

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                TObject local = Activator.CreateInstance <TObject>();
                foreach (string str in propertySetters.Keys)
                {
                    object obj2 = row[str];
                    if (obj2 != DBNull.Value)
                    {
                        Type propertyType   = properties[str].PropertyType;
                        Type underlyingType = Nullable.GetUnderlyingType(propertyType);
                        if (underlyingType == null)
                        {
                            underlyingType = propertyType;
                        }
                        if (underlyingType.IsEnum)
                        {
                            obj2 = Enum.Parse(underlyingType, Convert.ToString(obj2));
                        }
                        else
                        {
                            obj2 = Convert.ChangeType(obj2, underlyingType);
                        }
                        propertySetters[str](local, obj2);
                    }
                }
                list.Add(local);
            }
            return(list);
        }
Esempio n. 21
0
 private static Expression GenerateMemberSetters(ParameterExpression jsonReaderParam, ParameterExpression resultVar, ParameterExpression memberNameVar, ParameterExpression comparerVar, ParameterExpression settingsParam, IEnumerator <PropertyInfo> enumerator)
 {
     if (enumerator.MoveNext())
     {
         var p      = enumerator.Current;
         var setter = p.GetSetMethod(true);
         return(Expression.IfThenElse(
                    Expression.Call(
                        comparerVar,
                        ExpressionReflector.GetMethodInfo <IEqualityComparer <StringChunk> >(c => c.Equals(default(StringChunk), default(StringChunk))),
                        memberNameVar,
                        Expression.Constant(new StringChunk(p.Name))),
                    Expression.Call(
                        resultVar,
                        setter,
                        GetMemberFactory(jsonReaderParam, settingsParam, p)),
                    GenerateMemberSetters(jsonReaderParam, resultVar, memberNameVar, comparerVar, settingsParam, enumerator)));
     }
     else
     {
         // TODO
         return(Expression.Default(typeof(void)));
     }
 }
Esempio n. 22
0
        internal virtual Expression GetDeserializerExpression(ParameterExpression jsonReaderParam, ParameterExpression settingsParam)
        {
            var resultVar     = Expression.Variable(Type, "result");
            var memberNameVar = Expression.Variable(typeof(StringChunk), "memberName");
            var comparerVar   = Expression.Variable(typeof(IEqualityComparer <StringChunk>), "comparer");

            var breakLabel    = Expression.Label("break");
            var continueLabel = Expression.Label("continue");

            return(Expression.Block(
                       new[] { resultVar, memberNameVar, comparerVar },
                       MakeSureBlockStartsWith(jsonReaderParam, '{'),
                       Expression.Call(jsonReaderParam, ExpressionReflector.GetMethodInfo <JsonReader>(r => r.ReadNextChar())),
                       Expression.Assign(resultVar, CreateParameterLessFactory()),
                       Expression.Assign(comparerVar, Expression.Property(settingsParam, ExpressionReflector.GetPropertyInfo((JsonSettings s) => s.Comparer))),
                       new WhileExpression(
                           Expression.Equal(
                               Expression.Call(jsonReaderParam, nameof(JsonReader.CurrentChar), Type.EmptyTypes),
                               Expression.Constant('"')),
                           GetMemberExpressionLoopBlock(jsonReaderParam, jsonReaderParam, resultVar, memberNameVar, comparerVar, settingsParam, breakLabel, continueLabel),
                           breakLabel,
                           continueLabel),
                       resultVar));
        }
Esempio n. 23
0
        int IEntityOperator.InsertEntities(ArrayList list)
        {
            if (list.Count <= 0)
            {
                return(0);
            }
            var  type           = list[0].GetType();
            var  table          = TableInfoManager.GetTable(type);
            var  columns        = table.Columns;
            var  keyColumn      = table.Columns.FirstOrDefault(x => x.Value.IsKey).Value;
            var  count          = 0;
            var  maxIndex       = 0;
            bool autoIncreament = keyColumn != null && keyColumn.IsAutoIncreament;
            //SqlExecutor executor = null;
            var getters = ExpressionReflector.GetGetters(type);
            var setters = ExpressionReflector.GetSetters(type);
            Action <object, object> keySetter = null;

            if (keyColumn != null)
            {
                keySetter = setters.Get(keyColumn.PropertyInfo.Name);
            }
            if (!autoIncreament)
            {
                var obj = _sqlExecutor.ExecuteScalar(string.Format("select max(Count) from {0} where Name='{1}'", ConfigManager.SequenceTable, table.Name), new Dictionary <string, object>());
                if (obj == DBNull.Value)
                {
                    _sqlExecutor.ExecuteNonQuery(string.Format("insert into {0}(Name,Count) values('{1}',{2})", ConfigManager.SequenceTable, table.Name, 0), new Dictionary <string, object>());
                }
                else
                {
                    maxIndex = Convert.ToInt32(obj);
                }
            }
            #region 使用Insert语句插入
            int page, limit = 10;
            page = (int)Math.Ceiling(list.Count / (double)limit);
            int pageIndex   = 1;
            var insertStart = "insert into {0}({1}) values{2}";
            var tableName   = string.Empty;
            if (!string.IsNullOrWhiteSpace(table.DataBase))
            {
                tableName = string.Format("[{0}].", table.DataBase);
            }
            tableName = string.Format("[{0}]", table.Name);
            var fields = new List <string>();
            var autoincreamentColumn = string.Empty;
            foreach (var item in table.Columns.Values)
            {
                if (item.IsAutoIncreament)
                {
                    autoincreamentColumn = item.Name;
                    continue;
                }
                fields.Add(item.Name);
            }
            while (pageIndex <= page)
            {
                var       start    = (pageIndex - 1) * limit;
                ArrayList entities = null;
                if (start + limit > list.Count)
                {
                    entities = list.GetRange(start, list.Count - start);
                }
                else
                {
                    entities = list.GetRange(start, limit);
                }
                var values        = new List <string>();
                var index         = 0;
                var sqlParameters = new Dictionary <string, object>();
                foreach (var entity in entities)
                {
                    var value = new List <string>();
                    if (!autoIncreament && keySetter != null)
                    {
                        keySetter(entity, ++maxIndex);
                    }
                    foreach (var key in getters.Keys)
                    {
                        if (autoincreamentColumn == key)
                        {
                            continue;
                        }
                        value.Add(string.Format("@{0}{1}", key, index));
                        var valueParam = getters.Get(key)(entity);
                        var dateValue  = valueParam as DateTime?;
                        if (dateValue != null)
                        {
                            if (dateValue.Value.Date == dateValue.Value)
                            {
                                valueParam = dateValue.Value.ToString("yyyy-MM-dd");
                            }
                            else
                            {
                                valueParam = dateValue.Value.ToString("yyyy-MM-dd HH:mm:ss");
                            }
                        }
                        sqlParameters.Add(key + index, valueParam);
                    }
                    index++;
                    values.Add(string.Format("({0})", string.Join(",", value)));
                }
                insertStart = string.Format(insertStart, tableName, string.Join(",", fields), string.Join(",", values));
                count      += _sqlExecutor.ExecuteNonQuery(insertStart, sqlParameters);
                pageIndex++;
            }

            #endregion
            if (!autoIncreament)
            {
                _sqlExecutor.ExecuteNonQuery(string.Format("update {0} set [Count]={1} where Name='{2}'", ConfigManager.SequenceTable, maxIndex, table.Name), new Dictionary <string, object>());
            }
            return(count);
        }
Esempio n. 24
0
        public EntityResult <TModel> GetModelFromPost <TModel>() where TModel : class, new()
        {
            Type objectType              = typeof(TModel);
            var  propertySetters         = ExpressionReflector.GetSetters(objectType);
            EntityResult <TModel> result = new EntityResult <TModel>();
            var values = ExpressionReflector.GetProperties(objectType);
            NameValueCollection form = HttpContext.Current.Request.Form;
            TModel local             = Activator.CreateInstance <TModel>();

            foreach (PropertyInfo info in values.Values)
            {
                object obj2                      = null;
                string str                       = info.Name.ToLower();
                Type   underlyingType            = Nullable.GetUnderlyingType(info.PropertyType);
                ValidationAttribute[] attributes = AttributeHelper.GetAttributes <ValidationAttribute>(info);
                if (form.AllKeys.Contains <string>(str, StringComparer.InvariantCultureIgnoreCase))
                {
                    string str2 = form[str];
                    try
                    {
                        if (underlyingType != null)
                        {
                            obj2 = Convert.ChangeType(str2, underlyingType);
                        }
                        else
                        {
                            obj2 = Convert.ChangeType(str2, info.PropertyType);
                        }
                    }
                    catch (FormatException)
                    {
                    }
                }
                else if (underlyingType == null)
                {
                    //不是可空类型,必须要有一个值,所以应该提示一个错误
                    var requiredAttr = attributes.FirstOrDefault(x => x is RequiredAttribute);
                    if (requiredAttr == null || string.IsNullOrWhiteSpace(requiredAttr.ErrorMessage))
                    {
                        result.Message = "表单项 " + info.Name + " 验证失败";
                    }
                    else
                    {
                        result.Message = requiredAttr.ErrorMessage;
                    }
                    return(result);
                }
                foreach (ValidationAttribute attribute in attributes)
                {
                    if (!((attribute == null) || attribute.IsValid(obj2)))
                    {
                        result.Message = string.IsNullOrEmpty(attribute.ErrorMessage) ? ("表单项 " + info.Name + " 验证失败") : attribute.ErrorMessage;
                        return(result);
                    }
                }
                if ((obj2 == null) && (underlyingType == null))
                {
                    try
                    {
                        obj2 = Activator.CreateInstance(info.PropertyType);
                    }
                    catch (MissingMethodException)
                    {
                        obj2 = null;
                    }
                }
                propertySetters[info.Name](local, obj2);
            }
            result.Model   = local;
            result.Success = true;
            return(result);
        }
Esempio n. 25
0
        /// <summary>
        /// 初始化表格的列
        /// </summary>
        /// <param name="gridView">要初始化的DataGridView</param>
        /// <param name="autoSizeMode">行模式</param>
        /// <param name="dataSource">数据源</param>
        public static void InitColumns(DataGridView gridView, DataGridViewAutoSizeColumnsMode autoSizeMode = DataGridViewAutoSizeColumnsMode.Fill)
        {
            gridView.ColumnHeadersDefaultCellStyle.WrapMode = DataGridViewTriState.False;
            var value = gridView.DataSource;

            gridView.AutoSizeColumnsMode   = autoSizeMode;
            gridView.EditMode              = DataGridViewEditMode.EditProgrammatically;
            gridView.SelectionMode         = DataGridViewSelectionMode.FullRowSelect;
            gridView.AllowUserToAddRows    = false;
            gridView.AllowUserToDeleteRows = false;
            if (!(value is IList))
            {
                return;
            }
            var type = value.GetType().GetGenericArguments().FirstOrDefault();

            if (type != null)
            {
                var pis         = type.GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(x => ExpressionReflector.IsEntityPropertyType(x.PropertyType));
                var displayType = typeof(DataGridColumnAttribute);
                foreach (var item in pis)
                {
                    var attrs = item.GetCustomAttributes(displayType, false);
                    if (attrs.Length <= 0)
                    {
                        continue;
                    }
                    var dn = attrs[0] as DataGridColumnAttribute;
                    DataGridViewColumn column;
                    if (gridView.AutoGenerateColumns)
                    {
                        column = gridView.Columns[item.Name];
                        if (column == null)
                        {
                            continue;
                        }
                        if (dn == null)
                        {
                            continue;
                        }
                        column.HeaderText = dn.DisplayName;
                        column.Visible    = dn.Visible;
                        if (dn.Width <= 0 || dn.Width == -1)
                        {
                            continue;
                        }
                        try
                        {
                            column.Width = dn.Width;
                        }
                        catch
                        {
                        }
                    }
                    else
                    {
                        column            = new DataGridViewTextBoxColumn();
                        column.HeaderText = dn.DisplayName;
                        column.Visible    = dn.Visible;
                        column.Width      = dn.Width;
                        gridView.Columns.Add(column);
                    }
                }
            }
        }
Esempio n. 26
0
 /// <summary>
 /// 是否是实体成员
 /// </summary>
 /// <param name="memberInfo"></param>
 /// <returns></returns>
 public static bool IsEntityMember(MemberInfo memberInfo)
 {
     return(!ExpressionReflector.IsEntityPropertyType(GetMemberType(memberInfo)));
 }
Esempio n. 27
0
 /// <summary>
 /// 该类型是否可以作为实体属性的类型
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 internal static bool IsEntityPropertyType(Type type)
 {
     return(ExpressionReflector.IsEntityPropertyType(type));
 }
Esempio n. 28
0
        public int SaveChanges()
        {
            Dictionary <string, object> dbSets;

            if (!_dbSets.TryGetValue(_dataContextType, out dbSets))
            {
                throw new Exception("初始有问题");
            }
            var provider = ProviderFactory.CreateProvider(ConfigManager.DataBaseType);
            var count    = 0;

            using (var scope = new TransactionScope())
            {
                var op = provider.CreateEntityOperator();
                foreach (IEntityOperator dbSet in dbSets.Values)
                {
                    var list  = dbSet.GetAdding();
                    var total = op.InsertEntities(list);
                    if (total != list.Count)
                    {
                        throw new Exception("批量插入失败");
                    }
                    count += total;
                    var editings   = dbSet.GetEditing();
                    var entityType = dbSet.GetEntityType();
                    var table      = TableInfoManager.GetTable(entityType);
                    var keyColumn  = table.Columns.FirstOrDefault(x => x.Value.IsKey).Value;
                    if (keyColumn == null)
                    {
                        throw new InvalidOperationException("实体" + entityType.FullName + "不存在主键,无法更新");
                    }
                    var getters   = ExpressionReflector.GetGetters(entityType);
                    var keyGetter = getters.Get(keyColumn.PropertyInfo.Name);
                    if (keyGetter == null)
                    {
                        throw new InvalidOperationException("keyGetter为null");
                    }
                    foreach (var editing in editings)
                    {
                        var iGetUpdatedValue = editing as IGetUpdatedValues;
                        if (iGetUpdatedValue == null)
                        {
                            continue;
                        }
                        var values = iGetUpdatedValue.GetUpdatedValues();
                        if (values.Count <= 0)
                        {
                            continue;
                        }
                        if (values.Get(keyColumn.PropertyInfo.Name) != null)
                        {
                            throw new InvalidOperationException("不允许更新主键");
                        }
                        var keyValue = keyGetter(editing);
                        values.Add(keyColumn.Name, keyValue);
                        op.UpdateValues(keyColumn, table, values);
                    }

                    var removings = dbSet.GetRemoving();
                    var ids       = new List <int>();
                    foreach (var removing in removings)
                    {
                        var kv = keyGetter(removing);
                        if (kv == null)
                        {
                            throw new InvalidOperationException("删除时主键必须有值");
                        }
                        ids.Add(Convert.ToInt32(kv));
                    }
                    if (ids.Any())
                    {
                        op.Delete(keyColumn, table, ids.ToArray());
                    }
                }
                scope.Complete();
                foreach (IEntityOperator item in dbSets.Values)
                {
                    item.ClearAdding();
                    item.ClearEditing();
                    item.ClearRemoving();
                }
            }
            return(count);
        }
        protected override Expression VisitBinary(BinaryExpression node)
        {
            string left, right, op, condition;
            Match  match;

            Visit(node.Left);
            bool singleBool = false;

            if (node.Left.NodeType == ExpressionType.MemberAccess)
            {
                var leftExp = node.Left as MemberExpression;
                if (ExpressionReflector.GetNullableOrSelfType(leftExp.Type).FullName == "System.Boolean" && leftExp.Type.Assembly.GlobalAssemblyCache)
                {
                    //x.IsEnabled这种情况
                    if (node.Right.NodeType == ExpressionType.Constant)
                    {
                        //x.IsEnabled=true
                    }
                    else if (_conditionStack.Count > 0)
                    {
                        //x.IsEnabled && ......
                        _list.Add(_conditionStack.Peek(), true);//.Push("[" + leftExp.Member.Name + "]");
                        singleBool = true;
                    }
                }
            }
            if (node.Left.NodeType == ExpressionType.Not)
            {
                var unaryExp = node.Left as UnaryExpression;
                if (unaryExp.Operand.NodeType == ExpressionType.MemberAccess)
                {
                    var leftExp = unaryExp.Operand as MemberExpression;
                    if (leftExp.Type.FullName == "System.Boolean" && leftExp.Type.Assembly.GlobalAssemblyCache)
                    {
                        //x.IsEnabled这种情况
                        if (node.Right.NodeType == ExpressionType.Constant)
                        {
                            //x.IsEnabled=true
                        }
                        else if (_conditionStack.Count > 0)
                        {
                            //x.IsEnabled && ......
                            _list.Add(_conditionStack.Peek(), false);//.Push("[" + leftExp.Member.Name + "]");
                            singleBool = true;
                        }
                        else
                        {
                            bool value = (bool)_constStack.Pop();
                            if (value)
                            {
                                _conditionStack.Push("1=1");
                            }
                            else
                            {
                                _conditionStack.Push("1=2");
                            }
                        }
                    }
                }
            }
            //此时已获取到了值,一般情况下访问右支就是为了找值,所以直接组合
            if (singleBool)
            {
                right     = _conditionStack.Pop();
                left      = _conditionStack.Pop();
                op        = "=";
                condition = string.Format("({0} {1} {2})", left, op, right);
                _conditionStack.Push(condition);
            }
            if (node.NodeType == ExpressionType.ArrayIndex)
            {
                //处理数组访问,此时right存的是index,所以跳过Right访问
                var    constExp    = node.Right as ConstantExpression;
                var    index       = Convert.ToInt32(constExp.Value);
                var    arrayObject = _constStack.Pop() as Array;
                object arrayValue  = arrayObject.GetValue(index);
                while (_memberStack.Count > 0)
                {
                    var member = _memberStack.Pop();
                    if (member.MemberType == MemberTypes.Field)
                    {
                        arrayValue = ((FieldInfo)member).GetValue(arrayValue);
                    }
                    else if (member.MemberType == MemberTypes.Property)
                    {
                        arrayValue = ((PropertyInfo)member).GetValue(arrayValue, null);
                    }
                    else
                    {
                        throw new NotSupportedException("未知的成员类型:" + member.MemberType);
                    }
                }
                _list.Add(_conditionStack.Peek(), arrayValue);
                return(node);
            }
            else
            {
                if (node.Right is ConstantExpression)
                {
                    var constExp = node.Right as ConstantExpression;
                    _list.Add(_conditionStack.Peek(), constExp.Value);
                }
                else
                {
                    Visit(node.Right);
                }
            }
            if (_constStack.Count > 0)
            {
                //常量计算
                object c1 = _constStack.Pop();
                object c2 = _constStack.Pop();
                bool   c3 = false;
                switch (node.NodeType)
                {
                case ExpressionType.Equal:
                    c3 = c1 == c2;
                    break;

                case ExpressionType.GreaterThan:
                    if (c1 == null && c2 == null)
                    {
                        c3 = true;
                    }
                    else
                    {
                        c3 = false;
                    }
                    break;
                }
                if (c3)
                {
                    _conditionStack.Push("1=1");
                }
                else
                {
                    _conditionStack.Push("1=2");
                }
            }
            else
            {
                right = _conditionStack.Pop();
                left  = _conditionStack.Pop();
                op    = string.Empty;
                switch (node.NodeType)
                {
                case ExpressionType.AndAlso:
                    op = "and";
                    break;

                case ExpressionType.OrElse:
                    op = "or";
                    break;

                case ExpressionType.Equal:
                    op = "=";
                    break;

                case ExpressionType.GreaterThanOrEqual:
                    op = ">=";
                    break;

                case ExpressionType.GreaterThan:
                    op = ">";
                    break;

                case ExpressionType.LessThan:
                    op = "<";
                    break;

                case ExpressionType.LessThanOrEqual:
                    op = "<=";
                    break;

                case ExpressionType.ArrayIndex:
                    op = "=";
                    break;

                default:
                    throw new NotImplementedException("未实现逻辑关系:" + node.NodeType);
                }
                var lastParameter = _list.LastOrDefault();
                if (lastParameter.Value == null)
                {
                    right = "null";
                    _list.Remove(lastParameter.Key);
                }
                condition = string.Format("({0} {1} {2})", left, op, right);
                match     = Regex.Match(condition, @"(.*)? = null");
                if (match.Success || (match = Regex.Match(condition, "null = (.*)")).Success)
                {
                    _conditionStack.Push(match.Groups[1].Value + " is null)");
                }
                else
                {
                    _conditionStack.Push(condition);
                }
            }
            return(node);
        }
        protected override Expression VisitMember(MemberExpression node)
        {
            if (node.Expression is ParameterExpression)
            {
                //到达根节点,并且一定是左枝
                if (ExpressionUtil.IsEntityMember(node.Member))
                {
                    //x.User.Book.Id
                    string tableName = ExpressionUtil.GetEntityTableName(ExpressionUtil.GetMemberType(node.Member));
                    if (string.IsNullOrWhiteSpace(tableName))
                    {
                        throw new Exception("解析出错");
                    }
                    string alia = _aliaTableNameMap[tableName];
                    field = _memberStack.Pop().Name;
                    _conditionStack.Push("[" + alia + "].[" + field + "]");
                    _conditionStack.Push("@" + field);
                }
                else
                {
                    //按照属性处理
                    field = node.Member.Name;
                    if (_memberStack.Count > 0)
                    {
                        //有属性要转换为sql语句
                        var propertyInfo = (PropertyInfo)_memberStack.Pop();
                        if (propertyInfo.PropertyType.FullName == "System.DateTime" && propertyInfo.PropertyType.Assembly.GlobalAssemblyCache)
                        {
                            //该属性为日期时间型,可进行转换
                            _conditionStack.Push("CONVERT(NVARCHAR(20),[" + field + "],101)");
                        }
                        else
                        {
                            throw new NotImplementedException("不允许使用当前属性取值:" + propertyInfo.PropertyType.Name + "," + propertyInfo.Name);
                        }
                    }
                    else if (_memberStack.Count > 0)
                    {
                        //有方法要转换为sql语句
                        var method = _memberStack.Pop();
                        if (method.Name == "ToDateTime" && method.DeclaringType.Assembly.GlobalAssemblyCache)
                        {
                            _conditionStack.Push("CONVERT(NVARCHAR(20),[" + field + "],101)");
                        }
                        else
                        {
                            throw new NotSupportedException("不支持指定方法的转换:" + method.Name);
                        }
                    }
                    else
                    {
                        _conditionStack.Push("[" + field + "]");
                    }
                    _conditionStack.Push("@" + field);
                }
            }
            else if (node.Expression == null)
            {
                //一定是静态成员,例如:x=>DateTime.Now中的Now,直接取出值
                object value = null;
                if (node.Member.MemberType == MemberTypes.Field)
                {
                    var fieldInfo = node.Member as FieldInfo;
                    value = fieldInfo.GetValue(null);
                }
                else
                {
                    var propertyInfo = node.Member as PropertyInfo;
                    value = propertyInfo.GetValue(null, null);
                }
                while (_memberStack.Count > 0)
                {
                    var member = _memberStack.Pop();
                    if (member.MemberType == MemberTypes.Field)
                    {
                        value = ((FieldInfo)member).GetValue(value);
                    }
                    else if (member.MemberType == MemberTypes.Property)
                    {
                        value = ((PropertyInfo)member).GetValue(value, null);
                    }
                    else
                    {
                        throw new NotSupportedException("未知的成员类型:" + member.MemberType);
                    }
                }
                //if (node.Member.MemberType == MemberTypes.Field)
                //{
                //    var fieldInfo = node.Member as FieldInfo;
                //    _list.Add(fieldInfo.GetValue(null));
                //}
                //else
                //{
                //    var propertyInfo = node.Member as PropertyInfo;
                //    _list.Add(propertyInfo.GetValue(null, null));
                //}
                _list.Add(_conditionStack.Peek(), value);
            }
            else if (node.Expression is ConstantExpression)
            {
                //引用的局部变量
                //var constExp = node.Expression as ConstantExpression;
                //var field = constExp.Value.GetType().GetField(node.Member.Name);
                //var rootValue = field.GetValue(constExp.Value);
                //while (_propertyStack.Count > 0)
                //{
                //    var property = _propertyStack.Pop();
                //    rootValue = property.GetValue(rootValue, null);
                //}
                //_paramStack.Push(rootValue);
                ObjectValueExpressionVisitor visitor = new ObjectValueExpressionVisitor();
                visitor.Visit(node);
                if (visitor.Value is Array || visitor.Value is IEnumerable)
                {
                    var    rootValue = visitor.Value;
                    var    list      = rootValue as IList;
                    object result    = rootValue;
                    while (_memberStack.Count > 0)
                    {
                        var memberInfo = _memberStack.Pop();
                        if (memberInfo.MemberType == MemberTypes.Method)
                        {
                            var method = memberInfo as MethodInfo;
                            IEnumerable <object> args = null;
                            //if (method.Arguments[0] is ConstantExpression)
                            //{
                            //    args = mce.Arguments.Select(x => ((ConstantExpression)x).Value);
                            //    result = mce.Method.Invoke(rootValue, args.ToArray());
                            //}
                            //else
                            //{
                            //    visitor = new ObjectValueExpressionVisitor();
                            //    visitor.Visit(mce.Arguments[0]);
                            //    var extensionArgs = mce.Arguments.Skip(1).Select(x => ((ConstantExpression)x).Value).ToList();
                            //    extensionArgs.Insert(0, visitor.Value);
                            //    result = mce.Method.Invoke(null, extensionArgs.ToArray());
                            //}
                        }
                    }
                    if (_memberStack.Count > 0)
                    {
                        //MethodCallExpression mce = _memberStack.Pop();
                        //IEnumerable<object> args = null;
                        //if (mce.Arguments[0] is ConstantExpression)
                        //{
                        //    args = mce.Arguments.Select(x => ((ConstantExpression)x).Value);
                        //    result = mce.Method.Invoke(rootValue, args.ToArray());
                        //}
                        //else
                        //{
                        //    visitor = new ObjectValueExpressionVisitor();
                        //    visitor.Visit(mce.Arguments[0]);
                        //    var extensionArgs = mce.Arguments.Skip(1).Select(x => ((ConstantExpression)x).Value).ToList();
                        //    extensionArgs.Insert(0, visitor.Value);
                        //    result = mce.Method.Invoke(null, extensionArgs.ToArray());
                        //}
                    }

                    _list.Add(_conditionStack.Peek(), result);
                    //_constStack.Push(rootValue);
                }
                else
                {
                    _constStack.Push(visitor.Value);
                }
                _paramNameStack.Push(node.Member.Name);
            }
            else if (node.Expression is MemberExpression)
            {
                if (!ExpressionReflector.IsEntityPropertyType(ExpressionUtil.GetMemberType(((MemberExpression)node.Expression).Member)))
                {
                    //x=>x.User.Book.Id
                    _memberStack.Push(node.Member);
                }
                else
                {
                    //var a=false;x=>a这种情况
                }
            }
            else
            {
                _memberStack.Push(node.Member);
            }
            return(base.VisitMember(node));
        }