コード例 #1
0
        /// <summary>
        ///     将数据转化为 type 类型
        /// </summary>
        /// <param name="value">要转化的值</param>
        /// <param name="type">目标类型</param>
        /// <returns>转化为目标类型的 Object 对象</returns>
        public static object ChangeType(object value, Type type)
        {
            if (type.FullName == typeof(string).FullName)
            {
                return(Convert.ChangeType(Convert.IsDBNull(value) ? null : value, type));
            }
            else if (type.FullName == typeof(Guid).FullName)
            {
                if (null == value)
                {
                    return(Guid.Empty);
                }
                string str = value.ToString();
                if (!string.IsNullOrEmpty(str))
                {
                    return(Guid.Parse(str));
                }
                else
                {
                    return(Guid.Empty);
                }
            }
            else if (type.FullName == typeof(int).FullName)
            {
                if (null == value)
                {
                    return(0);
                }
                string str = value.ToString();
                if (!string.IsNullOrEmpty(str))
                {
                    return(int.Parse(str));
                }
                else
                {
                    return(0);
                }
            }
            else if (type.FullName == typeof(bool).FullName)
            {
                if (null == value)
                {
                    return(false);
                }
                string str = value.ToString();
                if (!string.IsNullOrEmpty(str))
                {
                    return(bool.Parse(str));
                }
                else
                {
                    return(false);
                }
            }
            else if (type.FullName == typeof(DateTime?).FullName)
            {
                if (value.Equals(DBNull.Value))
                {
                    return(null);
                }

                return((DateTime?)value);
            }
            else if (type.FullName == typeof(DateTime).FullName)
            {
                if (value.Equals(DBNull.Value))
                {
                    return(DateTime.MinValue);
                }

                bool bo = DateTime.TryParse(value.ToString(), out DateTime result);

                return(bo ? result : DateTime.MinValue);
            }
            else if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
            {
                NullableConverter convertor = new NullableConverter(type);
                return(Convert.IsDBNull(value) ? null : convertor.ConvertFrom(value));
            }
            return(value);
        }
コード例 #2
0
        /// <summary>
        /// Convert type of cell value to its predefined type in the sheet's ScriptMachine setting file.
        /// </summary>
        protected object ConvertFrom(ICell cell, Type t)
        {
            object value = null;

            if (t == typeof(float) || t == typeof(double) || t == typeof(int) || t == typeof(long))
            {
                if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                {
                    value = cell.NumericCellValue;
                }
                else if (cell.CellType == NPOI.SS.UserModel.CellType.String)
                {
                    //Get correct numeric value even the cell is string type but defined with a numeric type in a data class.
                    if (t == typeof(float))
                    {
                        value = Convert.ToSingle(cell.StringCellValue);
                    }
                    if (t == typeof(double))
                    {
                        value = Convert.ToDouble(cell.StringCellValue);
                    }
                    if (t == typeof(int))
                    {
                        value = Convert.ToInt32(cell.StringCellValue);
                    }
                    if (t == typeof(long))
                    {
                        value = Convert.ToInt64(cell.StringCellValue);
                    }
                }
                else if (cell.CellType == NPOI.SS.UserModel.CellType.Formula)
                {
                    // Get value even if cell is a formula
                    if (t == typeof(float))
                    {
                        value = Convert.ToSingle(cell.NumericCellValue);
                    }
                    if (t == typeof(double))
                    {
                        value = Convert.ToDouble(cell.NumericCellValue);
                    }
                    if (t == typeof(int))
                    {
                        value = Convert.ToInt32(cell.NumericCellValue);
                    }
                    if (t == typeof(long))
                    {
                        value = Convert.ToInt64(cell.NumericCellValue);
                    }
                }
            }
            else if (t == typeof(string) || t.IsArray)
            {
                // HACK: handles the case that a cell contains numeric value
                //       but a member field in a data class is defined as string type.
                if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                {
                    value = cell.NumericCellValue;
                }
                else
                {
                    value = cell.StringCellValue;
                }
            }
            else if (t == typeof(bool))
            {
                value = cell.BooleanCellValue;
            }

            if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
            {
                var nc = new NullableConverter(t);
                return(nc.ConvertFrom(value));
            }

            if (t.IsEnum)
            {
                // for enum type, first get value by string then convert it to enum.
                value = cell.StringCellValue;
                return(Enum.Parse(t, value.ToString(), true));
            }
            else if (t.IsArray)
            {
                // for array type, return comma separated string
                // then parse and covert its corresponding type.
                return(value as string);
            }
            else
            {
                // for all other types, convert its corresponding type.
                return(Convert.ChangeType(value, t));
            }
        }
コード例 #3
0
        private static Expression CreateFilterExpression(Type t, Filter f, string dataValue, string field, ParameterExpression queryParam)
        {
            object           value        = null;
            MemberExpression memberAccess = Expression.MakeMemberAccess(queryParam, t.GetProperty(field));
            Type             prop         = t.GetProperty(field).PropertyType;
            string           val          = dataValue.ToLower().Trim();

            if (prop.IsNullableValueType())
            {
                if (val != "null")
                {
                    Type underlyingType = new NullableConverter(prop).UnderlyingType;
                    value        = Convert.ChangeType(dataValue, underlyingType, CultureInfo.InvariantCulture);
                    memberAccess = Expression.Property(memberAccess, prop.GetProperty("Value"));
                }
            }

            // The field is not nullable, but for the 'emptyfilter' we want to compare to a value that can be considered 'empty' for this datatype,
            // which isn't null.
            else if (val == "null")
            {
                //prop
                switch (f.DataType)
                {
                case "numeric":
                    value = default(Int32);
                    break;

                case "boolean":
                    value = default(Boolean);
                    break;

                case "date":
                    value = default(DateTime);
                    break;
                }
            }
            else
            {
                value = Convert.ChangeType(dataValue, t.GetProperty(field).PropertyType);
            }
            Expression result = null;


            switch (f.DataComparison)
            {
            case lessThan:
                result = Expression.LessThan(memberAccess, Expression.Constant(value));
                break;

            case greaterThan:
                result = Expression.GreaterThan(memberAccess, Expression.Constant(value));
                break;

            default:
                if (f.DataType == "date")
                {
                    // When the object's DateTime property is actually nullable, we have to get to the .Value property to compare it
                    if (prop.IsNullableValueType())
                    {
                        memberAccess = Expression.Property(memberAccess, prop.GetProperty("Value").PropertyType.GetProperty("Date"));
                        result       = Expression.Equal(memberAccess, Expression.Constant(value));
                    }
                    else
                    {
                        var casted = Convert.ToDateTime(value);
                        result = Expression.And(
                            Expression.And(
                                Expression.Equal(
                                    Expression.Property(memberAccess, prop.GetProperty("Year")),
                                    Expression.Constant(casted.Year)
                                    ),
                                Expression.Equal(
                                    Expression.Property(memberAccess, prop.GetProperty("Month")),
                                    Expression.Constant(casted.Month)
                                    )
                                ),
                            Expression.Equal(
                                Expression.Property(memberAccess, prop.GetProperty("Day")),
                                Expression.Constant(casted.Day)
                                )
                            );
                    }
                }
                result = Expression.Equal(memberAccess, Expression.Constant(value));

                break;
            }

            return(result);
        }
コード例 #4
0
ファイル: Extention.DataTable.cs プロジェクト: lxshwyan/Lucky
        /// <summary>
        /// DataTable转List
        /// </summary>
        /// <typeparam name="T">转换类型</typeparam>
        /// <param name="dt">数据源</param>
        /// <returns></returns>
        public static List <T> ToList <T>(this DataTable dt)
        {
            List <T> list = new List <T>();

            //确认参数有效,若无效则返回Null
            if (dt == null)
            {
                return(list);
            }
            else if (dt.Rows.Count == 0)
            {
                return(list);
            }

            Dictionary <string, string> dicField    = new Dictionary <string, string>();
            Dictionary <string, string> dicProperty = new Dictionary <string, string>();
            Type type = typeof(T);

            //创建字段字典,方便查找字段名
            type.GetFields().ForEach(aFiled =>
            {
                dicField.Add(aFiled.Name.ToLower(), aFiled.Name);
            });

            //创建属性字典,方便查找属性名
            type.GetProperties().ForEach(aProperty =>
            {
                dicProperty.Add(aProperty.Name.ToLower(), aProperty.Name);
            });

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //创建泛型对象
                T _t = Activator.CreateInstance <T>();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string memberKey = dt.Columns[j].ColumnName.ToLower();

                    //字段赋值
                    if (dicField.ContainsKey(memberKey))
                    {
                        FieldInfo theField = type.GetField(dicField[memberKey]);
                        var       dbValue  = dt.Rows[i][j];
                        if (dbValue.GetType() == typeof(DBNull))
                        {
                            dbValue = null;
                        }
                        if (dbValue != null)
                        {
                            Type memberType = theField.FieldType;
                            if (memberType.IsGenericType && memberType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                            {
                                NullableConverter newNullableConverter = new NullableConverter(memberType);
                                dbValue = newNullableConverter.ConvertFrom(dbValue);
                            }
                            else
                            {
                                dbValue = Convert.ChangeType(dbValue, memberType);
                            }
                        }
                        theField.SetValue(_t, dbValue);
                    }
                    //属性赋值
                    if (dicProperty.ContainsKey(memberKey))
                    {
                        PropertyInfo theProperty = type.GetProperty(dicProperty[memberKey]);
                        var          dbValue     = dt.Rows[i][j];
                        if (dbValue.GetType() == typeof(DBNull))
                        {
                            dbValue = null;
                        }
                        if (dbValue != null)
                        {
                            Type memberType = theProperty.PropertyType;
                            if (memberType.IsGenericType && memberType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                            {
                                NullableConverter newNullableConverter = new NullableConverter(memberType);
                                dbValue = newNullableConverter.ConvertFrom(dbValue);
                            }
                            else
                            {
                                dbValue = Convert.ChangeType(dbValue, memberType);
                            }
                        }
                        theProperty.SetValue(_t, dbValue);
                    }
                }
                list.Add(_t);
            }
            return(list);
        }
