System.Nullable.GetUnderlyingType(System.Type)

Here are the examples of the csharp api System.Nullable.GetUnderlyingType(System.Type) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1137 Examples 7

19 Source : EntityMapperProvider.cs
with Apache License 2.0
from 1448376744

public MethodInfo FindConvertMethod(Type csharpType, Type dbType)
        {
            if (GetUnderlyingType(dbType) == typeof(bool) || GetUnderlyingType(csharpType) == typeof(bool))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToBooleanMethod : MemberMapperMethod.ToBooleanNullableMethod;
            }
            if (GetUnderlyingType(csharpType).IsEnum)
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToEnumMethod.MakeGenericMethod(csharpType) : MemberMapperMethod.ToEnumNullableMethod.MakeGenericMethod(GetUnderlyingType(csharpType));
            }
            if (GetUnderlyingType(dbType) == typeof(char) || GetUnderlyingType(csharpType) == typeof(char))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToCharMethod : MemberMapperMethod.ToCharNullableMethod;
            }
            if (csharpType == typeof(string))
            {
                return MemberMapperMethod.ToStringMethod;
            }
            if (GetUnderlyingType(dbType) == typeof(Guid) || GetUnderlyingType(csharpType) == typeof(Guid))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToGuidMethod : MemberMapperMethod.ToGuidNullableMethod;
            }
            if (GetUnderlyingType(dbType) == typeof(DateTime) || GetUnderlyingType(csharpType) == typeof(DateTime))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToDateTimeMethod : MemberMapperMethod.ToDateTimeNullableMethod;
            }
            if (GetUnderlyingType(dbType) == typeof(byte) || GetUnderlyingType(dbType) == typeof(sbyte) || GetUnderlyingType(csharpType) == typeof(byte) || GetUnderlyingType(csharpType) == typeof(sbyte))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToByteMethod : MemberMapperMethod.ToByteNullableMethod;
            }
            if (GetUnderlyingType(dbType) == typeof(short) || GetUnderlyingType(dbType) == typeof(ushort) || GetUnderlyingType(csharpType) == typeof(short) || GetUnderlyingType(csharpType) == typeof(ushort))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToIn16Method : MemberMapperMethod.ToIn16NullableMethod;
            }
            if (GetUnderlyingType(dbType) == typeof(int) || GetUnderlyingType(dbType) == typeof(uint) || GetUnderlyingType(csharpType) == typeof(int) || GetUnderlyingType(csharpType) == typeof(uint))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToIn32Method : MemberMapperMethod.ToIn32NullableMethod;
            }
            if (GetUnderlyingType(dbType) == typeof(long) || GetUnderlyingType(dbType) == typeof(long) || GetUnderlyingType(csharpType) == typeof(long) || GetUnderlyingType(csharpType) == typeof(ulong))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToIn64Method : MemberMapperMethod.ToIn64NullableMethod;
            }
            if (GetUnderlyingType(dbType) == typeof(float) || GetUnderlyingType(csharpType) == typeof(float))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToFloatMethod : MemberMapperMethod.ToFloatNullableMethod;
            }
            if (GetUnderlyingType(dbType) == typeof(double) || GetUnderlyingType(csharpType) == typeof(double))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToDoubleMethod : MemberMapperMethod.ToDoubleNullableMethod;
            }
            if (GetUnderlyingType(dbType) == typeof(decimal) || GetUnderlyingType(csharpType) == typeof(decimal))
            {
                return !IsNullableType(csharpType) ? MemberMapperMethod.ToDecimalMethod : MemberMapperMethod.ToDecimalNullableMethod;
            }
            return !IsNullableType(csharpType) ? MemberMapperMethod.ToObjectMethod.MakeGenericMethod(csharpType) : MemberMapperMethod.ToObjectNullableMethod.MakeGenericMethod(Nullable.GetUnderlyingType(GetUnderlyingType(csharpType)));
        }

19 Source : EntityMapperProvider.cs
with Apache License 2.0
from 1448376744

private Type GetUnderlyingType(Type type)
        {
            var underlyingType = Nullable.GetUnderlyingType(type);
            return underlyingType ?? type;
        }

19 Source : EntityMapperProvider.cs
with Apache License 2.0
from 1448376744

private bool IsNullableType(Type type)
        {
            if (type.IsValueType && Nullable.GetUnderlyingType(type) == null)
            {
                return false;
            }
            return true;
        }

19 Source : DbQuery.cs
with Apache License 2.0
from 1448376744

private string ResovleBatchInsert(IEnumerable<T> enreplacedys)
        {
            var table = GetTableMetaInfo().TableName;
            var filters = new GroupExpressionResovle(_filterExpression).Resovle().Split(',');
            var columns = GetColumnMetaInfos()
                .Where(a => !a.IsComplexType).ToList();
            var intcolumns = columns
                .Where(a => !filters.Contains(a.ColumnName) && !a.IsNotMapped && !a.IsIdenreplacedy)
                .ToList();
            var columnNames = string.Join(",", intcolumns.Select(s => s.ColumnName));
            if (_context.DbContextType == DbContextType.Mysql)
            {
                var buffer = new StringBuilder();
                buffer.Append($"INSERT INTO {table}({columnNames}) VALUES ");
                var serializer = GlobalSettings.EnreplacedyMapperProvider.GetDeserializer(typeof(T));
                var list = enreplacedys.ToList();
                for (var i = 0; i < list.Count; i++)
                {
                    var item = list[i];
                    var values = serializer(item);
                    buffer.Append("(");
                    for (var j = 0; j < intcolumns.Count; j++)
                    {
                        var column = intcolumns[j];
                        var value = values[column.CsharpName];
                        if (value == null)
                        {
                            buffer.Append(column.IsDefault ? "DEFAULT" : "NULL");
                        }
                        else if (column.CsharpType == typeof(bool) || column.CsharpType == typeof(bool?))
                        {
                            buffer.Append(Convert.ToBoolean(value) == true ? 1 : 0);
                        }
                        else if (column.CsharpType == typeof(DateTime) || column.CsharpType == typeof(DateTime?))
                        {
                            buffer.Append($"'{value}'");
                        }
                        else if (column.CsharpType.IsValueType || (Nullable.GetUnderlyingType(column.CsharpType)?.IsValueType == true))
                        {
                            buffer.Append(value);
                        }
                        else
                        {
                            var str = SqlEncoding(value.ToString());
                            buffer.Append($"'{str}'");
                        }
                        if (j + 1 < intcolumns.Count)
                        {
                            buffer.Append(",");
                        }
                    }
                    buffer.Append(")");
                    if (i + 1 < list.Count)
                    {
                        buffer.Append(",");
                    }
                }
                return buffer.Remove(buffer.Length - 1, 0).ToString();
            }
            throw new NotImplementedException();
        }

19 Source : ExpressionActivator.cs
with Apache License 2.0
from 1448376744

private Expression ResovleConstantExpression(string expression, Type type)
        {
            //生成指定类型的表达式
            if (expression == "null")
            {
                return Expression.Constant(null, type);
            }
            else if (type == typeof(string))
            {
                return Expression.Constant(expression.Trim('\'', '\''), type);
            }
            else
            {
                if (Nullable.GetUnderlyingType(type) == null)
                {
                    var value = Convert.ChangeType(expression, type);
                    return Expression.Constant(value, type);
                }
                else
                {
                    var undertype = Nullable.GetUnderlyingType(type);
                    var value = Convert.ChangeType(expression, undertype);
                    var expr = Expression.Constant(value, undertype);
                    return Expression.MakeUnary(ExpressionType.Convert, expr, type);
                }
            }
        }

19 Source : MySqlDbAdapter.cs
with MIT License
from 17MKH

public override void ResolveColumn(IColumnDescriptor columnDescriptor)
    {
        var propertyType = columnDescriptor.PropertyInfo.PropertyType;
        var isNullable = propertyType.IsNullable();
        if (isNullable)
        {
            propertyType = Nullable.GetUnderlyingType(propertyType);
            if (propertyType == null)
                throw new Exception("Property2Column error");
        }

        if (propertyType.IsEnum)
        {
            if (!isNullable)
            {
                columnDescriptor.DefaultValue = "0";
            }

            columnDescriptor.TypeName = "SMALLINT";
            return;
        }

        if (propertyType.IsGuid())
        {
            columnDescriptor.TypeName = "CHAR";
            columnDescriptor.Length = 36;
            return;
        }

        var typeCode = Type.GetTypeCode(propertyType);
        switch (typeCode)
        {
            case TypeCode.Char:
                columnDescriptor.TypeName = "CHAR";
                break;
            case TypeCode.String:
                columnDescriptor.TypeName = columnDescriptor.Length < 1 ? "TEXT" : "VARCHAR";
                break;
            case TypeCode.Boolean:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "b'0'";
                }

                columnDescriptor.TypeName = "BIT";
                break;
            case TypeCode.Byte:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }
                columnDescriptor.TypeName = "TINYINT";
                break;
            case TypeCode.Int16:
            case TypeCode.Int32:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "INT";
                break;
            case TypeCode.Int64:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "BIGINT";
                break;
            case TypeCode.DateTime:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "CURRENT_TIMESTAMP";
                }
                columnDescriptor.TypeName = "DATETIME";
                break;
            case TypeCode.Decimal:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "DECIMAL";
                break;
            case TypeCode.Double:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "DOUBLE";
                break;
            case TypeCode.Single:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "FLOAT";
                break;
        }

        //主键默认值为null
        if (columnDescriptor.IsPrimaryKey)
        {
            columnDescriptor.DefaultValue = null;
        }
    }

19 Source : SqliteDbAdapter.cs
with MIT License
from 17MKH

public override void ResolveColumn(IColumnDescriptor descriptor)
    {
        var propertyType = descriptor.PropertyInfo.PropertyType;
        var isNullable = propertyType.IsNullable();
        if (isNullable)
        {
            propertyType = Nullable.GetUnderlyingType(propertyType);
            if (propertyType == null)
                throw new Exception("Property2Column error");
        }

        if (propertyType.IsEnum)
        {
            if (!isNullable)
            {
                descriptor.DefaultValue = "0";
            }

            descriptor.TypeName = "integer";
            return;
        }

        if (propertyType.IsGuid())
        {
            descriptor.TypeName = "UNIQUEIDENTIFIER";

            return;
        }

        var typeCode = Type.GetTypeCode(propertyType);
        switch (typeCode)
        {
            case TypeCode.Boolean:
            case TypeCode.Byte:
            case TypeCode.Int16:
            case TypeCode.Int32:
            case TypeCode.Int64:
                descriptor.TypeName = "integer";
                break;
            case TypeCode.Decimal:
            case TypeCode.Double:
            case TypeCode.Single:
                descriptor.TypeName = "decimal";
                break;
            default:
                descriptor.TypeName = "text";
                break;
        }
    }

