Esempio n. 1
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. 2
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. 3
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. 4
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. 5
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. 6
0
        public static List <T> Import <T>(Stream stream, Func <string, string, string> onImportItemPropertyData, Action <T> onImportItemData)
            where T : class, new()
        {
            HSSFWorkbook book       = new HSSFWorkbook(stream);
            Type         type       = typeof(T);
            var          piDict     = ExpressionReflector.GetProperties(type);
            var          attrsDict  = new Dictionary <string, string>();
            var          properties = new Dictionary <int, string>();

            foreach (var propertyInfo in piDict.Values)
            {
                var attr = AttributeHelper.GetAttribute <DataGridColumnAttribute>(propertyInfo);
                if (attr == null)
                {
                    continue;
                }
                attrsDict.Add(attr.DisplayName, propertyInfo.Name);
            }
            Dictionary <int, Action <object, object> > settersMapped = new Dictionary <int, Action <object, object> >();
            var    setters   = ExpressionReflector.GetSetters(type);
            ISheet sheet     = book.GetSheetAt(0);
            IRow   headerRow = sheet.GetRow(0);

            for (int i = 0; i < headerRow.Cells.Count; i++)
            {
                ICell  cell = headerRow.Cells[i];
                string name = cell.StringCellValue.ToLower();
                if (attrsDict.ContainsKey(name))
                {
                    name = attrsDict[name].ToLower();
                }
                foreach (var key in setters.Keys.Where(key => key.ToLower() == name))
                {
                    settersMapped.Add(i, setters[key]);
                    properties.Add(i, name);
                    break;
                }
            }
            List <T> list = new List <T>();

            for (int i = 1; i <= sheet.LastRowNum; i++)
            {
                T t = new T();
                if (onImportItemData != null)
                {
                    onImportItemData(t);
                }
                var cells = sheet.GetRow(i).Cells;
                for (int j = 0; j < cells.Count; j++)
                {
                    string value = cells[j].ToString();
                    if (onImportItemPropertyData != null)
                    {
                        value = onImportItemPropertyData(value, properties[j]);
                    }
                    settersMapped[j](t, value);
                }
                list.Add(t);
            }
            return(list);
            //ISheet sheet= book.CreateSheet();
            //var header= sheet.CreateRow(0);
            //for (int i = 0; i < properties.Count; i++)
            //{
            //    ICell cell= header.CreateCell(i);
            //    string name = properties[i];

            //    if (attrsDict.ContainsKey(name))
            //    {
            //        name = attrsDict[properties[i]].DisplayName;
            //    }
            //    cell.SetCellValue(name);
            //}
        }
Esempio n. 7
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);
                }
            }
            if (list.Count <= 10)
            {
                #region 使用Insert语句插入
                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);
                }
                var values        = new List <string>();
                var index         = 0;
                var sqlParameters = new Dictionary <string, object>();
                foreach (var entity in list)
                {
                    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));
                        sqlParameters.Add(key + index, getters.Get(key)(entity));
                    }
                    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);
                #endregion
            }
            else
            {
                #region 使用SqlBulkCopy插入
                var sqlBulkCopy = new SqlBulkCopy(DataContext.ConnectionString);
                sqlBulkCopy.DestinationTableName = "dbo.[" + table.Name + "]";
                if (list.Count > 500000)
                {
                    sqlBulkCopy.BatchSize = list.Count / 10;
                }
                var dataTable = new DataTable();
                foreach (var column in table.Columns.Values)
                {
                    var dataColumn = new DataColumn();
                    dataColumn.ColumnName = column.Name;
                    dataColumn.DataType   = TypeHelper.GetUnderlyingType(column.PropertyInfo.PropertyType);
                    dataTable.Columns.Add(dataColumn);
                    sqlBulkCopy.ColumnMappings.Add(column.Name, column.Name);
                }
                foreach (var item in list)
                {
                    var row = dataTable.NewRow();
                    if (!autoIncreament && keySetter != null)
                    {
                        keySetter(item, ++maxIndex);
                    }
                    foreach (var key in getters.Keys)
                    {
                        row[columns.Get(key).Name] = getters.Get(key)(item);
                    }
                    dataTable.Rows.Add(row);
                }
                sqlBulkCopy.WriteToServer(dataTable);
                sqlBulkCopy.Close();
                #endregion
                count = list.Count;
            }
            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);
        }