コード例 #5
0
        public static DataTable ListToDataTable <T>(List <T> entitys)
        {
            if (entitys == null || entitys.Count < 1)
            {
                throw new Exception("需转换的集合为空");
            }
            // get all Properties
            Type entityType = entitys[0].GetType();
            List <PropertyInfo> entityProperties = entityType.GetProperties().ToList();

            //make table schema
            System.Data.DataTable dt = new System.Data.DataTable();
            for (int i = 0; i < entityProperties.Count; i++)
            {
                //convert into underlying type of nullable type as dataset doesn't support nullable type
                Type type = entityProperties[i].PropertyType;
                if (IsNullableType(type))
                {
                    type = GetNullableUnderlyingType(type);
                }
                DataColumn column = new DataColumn(entityProperties[i].Name, type);
                dt.Columns.Add(column);//entityProperties[i].Name);
            }

            var qry = entityProperties.AsQueryable();

            //convert entity to row
            foreach (object entity in entitys)
            {
                //ensure entity type
                if (entity.GetType() != entityType)
                {
                    throw new Exception("要转换的集合元素类型不一致");
                }
                DataRow row = dt.NewRow();
                foreach (DataColumn column in dt.Columns)
                {
                    PropertyInfo property = qry.FirstOrDefault(p => p.Name == column.ColumnName);
                    object       obj      = property.GetValue(entity, null);
                    if (property != null)
                    {
                        Type originalType = property.PropertyType;
                        if (IsNullableType(originalType))
                        {
                            Type type           = GetNullableUnderlyingType(originalType);
                            NullableConverter c = new NullableConverter(originalType);
                            if (obj == null)//type.IsValueType&&
                            {
                                row[column.ColumnName] = DBNull.Value;
                            }
                            else
                            {
                                row[column.ColumnName] = obj;// c.ConvertTo(obj, type);
                            }
                        }
                        else
                        {
                            row[column.ColumnName] = obj;
                        }
                    }
                }
                dt.Rows.Add(row);

                //object[] entityValues = new object[entityProperties.Length];
                //for (int i = 0; i < entityProperties.Length; i++)
                //{
                //    PropertyInfo property = entityProperties[i];
                //    Type type=property.PropertyType;
                //    if (IsNullableType(type))
                //    {
                //        type = GetNullableUnderlyingType(type);
                //        if (type.IsValueType)
                //        {
                //            entityValues[i] = Activator.CreateInstance(type);

                //        }
                //        else
                //        {
                //            entityValues[i] = property.GetValue(entity, null); }
                //    }
                //    else
                //    {
                //        entityValues[i] = entityProperties[i].GetValue(entity, null);
                //    }
                //}
                //dt.Rows.Add(entityValues);
            }
            return(dt);
        }
コード例 #6
0
        public static DataTable CopyToDataTableFromDynamic(this IEnumerable <object> list, string tableName = null, List <string> columnsToCreate = null)
        {
            if (list == null)
            {
                throw new ArgumentNullException("list");
            }

            DataTable table = null;

            PropertyInfo[] dynamicObjProperties = null;

            var notAllColumns = columnsToCreate != null && columnsToCreate.Count != 0;

            // Criar linhas

            foreach (var obj in list)
            {
                // Na primeira iteração cria as colunas da tabela (deve ser feito aqui senão a query Linq dispara 2x)

                if (table == null)
                {
                    table           = new DataTable();
                    table.TableName = tableName;

                    var firstElement = obj;

                    dynamicObjProperties = firstElement.GetType().GetProperties();

                    // Criar colunas com base no tipo do 1º elemento

                    foreach (var prop in dynamicObjProperties)
                    {
                        if (notAllColumns && !columnsToCreate.Contains(prop.Name))
                        {
                            continue;
                        }
                        var type = prop.PropertyType;

                        if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                        {
                            var nullableConverter = new NullableConverter(type);

                            type = nullableConverter.UnderlyingType;
                        }

                        table.Columns.Add(prop.Name, type);
                    }
                }

                var row = table.NewRow();

                foreach (var prop in dynamicObjProperties)
                {
                    var colName = prop.Name;
                    if (notAllColumns && !columnsToCreate.Contains(colName))
                    {
                        continue;
                    }

                    object value;

                    value = (object)prop.GetValue(obj, null);


                    row[colName] = value.AsDBNull();
                }

                table.Rows.Add(row);
            }

            return(table);
        }
コード例 #7
0
        /// <summary>
        /// Convert type of cell value to its predefined type which is specified in the sheet's ScriptMachine setting file.
        /// </summary>
        protected object ConvertFrom(ICell cell, Type t)
        {
            object value = null;

            if (t == typeof(float) || t == typeof(double) || t == typeof(short) || t == typeof(int) || t == typeof(long))
            {
                if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                {
                    value = cell.NumericCellValue;
                }
                else if (cell.CellType == NPOI.SS.UserModel.CellType.String)
                {
                    //Get correct numeric value even the cell is string type but defined with a numeric type in a data class.
                    if (t == typeof(float))
                    {
                        value = Convert.ToSingle(cell.StringCellValue);
                    }
                    if (t == typeof(double))
                    {
                        value = Convert.ToDouble(cell.StringCellValue);
                    }
                    if (t == typeof(short))
                    {
                        value = Convert.ToInt16(cell.StringCellValue);
                    }
                    if (t == typeof(int))
                    {
                        value = Convert.ToInt32(cell.StringCellValue);
                    }
                    if (t == typeof(long))
                    {
                        value = Convert.ToInt64(cell.StringCellValue);
                    }
                }
                else if (cell.CellType == NPOI.SS.UserModel.CellType.Formula)
                {
                    // Get value even if cell is a formula
                    if (t == typeof(float))
                    {
                        value = Convert.ToSingle(cell.NumericCellValue);
                    }
                    if (t == typeof(double))
                    {
                        value = Convert.ToDouble(cell.NumericCellValue);
                    }
                    if (t == typeof(short))
                    {
                        value = Convert.ToInt16(cell.NumericCellValue);
                    }
                    if (t == typeof(int))
                    {
                        value = Convert.ToInt32(cell.NumericCellValue);
                    }
                    if (t == typeof(long))
                    {
                        value = Convert.ToInt64(cell.NumericCellValue);
                    }
                }
            }
            else if (t == typeof(string) || t.IsArray)
            {
                // HACK: handles the case that a cell contains numeric value
                //       but a member field in a data class is defined as string type.
                //       e.g. string s = "123"
                if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
                {
                    value = cell.NumericCellValue;
                }
                else
                {
                    value = cell.StringCellValue;
                }
            }
            else if (t == typeof(bool))
            {
                value = cell.BooleanCellValue;
            }

            if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
            {
                Debug.Log("generic");
                var nc = new NullableConverter(t);
                return(nc.ConvertFrom(value));
            }

            if (t.Equals(typeof(Sprite)))
            {
                Debug.Log("type change sprite");
                return((Sprite)value);
            }

            if (t.IsEnum)
            {
                // for enum type, first get value by string then convert it to enum.
                value = cell.StringCellValue;
                return(Enum.Parse(t, value.ToString(), true));
            }
            else if (t.IsArray)
            {
                if (t.GetElementType() == typeof(float))
                {
                    return(ConvertExt.ToSingleArray((string)value));
                }

                if (t.GetElementType() == typeof(double))
                {
                    return(ConvertExt.ToDoubleArray((string)value));
                }

                if (t.GetElementType() == typeof(short))
                {
                    return(ConvertExt.ToInt16Array((string)value));
                }

                if (t.GetElementType() == typeof(int))
                {
                    return(ConvertExt.ToInt32Array((string)value));
                }

                if (t.GetElementType() == typeof(long))
                {
                    return(ConvertExt.ToInt64Array((string)value));
                }

                if (t.GetElementType() == typeof(string))
                {
                    return(ConvertExt.ToStringArray((string)value));
                }
            }

            Debug.Log("other convert");
            // for all other types, convert its corresponding type.
            return(Convert.ChangeType(value, t));
        }