19 Source : SqlServerDbAdapter.cs
with MIT License
from 17MKH

public override void ResolveColumn(IColumnDescriptor columnDescriptor)
    {
        var propertyType = columnDescriptor.PropertyInfo.PropertyType;
        var isNullable = propertyType.IsNullable();
        if (isNullable)
        {
            propertyType = Nullable.GetUnderlyingType(propertyType);
            if (propertyType == null)
                throw new Exception("Property2Column error");
        }

        if (propertyType.IsEnum)
        {
            if (!isNullable)
            {
                columnDescriptor.DefaultValue = "0";
            }

            columnDescriptor.TypeName = "SMALLINT";
            return;
        }

        if (propertyType.IsGuid())
        {
            columnDescriptor.TypeName = "UNIQUEIDENTIFIER";

            return;
        }

        var typeCode = Type.GetTypeCode(propertyType);
        switch (typeCode)
        {
            case TypeCode.Char:
            case TypeCode.String:
                columnDescriptor.TypeName = "NVARCHAR";
                break;
            case TypeCode.Boolean:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "BIT";
                break;
            case TypeCode.Byte:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }
                columnDescriptor.TypeName = "TINYINT";
                break;
            case TypeCode.Int16:
            case TypeCode.Int32:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "INT";
                break;
            case TypeCode.Int64:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "BIGINT";
                break;
            case TypeCode.DateTime:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "GETDATE()";
                }
                columnDescriptor.TypeName = "DATETIME";
                break;
            case TypeCode.Decimal:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "DECIMAL";
                break;
            case TypeCode.Double:
            case TypeCode.Single:
                if (!isNullable)
                {
                    columnDescriptor.DefaultValue = "0";
                }

                columnDescriptor.TypeName = "FLOAT";
                break;
        }

        //主键默认值为null
        if (columnDescriptor.IsPrimaryKey)
        {
            columnDescriptor.DefaultValue = null;
        }
    }

19 Source : ExpressionResolver.cs
with MIT License
from 17MKH

public static void AppendValue(QueryBody queryBody, object value, StringBuilder sqlBuilder, IQueryParameters parameters)
    {
        if (value == null)
        {
            var len = sqlBuilder.Length;
            if (sqlBuilder[len - 1] == ' ' && sqlBuilder[len - 2] == '>' && sqlBuilder[len - 3] == '<')
            {
                sqlBuilder.Remove(len - 3, 3);
                sqlBuilder.Append("IS NOT NULL");
                return;
            }

            if (sqlBuilder[len - 1] == ' ' && sqlBuilder[len - 2] == '=')
            {
                sqlBuilder.Remove(len - 2, 2);
                sqlBuilder.Append("IS NULL");
            }

            return;
        }

        var dbAdapter = queryBody.DbAdapter;
        if (queryBody.UseParameters)
        {
            //使用参数化
            var pName = parameters.Add(value);
            sqlBuilder.Append(dbAdapter.AppendParameter(pName));
        }
        else
        {
            var type = value.GetType();
            //不使用参数化
            if (type.IsNullable())
            {
                type = Nullable.GetUnderlyingType(type);
            }

            if (type!.IsEnum)
            {
                sqlBuilder.AppendFormat("{0}", value.ToInt());
            }
            else if (type.IsBool())
            {
                sqlBuilder.AppendFormat("{0}", value.ToBool() ? dbAdapter.BooleanTrueValue : dbAdapter.BooleanFalseValue);
            }
            else if (type.IsDateTime())
            {
                sqlBuilder.AppendFormat("'{0:yyyy-MM-dd HH:mm:ss}'", value);
            }
            else if (type.IsString() || type.IsGuid())
            {
                sqlBuilder.AppendFormat("'{0}'", value);
            }
            else
            {
                sqlBuilder.AppendFormat("{0}", value);
            }
        }
    }

19 Source : RandomHelper.cs
with MIT License
from 1996v

private static bool IsNullable(this Type t)
        {
            return Nullable.GetUnderlyingType(t) != null;
        }

19 Source : RandomHelper.cs
with MIT License
from 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d= BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 40);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    string n = RandomHelper.RandomValue<string>(false);
                    while(dt.Columns.Contains(n))
                        n = RandomHelper.RandomValue<string>(false);
                    dt.Columns.Add(n, typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                       

                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 Source : RandomHelper.cs
with MIT License
from 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d = BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 28);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    dt.Columns.Add(RandomHelper.RandomValue<string>(false), typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 Source : Helpers.cs
with MIT License
from 404Lcc

internal static System.Type GetUnderlyingType(System.Type type)
        {
#if NO_GENERICS
            return null; // never a Nullable<T>, so always returns null
#else
            return Nullable.GetUnderlyingType(type);
#endif
        }

19 Source : ReaderCache.cs
with Apache License 2.0
from aadreja

internal static Func<IDataReader, T> ReaderToObject(IDataReader rdr)
        {
            MethodInfo rdrGetValueMethod = rdr.GetType().GetMethod("get_Item", new Type[] { typeof(int) });

            Type[] args = { typeof(IDataReader) };
            DynamicMethod method = new DynamicMethod("DynamicRead" + Guid.NewGuid().ToString(), typeof(T), args, typeof(Repository<T>).Module, true);
            ILGenerator il = method.GetILGenerator();

            LocalBuilder result = il.DeclareLocal(typeof(T)); //loc_0
            il.Emit(OpCodes.Newobj, typeof(T).GetConstructor(Type.EmptyTypes));
            il.Emit(OpCodes.Stloc_0, result); //Pops the current value from the top of the evaluation stack and stores it in a the local variable list at a specified index.

            Label tryBlock = il.BeginExceptionBlock();

            LocalBuilder valueCopy = il.DeclareLocal(typeof(object)); //declare local variable to store object value. loc_1

            il.DeclareLocal(typeof(int)); //declare local variable to store index //loc_2
            il.Emit(OpCodes.Ldc_I4_0); //load 0 in index
            il.Emit(OpCodes.Stloc_2); //pop and save to local variable loc 2

            //get FieldInfo of all properties
            TableAttribute tableInfo = EnreplacedyCache.Get(typeof(T));

            for (int i = 0; i < rdr.FieldCount; i++)
            {
                tableInfo.Columns.TryGetValue(rdr.GetName(i), out ColumnAttribute columnInfo);

                if (columnInfo != null && columnInfo.SetMethod != null)
                {
                    Label endIfLabel = il.DefineLabel();

                    il.Emit(OpCodes.Ldarg_0);//load the argument. Loads the argument at index 0 onto the evaluation stack.
                    il.Emit(OpCodes.Ldc_I4, i); //push field index as int32 to the stack. Pushes a supplied value of type int32 onto the evaluation stack as an int32.
                    il.Emit(OpCodes.Dup);//copy value
                    il.Emit(OpCodes.Stloc_2);//pop and save value to loc 2
                    il.Emit(OpCodes.Callvirt, rdrGetValueMethod); //Call rdr[i] method - Calls a late - bound method on an object, pushing the return value onto the evaluation stack.

                    //TODO: dynamic location using valueCopyLocal
                    il.Emit(OpCodes.Stloc_1); //pop the value and push in stack location 1
                    il.Emit(OpCodes.Ldloc_1); //load the variable in location 1

                    il.Emit(OpCodes.Isinst, typeof(DBNull)); //check whether value is null - Tests whether an object reference (type O) is an instance of a particular clreplaced.
                    il.Emit(OpCodes.Brtrue, endIfLabel); //go to end block if value is null

                    il.Emit(OpCodes.Ldloc_0); //load T result
                    il.Emit(OpCodes.Ldloc_1); //TODO: dynamic location using valueCopyLocal

                    //when Enum are without number values
                    if (columnInfo.Property.PropertyType.IsEnum)
                    {
                        Type numericType = Enum.GetUnderlyingType(columnInfo.Property.PropertyType);
                        if (rdr.GetFieldType(i) == typeof(string))
                        {
                            LocalBuilder stringEnumLocal = il.DeclareLocal(typeof(string));

                            il.Emit(OpCodes.Castclreplaced, typeof(string)); // stack is now [...][string]
                            il.Emit(OpCodes.Stloc, stringEnumLocal); // stack is now [...]
                            il.Emit(OpCodes.Ldtoken, columnInfo.Property.PropertyType); // stack is now [...][enum-type-token]
                            il.EmitCall(OpCodes.Call, typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle)), null);// stack is now [...][enum-type]
                            il.Emit(OpCodes.Ldloc, stringEnumLocal); // stack is now [...][enum-type][string]
                            il.Emit(OpCodes.Ldc_I4_1); // stack is now [...][enum-type][string][true]
                            il.EmitCall(OpCodes.Call, enumParse, null); // stack is now [...][enum-as-object]
                            il.Emit(OpCodes.Unbox_Any, columnInfo.Property.PropertyType); // stack is now [...][typed-value]
                        }
                        else
                        {
                            ConvertValueToEnum(il, rdr.GetFieldType(i), columnInfo.Property.PropertyType, numericType);
                        }
                    }
                    else if (columnInfo.Property.PropertyType.IsValueType)
                        il.Emit(OpCodes.Unbox_Any, rdr.GetFieldType(i)); //type cast

                    // for nullable type fields
                    if (columnInfo.Property.PropertyType.IsGenericType && columnInfo.Property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        var underlyingType = Nullable.GetUnderlyingType(columnInfo.Property.PropertyType);
                        il.Emit(OpCodes.Newobj, columnInfo.Property.PropertyType.GetConstructor(new Type[] { underlyingType }));
                    }

                    il.Emit(OpCodes.Callvirt, columnInfo.SetMethod);
                    il.Emit(OpCodes.Nop);

                    il.MarkLabel(endIfLabel);
                }
            }

            il.BeginCatchBlock(typeof(Exception)); //begin try block. exception is in stack
            il.Emit(OpCodes.Ldloc_2); //load index
            il.Emit(OpCodes.Ldarg_0); //load argument reader
            il.Emit(OpCodes.Ldloc_1); //load value //TODO: dynamic location using valueCopyLocal
            il.EmitCall(OpCodes.Call, typeof(ReaderCache<T>).GetMethod(nameof(ReaderCache<T>.HandleException)), null); //call exception handler
            il.EndExceptionBlock();

            il.Emit(OpCodes.Ldloc, result);
            il.Emit(OpCodes.Ret);
            

            var funcType = System.Linq.Expressions.Expression.GetFuncType(typeof(IDataReader), typeof(T));
            return (Func<IDataReader, T>)method.CreateDelegate(funcType);
        }

19 Source : ReaderCache.cs
with Apache License 2.0
from aadreja

private static Type GetTypeOfDynamicProperty(PropertyInfo property, object dynamicObject)
        {
            //dynamic property will always return System.Object as property type. Get Type from the value

            Type type = property.PropertyType;

            if (type == typeof(object))
                type = property.GetValue(dynamicObject)?.GetType() ?? typeof(object);
            else
            {
                if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    type = Nullable.GetUnderlyingType(property.PropertyType);
                else
                    type = property.PropertyType;
            }

            return type;
        }

19 Source : FormGeneratorComponentModelBasedRepository.cs
with MIT License
from Aaltuj

protected override Type GetComponent(Type key)
        {
            var type = key;
            // When the type is an ENUM use Enum as type instead of property
            if (key.IsEnum)
            {
                type = typeof(Enum);
            }
            // When the type is a ValuesReferences use the base type. example ValuesReferences<bool>
            else if (key.BaseType == typeof(ValueReferences))
            {
                type = typeof(ValueReferences);
            }
            // When it's a Nullable type use the underlying type for matching
            else if(Nullable.GetUnderlyingType(key) != null )
            {
                type = Nullable.GetUnderlyingType(key);
            }

            return base.GetComponent(type);
        }

19 Source : FdbConverters.cs
with MIT License
from abdullin

[ContractAnnotation("=> halt")]
		private static void FailCannotConvert(Type source, Type destination)
		{
			// prettyprint nullable type names to have something more usefull than "Nullable`1"
			//TODO: extend this to all generic types ?
			var nt = Nullable.GetUnderlyingType(source);
			string sourceName = nt == null ? source.Name : String.Format("Nullable<{0}>", nt.Name);
			nt = Nullable.GetUnderlyingType(destination);
			string destinationName = nt == null ? destination.Name : String.Format("Nullable<{0}>", nt.Name);

			throw new InvalidOperationException(String.Format("Cannot convert values of type {0} into {1}", sourceName, destinationName));
		}

19 Source : FdbTuplePackers.cs
with MIT License
from abdullin

private static Delegate GetSerializerFor([NotNull] Type type)
		{
			if (type == null) throw new ArgumentNullException("type");

			if (type == typeof(object))
			{ // return a generic serializer that will inspect the runtime type of the object
				return new Encoder<object>(FdbTuplePackers.SerializeObjectTo);
			}

			var typeArgs = new[] { typeof(TupleWriter).MakeByRefType(), type };
			var method = typeof(FdbTuplePackers).GetMethod("SerializeTo", BindingFlags.Static | BindingFlags.Public, null, typeArgs, null);
			if (method != null)
			{ // we have a direct serializer
				return method.CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
			}

			// maybe if it is a tuple ?
			if (typeof(IFdbTuple).IsreplacedignableFrom(type))
			{
				method = typeof(FdbTuplePackers).GetMethod("SerializeTupleTo", BindingFlags.Static | BindingFlags.Public);
				if (method != null)
				{
					return method.MakeGenericMethod(type).CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
				}
			}

			if (typeof(ITupleFormattable).IsreplacedignableFrom(type))
			{
				method = typeof(FdbTuplePackers).GetMethod("SerializeFormattableTo", BindingFlags.Static | BindingFlags.Public);
				if (method != null)
				{
					return method.CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
				}
			}

			if (typeof(IFdbKey).IsreplacedignableFrom(type))
			{
				method = typeof(FdbTuplePackers).GetMethod("SerializeFdbKeyTo", BindingFlags.Static | BindingFlags.Public);
				if (method != null)
				{
					return method.CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
				}
			}

			var nullableType = Nullable.GetUnderlyingType(type);
			if (nullableType != null)
			{ // nullable types can reuse the underlying type serializer
				method = typeof(FdbTuplePackers).GetMethod("SerializeNullableTo", BindingFlags.Static | BindingFlags.Public);
				if (method != null)
				{
					return method.MakeGenericMethod(nullableType).CreateDelegate(typeof(Encoder<>).MakeGenericType(type));
				}
			}

			// TODO: look for a static SerializeTo(BWB, T) method on the type itself ?

			// no luck..
			return null;
		}

19 Source : FdbConverters.cs
with MIT License
from abdullin

[CanBeNull]
		public static R ConvertBoxed<R>(object value)
		{
			if (value == null) return default(R);
			var type = value.GetType();

			var targetType = typeof(R);

			// cast !
			if (targetType.IsreplacedignableFrom(type)) return (R)value;

			IFdbConverter converter;
			if (!Converters.TryGetValue(new ComparisonHelper.TypePair(type, targetType), out converter))
			{
				// maybe it is a nullable type ?
				var nullableType = Nullable.GetUnderlyingType(targetType);
				if (nullableType != null)
				{ // we already nullchecked value above, so we just have to convert it to the underlying type...

					// shortcut for converting a R into a Nullable<R> ...
					if (type == nullableType) return (R)value;

					// maybe we have a converter for the underlying type ?
					if (Converters.TryGetValue(new ComparisonHelper.TypePair(type, nullableType), out converter))
					{
						return (R)converter.ConvertBoxed(value);
					}
				}

				FailCannotConvert(type, targetType);
			}

			return (R)converter.ConvertBoxed(value);
		}

19 Source : ConversionHelper.cs
with MIT License
from abdullin

private static bool IsNumericType([NotNull] Type t)
		{
			// Return true for valuetypes that are considered numbers.
			// Notes:
			// - We do not consider 'byte' to be a number, because we will serialize it as a byte[1]
			// - We do not consider 'char' to be a number, because we will serialize it as a string
			// - For nullable types, we consider the underlying type, so "int?" is considered to be a number"

			switch (Type.GetTypeCode(t))
			{
				case TypeCode.SByte:
				case TypeCode.Int16:
				case TypeCode.UInt16:
				case TypeCode.Int32:
				case TypeCode.UInt32:
				case TypeCode.Int64:
				case TypeCode.UInt64:
				case TypeCode.Single:
				case TypeCode.Double:
					return true;

				case TypeCode.Object:
					{
						// Could be a Nullable<T>
						var nullableType = Nullable.GetUnderlyingType(t);
						return nullableType != null && IsNumericType(nullableType);
					}
				default:
					{
						return false;
					}
			}
		}

19 Source : FdbTuplePackers.cs
with MIT License
from abdullin

[NotNull]
		internal static Func<Slice, T> GetDeserializer<T>(bool required)
		{
			Type type = typeof(T);

			Delegate decoder;
			if (s_sliceUnpackers.TryGetValue(type, out decoder))
			{
				return (Func<Slice, T>)decoder;
			}

			//TODO: handle nullable types?
			var underlyingType = Nullable.GetUnderlyingType(typeof(T));
			if (underlyingType != null && s_sliceUnpackers.TryGetValue(underlyingType, out decoder))
			{
				decoder = MakeNullableDeserializer(type, underlyingType, decoder);
				if (decoder != null) return (Func<Slice, T>)decoder;
			}

			if (required)
			{
				return (_) => { throw new InvalidOperationException(String.Format("Does not know how to deserialize keys into values of type {0}", typeof(T).Name)); };
			}
			else
			{ // when all else fails...
				return (value) => FdbConverters.ConvertBoxed<T>(DeserializeBoxed(value));
			}
		}

19 Source : UnknownEnum.cs
with MIT License
from actions

public static object Parse(Type enumType, string stringValue)
        {
            var underlyingType = Nullable.GetUnderlyingType(enumType);
            enumType = underlyingType != null ? underlyingType : enumType;

            var names = Enum.GetNames(enumType);
            if (!string.IsNullOrEmpty(stringValue))
            {
                var match = names.FirstOrDefault(name => string.Equals(name, stringValue, StringComparison.OrdinalIgnoreCase));
                if (match != null)
                {
                    return Enum.Parse(enumType, match);
                }

                // maybe we have an enum member with an EnumMember attribute specifying a custom name
                foreach (var field in enumType.GetFields())
                {
                    var enumMemberAttribute = field.GetCustomAttributes(typeof(EnumMemberAttribute), false).FirstOrDefault() as EnumMemberAttribute;
                    if (enumMemberAttribute != null && string.Equals(enumMemberAttribute.Value, stringValue, StringComparison.OrdinalIgnoreCase))
                    {
                        // we already have the field, no need to do enum.parse on it
                        return field.GetValue(null);
                    }
                }
            }

            return Enum.Parse(enumType, UnknownName);
        }

19 Source : ObjectShredder.cs
with MIT License
from Adoxio

public DataTable ExtendTable(DataTable table, Type type)
		{
			// Extend the table schema if the input table was null or if the value 
			// in the sequence is derived from type T.            
			foreach (FieldInfo f in type.GetFields())
			{
				if (!_ordinalMap.ContainsKey(f.Name))
				{
					var ft = f.FieldType;

					if (ft.IsGenericType && ft.GetGenericTypeDefinition() == typeof(Nullable<>))
					{
						ft = Nullable.GetUnderlyingType(ft);
					}

					// Add the field as a column in the table if it doesn't exist
					// already.
					DataColumn dc = table.Columns.Contains(f.Name)
						? table.Columns[f.Name]
						: table.Columns.Add(f.Name, ft);

					// Add the field to the ordinal map.
					_ordinalMap.Add(f.Name, dc.Ordinal);
				}
			}
			foreach (PropertyInfo p in type.GetProperties())
			{
				if (!_ordinalMap.ContainsKey(p.Name))
				{
					var pt = p.PropertyType;

					if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>))
					{
						pt = Nullable.GetUnderlyingType(pt);
					}

					// Add the property as a column in the table if it doesn't exist
					// already.
					DataColumn dc = table.Columns.Contains(p.Name)
						? table.Columns[p.Name]
						: table.Columns.Add(p.Name, pt);

					// Add the property to the ordinal map.
					_ordinalMap.Add(p.Name, dc.Ordinal);
				}
			}

			// Return the table.
			return table;
		}