コード例 #8
0
        virtual public CommonResponse GetPage(int perPage, int page)
        {
            CommonResponse response = new CommonResponse();
            List <Expression <Func <Entity, bool> > > db_wheres = new List <Expression <Func <Entity, bool> > >();
            List <Expression <Func <Entity, bool> > > wheres    = new List <Expression <Func <Entity, bool> > >();

            string filterGeneral = HttpContext.Current.Request["filterGeneral"];

            if (!isValidJSValue(filterGeneral))
            {
                filterGeneral = "";
            }

            string filterParentField = HttpContext.Current.Request["parentField"];

            if (!isValidJSValue(filterParentField))
            {
                filterParentField = "";
            }

            string filterParentKey = HttpContext.Current.Request["parentKey"];

            if (!isValidJSValue(filterParentKey))
            {
                filterParentKey = "";
            }

            string filterUser = HttpContext.Current.Request["filterUser"];

            if (!isValidJSValue(filterUser))
            {
                filterUser = "";
            }
            else
            {
                if (typeof(Entity).IsSubclassOf(typeof(BaseDocument)))
                {
                    wheres.Add(e => (e as BaseDocument).InfoTrack.User_AssignedToKey == int.Parse(filterUser));
                }
            }

            try
            {
                if (filterParentKey.Length > 0 && filterParentField.Length > 0)
                {
                    ParameterExpression entityParameter = Expression.Parameter(typeof(Entity), "entityParameter");
                    Expression          childProperty   = Expression.PropertyOrField(entityParameter, filterParentField);

                    Expression comparison = Expression.Equal(childProperty, Expression.Constant(int.Parse(filterParentKey)));

                    Expression <Func <Entity, bool> > lambda = Expression.Lambda <Func <Entity, bool> >(comparison, entityParameter);

                    //ConstantExpression idExpression = Expression.Constant(int.Parse(filterParentKey), typeof(int));
                    //BinaryExpression parentFieldEqualsIdExpression = Expression.Equal(parentField, idExpression);
                    //Expression<Func<int, bool>> lambda1 =
                    //    Expression.Lambda<Func<int, bool>>(
                    //        parentFieldEqualsIdExpression,
                    //        new ParameterExpression[] { parentField });

                    //Expression<Func<Entity, bool>> where = entityFiltered =>
                    //        typeof(Entity).GetProperty(filterParentField).GetValue(entityFiltered, null).ToString() == filterParentKey;

                    db_wheres.Add(lambda);
                }

                foreach (var queryParam in HttpContext.Current.Request.QueryString.AllKeys)
                {
                    string queryParamValue = HttpContext.Current.Request.QueryString[queryParam];
                    if (isValidParam(queryParam) && isValidJSValue(queryParamValue))
                    {
                        string sPropertyName = queryParam;//.Substring(6);

                        PropertyInfo oProp = typeof(Entity).GetProperty(sPropertyName);
                        Type         tProp = oProp.PropertyType;
                        //Nullable properties have to be treated differently, since we
                        //  use their underlying property to set the value in the object
                        if (tProp.IsGenericType &&
                            tProp.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                        {
                            //Get the underlying type property instead of the nullable generic
                            tProp = new NullableConverter(oProp.PropertyType).UnderlyingType;
                        }

                        ParameterExpression entityParameter = Expression.Parameter(typeof(Entity), "entityParameter");
                        Expression          childProperty   = Expression.PropertyOrField(entityParameter, sPropertyName);


                        var value = Expression.Constant(Convert.ChangeType(queryParamValue, tProp));

                        // let's perform the conversion only if we really need it
                        var converted = value.Type != childProperty.Type
                            ? Expression.Convert(value, childProperty.Type)
                            : (Expression)value;

                        Expression comparison = Expression.Equal(childProperty, converted);

                        Expression <Func <Entity, bool> > lambda = Expression.Lambda <Func <Entity, bool> >(comparison, entityParameter);

                        db_wheres.Add(lambda);
                    }
                }
            }
            catch (Exception ex)
            {
                return(response.Error(ex.ToString()));
            }

            return(_logic.GetPage(perPage, page, filterGeneral, wheres.ToArray(), orderBy, db_wheres.ToArray()));
        }
コード例 #9
0
ファイル: Converter.cs プロジェクト: terryzamal/DotStd
        /// <remarks>
        /// This method exists as a workaround to System.Convert.ChangeType(Object, Type) which does not handle
        /// nullables as of version 2.0 (2.0.50727.42) of the .NET Framework.
        /// Try to be much more forgiving than Convert.ChangeType for enums, bool and int.
        /// </remarks>
        public static object ChangeType(object value, Type convertToType)
        {
            // Note: This if block was taken from Convert.ChangeType as is, and is needed here since we're
            // checking properties on conversionType below.

            ValidState.ThrowIfNull(convertToType, nameof(convertToType));
            if (ValidState.IsNull(value))  // NULL or DBNull is always null.
            {
                return(null);
            }

            // Array of a single value can act like the single value for my purposes.
            Type     convertFromType = value.GetType();
            TypeCode typeCodeFrom    = Type.GetTypeCode(convertFromType);

            if (typeCodeFrom == TypeCode.Object)    // NOT string. for 'StringValues'
            {
                IEnumerable array = value as IEnumerable;
                if (array != null)
                {
                    value = GetSingle(array);
                    if (value == null)  // Cant handle this.
                    {
                        return(null);
                    }
                }
            }
            if (typeCodeFrom == TypeCode.String && convertToType == typeof(byte[]))
            {
                if (value.ToString() == "...")   // Weird MySQL export thing.
                {
                    return(null);
                }
            }

            // If it's not a nullable type, just pass through the parameters to Convert.ChangeType
            if (IsNullableType(convertToType))
            {
                // It's a nullable type, so instead of calling Convert.ChangeType directly which would throw a
                // InvalidCastException (per http://weblogs.asp.net/pjohnson/archive/2006/02/07/437631.aspx),

                // It's a nullable type, and not null, so that means it can be converted to its underlying type,
                // so overwrite the passed-in conversion type with this underlying type
                var nullableConverter = new NullableConverter(convertToType);
                convertToType = nullableConverter.UnderlyingType;
            }

            // BEWARE ENUMS HERE . Invalid cast of int to enum.
            if (convertToType.BaseType == typeof(System.Enum))
            {
                return(Enum.ToObject(convertToType, Converter.ToInt(value)));
            }

            if (convertToType == typeof(string))
            {
                return(value.ToString());        // anything can be a string.
            }
            if (convertToType == typeof(bool))   // Be more forgiving converting to bool. "1" = true.
            {
                return(ToBool(value));
            }
            if (convertToType == typeof(int))
            {
                return(ToInt(value));
            }

            // Now that we've guaranteed conversionType is something Convert.ChangeType can handle (i.e. not a
            // nullable type), pass the call on to Convert.ChangeType
            return(Convert.ChangeType(value, convertToType, CultureInfo.InvariantCulture));
        }
コード例 #10
0
        /// <summary>
        /// 将动态类型转为指定类型实体
        /// </summary>
        /// <param name="data"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private static object DynamicToEntity(ExpandoObject data, Type type)
        {
            var entity = Activator.CreateInstance(type);

            var dic = data as IDictionary <string, object>;

            foreach (var item in dic)
            {
                if (item.Value == null)
                {
                    continue;
                }

                var type_value = item.Value.GetType();

                if (type_value == typeof(DBNull))
                {
                    continue;
                }

                var prop = type.GetProperty(item.Key, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static);

                if (prop == null)
                {
                    continue;
                }

                object value = item.Value;

                if (type_value != prop.PropertyType)
                {
                    if (type_value == typeof(List <object>))
                    {
                        var valueList    = Activator.CreateInstance(prop.PropertyType);
                        var dicValueList = value as List <object>;

                        foreach (var valueItem in dicValueList)
                        {
                            prop.PropertyType.GetMethod("Add")
                            .Invoke(valueList, new object[] {
                                DynamicToEntity(valueItem as ExpandoObject, prop.PropertyType.GenericTypeArguments[0])
                            });
                        }

                        value = valueList;
                    }
                    else if (type_value == typeof(ExpandoObject))
                    {
                        value = DynamicToEntity(item.Value as ExpandoObject, prop.PropertyType);
                    }
                    else if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                    {
                        NullableConverter newNullableConverter = new NullableConverter(prop.PropertyType);
                        try
                        {
                            if (!newNullableConverter.CanConvertFrom(item.Value.GetType()))
                            {
                                value = Convert.ChangeType(item.Value, newNullableConverter.UnderlyingType);
                            }
                            else
                            {
                                value = newNullableConverter.ConvertFrom(item.Value);
                            }
                        }
#pragma warning disable CA1031 // Do not catch general exception types
                        catch
                        {
                            value = newNullableConverter.ConvertFromString(item.Value?.ToString());
                        }
#pragma warning restore CA1031 // Do not catch general exception types
                    }
                    else
                    {
                        value = Convert.ChangeType(item.Value, prop.PropertyType);
                    }
                }
                prop.SetValue(entity, value);
            }
            return(entity);
        }
コード例 #11
0
        private static void SelectDynamicReport(ReportArgument rArgument, SearchArgument sArgument, string orderBy, string companyName, string branchName, string foreignKeyName, int id, string UserName)
        {
            // IEnumerable<T> data;
            List <RollBackDistributionCompanyInfo> data;
            int count;

            if (!String.IsNullOrEmpty(foreignKeyName))
            {
                if (sArgument != null)
                {
                    data  = SelectDynamicSearchByFK(foreignKeyName, id, sArgument, orderBy).ToList <RollBackDistributionCompanyInfo>();
                    count = SelectSearchByFKCountCached(foreignKeyName, id, sArgument);
                }
                else
                {
                    data  = SelectDynamicByFK(foreignKeyName, id, orderBy).ToList <RollBackDistributionCompanyInfo>();
                    count = SelectByFKCountCached(foreignKeyName, id);
                }
            }
            else
            {
                if (sArgument != null)
                {
                    data  = SelectSearch(sArgument, orderBy).ToList <RollBackDistributionCompanyInfo>();
                    count = data.Count;
                    //count = SelectSearchCountCached(sArgument);
                }
                else
                {
                    data  = Select(orderBy).ToList <RollBackDistributionCompanyInfo>();
                    count = data.Count;
                    //count = SelectCountCached();
                }
            }
            int n = count;
            int m = rArgument.ReportArguments.Count;

            TypeCode[]     codes = new TypeCode[m];
            PropertyInfo[] infos = new PropertyInfo[m];
            bool           first = true;

            if (rArgument.Format == "PDF")
            {
                PDFCreators creator = new PDFCreators(rArgument.Orientation, rArgument.MarginLeft, rArgument.MarginRight, rArgument.MarginTop, rArgument.MarginBottom);

                creator.SetDocumentHeaderFooter(companyName);
                creator.OpenPDF();
                creator.SetTitle(rArgument.ReportName);
                string[] headers = new string[m];
                for (int i = 0; i < m; i++)
                {
                    headers[i] = rArgument.ReportArguments[i].HeaderText;
                }
                creator.CreateTable(m, true, headers, branchName);

                for (int i = 0; i < n; i++)
                {
                    object[] values = new object[m];
                    for (int j = 0; j < m; j++)
                    {
                        if (first)
                        {
                            infos[j] = typeof(RollBackDistributionCompanyInfo).GetProperty(rArgument.ReportArguments[j].PropertyField);
                            if (IsNullableType(infos[j].PropertyType))
                            {
                                NullableConverter nc = new NullableConverter(infos[j].PropertyType);
                                codes[j] = Type.GetTypeCode(nc.UnderlyingType);
                            }
                            else
                            {
                                codes[j] = Type.GetTypeCode(infos[j].PropertyType);
                            }
                        }
                        values[j] = infos[j].GetValue(data[i], null);
                        if (codes[j] == TypeCode.DateTime)
                        {
                            DateTime date = (DateTime)values[j];
                            values[j] = date.ToShortDateString();
                        }

                        if (codes[j] == TypeCode.Decimal)
                        {
                            decimal dec = (decimal)values[j];
                            values[j] = String.Format("{0:#,0.00}", dec);
                        }

                        if (codes[j] == TypeCode.Boolean)
                        {
                            bool temp = (bool)values[j];
                            if (temp == true)
                            {
                                values[j] = "Да";
                            }
                            else
                            {
                                values[j] = "Не";
                            }
                        }
                    }
                    first = false;
                    if (creator.AddDataRow(values, m, codes))
                    {
                        i--;
                    }
                }
                creator.AddTable();
                creator.FinishPDF();
            }

            //Creating Excel document
            else if (rArgument.Format == "XLS")
            {
                ExcelFileWriter <RollBackDistributionCompanyInfo> myExcel = new ExcelFileWriter <RollBackDistributionCompanyInfo>();
                string[] headers = new string[m];
                for (int i = 0; i < m; i++)
                {
                    headers[i] = rArgument.ReportArguments[i].HeaderText;
                }
                myExcel.Headers = headers;

                int    temp_num    = ('A') + m - 1;
                char   lastCol     = Convert.ToChar(temp_num);
                string finalColumn = lastCol + "1";

                myExcel.ColumnCount = m - 1;
                myExcel.RowCount    = n;

                myExcel.ActivateExcel();
                myExcel.FillHeaderColumn(headers, "A1", finalColumn);

                for (int i = 0; i < n; i++)
                {
                    object[] values = new object[m];

                    for (int j = 0; j < m; j++)
                    {
                        if (first)
                        {
                            infos[j] = typeof(RollBackDistributionCompanyInfo).GetProperty(rArgument.ReportArguments[j].PropertyField);
                            if (IsNullableType(infos[j].PropertyType))
                            {
                                NullableConverter nc = new NullableConverter(infos[j].PropertyType);
                                codes[j] = Type.GetTypeCode(nc.UnderlyingType);
                            }
                            else
                            {
                                codes[j] = Type.GetTypeCode(infos[j].PropertyType);
                            }
                        }
                        values[j] = infos[j].GetValue(data[i], null);

                        if (codes[j] == TypeCode.DateTime)
                        {
                            DateTime date = (DateTime)values[j];
                            values[j] = date.ToShortDateString();
                        }

                        if (codes[j] == TypeCode.Boolean)
                        {
                            bool temp = (bool)values[j];
                            if (temp == true)
                            {
                                values[j] = "Да";
                            }
                            else
                            {
                                values[j] = "Не";
                            }
                        }
                    }
                    first = false;
                    string fColumn = "A" + (i + 2).ToString();
                    string lColumn = lastCol + (i + 2).ToString();
                    myExcel.FillRowData_Mine(values, fColumn, lColumn);
                }
                string fileName = UserName + "_" + rArgument.ReportName + ".xls";
                myExcel.SaveExcel(fileName);
                myExcel.FinishExcel(fileName);
            }

            //Create Word document
            else if (rArgument.Format == "DOC")
            {
                WordFileWriter <RollBackDistributionCompanyInfo> myWord = new WordFileWriter <RollBackDistributionCompanyInfo>();
                myWord.Orientation = rArgument.Orientation;
                myWord.ActivateWord();

                //myWord.InsertingText(rArgument.ReportName);
                //myWord.InsertingText("Датум на извештај: " + DateTime.Now.ToShortDateString());

                string[] headers = new string[m];
                for (int i = 0; i < m; i++)
                {
                    headers[i] = rArgument.ReportArguments[i].HeaderText;
                }
                myWord.Headers           = headers;
                object[,] tempFillValues = new object[n, m];

                CultureInfo oldCI   = System.Threading.Thread.CurrentThread.CurrentCulture;
                CultureInfo oldUICI = System.Threading.Thread.CurrentThread.CurrentUICulture;

                System.Threading.Thread.CurrentThread.CurrentCulture   = new CultureInfo("mk-MK");
                System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("mk-MK");


                for (int i = 0; i < n; i++)
                {
                    object[] values = new object[m];
                    for (int j = 0; j < m; j++)
                    {
                        if (first)
                        {
                            infos[j] = typeof(RollBackDistributionCompanyInfo).GetProperty(rArgument.ReportArguments[j].PropertyField);
                            if (IsNullableType(infos[j].PropertyType))
                            {
                                NullableConverter nc = new NullableConverter(infos[j].PropertyType);
                                codes[j] = Type.GetTypeCode(nc.UnderlyingType);
                            }
                            else
                            {
                                codes[j] = Type.GetTypeCode(infos[j].PropertyType);
                            }
                        }
                        values[j] = infos[j].GetValue(data[i], null);

                        if (codes[j] == TypeCode.DateTime)
                        {
                            DateTime date = (DateTime)values[j];
                            values[j] = date.ToShortDateString();
                        }

                        if (codes[j] == TypeCode.Boolean)
                        {
                            bool temp = (bool)values[j];
                            if (temp == true)
                            {
                                values[j] = "Да";
                            }
                            else
                            {
                                values[j] = "Не";
                            }
                        }
                        tempFillValues[i, j] = values[j];
                    }
                    first = false;
                }

                System.Threading.Thread.CurrentThread.CurrentCulture   = oldCI;
                System.Threading.Thread.CurrentThread.CurrentUICulture = oldUICI;

                myWord.FillValues = tempFillValues;
                myWord.CreateTable(n, m);

                myWord.InsertFooter();
                myWord.InsertHeader(rArgument.BranchName);

                string fileName = UserName + "_" + rArgument.ReportName + ".doc";
                myWord.SaveDOC(fileName);
                myWord.FinishDOC(fileName);
            }
        }
コード例 #12
0
        private static IQueryable <RollBackDistributionCompanyInfo> SelectDynamicFilter(FilterArgument fArgument, string orderBy)
        {
            string       propertyName = fArgument.PropertyField;
            string       comparator   = fArgument.Comparator;
            object       value        = fArgument.FValue;
            PropertyInfo prop         = typeof(RollBackDistributionCompanyInfo).GetProperty(propertyName);
            Type         myType;
            bool         nullable = false;

            if (IsNullableType(prop.PropertyType))
            {
                NullableConverter nc = new NullableConverter(prop.PropertyType);
                myType   = nc.UnderlyingType;
                nullable = true;
            }
            else
            {
                myType = prop.PropertyType;
            }

            if (!nullable)
            {
                switch (Type.GetTypeCode(myType))
                {
                case TypeCode.Boolean:
                    return(GetDynamicFilterResults <bool>(propertyName, comparator, Convert.ToBoolean(value), orderBy, myType));

                case TypeCode.Byte:
                    return(GetDynamicFilterResults <byte>(propertyName, comparator, Convert.ToByte(value), orderBy, myType));

                case TypeCode.Char:
                    return(GetDynamicFilterResults <char>(propertyName, comparator, Convert.ToChar(value), orderBy, myType));

                case TypeCode.DateTime:
                    return(GetDynamicFilterResults <DateTime>(propertyName, comparator, Convert.ToDateTime(value), orderBy, myType));

                case TypeCode.Decimal:
                    return(GetDynamicFilterResults <Decimal>(propertyName, comparator, Convert.ToDecimal(value), orderBy, myType));

                case TypeCode.Double:
                    return(GetDynamicFilterResults <double>(propertyName, comparator, Convert.ToDouble(value), orderBy, myType));

                case TypeCode.Int16:
                    return(GetDynamicFilterResults <Int16>(propertyName, comparator, Convert.ToInt16(value), orderBy, myType));

                case TypeCode.Int32:
                    return(GetDynamicFilterResults <Int32>(propertyName, comparator, Convert.ToInt32(value), orderBy, myType));

                case TypeCode.Int64:
                    return(GetDynamicFilterResults <Int64>(propertyName, comparator, Convert.ToInt64(value), orderBy, myType));

                case TypeCode.Single:
                    return(GetDynamicFilterResults <Single>(propertyName, comparator, Convert.ToSingle(value), orderBy, myType));

                case TypeCode.String:
                    return(GetDynamicFilterResults <String>(propertyName, comparator, Convert.ToString(value), orderBy, myType));

                default:
                    throw new Exception("Cannot filter by column " + propertyName + " because of its type");
                }
            }
            else
            {
                switch (Type.GetTypeCode(myType))
                {
                case TypeCode.Boolean:
                    return(GetDynamicFilterResults <System.Nullable <bool> >(propertyName, comparator, Convert.ToBoolean(value), orderBy, myType));

                case TypeCode.Byte:
                    return(GetDynamicFilterResults <System.Nullable <byte> >(propertyName, comparator, Convert.ToByte(value), orderBy, myType));

                case TypeCode.Char:
                    return(GetDynamicFilterResults <System.Nullable <char> >(propertyName, comparator, Convert.ToChar(value), orderBy, myType));

                case TypeCode.DateTime:
                    return(GetDynamicFilterResults <System.Nullable <DateTime> >(propertyName, comparator, Convert.ToDateTime(value), orderBy, myType));

                case TypeCode.Decimal:
                    return(GetDynamicFilterResults <System.Nullable <Decimal> >(propertyName, comparator, Convert.ToDecimal(value), orderBy, myType));

                case TypeCode.Double:
                    return(GetDynamicFilterResults <System.Nullable <double> >(propertyName, comparator, Convert.ToDouble(value), orderBy, myType));

                case TypeCode.Int16:
                    return(GetDynamicFilterResults <System.Nullable <Int16> >(propertyName, comparator, Convert.ToInt16(value), orderBy, myType));

                case TypeCode.Int32:
                    return(GetDynamicFilterResults <System.Nullable <Int32> >(propertyName, comparator, Convert.ToInt32(value), orderBy, myType));

                case TypeCode.Int64:
                    return(GetDynamicFilterResults <System.Nullable <Int64> >(propertyName, comparator, Convert.ToInt64(value), orderBy, myType));

                case TypeCode.Single:
                    return(GetDynamicFilterResults <System.Nullable <Single> >(propertyName, comparator, Convert.ToSingle(value), orderBy, myType));

                case TypeCode.String:
                    return(GetDynamicFilterResults <String>(propertyName, comparator, Convert.ToString(value), orderBy, myType));

                default:
                    throw new Exception("Cannot filter by column " + propertyName + " because of its type");
                }
            }
        }
コード例 #13
0
        private static IQueryable <RollBackDistributionCompanyInfo> SelectDynamicSearch(SearchArgument sArgument, string orderBy)
        {
            int n = sArgument.SearchArguments.Count;
            ParameterExpression e = Expression.Parameter(typeof(RollBackDistributionCompanyInfo), "e");
            Expression <Func <RollBackDistributionCompanyInfo, bool> > lambda = null;
            Expression be = null;
            int        i;

            for (i = 0; i < n; i++)
            {
                string       pField     = sArgument.SearchArguments[i].PropertyField;
                string       comparator = sArgument.SearchArguments[i].Comparator;
                object       fvalue     = sArgument.SearchArguments[i].FValue;
                PropertyInfo prop       = typeof(RollBackDistributionCompanyInfo).GetProperty(pField);
                Type         myType;
                bool         nullable = false;
                if (IsNullableType(prop.PropertyType))
                {
                    NullableConverter nc = new NullableConverter(prop.PropertyType);
                    myType   = nc.UnderlyingType;
                    nullable = true;
                }
                else
                {
                    myType = prop.PropertyType;
                }
                Expression next = null;
                if (!nullable)
                {
                    switch (Type.GetTypeCode(myType))
                    {
                    case TypeCode.Boolean:
                        next = GetDynamicSearchExpression <bool>(pField, comparator, Convert.ToBoolean(fvalue), e, myType);
                        break;

                    case TypeCode.Byte:
                        next = GetDynamicSearchExpression <byte>(pField, comparator, Convert.ToByte(fvalue), e, myType);
                        break;

                    case TypeCode.Char:
                        next = GetDynamicSearchExpression <char>(pField, comparator, Convert.ToChar(fvalue), e, myType);
                        break;

                    case TypeCode.DateTime:
                        next = GetDynamicSearchExpression <DateTime>(pField, comparator, Convert.ToDateTime(fvalue), e, myType);
                        break;

                    case TypeCode.Decimal:
                        next = GetDynamicSearchExpression <Decimal>(pField, comparator, Convert.ToDecimal(fvalue), e, myType);
                        break;

                    case TypeCode.Double:
                        next = GetDynamicSearchExpression <double>(pField, comparator, Convert.ToDouble(fvalue), e, myType);
                        break;

                    case TypeCode.Int16:
                        next = GetDynamicSearchExpression <Int16>(pField, comparator, Convert.ToInt16(fvalue), e, myType);
                        break;

                    case TypeCode.Int32:
                        next = GetDynamicSearchExpression <Int32>(pField, comparator, Convert.ToInt32(fvalue), e, myType);
                        break;

                    case TypeCode.Int64:
                        next = GetDynamicSearchExpression <Int64>(pField, comparator, Convert.ToInt64(fvalue), e, myType);
                        break;

                    case TypeCode.Single:
                        next = GetDynamicSearchExpression <Single>(pField, comparator, Convert.ToSingle(fvalue), e, myType);
                        break;

                    case TypeCode.String:
                        next = GetDynamicSearchExpression <String>(pField, comparator, Convert.ToString(fvalue), e, myType);
                        break;

                    default:
                        throw new Exception("Cannot search by column " + pField + " because of its type");
                    }
                }
                else
                {
                    switch (Type.GetTypeCode(myType))
                    {
                    case TypeCode.Boolean:
                        next = GetDynamicSearchExpression <System.Nullable <bool> >(pField, comparator, Convert.ToBoolean(fvalue), e, myType);
                        break;

                    case TypeCode.Byte:
                        next = GetDynamicSearchExpression <System.Nullable <byte> >(pField, comparator, Convert.ToByte(fvalue), e, myType);
                        break;

                    case TypeCode.Char:
                        next = GetDynamicSearchExpression <System.Nullable <char> >(pField, comparator, Convert.ToChar(fvalue), e, myType);
                        break;

                    case TypeCode.DateTime:
                        next = GetDynamicSearchExpression <System.Nullable <DateTime> >(pField, comparator, Convert.ToDateTime(fvalue), e, myType);
                        break;

                    case TypeCode.Decimal:
                        next = GetDynamicSearchExpression <System.Nullable <Decimal> >(pField, comparator, Convert.ToDecimal(fvalue), e, myType);
                        break;

                    case TypeCode.Double:
                        next = GetDynamicSearchExpression <System.Nullable <double> >(pField, comparator, Convert.ToDouble(fvalue), e, myType);
                        break;

                    case TypeCode.Int16:
                        next = GetDynamicSearchExpression <System.Nullable <Int16> >(pField, comparator, Convert.ToInt16(fvalue), e, myType);
                        break;

                    case TypeCode.Int32:
                        next = GetDynamicSearchExpression <System.Nullable <Int32> >(pField, comparator, Convert.ToInt32(fvalue), e, myType);
                        break;

                    case TypeCode.Int64:
                        next = GetDynamicSearchExpression <System.Nullable <Int64> >(pField, comparator, Convert.ToInt64(fvalue), e, myType);
                        break;

                    case TypeCode.Single:
                        next = GetDynamicSearchExpression <System.Nullable <Single> >(pField, comparator, Convert.ToSingle(fvalue), e, myType);
                        break;

                    case TypeCode.String:
                        next = GetDynamicSearchExpression <String>(pField, comparator, Convert.ToString(fvalue), e, myType);
                        break;

                    default:
                        throw new Exception("Cannot filter by column " + pField + " because of its type");
                    }
                }
                if (i == 0)
                {
                    be = next;
                }
                else
                {
                    be = Expression.And(be, next);
                }
            }
            lambda = Expression.Lambda <Func <RollBackDistributionCompanyInfo, bool> >(be, e);
            return(Select(orderBy).AsQueryable().Where(lambda));
        }
コード例 #14
0
        /// <summary>
        /// Used to perform typed and dynamic order by.
        /// </summary>
        /// <param name="orderBy">The full order by expression, e.g. AuthorName DESC</param>
        private static IQueryable <RollBackDistributionCompanyInfo> SelectDynamicSort(string orderBy)
        {
            // Parse order by
            string orderByColumn    = String.Empty;
            string orderByDirection = "asc";

            ParseOrderBy(orderBy, ref orderByColumn, ref orderByDirection);

            // Get sort results

            PropertyInfo prop = typeof(RollBackDistributionCompanyInfo).GetProperty(orderByColumn);
            Type         myType;
            bool         nullable = false;

            if (IsNullableType(prop.PropertyType))
            {
                NullableConverter nc = new NullableConverter(prop.PropertyType);
                myType   = nc.UnderlyingType;
                nullable = true;
            }
            else
            {
                myType = prop.PropertyType;
            }

            if (!nullable)
            {
                switch (Type.GetTypeCode(myType))
                {
                case TypeCode.Boolean:
                    return(GetDynamicSortResults <bool>(orderByColumn, orderByDirection));

                case TypeCode.Byte:
                    return(GetDynamicSortResults <byte>(orderByColumn, orderByDirection));

                case TypeCode.Char:
                    return(GetDynamicSortResults <char>(orderByColumn, orderByDirection));

                case TypeCode.DateTime:
                    return(GetDynamicSortResults <DateTime>(orderByColumn, orderByDirection));

                case TypeCode.Decimal:
                    return(GetDynamicSortResults <Decimal>(orderByColumn, orderByDirection));

                case TypeCode.Double:
                    return(GetDynamicSortResults <double>(orderByColumn, orderByDirection));

                case TypeCode.Int16:
                    return(GetDynamicSortResults <Int16>(orderByColumn, orderByDirection));

                case TypeCode.Int32:
                    return(GetDynamicSortResults <Int32>(orderByColumn, orderByDirection));

                case TypeCode.Int64:
                    return(GetDynamicSortResults <Int64>(orderByColumn, orderByDirection));

                case TypeCode.Single:
                    return(GetDynamicSortResults <Single>(orderByColumn, orderByDirection));

                case TypeCode.String:
                    return(GetDynamicSortResults <String>(orderByColumn, orderByDirection));

                default:
                    throw new Exception("Cannot sort column " + orderByColumn + " because of its type");
                }
            }
            else
            {
                switch (Type.GetTypeCode(myType))
                {
                case TypeCode.Boolean:
                    return(GetDynamicSortResults <System.Nullable <bool> >(orderByColumn, orderByDirection));

                case TypeCode.Byte:
                    return(GetDynamicSortResults <System.Nullable <byte> >(orderByColumn, orderByDirection));

                case TypeCode.Char:
                    return(GetDynamicSortResults <System.Nullable <char> >(orderByColumn, orderByDirection));

                case TypeCode.DateTime:
                    return(GetDynamicSortResults <System.Nullable <DateTime> >(orderByColumn, orderByDirection));

                case TypeCode.Decimal:
                    return(GetDynamicSortResults <System.Nullable <Decimal> >(orderByColumn, orderByDirection));

                case TypeCode.Double:
                    return(GetDynamicSortResults <System.Nullable <double> >(orderByColumn, orderByDirection));

                case TypeCode.Int16:
                    return(GetDynamicSortResults <System.Nullable <Int16> >(orderByColumn, orderByDirection));

                case TypeCode.Int32:
                    return(GetDynamicSortResults <System.Nullable <Int32> >(orderByColumn, orderByDirection));

                case TypeCode.Int64:
                    return(GetDynamicSortResults <System.Nullable <Int64> >(orderByColumn, orderByDirection));

                case TypeCode.Single:
                    return(GetDynamicSortResults <System.Nullable <Single> >(orderByColumn, orderByDirection));

                case TypeCode.String:
                    return(GetDynamicSortResults <String>(orderByColumn, orderByDirection));

                default:
                    throw new Exception("Cannot sort column " + orderByColumn + " because of its type");
                }
            }
        }
コード例 #15
0
ファイル: DataRowConvert.cs プロジェクト: ciker/TsOrm
        public static Nullable <int> NullableInt(object obj)
        {
            NullableConverter converter = new NullableConverter(typeof(int?));

            return((int?)converter.ConvertFromString(obj.ToString()));
        }
コード例 #16
0
ファイル: ListHelper.cs プロジェクト: hlxaaa/Common
        /// <summary>
        /// 利用反射和泛型
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List <T> ConvertToList <T>(this DataTable dt) where T : class, new()
        {
            // 定义集合
            List <T> ts = new List <T>();
            // 获得此模型的类型
            Type type = typeof(T);
            //定义一个临时变量
            string tempName = string.Empty;

            //遍历DataTable中所有的数据行
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                // 获得此模型的公共属性
                PropertyInfo[] propertys = t.GetType().GetProperties();
                //遍历该对象的所有属性
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;//将属性名称赋值给临时变量
                    //检查DataTable是否包含此列(列名==对象的属性名)
                    if (dt.Columns.Contains(tempName))
                    {
                        // 判断此属性是否有Setter
                        if (!pi.CanWrite)
                        {
                            continue;              //该属性不可写,直接跳出
                        }
                        // 取值
                        object value = dr[tempName];
                        if (value != DBNull.Value)
                        {
                            var type_model = System.Type.GetType(pi.PropertyType.FullName, true);
                            if (type_model.Name.Contains("Nullable"))
                            {
                                //如果convertsionType为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
                                NullableConverter nullableConverter = new NullableConverter(type_model);
                                //将convertsionType转换为nullable对的基础基元类型
                                type_model = nullableConverter.UnderlyingType;
                                object model;
                                if (type_model.BaseType.Name == "Enum")
                                {
                                    model = Enum.Parse(type_model, value.ToString());
                                }
                                else
                                {
                                    model = Convert.ChangeType(value, type_model);
                                }
                                //如果非空,则赋给对象的属性
                                pi.SetValue(t, model, null);
                            }
                            else
                            {
                                object model;
                                if (type_model.BaseType.Name == "Enum")
                                {
                                    model = Enum.Parse(type_model, value.ToString());
                                }
                                else
                                {
                                    model = Convert.ChangeType(value, type_model);
                                }
                                //如果非空,则赋给对象的属性
                                pi.SetValue(t, model, null);
                            }//-txy
                        }
                    }
                }
                //对象添加到泛型集合中
                ts.Add(t);
            }
            return(ts);
        }
コード例 #17
0
ファイル: DataRowConvert.cs プロジェクト: ciker/TsOrm
        public static Nullable <Int64> NullableInt64(object obj)
        {
            NullableConverter converter = new NullableConverter(typeof(Int64?));

            return((Int64?)converter.ConvertFromString(obj.ToString()));
        }
コード例 #18
0
ファイル: GenericExtension.cs プロジェクト: palzj/pure.ext
    /// <summary>
    /// 转换到指定类型值
    /// </summary>
    /// <param name="value"></param>
    /// <param name="conversionType"></param>
    /// <param name="defaultValue"></param>
    /// <returns></returns>
    public static object ToType(this object value, Type conversionType, object defaultValue = null)
    {
        Guard.ArgumentNull(conversionType, "conversionType", null);
        if (value.IsNullOrEmpty())
        {
            if (!conversionType.IsNullableType() && (defaultValue == null))
            {
                return(conversionType.GetDefaultValue());
            }
            return(null);
        }
        if (value.GetType() == conversionType)
        {
            return(value);
        }
        try
        {
            if (conversionType.IsEnum)
            {
                return(Enum.Parse(conversionType, value.ToString(), true));
            }
            if ((conversionType == typeof(bool?)) && (Convert.ToInt32(value) == -1))
            {
                return(null);
            }
            if (conversionType.IsNullableType())
            {
                if (value == null || value.IsNullOrEmpty())
                {
                    return(null);
                }

                //如果convertsionType为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
                NullableConverter nullableConverter = new NullableConverter(conversionType);
                //将convertsionType转换为nullable对的基础基元类型
                conversionType = nullableConverter.UnderlyingType;

                return(value == null?Activator.CreateInstance(conversionType) : Convert.ChangeType(value, conversionType));
            }
            if (conversionType == typeof(bool))
            {
                if (value is string)
                {
                    string str = ((string)value).ToLower();
                    return((((str == "true") || (str == "t")) || ((str == "1") || (str == "yes"))) ? ((object)1) : ((object)(str == "on")));
                }
                return(Convert.ToInt32(value) == 1);
            }
            if (value is bool)
            {
                if (conversionType == typeof(string))
                {
                    return(Convert.ToBoolean(value) ? "true" : "false");
                }
                return(Convert.ToBoolean(value) ? 1 : 0);
            }
            if (conversionType == typeof(Type))
            {
                return(Type.GetType(value.ToString(), false, true));
            }
            if ((value is Type) && (conversionType == typeof(string)))
            {
                return(((Type)value).FullName);
            }
            if (typeof(IConvertible).IsAssignableFrom(conversionType))
            {
                return(Convert.ChangeType(value, conversionType, null));
            }
            return(value);
        }
        catch (Exception)
        {
            return(defaultValue);
        }
    }