19 Source : TypeExtensions.cs
with MIT License
from Adoxio

public static Type GetUnderlyingType(this Type type)
		{
			return Nullable.GetUnderlyingType(type) ?? type;
		}

19 Source : Initobj.cs
with GNU General Public License v3.0
from Aekras1a

public void Load(DarksVMContext ctx, out ExecutionState state)
        {
            var sp = ctx.Registers[DarksVMConstants.REG_SP].U4;
            var typeSlot = ctx.Stack[sp--];
            var addrSlot = ctx.Stack[sp--];

            var type = (Type) ctx.Instance.Data.LookupReference(typeSlot.U4);
            if(addrSlot.O is IReference)
            {
                var reference = (IReference) addrSlot.O;
                var slot = new DarksVMSlot();
                if(type.IsValueType)
                {
                    object def = null;
                    if(Nullable.GetUnderlyingType(type) == null)
                        def = FormatterServices.GetUninitializedObject(type);
                    slot.O = ValueTypeBox.Box(def, type);
                }
                else
                {
                    slot.O = null;
                }
                reference.SetValue(ctx, slot, PointerType.OBJECT);
            }
            else
            {
                throw new NotSupportedException();
            }

            ctx.Stack.SetTopPosition(sp);
            ctx.Registers[DarksVMConstants.REG_SP].U4 = sp;
            state = ExecutionState.Next;
        }

19 Source : DataConverter.cs
with GNU General Public License v3.0
from aiportal

public static object ChangeType(object obj, Type type)
		{
			if (obj == null || obj == DBNull.Value)
				return null;
			if (type == typeof(object) || type == obj.GetType())
				return obj;
			if (obj is string && string.IsNullOrEmpty(obj as string))
				return null;

			object result = null;
			try
			{
				type = Nullable.GetUnderlyingType(type) ?? type;
				if (obj is string)
					result = ObjectFromString(obj as string, type);
				else if (type == typeof(string))
					result = ObjectToString(obj);
				else if (type.IsEnum)
					result = Enum.ToObject(type, obj);
				else
					result = System.Convert.ChangeType(obj, type);
			}
			catch (Exception ex) { TraceLog.WriteException(ex); throw; }
			return result;
		}

19 Source : DataConverter.cs
with GNU General Public License v3.0
from aiportal

private static string ObjectToString(object obj)
		{
			if (obj == null || obj == DBNull.Value)
				return null;
			if (obj is string) 
				return obj as string;

			Type type = obj.GetType();
			type = Nullable.GetUnderlyingType(type) ?? type;

			string result = null;
			if (type == typeof(Guid))
				result= ((Guid)obj).ToString("n");
			else if (type == typeof(DateTime))
				result=((DateTime)obj).ToString();
			else if (type == typeof(Decimal))
				result=((Decimal)obj).ToString();
			else if (type.IsEnum)
				result= obj.ToString();
			else if (type.IsArray)
				result= ArrayToString(obj);
			else
			{
				var parse = type.GetParseMethod();
				if (parse != null)
					result =obj.ToString();
				else
				{
					if (type.IsValueType && !type.IsPrimitive)
						result = StructToString(obj);
					else
						result= obj.ToString();
				}
			}
			return result;
		}

19 Source : JavaScriptDateTimeConverter.cs
with MIT License
from akaskela

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                if (!ReflectionUtils.IsNullable(objectType))
                {
                    throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
                }

                return null;
            }

            if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal))
            {
                throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing date. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value));
            }

            reader.Read();

            if (reader.TokenType != JsonToken.Integer)
            {
                throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
            }

            long ticks = (long)reader.Value;

            DateTime d = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks);

            reader.Read();

            if (reader.TokenType != JsonToken.EndConstructor)
            {
                throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected EndConstructor, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
            }

#if !NET20
            Type t = (ReflectionUtils.IsNullableType(objectType))
                ? Nullable.GetUnderlyingType(objectType)
                : objectType;
            if (t == typeof(DateTimeOffset))
            {
                return new DateTimeOffset(d);
            }
#endif

            return d;
        }

19 Source : StringEnumConverter.cs
with MIT License
from akaskela

public override bool CanConvert(Type objectType)
        {
            Type t = (ReflectionUtils.IsNullableType(objectType))
                ? Nullable.GetUnderlyingType(objectType)
                : objectType;

            return t.IsEnum();
        }

19 Source : KeyValuePairConverter.cs
with MIT License
from akaskela

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                if (!ReflectionUtils.IsNullableType(objectType))
                {
                    throw JsonSerializationException.Create(reader, "Cannot convert null value to KeyValuePair.");
                }

                return null;
            }

            object key = null;
            object value = null;

            reader.ReadAndreplacedert();

            Type t = ReflectionUtils.IsNullableType(objectType)
                ? Nullable.GetUnderlyingType(objectType)
                : objectType;

            ReflectionObject reflectionObject = ReflectionObjectPerType.Get(t);

            while (reader.TokenType == JsonToken.PropertyName)
            {
                string propertyName = reader.Value.ToString();
                if (string.Equals(propertyName, KeyName, StringComparison.OrdinalIgnoreCase))
                {
                    reader.ReadAndreplacedert();
                    key = serializer.Deserialize(reader, reflectionObject.GetType(KeyName));
                }
                else if (string.Equals(propertyName, ValueName, StringComparison.OrdinalIgnoreCase))
                {
                    reader.ReadAndreplacedert();
                    value = serializer.Deserialize(reader, reflectionObject.GetType(ValueName));
                }
                else
                {
                    reader.Skip();
                }

                reader.ReadAndreplacedert();
            }

            return reflectionObject.Creator(key, value);
        }

19 Source : StringEnumConverter.cs
with MIT License
from akaskela

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                if (!ReflectionUtils.IsNullableType(objectType))
                {
                    throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
                }

                return null;
            }

            bool isNullable = ReflectionUtils.IsNullableType(objectType);
            Type t = isNullable ? Nullable.GetUnderlyingType(objectType) : objectType;

            try
            {
                if (reader.TokenType == JsonToken.String)
                {
                    string enumText = reader.Value.ToString();
                    return EnumUtils.ParseEnumName(enumText, isNullable, t);
                }

                if (reader.TokenType == JsonToken.Integer)
                {
                    if (!AllowIntegerValues)
                    {
                        throw JsonSerializationException.Create(reader, "Integer value {0} is not allowed.".FormatWith(CultureInfo.InvariantCulture, reader.Value));
                    }

                    return ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, t);
                }
            }
            catch (Exception ex)
            {
                throw JsonSerializationException.Create(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.FormatValueForPrint(reader.Value), objectType), ex);
            }

            // we don't actually expect to get here.
            throw JsonSerializationException.Create(reader, "Unexpected token {0} when parsing enum.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
        }

19 Source : JToken.cs
with MIT License
from akaskela

public object ToObject(Type objectType)
        {
            if (JsonConvert.DefaultSettings == null)
            {
                bool isEnum;
                PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(objectType, out isEnum);

                if (isEnum)
                {
                    if (Type == JTokenType.String)
                    {
                        try
                        {
                            // use serializer so JsonConverter(typeof(StringEnumConverter)) + EnumMemberAttributes are respected
                            return ToObject(objectType, JsonSerializer.CreateDefault());
                        }
                        catch (Exception ex)
                        {
                            Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType);
                            throw new ArgumentException("Could not convert '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, (string)this, enumType.Name), ex);
                        }
                    }

                    if (Type == JTokenType.Integer)
                    {
                        Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType);
                        return Enum.ToObject(enumType, ((JValue)this).Value);
                    }
                }

                switch (typeCode)
                {
                    case PrimitiveTypeCode.BooleanNullable:
                        return (bool?)this;
                    case PrimitiveTypeCode.Boolean:
                        return (bool)this;
                    case PrimitiveTypeCode.CharNullable:
                        return (char?)this;
                    case PrimitiveTypeCode.Char:
                        return (char)this;
                    case PrimitiveTypeCode.SByte:
                        return (sbyte?)this;
                    case PrimitiveTypeCode.SByteNullable:
                        return (sbyte)this;
                    case PrimitiveTypeCode.ByteNullable:
                        return (byte?)this;
                    case PrimitiveTypeCode.Byte:
                        return (byte)this;
                    case PrimitiveTypeCode.Int16Nullable:
                        return (short?)this;
                    case PrimitiveTypeCode.Int16:
                        return (short)this;
                    case PrimitiveTypeCode.UInt16Nullable:
                        return (ushort?)this;
                    case PrimitiveTypeCode.UInt16:
                        return (ushort)this;
                    case PrimitiveTypeCode.Int32Nullable:
                        return (int?)this;
                    case PrimitiveTypeCode.Int32:
                        return (int)this;
                    case PrimitiveTypeCode.UInt32Nullable:
                        return (uint?)this;
                    case PrimitiveTypeCode.UInt32:
                        return (uint)this;
                    case PrimitiveTypeCode.Int64Nullable:
                        return (long?)this;
                    case PrimitiveTypeCode.Int64:
                        return (long)this;
                    case PrimitiveTypeCode.UInt64Nullable:
                        return (ulong?)this;
                    case PrimitiveTypeCode.UInt64:
                        return (ulong)this;
                    case PrimitiveTypeCode.SingleNullable:
                        return (float?)this;
                    case PrimitiveTypeCode.Single:
                        return (float)this;
                    case PrimitiveTypeCode.DoubleNullable:
                        return (double?)this;
                    case PrimitiveTypeCode.Double:
                        return (double)this;
                    case PrimitiveTypeCode.DecimalNullable:
                        return (decimal?)this;
                    case PrimitiveTypeCode.Decimal:
                        return (decimal)this;
                    case PrimitiveTypeCode.DateTimeNullable:
                        return (DateTime?)this;
                    case PrimitiveTypeCode.DateTime:
                        return (DateTime)this;
#if !NET20
                    case PrimitiveTypeCode.DateTimeOffsetNullable:
                        return (DateTimeOffset?)this;
                    case PrimitiveTypeCode.DateTimeOffset:
                        return (DateTimeOffset)this;
#endif
                    case PrimitiveTypeCode.String:
                        return (string)this;
                    case PrimitiveTypeCode.GuidNullable:
                        return (Guid?)this;
                    case PrimitiveTypeCode.Guid:
                        return (Guid)this;
                    case PrimitiveTypeCode.Uri:
                        return (Uri)this;
                    case PrimitiveTypeCode.TimeSpanNullable:
                        return (TimeSpan?)this;
                    case PrimitiveTypeCode.TimeSpan:
                        return (TimeSpan)this;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
                    case PrimitiveTypeCode.BigIntegerNullable:
                        return ToBigIntegerNullable(this);
                    case PrimitiveTypeCode.BigInteger:
                        return ToBigInteger(this);
#endif
                }
            }

            return ToObject(objectType, JsonSerializer.CreateDefault());
        }