コード例 #19
0
 public NullableConverterImpl(NullableConverter nullableConverter)
 {
     _nullableConverter = nullableConverter;
 }
コード例 #20
0
        static Type GetNullableUnderlyingType(Type nullableType)
        {
            NullableConverter nc = new NullableConverter(nullableType);

            return(nc.UnderlyingType);
        }
コード例 #21
0
        public IEnumerable <T> Filter(out int total)
        {
            if (Entity == null)
            {
                total = 0;
                return(null);
            }
            if (NeedDataSourceEventArgs == null)
            {
                total = finalResult.Count();
                return(finalResult);
            }
            var filterArgs = NeedDataSourceEventArgs.filter;
            var filters    = filterArgs != null && filterArgs.filters != null ? filterArgs.filters : new List <descriptor>();

            foreach (var desc in filters)
            {
                #region get dynamic
                Func <T, bool> filter = e =>
                {
                    var type     = typeof(T);
                    var property = type.GetProperty(desc.field);
                    var propType = property.PropertyType;

                    if (propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(Nullable <>))
                    {
                        //Get the underlying type property instead of the nullable generic
                        propType = new NullableConverter(propType).UnderlyingType;
                    }

                    var val1 = Convert.ChangeType(property.GetValue(e), propType);
                    var val2 = Convert.ChangeType(desc.value, propType);

                    Double x1, x2;
                    int    comparisonResult;
                    switch (desc.@operator)
                    {
                    case Operator.neq:
                        if (TryDateCompare(val1, val2, out comparisonResult))
                        {
                            return(comparisonResult != 0);
                        }

                        return(!val2.Equals(val1));

                    case Operator.gt:
                        if (TryDateCompare(val1, val2, out comparisonResult))
                        {
                            return(comparisonResult > 0);
                        }


                        x1 = Convert.ToDouble(val1);
                        x2 = Convert.ToDouble(val2);
                        return(x1 > x2);

                    case Operator.gte:
                        if (TryDateCompare(val1, val2, out comparisonResult))
                        {
                            return(comparisonResult >= 0);
                        }

                        x1 = Convert.ToDouble(val1);
                        x2 = Convert.ToDouble(val2);
                        return(x1 >= x2);

                    case Operator.lt:
                        if (TryDateCompare(val1, val2, out comparisonResult))
                        {
                            return(comparisonResult < 0);
                        }
                        x1 = Convert.ToDouble(val1);
                        x2 = Convert.ToDouble(val2);
                        return(x1 < x2);

                    case Operator.lte:
                        if (TryDateCompare(val1, val2, out comparisonResult))
                        {
                            return(comparisonResult <= 0);
                        }
                        x1 = Convert.ToDouble(val1);
                        x2 = Convert.ToDouble(val2);
                        return(x1 <= x2);

                    case Operator.startswith:
                        return(val1.ToString().StartsWith(val2.ToString(), StringComparison.OrdinalIgnoreCase));

                    case Operator.contains:
                        var index = CultureInfo.InvariantCulture.CompareInfo.IndexOf(val1.ToString(),
                                                                                     val2.ToString(), CompareOptions.IgnoreCase);
                        return(index >= 0);

                    case Operator.endswith:
                        return(val1.ToString().EndsWith(val2.ToString(), StringComparison.OrdinalIgnoreCase));

                    case Operator.doesnotcontain:
                        var index2 = CultureInfo.InvariantCulture.CompareInfo
                                     .IndexOf(val1.ToString(), val2.ToString(), CompareOptions.IgnoreCase);
                        return(index2 < 0);

                    default:
                        if (TryDateCompare(val1, val2, out comparisonResult))
                        {
                            return(comparisonResult == 0);
                        }

                        return(val2.Equals(val1));
                    }
                };

                #endregion

                var recordSet = finalResult.Where(filter);
                finalResult = recordSet as IList <T> ?? recordSet.ToList();
            }
            total = finalResult.Count();

            try
            {
                finalResult = Sort(finalResult);
                finalResult = finalResult.Skip(NeedDataSourceEventArgs.skip).Take(NeedDataSourceEventArgs.take);
            }
            catch (Exception) { }
            return(finalResult.AsEnumerable());
        }
コード例 #22
0
        public static SqlDbType ConvertTypeToSqlDbType(Type t)
        {
            //判断convertsionType类型是否为泛型,因为nullable是泛型类,
            //判断convertsionType是否为nullable泛型类
            if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
            {
                //如果convertsionType为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
                NullableConverter nullableConverter = new NullableConverter(t);
                //将convertsionType转换为nullable对的基础基元类型
                t = nullableConverter.UnderlyingType;
            }
            var code = Type.GetTypeCode(t);


            switch (code)
            {
            case TypeCode.Boolean:
                return(SqlDbType.Bit);

            case TypeCode.Byte:
                return(SqlDbType.TinyInt);

            case TypeCode.DateTime:
                return(SqlDbType.NVarChar);

            //case TypeCode.DateTime:
            //    return SqlDbType.DateTime2;
            case TypeCode.Decimal:
                return(SqlDbType.Decimal);

            case TypeCode.Double:
                return(SqlDbType.Float);

            case TypeCode.Int16:
                return(SqlDbType.SmallInt);

            case TypeCode.Int32:
                return(SqlDbType.Int);

            case TypeCode.Int64:
                return(SqlDbType.BigInt);

            case TypeCode.SByte:
                return(SqlDbType.TinyInt);

            case TypeCode.Single:
                return(SqlDbType.Real);

            case TypeCode.String:
                return(SqlDbType.NVarChar);

            case TypeCode.UInt16:
                return(SqlDbType.SmallInt);

            case TypeCode.UInt32:
                return(SqlDbType.Int);

            case TypeCode.UInt64:
                return(SqlDbType.BigInt);

            case TypeCode.Object:
                return(SqlDbType.Variant);

            default:
                if (t == typeof(byte[]))
                {
                    return(SqlDbType.Binary);
                }
                return(SqlDbType.Variant);
            }
        }
コード例 #23
0
        /// <summary>
        /// DataTable转DTO列表
        /// </summary>
        /// <typeparam name="TTarget"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public IList <TTarget> Adapt <TTarget>(DataTable dt) where TTarget : class, new()
        {
            // 定义集合
            IList <TTarget> ts       = new List <TTarget>();
            string          tempName = "";

            if (dt == null)
            {
                return(ts);
            }
            foreach (DataRow dr in dt.Rows)
            {
                var t = new TTarget();
                // 获得此模型的公共属性
                PropertyInfo[] propertys = t.GetType().GetProperties();
                string         logName   = t.GetType().Name;
                foreach (PropertyInfo pi in propertys)
                {
                    if (!pi.PropertyType.IsValueType && pi.PropertyType.Name != "String")
                    {
                        continue;
                    }

                    tempName = pi.Name;
                    // 检查DataTable是否包含此列
                    if (dt.Columns.Contains(tempName))
                    {
                        // 判断此属性是否有Setter
                        if (!pi.CanWrite)
                        {
                            continue;
                        }

                        object value = dr[tempName];
                        if (value != DBNull.Value)
                        {
                            Type propType = pi.PropertyType;
                            if (propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(Nullable <>))
                            {
                                NullableConverter nullableConverter = new NullableConverter(propType);
                                propType = nullableConverter.UnderlyingType;
                            }

                            if (propType == typeof(Guid))
                            {
                                Guid gid = new Guid(value.ToString());
                                pi.SetValue(t, gid, null);
                            }
                            else if (propType.IsEnum)
                            {
                                pi.SetValue(t, Convert.ToInt32(value), null);
                            }
                            else
                            {
                                pi.SetValue(t, Convert.ChangeType(value, propType), null);
                            }
                        }
                    }
                }
                ts.Add(t);
            }
            return(ts);
        }