19 Source : DefaultContractResolver.cs
with MIT License
from akaskela

internal static bool IsIConvertible(Type t)
        {
            if (typeof(IConvertible).IsreplacedignableFrom(t)
                || (ReflectionUtils.IsNullableType(t) && typeof(IConvertible).IsreplacedignableFrom(Nullable.GetUnderlyingType(t))))
            {
                return !typeof(JToken).IsreplacedignableFrom(t);
            }

            return false;
        }

19 Source : BinaryConverter.cs
with MIT License
from akaskela

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                if (!ReflectionUtils.IsNullable(objectType))
                {
                    throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
                }

                return null;
            }

            byte[] data;

            if (reader.TokenType == JsonToken.StartArray)
            {
                data = ReadByteArray(reader);
            }
            else if (reader.TokenType == JsonToken.String)
            {
                // current token is already at base64 string
                // unable to call ReadAsBytes so do it the old fashion way
                string encodedData = reader.Value.ToString();
                data = Convert.FromBase64String(encodedData);
            }
            else
            {
                throw JsonSerializationException.Create(reader, "Unexpected token parsing binary. Expected String or StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
            }

            Type t = (ReflectionUtils.IsNullableType(objectType))
                ? Nullable.GetUnderlyingType(objectType)
                : objectType;

#if !NET20
            if (t.replacedignableToTypeName(BinaryTypeName))
            {
                EnsureReflectionObject(t);

                return _reflectionObject.Creator(data);
            }
#endif

            if (t == typeof(SqlBinary))
            {
                return new SqlBinary(data);
            }

            throw JsonSerializationException.Create(reader, "Unexpected object type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, objectType));
        }

19 Source : Extensions.cs
with MIT License
from akaskela

internal static U Convert<T, U>(this T token) where T : JToken
        {
            if (token == null)
            {
                return default(U);
            }

            if (token is U
                // don't want to cast JValue to its interfaces, want to get the internal value
                && typeof(U) != typeof(IComparable) && typeof(U) != typeof(IFormattable))
            {
                // HACK
                return (U)(object)token;
            }
            else
            {
                JValue value = token as JValue;
                if (value == null)
                {
                    throw new InvalidCastException("Cannot cast {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, token.GetType(), typeof(T)));
                }

                if (value.Value is U)
                {
                    return (U)value.Value;
                }

                Type targetType = typeof(U);

                if (ReflectionUtils.IsNullableType(targetType))
                {
                    if (value.Value == null)
                    {
                        return default(U);
                    }

                    targetType = Nullable.GetUnderlyingType(targetType);
                }

                return (U)System.Convert.ChangeType(value.Value, targetType, CultureInfo.InvariantCulture);
            }
        }

19 Source : JsonSchemaGenerator.cs
with MIT License
from akaskela

private JsonSchemaType GetJsonSchemaType(Type type, Required valueRequired)
        {
            JsonSchemaType schemaType = JsonSchemaType.None;
            if (valueRequired != Required.Always && ReflectionUtils.IsNullable(type))
            {
                schemaType = JsonSchemaType.Null;
                if (ReflectionUtils.IsNullableType(type))
                {
                    type = Nullable.GetUnderlyingType(type);
                }
            }

            PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(type);

            switch (typeCode)
            {
                case PrimitiveTypeCode.Empty:
                case PrimitiveTypeCode.Object:
                    return schemaType | JsonSchemaType.String;
#if !(DOTNET || PORTABLE)
                case PrimitiveTypeCode.DBNull:
                    return schemaType | JsonSchemaType.Null;
#endif
                case PrimitiveTypeCode.Boolean:
                    return schemaType | JsonSchemaType.Boolean;
                case PrimitiveTypeCode.Char:
                    return schemaType | JsonSchemaType.String;
                case PrimitiveTypeCode.SByte:
                case PrimitiveTypeCode.Byte:
                case PrimitiveTypeCode.Int16:
                case PrimitiveTypeCode.UInt16:
                case PrimitiveTypeCode.Int32:
                case PrimitiveTypeCode.UInt32:
                case PrimitiveTypeCode.Int64:
                case PrimitiveTypeCode.UInt64:
#if !(PORTABLE || NET35 || NET20)
                case PrimitiveTypeCode.BigInteger:
#endif
                    return schemaType | JsonSchemaType.Integer;
                case PrimitiveTypeCode.Single:
                case PrimitiveTypeCode.Double:
                case PrimitiveTypeCode.Decimal:
                    return schemaType | JsonSchemaType.Float;
                // convert to string?
                case PrimitiveTypeCode.DateTime:
#if !NET20
                case PrimitiveTypeCode.DateTimeOffset:
#endif
                    return schemaType | JsonSchemaType.String;
                case PrimitiveTypeCode.String:
                case PrimitiveTypeCode.Uri:
                case PrimitiveTypeCode.Guid:
                case PrimitiveTypeCode.TimeSpan:
                case PrimitiveTypeCode.Bytes:
                    return schemaType | JsonSchemaType.String;
                default:
                    throw new JsonException("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type));
            }
        }

19 Source : ConvertUtils.cs
with MIT License
from akaskela

public static PrimitiveTypeCode GetTypeCode(Type t, out bool isEnum)
        {
            PrimitiveTypeCode typeCode;
            if (TypeCodeMap.TryGetValue(t, out typeCode))
            {
                isEnum = false;
                return typeCode;
            }

            if (t.IsEnum())
            {
                isEnum = true;
                return GetTypeCode(Enum.GetUnderlyingType(t));
            }

            // performance?
            if (ReflectionUtils.IsNullableType(t))
            {
                Type nonNullable = Nullable.GetUnderlyingType(t);
                if (nonNullable.IsEnum())
                {
                    Type nullableUnderlyingType = typeof(Nullable<>).MakeGenericType(Enum.GetUnderlyingType(nonNullable));
                    isEnum = true;
                    return GetTypeCode(nullableUnderlyingType);
                }
            }

            isEnum = false;
            return PrimitiveTypeCode.Object;
        }

19 Source : ReflectionUtils.cs
with MIT License
from akaskela

public static Type EnsureNotNullableType(Type t)
        {
            return (IsNullableType(t))
                ? Nullable.GetUnderlyingType(t)
                : t;
        }

19 Source : IsoDateTimeConverter.cs
with MIT License
from akaskela

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            bool nullable = ReflectionUtils.IsNullableType(objectType);
#if !NET20
            Type t = (nullable)
                ? Nullable.GetUnderlyingType(objectType)
                : objectType;
#endif

            if (reader.TokenType == JsonToken.Null)
            {
                if (!ReflectionUtils.IsNullableType(objectType))
                {
                    throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
                }

                return null;
            }

            if (reader.TokenType == JsonToken.Date)
            {
#if !NET20
                if (t == typeof(DateTimeOffset))
                {
                    return (reader.Value is DateTimeOffset) ? reader.Value : new DateTimeOffset((DateTime)reader.Value);
                }

                // converter is expected to return a DateTime
                if (reader.Value is DateTimeOffset)
                {
                    return ((DateTimeOffset)reader.Value).DateTime;
                }
#endif

                return reader.Value;
            }

            if (reader.TokenType != JsonToken.String)
            {
                throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
            }

            string dateText = reader.Value.ToString();

            if (string.IsNullOrEmpty(dateText) && nullable)
            {
                return null;
            }

#if !NET20
            if (t == typeof(DateTimeOffset))
            {
                if (!string.IsNullOrEmpty(_dateTimeFormat))
                {
                    return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
                }
                else
                {
                    return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles);
                }
            }
#endif

            if (!string.IsNullOrEmpty(_dateTimeFormat))
            {
                return DateTime.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
            }
            else
            {
                return DateTime.Parse(dateText, Culture, _dateTimeStyles);
            }
        }

19 Source : KeyValuePairConverter.cs
with MIT License
from akaskela

public override bool CanConvert(Type objectType)
        {
            Type t = (ReflectionUtils.IsNullableType(objectType))
                ? Nullable.GetUnderlyingType(objectType)
                : objectType;

            if (t.IsValueType() && t.IsGenericType())
            {
                return (t.GetGenericTypeDefinition() == typeof(KeyValuePair<,>));
            }

            return false;
        }

19 Source : ConvertUtils.cs
with MIT License
from akaskela

private static ConvertResult TryConvertInternal(object initialValue, CultureInfo culture, Type targetType, out object value)
        {
            if (initialValue == null)
            {
                throw new ArgumentNullException(nameof(initialValue));
            }

            if (ReflectionUtils.IsNullableType(targetType))
            {
                targetType = Nullable.GetUnderlyingType(targetType);
            }

            Type initialType = initialValue.GetType();

            if (targetType == initialType)
            {
                value = initialValue;
                return ConvertResult.Success;
            }

            // use Convert.ChangeType if both types are IConvertible
            if (ConvertUtils.IsConvertible(initialValue.GetType()) && ConvertUtils.IsConvertible(targetType))
            {
                if (targetType.IsEnum())
                {
                    if (initialValue is string)
                    {
                        value = Enum.Parse(targetType, initialValue.ToString(), true);
                        return ConvertResult.Success;
                    }
                    else if (IsInteger(initialValue))
                    {
                        value = Enum.ToObject(targetType, initialValue);
                        return ConvertResult.Success;
                    }
                }

                value = System.Convert.ChangeType(initialValue, targetType, culture);
                return ConvertResult.Success;
            }

#if !NET20
            if (initialValue is DateTime && targetType == typeof(DateTimeOffset))
            {
                value = new DateTimeOffset((DateTime)initialValue);
                return ConvertResult.Success;
            }
#endif

            if (initialValue is byte[] && targetType == typeof(Guid))
            {
                value = new Guid((byte[])initialValue);
                return ConvertResult.Success;
            }

            if (initialValue is Guid && targetType == typeof(byte[]))
            {
                value = ((Guid)initialValue).ToByteArray();
                return ConvertResult.Success;
            }

            string s = initialValue as string;
            if (s != null)
            {
                if (targetType == typeof(Guid))
                {
                    value = new Guid(s);
                    return ConvertResult.Success;
                }
                if (targetType == typeof(Uri))
                {
                    value = new Uri(s, UriKind.RelativeOrAbsolute);
                    return ConvertResult.Success;
                }
                if (targetType == typeof(TimeSpan))
                {
                    value = ParseTimeSpan(s);
                    return ConvertResult.Success;
                }
                if (targetType == typeof(byte[]))
                {
                    value = System.Convert.FromBase64String(s);
                    return ConvertResult.Success;
                }
                if (targetType == typeof(Version))
                {
                    Version result;
                    if (VersionTryParse(s, out result))
                    {
                        value = result;
                        return ConvertResult.Success;
                    }
                    value = null;
                    return ConvertResult.NoValidConversion;
                }
                if (typeof(Type).IsreplacedignableFrom(targetType))
                {
                    value = Type.GetType(s, true);
                    return ConvertResult.Success;
                }
            }

#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
            if (targetType == typeof(BigInteger))
            {
                value = ToBigInteger(initialValue);
                return ConvertResult.Success;
            }
            if (initialValue is BigInteger)
            {
                value = FromBigInteger((BigInteger)initialValue, targetType);
                return ConvertResult.Success;
            }
#endif

#if !(PORTABLE40 || PORTABLE)
            // see if source or target types have a TypeConverter that converts between the two
            TypeConverter toConverter = GetConverter(initialType);

            if (toConverter != null && toConverter.CanConvertTo(targetType))
            {
                value = toConverter.ConvertTo(null, culture, initialValue, targetType);
                return ConvertResult.Success;
            }

            TypeConverter fromConverter = GetConverter(targetType);

            if (fromConverter != null && fromConverter.CanConvertFrom(initialType))
            {
                value = fromConverter.ConvertFrom(null, culture, initialValue);
                return ConvertResult.Success;
            }
#endif
#if !(DOTNET || PORTABLE40 || PORTABLE)
            // handle DBNull and INullable
            if (initialValue == DBNull.Value)
            {
                if (ReflectionUtils.IsNullable(targetType))
                {
                    value = EnsureTypereplacedignable(null, initialType, targetType);
                    return ConvertResult.Success;
                }

                // cannot convert null to non-nullable
                value = null;
                return ConvertResult.CannotConvertNull;
            }
#endif
#if !(DOTNET || PORTABLE40 || PORTABLE)
            if (initialValue is INullable)
            {
                value = EnsureTypereplacedignable(ToValue((INullable)initialValue), initialType, targetType);
                return ConvertResult.Success;
            }
#endif

            if (targetType.IsInterface() || targetType.IsGenericTypeDefinition() || targetType.IsAbstract())
            {
                value = null;
                return ConvertResult.NotInstantiableType;
            }

            value = null;
            return ConvertResult.NoValidConversion;
        }

19 Source : GreedyMetaDynamic.cs
with MIT License
from albahari

private DynamicMetaObject BuildCallMethodWithResult<TBinder> (MethodInfo method, TBinder binder, Expression[] args, DynamicMetaObject fallbackResult, Fallback<TBinder> fallbackInvoke)
				where TBinder : DynamicMetaObjectBinder
			{
				if (!IsOverridden (method))
				{
					return fallbackResult;
				}

				//
				// Build a new expression like:
				// {
				//   object result;
				//   TryGetMember(payload, out result) ? fallbackInvoke(result) : fallbackResult
				// }
				//
				ParameterExpression result = Expression.Parameter (typeof (object), null);
				ParameterExpression callArgs = method != DynamicObject_TryBinaryOperation ? Expression.Parameter (typeof (object[]), null) : Expression.Parameter (typeof (object), null);
				ReadOnlyCollection<Expression> callArgsValue = GetConvertedArgs (args);

				var resultMO = new DynamicMetaObject (result, BindingRestrictions.Empty);

				// Need to add a conversion if calling TryConvert
				if (binder.ReturnType != typeof (object))
				{
					Debug.replacedert (binder is ConvertBinder && fallbackInvoke == null);

					UnaryExpression convert = Expression.Convert (resultMO.Expression, binder.ReturnType);
					// will always be a cast or unbox
					Debug.replacedert (convert.Method == null);


					// Prepare a good exception message in case the convert will fail
					// JJA - we don't have access to the Strings type:
					//string convertFailed = System.Linq.Expressions.Strings.DynamicObjectResultNotreplacedignable (
					//	"{0}",
					//	this.Value.GetType(),
					//	binder.GetType(),
					//	binder.ReturnType
					//);				
					string convertFailed = $"Dynamic conversion failed: Could not convert type '{Value.WrappedType}' to '{binder.ReturnType}'.";

					Expression condition;
					// If the return type can not be replacedigned null then just check for type replacedignability otherwise allow null.
					if (binder.ReturnType.IsValueType && Nullable.GetUnderlyingType (binder.ReturnType) == null)
					{
						condition = Expression.TypeIs (resultMO.Expression, binder.ReturnType);
					}
					else
					{
						condition = Expression.OrElse (
										Expression.Equal (resultMO.Expression, AstUtils.Null),
										Expression.TypeIs (resultMO.Expression, binder.ReturnType));
					}

					Expression checkedConvert = Expression.Condition (
						condition,
						convert,
						Expression.Throw (
							Expression.New (
								InvalidCastException_Ctor_String,
								new TrueReadOnlyCollection<Expression> (
									Expression.Call (
										String_Format_String_ObjectArray,
										Expression.Constant (convertFailed),
										Expression.NewArrayInit (
											typeof (object),
											new TrueReadOnlyCollection<Expression> (
												Expression.Condition (
													Expression.Equal (resultMO.Expression, AstUtils.Null),
													Expression.Constant ("null"),
													Expression.Call (
														resultMO.Expression,
														Object_GetType
													),
													typeof (object)
												)
											)
										)
									)
								)
							),
							binder.ReturnType
						),
						binder.ReturnType
					);

					resultMO = new DynamicMetaObject (checkedConvert, resultMO.Restrictions);
				}

				if (fallbackInvoke != null)
				{
					resultMO = fallbackInvoke (this, binder, resultMO);
				}

				var callDynamic = new DynamicMetaObject (
					Expression.Block (
						new TrueReadOnlyCollection<ParameterExpression> (result, callArgs),
						new TrueReadOnlyCollection<Expression> (
							method != DynamicObject_TryBinaryOperation ? Expression.replacedign (callArgs, Expression.NewArrayInit (typeof (object), callArgsValue)) : Expression.replacedign (callArgs, callArgsValue[0]),
							Expression.Condition (
								Expression.Call (
									GetLimitedSelf (),
									method,
									BuildCallArgs (
										binder,
										method.Name == "TryInvokeMember", // JJA
										args,
										callArgs,
										result
									)
								),
								Expression.Block (
									method != DynamicObject_TryBinaryOperation ? ReferenceArgreplacedign (callArgs, args) : AstUtils.Empty,
									resultMO.Expression
								),
								fallbackResult.Expression,
								binder.ReturnType
							)
						)
					),
					GetRestrictions ().Merge (resultMO.Restrictions).Merge (fallbackResult.Restrictions)
				);
				return callDynamic;
			}

19 Source : Extension.cs
with MIT License
from AlenToma

public static List<string> GetDbTypeListByType(this IFastDeepClonerProperty prop, DataBaseTypes dbType)
        {
            var type = prop.PropertyType;

            if (prop.ContainAttribute<Stringify>() ||
                prop.ContainAttribute<DataEncode>() ||
                prop.ContainAttribute<ToBase64String>() ||
                prop.ContainAttribute<JsonDoreplacedent>() ||
                prop.ContainAttribute<XmlDoreplacedent>())
                return new List<string>() { typeof(string).GetDbTypeByType(dbType) };

            if (prop.ContainAttribute<ColumnType>() && prop.Attributes.Any(x => x is ColumnType && !string.IsNullOrEmpty((x as ColumnType).DataType) && ((x as ColumnType).DataBaseTypes == dbType) || !(x as ColumnType).DataBaseTypes.HasValue))
                return prop.Attributes.Where(x => x is ColumnType && !string.IsNullOrEmpty((x as ColumnType).DataType) && ((x as ColumnType).DataBaseTypes == dbType) || !(x as ColumnType).DataBaseTypes.HasValue).Select(x => (x as ColumnType).DataType).ToList();

            if (type.GetTypeInfo().IsEnum)
                type = typeof(long);

            if (Nullable.GetUnderlyingType(type) != null)
                type = Nullable.GetUnderlyingType(type);
            if (dbType == DataBaseTypes.Mssql)
                return DbMsSqlMapper.ContainsKey(type) ? DbMsSqlMapper[type] : null;
            else if (dbType == DataBaseTypes.Sqllight)
                return DbSQLiteMapper.ContainsKey(type) ? DbSQLiteMapper[type] : null;
            else return DbPostGresqlMapper.ContainsKey(type) ? DbPostGresqlMapper[type] : null;
        }

19 Source : Extension.cs
with MIT License
from AlenToma

public static string GetDbTypeByType(this Type type, DataBaseTypes dbType)
        {
            if (type.GetTypeInfo().IsEnum)
                type = typeof(long);


            if (Nullable.GetUnderlyingType(type) != null)
                type = Nullable.GetUnderlyingType(type);
            if (dbType == DataBaseTypes.Mssql)
                return DbMsSqlMapper.ContainsKey(type) ? DbMsSqlMapper[type].First() : null;
            else if (dbType == DataBaseTypes.Sqllight)
                return DbSQLiteMapper.ContainsKey(type) ? DbSQLiteMapper[type].First() : null;
            else return DbPostGresqlMapper.ContainsKey(type) ? DbPostGresqlMapper[type].First() : null;
        }

19 Source : Extension.cs
with MIT License
from AlenToma

public static string GetDbTypeByType(this IFastDeepClonerProperty prop, DataBaseTypes dbType)
        {
            var type = prop.PropertyType;

            if (prop.ContainAttribute<Stringify>() ||
                prop.ContainAttribute<DataEncode>() ||
                prop.ContainAttribute<ToBase64String>() ||
                prop.ContainAttribute<JsonDoreplacedent>() ||
                prop.ContainAttribute<XmlDoreplacedent>())
                return typeof(string).GetDbTypeByType(dbType);

            if (prop.ContainAttribute<ColumnType>() && prop.Attributes.Any(x => x is ColumnType && !string.IsNullOrEmpty((x as ColumnType).DataType) && ((x as ColumnType).DataBaseTypes == dbType) || !(x as ColumnType).DataBaseTypes.HasValue))
                return prop.Attributes.Where(x => x is ColumnType && !string.IsNullOrEmpty((x as ColumnType).DataType) && ((x as ColumnType).DataBaseTypes == dbType) || !(x as ColumnType).DataBaseTypes.HasValue).Select(x => (x as ColumnType).DataType).First();

            if (type.GetTypeInfo().IsEnum)
                type = typeof(long);

            if (Nullable.GetUnderlyingType(type) != null)
                type = Nullable.GetUnderlyingType(type);
            if (dbType == DataBaseTypes.Mssql)
                return DbMsSqlMapper.ContainsKey(type) ? DbMsSqlMapper[type].First() : null;
            else if (dbType == DataBaseTypes.Sqllight)
                return DbSQLiteMapper.ContainsKey(type) ? DbSQLiteMapper[type].First() : null;
            else return DbPostGresqlMapper.ContainsKey(type) ? DbPostGresqlMapper[type].First() : null;
        }

19 Source : Querys.cs
with MIT License
from AlenToma

internal static string GetValueByType(object value, DataBaseTypes dbType)
        {
            if (value == null)
                return string.Format("String[{0}]", "NULL");
            var type = value.GetType();
            if (Nullable.GetUnderlyingType(type) != null)
                type = Nullable.GetUnderlyingType(type);

            if (type == typeof(decimal) || type == typeof(double) || type == typeof(float) || type == typeof(int) || type == typeof(long) || type == typeof(bool))
            {
                if (type == typeof(bool) && (dbType == DataBaseTypes.Mssql || dbType == DataBaseTypes.Sqllight))
                    return Convert.ToInt16(value).ToString();
                return value.ToString().ToLower();
            }
            if (type == typeof(Guid))
                return string.Format("Guid[{0}]", value);

            if (type.IsEnum)
                return ((int)(value)).ToString();
            return string.Format("String[{0}]", value);
        }

19 Source : Querys.cs
with MIT License
from AlenToma

internal static string GetValueByTypeSTRING(object value, DataBaseTypes dbType)
        {
            if (value == null)
                return string.Format("{0}", "NULL");
            var type = value.GetType();
            if (Nullable.GetUnderlyingType(type) != null)
                type = Nullable.GetUnderlyingType(type);

            if (type == typeof(decimal) || type == typeof(double) || type == typeof(float) || type == typeof(int) || type == typeof(long) || type == typeof(bool))
            {
                if (type == typeof(bool) && (dbType == DataBaseTypes.Mssql || dbType == DataBaseTypes.Sqllight))
                    return Convert.ToInt16(value).ToString();
                return value.ToString().ToLower();
            }
            if (type == typeof(Guid))
                return string.Format("'{0}'", value);
            if (type.IsEnum)
                return ((int)(value)).ToString();
            return string.Format("'{0}'", value);

        }

19 Source : Querys.cs
with MIT License
from AlenToma

public QueryConditions Column<T, P>(Expression<Func<T, P>> action)
        {
            var member = action.Body is UnaryExpression ? ((MemberExpression)((UnaryExpression)action.Body).Operand) : (action.Body is MethodCallExpression ? ((MemberExpression)((MethodCallExpression)action.Body).Object) : (MemberExpression)action.Body);
            if (member == null) return new QueryConditions(_sql, DataBaseTypes);
            var key = member.Member.Name;
            var type = typeof(P);
            if (Nullable.GetUnderlyingType(type) != null)
                type = Nullable.GetUnderlyingType(type);
            var col = key;
            if (col.ToLower().Contains(" as "))
                col = col.Remove(col.ToLower().IndexOf(" as ", StringComparison.Ordinal));
            if (type == typeof(decimal) || type == typeof(double) || type == typeof(float))
                _sql += DataBaseTypes == DataBaseTypes.Mssql ? " " + "CONVERT(decimal(18,5),[" + col + "]) " : " Cast(" + DataBaseTypes.GetValidSqlName(col) + " AS decimal(18,5)) ";
            else if (type == typeof(int) || type == typeof(long))
                _sql += DataBaseTypes == DataBaseTypes.Mssql ? " " + "CONVERT(decimal(18,5),[" + col + "]) " : " Cast(" + DataBaseTypes.GetValidSqlName(col) + " AS bigint) ";
            else if (type == typeof(Guid))
                _sql += DataBaseTypes.GetValidSqlName(col);
            else
                _sql += DataBaseTypes == DataBaseTypes.Mssql ? " " + "CONVERT(nvarchar(max),[" + col + "]) " : (DataBaseTypes == DataBaseTypes.Sqllight ? " Cast(" + DataBaseTypes.GetValidSqlName(col) + " AS nvarchar(4000)) " : " Cast(" + DataBaseTypes.GetValidSqlName(col) + " AS varchar(4000)) ");

            return new QueryConditions(_sql, DataBaseTypes);
        }

19 Source : DbSchema.cs
with MIT License
from AlenToma

public CodeToDataBaseMergeCollection GetDatabase_Diff(Type tableType, CodeToDataBaseMergeCollection str = null, List<Type> createdTables = null)
        {

            str = str ?? new CodeToDataBaseMergeCollection(_repository);
            if (tableType.GetCustomAttribute<ExcludeFromAbstract>() != null || _alreadyControlled.Any(x => x == tableType))
                return str;
            _repository.CreateSchema(tableType);
            tableType = tableType.GetActualType();
            _alreadyControlled.Add(tableType);
            createdTables = createdTables ?? new List<Type>();
            if (createdTables.Any(x => x == tableType) || tableType.GetPrimaryKey() == null)
                return str;

            if (CodeToDataBaseMergeCollection.ExecutedData.ContainsKey(tableType.FullName + _repository.DataBaseTypes.ToString()))
                return str;

            createdTables.Add(tableType);
            var table = _repository.GetColumnSchema(tableType);
            var tableName = tableType.TableName();
            var props = DeepCloner.GetFastDeepClonerProperties(tableType).Where(x => x.CanRead && !x.ContainAttribute<ExcludeFromAbstract>());
            var codeToDataBaseMerge = new CodeToDataBaseMerge() { Object_Type = tableType };
            var isPrimaryKey = "";
            if (!IsValidName(tableName.Name))
                throw new EnreplacedyException(tableName.Name + " is not a valid Name for the current provider " + _repository.DataBaseTypes);


            if (!table.Values.Any())
            {
                codeToDataBaseMerge.Sql = new StringBuilder($"CREATE TABLE {tableName.GetName(_repository.DataBaseTypes)} (");
                foreach (var prop in props.Where(x => (x.GetDbTypeByType(_repository.DataBaseTypes) != null || !x.IsInternalType ||
                x.ContainAttribute<JsonDoreplacedent>() || x.ContainAttribute<XmlDoreplacedent>()) &&
                !x.ContainAttribute<ExcludeFromAbstract>()).GroupBy(x => x.Name).Select(x => x.First())
                        .OrderBy(x => x.ContainAttribute<PrimaryKey>() ? null : x.Name))
                {
                    if (!prop.IsInternalType && !prop.ContainAttribute<JsonDoreplacedent>() && !prop.ContainAttribute<XmlDoreplacedent>())
                    {
                        if (!str.Any(x => x.Object_Type == prop.PropertyType.GetActualType()) && createdTables.All(x => x != prop.PropertyType.GetActualType()))
                            GetDatabase_Diff(prop.PropertyType, str, createdTables);
                        continue;
                    }

                    isPrimaryKey = prop.ContainAttribute<PrimaryKey>() ? prop.GetPropertyName() : isPrimaryKey;
                    var foreignKey = prop.GetCustomAttribute<ForeignKey>();
                    var dbType = prop.GetDbTypeByType(_repository.DataBaseTypes);
                    var propName = string.Format("[{0}]", prop.GetPropertyName());
                    codeToDataBaseMerge.Sql.Append(propName + " ");
                    if (!IsValidName(prop.GetPropertyName()))
                        throw new Exception(prop.GetPropertyName() + " is not a valid Name for the current provider " + _repository.DataBaseTypes);



                    if (!prop.ContainAttribute<PrimaryKey>() || _repository.DataBaseTypes == DataBaseTypes.Mssql)
                        codeToDataBaseMerge.Sql.Append(dbType + " ");


                    if (foreignKey != null && createdTables.All(x => x != foreignKey.Type))
                        GetDatabase_Diff(foreignKey.Type, str, createdTables);

                    if (prop.ContainAttribute<PrimaryKey>())
                    {
                        if (prop.PropertyType.IsNumeric() && prop.GetCustomAttribute<PrimaryKey>().AutoGenerate)
                            codeToDataBaseMerge.Sql.Append(_repository.DataBaseTypes == DataBaseTypes.Mssql ? "IDENreplacedY(1,1) NOT NULL," : (_repository.DataBaseTypes == DataBaseTypes.Sqllight ? " Integer PRIMARY KEY AUTOINCREMENT," : " BIGSERIAL PRIMARY KEY,"));
                        else codeToDataBaseMerge.Sql.Append(_repository.DataBaseTypes == DataBaseTypes.Mssql ? "NOT NULL," : " " + dbType + "  PRIMARY KEY,");
                        continue;
                    }

                    if (foreignKey != null)
                    {
                        var key = propName + "-" + tableName.GetName(_repository.DataBaseTypes);
                        if (!str.Keys.ContainsKey(key))
                            str.Keys.Add(key, new Tuple<string, ForeignKey>(tableName.GetName(_repository.DataBaseTypes), foreignKey));
                    }

                    codeToDataBaseMerge.Sql.Append((Nullable.GetUnderlyingType(prop.PropertyType) != null || prop.PropertyType == typeof(string)) && !prop.ContainAttribute<NotNullable>() ? " NULL," : " NOT NULL,");
                }

                if (str.Keys.Any() && _repository.DataBaseTypes == DataBaseTypes.Sqllight)
                {
                    while (str.Keys.Any(x => x.Value.Item1 == tableName.Name))
                    {

                        var key = str.Keys.FirstOrDefault(x => x.Value.Item1 == tableName.Name);
                        var type = key.Value.Item2.Type.GetActualType();
                        var keyPrimary = type.GetPrimaryKey().GetPropertyName();
                        var tb = type.TableName();
                        codeToDataBaseMerge.Sql.Append("FOREIGN KEY(" + key.Key.Split('-')[0] + ") REFERENCES " + tb.GetName(_repository.DataBaseTypes) + "(" + keyPrimary + "),");
                        str.Keys.Remove(key.Key);
                    }

                }

                if (!string.IsNullOrEmpty(isPrimaryKey) && _repository.DataBaseTypes == DataBaseTypes.Mssql)
                {
                    codeToDataBaseMerge.Sql.Append(" CONSTRAINT [PK_" + tableName.Name + "] PRIMARY KEY CLUSTERED");
                    codeToDataBaseMerge.Sql.Append(" ([" + isPrimaryKey + "] ASC");
                    codeToDataBaseMerge.Sql.Append(")");
                    codeToDataBaseMerge.Sql.Append("WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]");
                    codeToDataBaseMerge.Sql.Append(") ON [PRIMARY]");
                }
                else
                {
                    if (_repository.DataBaseTypes == DataBaseTypes.Sqllight)
                        codeToDataBaseMerge.Sql = new StringBuilder(codeToDataBaseMerge.Sql.ToString().TrimEnd(','));
                    codeToDataBaseMerge.Sql.Append(")");
                }

                str.Add(codeToDataBaseMerge);
            }
            else
            {
                foreach (var prop in props.Where(x => (x.GetDbTypeByType(_repository.DataBaseTypes) != null || !x.IsInternalType) && !x.ContainAttribute<ExcludeFromAbstract>()).GroupBy(x => x.Name).Select(x => x.First())
                .OrderBy(x => x.ContainAttribute<PrimaryKey>() ? null : x.Name))
                {

                    if (prop.ContainAttribute<ForeignKey>())
                        GetDatabase_Diff(prop.GetCustomAttribute<ForeignKey>().Type, str, createdTables);
                    var propType = prop.PropertyType;
                    if (prop.ContainAttribute<Stringify>() ||
                        prop.ContainAttribute<DataEncode>() ||
                        prop.ContainAttribute<ToBase64String>() ||
                        prop.ContainAttribute<JsonDoreplacedent>() ||
                        prop.ContainAttribute<XmlDoreplacedent>())
                        propType = typeof(string);

                    var modify = prop.IsInternalType || prop.ContainAttribute<JsonDoreplacedent>() || prop.ContainAttribute<XmlDoreplacedent>() ? (_repository.DataBaseTypes == DataBaseTypes.PostgreSql ? table.Get(prop.GetPropertyName().ToLower()) : table.Get(prop.GetPropertyName())) : null;
                    if (modify != null)
                    {

                        if (_repository.DataBaseTypes != DataBaseTypes.Sqllight && !(prop.GetDbTypeListByType(_repository.DataBaseTypes).Any(x => x.ToLower().Contains(modify.DataType.ToLower()))) && _repository.DataBaseTypes != DataBaseTypes.PostgreSql)
                        {
                            var constraine = Properties.Resources.DropContraine
                                .Replace("@tb", $"'{tableName.Name}'").Replace("@col", $"'{prop.GetPropertyName()}'")
                                .Replace("@schema", $"'{tableName.Schema ?? ""}'")
                                .Replace("@TableName", "@" + counter++)
                                .Replace("@ColumnName", "@" + counter++)
                                .Replace("@fullName", "@" + counter++)
                                .Replace("@DROP_COMMAND", "@" + counter++)
                                .Replace("@FOREIGN_KEY_NAME", "@" + counter++);
                            codeToDataBaseMerge.Sql.Append(constraine);
                            codeToDataBaseMerge.Sql.Append($"\nALTER TABLE {tableName.GetName(_repository.DataBaseTypes)} ALTER COLUMN [{prop.GetPropertyName()}] {prop.GetDbTypeByType(_repository.DataBaseTypes)} {((Nullable.GetUnderlyingType(propType) != null || propType == typeof(string)) && !prop.ContainAttribute<NotNullable>() ? " NULL" : " NOT NULL")}");
                        }
                        else
                        {
                            if (!(prop.GetDbTypeListByType(_repository.DataBaseTypes).Any(x => x.ToLower().Contains(modify.DataType.ToLower()))) && _repository.DataBaseTypes == DataBaseTypes.PostgreSql)
                                codeToDataBaseMerge.Sql.Append($"\nALTER TABLE {tableName.GetName(_repository.DataBaseTypes)} ALTER COLUMN [{prop.GetPropertyName()}] TYPE {prop.GetDbTypeByType(_repository.DataBaseTypes)}, ALTER COLUMN [{prop.GetPropertyName()}] SET DEFAULT {Querys.GetValueByTypeSTRING(MethodHelper.ConvertValue(null, propType), _repository.DataBaseTypes)};");


                        }
                    }
                    else if (!prop.IsInternalType && !prop.ContainAttribute<JsonDoreplacedent>() && !prop.ContainAttribute<XmlDoreplacedent>())
                        GetDatabase_Diff(prop.PropertyType, str, createdTables);
                    else
                    {
                        codeToDataBaseMerge.Sql.Append(string.Format("\nALTER TABLE {0} ADD " + (_repository.DataBaseTypes == DataBaseTypes.PostgreSql ? "COLUMN" : "") + " [{1}] {2} {3} DEFAULT {4};", tableName.GetName(_repository.DataBaseTypes), prop.GetPropertyName(), prop.GetDbTypeByType(_repository.DataBaseTypes),
                              (Nullable.GetUnderlyingType(propType) != null || propType == typeof(string)) && !prop.ContainAttribute<NotNullable>() ? " NULL" : " NOT NULL", Querys.GetValueByTypeSTRING(MethodHelper.ConvertValue(null, propType), _repository.DataBaseTypes)));
                    }
                }
            }

            var colRemove = new CodeToDataBaseMerge() { Object_Type = tableType };
            // Now lets clean the table and remove unused columns
            foreach (var col in table.Values.Where(x =>
             !props.Any(a => string.Equals(x.ColumnName, a.GetPropertyName(), StringComparison.CurrentCultureIgnoreCase) &&
             (a.GetDbTypeByType(_repository.DataBaseTypes) != null || (!a.IsInternalType || a.ContainAttribute<JsonDoreplacedent>() || a.ContainAttribute<XmlDoreplacedent>())) &&
             !a.ContainAttribute<ExcludeFromAbstract>())))
            {
                if (_repository.DataBaseTypes != DataBaseTypes.Sqllight)
                {
                    if (_repository.DataBaseTypes == DataBaseTypes.Mssql)
                    {
                        var constraine = Properties.Resources.DropContraine
                            .Replace("@tb", $"'{tableName.Name}'")
                            .Replace("@col", $"'{col.ColumnName}'")
                            .Replace("@schema", $"'{tableName.Schema ?? ""}'")
                            .Replace("@TableName", "@" + counter++)
                            .Replace("@ColumnName", "@" + counter++)
                            .Replace("@fullName", "@" + counter++)
                            .Replace("@DROP_COMMAND", "@" + counter++)
                            .Replace("@FOREIGN_KEY_NAME", "@" + counter++);

                        colRemove.Sql.Append(constraine);

                    }
                    colRemove.Sql.Append(string.Format("\nALTER TABLE {0} DROP COLUMN IF EXISTS [{1}];", tableName.GetName(_repository.DataBaseTypes), col.ColumnName));

                }
                else
                {
                    colRemove.Sql.Append(string.Format("DROP TABLE IF exists [{0}_temp];\nCREATE TABLE [{0}_temp] AS SELECT {1} FROM [{0}];", tableName.Name, string.Join(",", table.Values.ToList().FindAll(x =>
                    props.Any(a => string.Equals(x.ColumnName, a.GetPropertyName(), StringComparison.CurrentCultureIgnoreCase) &&
                    (a.GetDbTypeByType(_repository.DataBaseTypes) != null || !a.IsInternalType) &&
                    !a.ContainAttribute<ExcludeFromAbstract>())).Select(x => x.ColumnName))));
                    colRemove.Sql.Append(string.Format("DROP TABLE [{0}];\n", tableName.Name));
                    colRemove.Sql.Append(string.Format("ALTER TABLE [{0}_temp] RENAME TO [{0}]; ", tableName.Name));
                }
                colRemove.DataLoss = true;
            }
            str.Add(colRemove);

            foreach (var prop in props.Where(x => !x.IsInternalType && !x.ContainAttribute<JsonDoreplacedent>() && !x.ContainAttribute<XmlDoreplacedent>() && !x.ContainAttribute<XmlDoreplacedent>() && !x.ContainAttribute<ExcludeFromAbstract>()).GroupBy(x => x.Name).Select(x => x.First()))
            {
                var type = prop.PropertyType.GetActualType();
                if (type.GetPrimaryKey() != null)
                    GetDatabase_Diff(type, str, createdTables);
            }

            str.Add(codeToDataBaseMerge);
            return str;
        }

19 Source : Querys.cs
with MIT License
from AlenToma

public QueryConditions Column<T>(string columnName)
        {
            var col = columnName;
            if (col.ToLower().Contains(" as "))
                col = col.Remove(col.ToLower().IndexOf(" as ", StringComparison.Ordinal));
            var type = typeof(T);
            if (Nullable.GetUnderlyingType(type) != null)
                type = Nullable.GetUnderlyingType(type);
            if (type == typeof(decimal) || type == typeof(double) || type == typeof(float))
                _sql += DataBaseTypes == DataBaseTypes.Mssql ? " " + "CONVERT(decimal(18,5),[" + col + "]) " : " Cast(" + DataBaseTypes.GetValidSqlName(col) + " AS decimal(18,5)) ";
            else if (type == typeof(int) || type == typeof(long))
                _sql += DataBaseTypes == DataBaseTypes.Mssql ? " " + "CONVERT(decimal(18,5),[" + col + "]) " : " Cast(" + DataBaseTypes.GetValidSqlName(col) + " AS bigint) ";
            else if (type == typeof(Guid))
                _sql += DataBaseTypes.GetValidSqlName(col);
            else
                _sql += DataBaseTypes == DataBaseTypes.Mssql ? " " + "CONVERT(nvarchar(max),[" + col + "]) " : (DataBaseTypes == DataBaseTypes.Sqllight ? " Cast(" + DataBaseTypes.GetValidSqlName(col) + " AS nvarchar(4000)) " : " Cast(" + DataBaseTypes.GetValidSqlName(col) + " AS varchar(4000)) ");

            return new QueryConditions(_sql, DataBaseTypes);
        }

See More Examples