コード例 #24
0
ファイル: SpproRepository.cs プロジェクト: t9mike/SpproEntity
        /// <summary>
        /// Populate SharePoint Entity using Reflection
        /// Convert retreived data in NSW Eastern Standard Time.
        /// for QLD Standard time use "E. Australia Standard Time"
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        internal async Task <T> PopulateSEntity(ListItem item)
        {
            var entity = CreateInstance();

            entity.ID = item.Id;
            foreach (var field in item.FieldValues)
            {
                try
                {
                    var property = SpNameUtility.GetProperty(field.Key, typeof(T)); //typeof(T).GetProperty(SpNameUtility.GetPropertyName(field.Key, typeof(T)));
                    if (property != null)
                    {
                        var customAttributes = property.GetCustomAttributes(typeof(SpproNavigationAttribute), true);
                        if (!(customAttributes.Length > 0 && ((SpproNavigationAttribute)customAttributes[0]).NavigationProperty))
                        {
                            var targetType = property.PropertyType;
                            //Nullable properties have to be treated differently, since we
                            //  use their underlying property to set the value in the object
                            if (targetType.IsGenericType &&
                                targetType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                            {
                                //if it's null, just set the value from the reserved word null, and return
                                if (field.Value == null)
                                {
                                    property.SetValue(entity, null, null);
                                    continue;
                                }

                                //Get the underlying type property instead of the nullable generic
                                targetType = new NullableConverter(property.PropertyType).UnderlyingType;
                            }
                            customAttributes = property.GetCustomAttributes(typeof(SpproFieldAttribute), true);
                            if (customAttributes.Length > 0 && !string.IsNullOrWhiteSpace(((SpproFieldAttribute)customAttributes[0]).FieldType))
                            {
                                var attribute = (SpproFieldAttribute)customAttributes[0];
                                switch (attribute.FieldType)
                                {
                                case "File":
                                    #region File Type
                                    Microsoft.SharePoint.Client.File file = item.File;
                                    SpproFile spproFile  = new SpproFile();
                                    var       fileStream = file.OpenBinaryStream();
                                    ClientContext.Load(file);
                                    ClientContext.ExecuteQuery();
                                    using (var ms = new MemoryStream())
                                    {
                                        fileStream.Value.CopyTo(ms);
                                        spproFile.Content  = ms.ToArray();
                                        spproFile.FileName = item.File.Name;
                                        property.SetValue(entity, spproFile);
                                    }
                                    #endregion
                                    break;

                                case "Lookup":
                                    #region Lookup Type
                                    if (field.Value != null && !(IsObjectFalsy(field.Value)))
                                    {
                                        dynamic value;
                                        switch (attribute.FieldValue)
                                        {
                                        case "IdAndValue":
                                            property.SetValue(entity, field.Value);
                                            break;

                                        case "Value":
                                            value = ((FieldLookupValue)field.Value).LookupId;
                                            property.SetValue(entity, value);
                                            break;

                                        case "Id":
                                        case null:
                                            if (field.Value == null || field.Value.ToString() == "")
                                            {
                                                property.SetValue(entity, 0);
                                            }
                                            else
                                            {
                                                value = ((FieldLookupValue)field.Value).LookupId;
                                                property.SetValue(entity, value);
                                            }
                                            break;
                                        }
                                    }
                                    #endregion
                                    break;

                                case "User":
                                    #region User Type
                                    if (field.Value != null)
                                    {
                                        dynamic value;
                                        switch (attribute.FieldValue)
                                        {
                                        case "Value":
                                            if (field.Value is FieldUserValue[])
                                            {
                                                value = ((FieldUserValue[])field.Value).Select(a => a.LookupValue).ToList();
                                            }
                                            else
                                            {
                                                value = ((FieldUserValue)field.Value).LookupValue;
                                            }
                                            property.SetValue(entity, value);
                                            break;

                                        case "IdAndValue":
                                            property.SetValue(entity, field.Value);
                                            break;

                                        default:
                                        case "Id":
                                        case null:
                                            if (field.Value is FieldUserValue[])
                                            {
                                                value = ((FieldUserValue[])field.Value).Select(a => a.LookupId).ToList();
                                                property.SetValue(entity, value);
                                            }
                                            else
                                            {
                                                value = ((FieldUserValue)field.Value).LookupId;
                                                property.SetValue(entity, value);
                                            }
                                            break;
                                        }
                                    }
                                    #endregion
                                    break;

                                case "Multi-Choice":
                                    property.SetValue(entity, (string[])field.Value);
                                    break;
                                }
                            }
                            else
                            {
                                //Deal with null SP Columns
                                if (TypeUtility.IsNumeric(targetType) && field.Value == null)
                                {
                                    property.SetValue(entity, Convert.ChangeType(0, targetType));
                                }
                                else
                                {
                                    //Handle unusal object types (ie GeoCoordinate = FieldGeolocation)
                                    switch (targetType.Name)
                                    {
                                    case "GeoCoordinate":
                                        if (field.Value != null)
                                        {
                                            GeoCoordinate GeoValue = new GeoCoordinate();
                                            GeoValue.Longitude = ((FieldGeolocationValue)field.Value).Longitude;
                                            GeoValue.Latitude  = ((FieldGeolocationValue)field.Value).Latitude;
                                            GeoValue.Altitude  = 0;
                                            property.SetValue(entity, GeoValue);
                                        }
                                        break;

                                    case "Boolean":
                                        if (field.Value == null)
                                        {
                                            property.SetValue(entity, false);
                                        }
                                        else
                                        {
                                            property.SetValue(entity, field.Value.ToString().ToLower() == "yes" || field.Value.ToString().ToLower() == "true");
                                        }
                                        break;

                                    case "DateTime":
                                    case "DateTime?":
                                        //DateTime localTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId((DateTime)field.Value, timeZone);
                                        var dateValue = new DateTime();
                                        if (DateTime.TryParse(field.Value.ToString(), out dateValue))
                                        {
                                            property.SetValue(entity, dateValue);
                                        }
                                        break;

                                    default:
                                        property.SetValue(entity, Convert.ChangeType(field.Value, targetType));
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Error with " + field, ex);
                }
            }

            //Populate Navigation Properties
            //Beware this requries calls to SharePoint via ClientContext and too many may slow down application
            if (LazyLoading)
            {
                foreach (var property in entity.GetType().GetProperties())
                {
                    var customAttributes = property.GetCustomAttributes(typeof(SpproNavigationAttribute), true);
                    if (customAttributes.Length > 0 && ((SpproNavigationAttribute)customAttributes[0]).NavigationProperty)
                    {
                        var foriegnKey = ((SpproNavigationAttribute)customAttributes[0]).LookupField;

                        var genericType         = property.PropertyType.GetGenericArguments()[0];
                        var repo                = typeof(SpproRepository <>);
                        var constructedRepoType = repo.MakeGenericType(genericType);
                        var listName            = genericType.Name;
                        var genericAttributes   = genericType.GetCustomAttributes(typeof(SpproListAttribute), true);
                        if (genericAttributes.Length > 0 && !string.IsNullOrWhiteSpace(((SpproListAttribute)genericAttributes[0]).ListName))
                        {
                            listName = ((SpproListAttribute)genericAttributes[0]).ListName;
                        }
                        dynamic repoInstance = Activator.CreateInstance(constructedRepoType, listName, ClientContext);
                        var     values       = await repoInstance.Query(string.Format("{0}={1}", foriegnKey, entity.ID));

                        property.SetValue(entity, values);
                    }
                    else if (customAttributes.Length > 0 && ((SpproNavigationAttribute)customAttributes[0]).ForeignKey)
                    {
                        var foriegnKey = ((SpproNavigationAttribute)customAttributes[0]).LookupField;
                        try
                        {
                            var foriegnId = Convert.ToInt32(((FieldLookupValue)item.FieldValues[foriegnKey]).LookupId);
                            if (foriegnId > 0)
                            {
                                var repo = typeof(SpproRepository <>);
                                var constructedRepoType = repo.MakeGenericType(property.PropertyType);
                                var listName            = property.PropertyType.Name;
                                var propertyAttributes  = property.PropertyType.GetCustomAttributes(typeof(SpproListAttribute), true);
                                if (propertyAttributes.Length > 0 && !string.IsNullOrWhiteSpace(((SpproListAttribute)propertyAttributes[0]).ListName))
                                {
                                    listName = ((SpproListAttribute)propertyAttributes[0]).ListName;
                                }
                                dynamic repoInstance = Activator.CreateInstance(constructedRepoType, listName, ClientContext);
                                var     values       = await repoInstance.GetById(foriegnId);

                                property.SetValue(entity, values);
                            }
                        }
                        catch (Exception ex)
                        {
                            log.Error("Error with lazy loading foriegn key", ex);
                        }
                    }
                }
            }

            return(entity);
        }
コード例 #25
0
        public object ChanageType(object pValue, Type pConvertsionType)
        {
            var iEnumerableType = typeof(IEnumerable);
            var isMultiValue    =
                (
                    pValue.GetType().IsArray ||
                    iEnumerableType.IsAssignableFrom(pValue.GetType())
                ) && pValue.GetType() != typeof(string);

            if (iEnumerableType.IsAssignableFrom(pConvertsionType) && pConvertsionType != typeof(string))
            {
                if (pConvertsionType.IsArray)
                {
                    var resultObj = new ArrayList();
                    var underType = pConvertsionType.GetElementType();
                    if (isMultiValue)
                    {
                        var iEnumerableValue = (IEnumerable)pValue;

                        foreach (var itemValue in iEnumerableValue)
                        {
                            object realValue = null;
                            try
                            {
                                realValue = ChanageType(itemValue, underType);
                            }
                            catch { }
                            if (realValue == null)
                            {
                                continue;
                            }
                            resultObj.Add(realValue);
                        }
                    }
                    else
                    {
                        object realValue = null;
                        try
                        {
                            realValue = ChanageType(pValue, underType);
                        }
                        catch { }
                        if (realValue != null)
                        {
                            resultObj.Add(realValue);
                        }
                    }
                    return(resultObj.ToArray(underType));
                }
                else
                {
                    var        resultObj  = Activator.CreateInstance(pConvertsionType);
                    var        resultType = resultObj.GetType();
                    MethodInfo resultAddMethod;
                    var        underType = typeof(object);
                    if (pConvertsionType.IsGenericType)
                    {
                        underType = pConvertsionType.GetGenericArguments()[0];
                    }
                    resultAddMethod = resultType.GetMethod("Add");

                    if (isMultiValue)
                    {
                        var iEnumerableValue = (IEnumerable)pValue;
                        var i = 0;
                        foreach (var itemValue in iEnumerableValue)
                        {
                            object realValue = null;
                            try
                            {
                                realValue = ChanageType(itemValue, underType);
                            }
                            catch { }
                            if (realValue == null)
                            {
                                continue;
                            }
                            resultAddMethod.Invoke(resultObj, new object[] { realValue });
                            i++;
                        }
                    }
                    else
                    {
                        object realValue = null;
                        try
                        {
                            realValue = ChanageType(pValue, underType);
                        }
                        catch { }
                        if (realValue != null)
                        {
                            resultAddMethod.Invoke(resultObj, new object[] { realValue });
                        }
                    }
                    return(resultObj);
                }
            }
            //判断convertsionType类型是否为泛型,因为nullable是泛型类,
            if (pConvertsionType.IsGenericType &&
                //判断convertsionType是否为nullable泛型类
                pConvertsionType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
            {
                if (pValue == null || pValue.ToString().Length == 0)
                {
                    return(null);
                }

                //如果convertsionType为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
                NullableConverter nullableConverter = new NullableConverter(pConvertsionType);
                //将convertsionType转换为nullable对的基础基元类型
                pConvertsionType = nullableConverter.UnderlyingType;
            }
            if (pConvertsionType == typeof(Guid) && pValue is string)
            {
                var newValue = new Guid(pValue.ToString());
                return(newValue);
            }
            return(Convert.ChangeType(pValue, pConvertsionType));
        }
コード例 #26
0
ファイル: formatter.cs プロジェクト: xuweijinjin/winforms
        /// <devdoc>
        /// Extract the inner type converter from a nullable type converter
        /// </devdoc>
        private static TypeConverter NullableUnwrap(TypeConverter typeConverter)
        {
            NullableConverter nullableConverter = typeConverter as NullableConverter;

            return((nullableConverter != null) ? nullableConverter.UnderlyingTypeConverter : typeConverter);
        }
コード例 #27
0
        /// <summary>
        /// Cria uma nova instância de expressão lambda, substituindo o valor "template" com um valor atualizado
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Expression <Func <TEntity, bool> > ModifyExpression <TEntity>(Expression <Func <TEntity, object> > expression, object value)
        {
            var lambda        = (LambdaExpression)expression;
            var parameterExpr = lambda.Parameters[0];

            switch (lambda.Body.NodeType)
            {
            case ExpressionType.Equal:    // x => x.Id == 1
            {
                var binary    = (BinaryExpression)lambda.Body;
                var left      = binary.Left;
                var member    = (MemberExpression)left;
                var type      = member.Type;
                var right     = Expression.Constant(Convert.ChangeType(value, type));
                var newBinary = Expression.MakeBinary(ExpressionType.Equal, left, right);

                return(Expression.Lambda <Func <TEntity, bool> >(newBinary, parameterExpr));
            }

            case ExpressionType.Call:     // x => x.Nome.Contains("value")
            {
                var call = (MethodCallExpression)lambda.Body;
                var type = call.Arguments[0].Type;
                var arg  = Expression.Constant(Convert.ChangeType(value, type));

                var newCall = Expression.Call(call.Object, call.Method, new Expression[] { arg });
                return(Expression.Lambda <Func <TEntity, bool> >(newCall, parameterExpr));
            }

            case ExpressionType.Convert:     //x => x.Id
            {
                var unary   = (UnaryExpression)lambda.Body;
                var operand = unary.Operand;

                if (operand is MethodCallExpression)
                {
                    var call = (MethodCallExpression)operand;
                    var type = call.Arguments[0].Type;
                    var arg  = Expression.Constant(Convert.ChangeType(value, type));

                    var newCall = Expression.Call(call.Object, call.Method, new Expression[] { arg });
                    return(Expression.Lambda <Func <TEntity, bool> >(newCall, parameterExpr));
                }
                else
                {
                    var member = (MemberExpression)operand;

                    var nonNullableType = Nullable.GetUnderlyingType(member.Type);

                    object convertedValue;

                    if (nonNullableType != null)
                    {
                        var converter = new NullableConverter(member.Type);
                        convertedValue = Convert.ChangeType(value, converter.UnderlyingType);
                    }
                    else
                    {
                        convertedValue = Convert.ChangeType(value, member.Type);
                    }

                    var right     = Expression.Constant(convertedValue, member.Type);
                    var newBinary = Expression.MakeBinary(ExpressionType.Equal, operand, right);

                    return(Expression.Lambda <Func <TEntity, bool> >(newBinary, parameterExpr));
                }
            }

            case ExpressionType.MemberAccess:     // x => x.Status
            {
                var unary     = (UnaryExpression)lambda.Body;
                var operand   = unary.Operand;
                var member    = (MemberExpression)operand;
                var type      = member.Type;
                var right     = Expression.Constant(Convert.ChangeType(value, type));
                var newBinary = Expression.MakeBinary(ExpressionType.Equal, operand, right);

                return(Expression.Lambda <Func <TEntity, bool> >(newBinary, parameterExpr));
            }
            }

            return(null);
        }
        protected int Compare(T left, T right)
        {
            if (left is IComparable <T> comparable)
            {
                return(comparable.CompareTo(right));
            }
            if (Equals(left, right))
            {
                return(0);
            }
            if (ReferenceEquals(left, null))
            {
                return(-1);
            }
            if (ReferenceEquals(right, null))
            {
                return(1);
            }

            return((int)Comparer.Invoke(NullableConverter.ConvertTo(left, RawType), new[] { NullableConverter.ConvertTo(right, RawType) }));
        }
コード例 #29
0
        /// <summary>
        /// Returns an Object with the specified Type and whose value is equivalent to the specified object.
        /// </summary>
        /// <param name="value">An Object that implements the IConvertible interface.</param>
        /// <param name="conversionType">The Type to which value is to be converted.</param>
        /// <returns>An object whose Type is <paramref name="conversionType"/> (or conversionType's underlying type if conversionType
        /// is Nullable&lt;&gt;) and whose value is equivalent to <paramref name="value"/>. -or- a null reference, if value is a null
        /// reference and conversionType is not a value type.</returns>
        /// <remarks>
        /// This method exists as a workaround to System.Convert.ChangeType(Object, Type) which does not handle
        /// nullables as of version 2.0 (2.0.50727.42) of the .NET Framework. The idea is that this method will
        /// be deleted once Convert.ChangeType is updated in a future version of the .NET Framework to handle
        /// nullable types, so we want this to behave as closely to Convert.ChangeType as possible.
        /// This method was written by Peter Johnson at:
        /// http://aspalliance.com/author.aspx?uId=1026.
        ///
        /// Origianal source http://aspalliance.com/852
        ///
        /// </remarks>
        public static object ChangeType(object value, Type conversionType)
        {
            // Note: This if block was taken from Convert.ChangeType as is, and is needed here since we're
            // checking properties on conversionType below.
            if (conversionType == null)
            {
                throw new ArgumentNullException("conversionType");
            } // end if

            // If it's not a nullable type, just pass through the parameters to Convert.ChangeType

            if (conversionType.IsGenericType &&
                conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
            {
                // It's a nullable type, so instead of calling Convert.ChangeType directly which would throw a
                // InvalidCastException (per http://weblogs.asp.net/pjohnson/archive/2006/02/07/437631.aspx),
                // determine what the underlying type is
                // If it's null, it won't convert to the underlying type, but that's fine since nulls don't really
                // have a type--so just return null
                // Note: We only do this check if we're converting to a nullable type, since doing it outside
                // would diverge from Convert.ChangeType's behavior, which throws an InvalidCastException if
                // value is null and conversionType is a value type.
                if (value == null)
                {
                    return(null);
                } // end if

#if SILVERLIGHT
                conversionType = Nullable.GetUnderlyingType(conversionType);
#else
                // It's a nullable type, and not null, so that means it can be converted to its underlying type,
                // so overwrite the passed-in conversion type with this underlying type
                var nullableConverter = new NullableConverter(conversionType);
                conversionType = nullableConverter.UnderlyingType;
#endif
            } // end if


            if (value != null && value.GetType() == conversionType)
            {
                return(value);
            }

            if (value is string && conversionType == typeof(Guid))
            {
                return(new Guid(value as string));
            }

            if (value is Date && conversionType == typeof(DateTime))
            {
                return(new DateTime(((Date)value).Year, ((Date)value).Month, ((Date)value).Day));
            }

            if (value is DateTime && conversionType == typeof(Date))
            {
                var dateTime = (DateTime)value;
                return(DateTime.MinValue.Equals(dateTime)
                           ? (Date)null
                           : new Date(dateTime.Year, dateTime.Month, dateTime.Day));
            }


            if (conversionType.IsEnum)
            {
                return(ConvertToEnum(conversionType, value));
            }


#if !SILVERLIGHT
            if (!ReferenceEquals(value, null) && ReflectionUtil.GetTypeOrUnderlyingType(value.GetType()).IsEnum)
            {
                return(ConvertFromEnum(conversionType, value));
            }
#endif

            var convertible = value as IConvertible;
            if (convertible == null)
            {
                if (value != null && conversionType.IsAssignableFrom(value.GetType()))
                {
                    return(value);
                }
            }

            if (value != null && conversionType == typeof(string))
            {
                return(value.ToString());
            }

            // Handle non-text-based boolean variables (e.g. ones and zeroes from bit columns)
            // This is required as the conversion of an object to bool only works with text values, e.g. 'true' or 'false'
            // If it's not a "1" or "0", we'll drop down into the next block of code
            if (value != null && conversionType == typeof(bool))
            {
                switch (value.ToString())
                {
                case "1":
                    return(true);

                case "0":
                    return(false);

                default:
                    break;
                }
            }

            // Now that we've guaranteed conversionType is something Convert.ChangeType can handle (i.e. not a
            // nullable type), pass the call on to Convert.ChangeType
            return(Convert.ChangeType(value, conversionType, null));
        }
コード例 #30
0
        private static object TryParse(this object o, Type targerttype, object defaultvalue)
        {
            if (o.IsNull())
            {
                return(defaultvalue);
            }

            string value = o.ToString();

            if (targerttype.IsGenericType && targerttype.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
            {
                targerttype = new NullableConverter(targerttype).UnderlyingType;
            }

            TypeCode typeCode = Type.GetTypeCode(targerttype);

            switch (typeCode)
            {
            case TypeCode.Boolean:
                Boolean boolean;
                return(Boolean.TryParse(value, out boolean) ? boolean : defaultvalue);

            case TypeCode.Char:
                Char ch;
                return(Char.TryParse(value, out ch) ? ch : defaultvalue);

            case TypeCode.SByte:
                SByte sb;
                return(SByte.TryParse(value, out sb) ? sb : defaultvalue);

            case TypeCode.Byte:
                Byte by;
                return(Byte.TryParse(value, out by) ? by : defaultvalue);

            case TypeCode.Int16:
                Int16 int16;
                return(Int16.TryParse(value, out int16) ? int16 : defaultvalue);

            case TypeCode.UInt16:
                UInt16 uInt16;
                return(UInt16.TryParse(value, out uInt16) ? uInt16 : defaultvalue);

            case TypeCode.Int32:
                Int32 int32;
                return(Int32.TryParse(value, out int32) ? int32 : defaultvalue);

            case TypeCode.UInt32:
                UInt32 uInt32;
                return(UInt32.TryParse(value, out uInt32) ? uInt32 : defaultvalue);

            case TypeCode.Int64:
                Int64 int64;
                return(Int64.TryParse(value, out int64) ? int64 : defaultvalue);

            case TypeCode.UInt64:
                UInt64 uInt64;
                return(UInt64.TryParse(value, out uInt64) ? uInt64 : defaultvalue);

            case TypeCode.Single:
                Single single;
                return(Single.TryParse(value, out single) ? single : defaultvalue);

            case TypeCode.Double:
                Double dou;
                return(Double.TryParse(value, out dou) ? dou : defaultvalue);

            case TypeCode.Decimal:
                Decimal de;
                return(Decimal.TryParse(value, out de) ? de : defaultvalue);

            case TypeCode.DateTime:
                DateTime dt;
                return(DateTime.TryParse(value, out dt) ? dt : defaultvalue);
            }
            if (targerttype.Equals(typeof(Guid)))
            {
                Guid guid;
                return(Guid.TryParse(value, out guid) ? guid : defaultvalue);
            }
            if (targerttype.Equals(typeof(TimeSpan)))
            {
                TimeSpan ts;
                return(TimeSpan.TryParse(value, out ts) ? ts : defaultvalue);
            }
            return(defaultvalue);
        }
コード例 #31
0
ファイル: XsdType.cs プロジェクト: pvginkel/ProtoVariant
        public static XsdType FindConverter(Type type)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            var actualType = Nullable.GetUnderlyingType(type) ?? type;
            bool isNullable = !type.IsInterface && !type.IsClass && IsNullable(type);

            XsdType result;

            if (actualType.IsEnum)
            {
                lock (_syncRoot)
                {
                    EnumConverter enumConverter;

                    if (!EnumConverters.TryGetValue(actualType, out enumConverter))
                    {
                        enumConverter = new EnumConverter(actualType);

                        EnumConverters.Add(actualType, enumConverter);
                    }

                    result = enumConverter;
                }
            }
            else
            {
                _convertersByType.TryGetValue(actualType, out result);
            }

            if (result != null && isNullable)
                result = new NullableConverter(actualType, result);

            return result;
        }