internal static Comparator GetComparator(Type type)
        {
            if (type.IsNullable<DateTime>())
            {
                return new NullableDateComparator();
            }

            if (type == typeof (DateTime))
            {
                return new DateComparator();
            }

            if (type == typeof (string))
            {
                return new StringComparator();
            }

            if (type.IsNullable())
            {
                return new NullableComparator();
            }

            if (type.IsValueType)
            {
                return new ValueTypeComparator();
            }

            return new Comparator();
        }
        public void GenerateCanEvalutateManyTimesTest(Type type, bool typeSupported, double min, double max)
        {
            if (typeSupported == false)
            {
                // Ignore this test
                return;
            }

            var target = new NumericValueGenerator();

            for (var index = 0; index < 10000; index++)
            {
                var value = target.Generate(type, null, null);
                
                if (type.IsNullable() && value == null)
                {
                    // Nullable values could be returned so nothing more to assert
                    return;
                }

                var evaluateType = type;

                if (type.IsNullable())
                {
                    evaluateType = type.GenericTypeArguments[0];
                }

                value.Should().BeOfType(evaluateType);

                var convertedValue = Convert.ToDouble(value);

                convertedValue.Should().BeGreaterOrEqualTo(min);
                convertedValue.Should().BeLessOrEqualTo(max);
            }
        }
Esempio n. 3
0
 /// <summary>
 /// Checks that a type is the same as the expected one.
 /// </summary>
 /// <param name="instanceType">The type of the instance to be checked.</param>
 /// <param name="expectedType">The expected type for the instance to be checked.</param>
 /// <param name="value">The value of the instance to be checked (may be a nullable instance).</param>
 public static void IsSameType(Type instanceType, Type expectedType, object value)
 {
     if (instanceType != expectedType || (value == null && !instanceType.IsNullable()))
     {
         throw new FluentCheckException(BuildErrorMessageForNullable(instanceType, expectedType, value, false));
     }
 }
Esempio n. 4
0
        static System.Type CalculateAverageType(System.Type inputType)
        {
            var isNullable = false;

            if (inputType.IsNullable())
            {
                isNullable = true;
                inputType  = inputType.NullableOf();
            }

            switch (System.Type.GetTypeCode(inputType))
            {
            case TypeCode.Int16:
            case TypeCode.Int32:
            case TypeCode.Int64:
            case TypeCode.Single:
            case TypeCode.Double:
                return(isNullable ? typeof(double?) : typeof(double));

            case TypeCode.Decimal:
                return(isNullable ? typeof(decimal?) : typeof(decimal));
            }

            throw new NotSupportedException(inputType.FullName);
        }
Esempio n. 5
0
        /// <summary>
        /// Gets TsTypeFamily of the CLR type.
        /// </summary>
        /// <param name="type">The CLR type to get TsTypeFamily of</param>
        /// <returns>TsTypeFamily of the CLR type</returns>
        internal static TsTypeFamily GetTypeFamily(System.Type type)
        {
            if (type.IsNullable())
            {
                return(TsType.GetTypeFamily(type.GetNullableValueType()));
            }

            var isString     = (type == typeof(string));
            var isEnumerable = typeof(IEnumerable).IsAssignableFrom(type);

            // surprisingly  Decimal isn't a primitive type
            if (isString || type.IsPrimitive || type.FullName == "System.Decimal" || type.FullName == "System.DateTime" || type.FullName == "System.DateTimeOffset")
            {
                return(TsTypeFamily.System);
            }
            else if (isEnumerable)
            {
                return(TsTypeFamily.Collection);
            }

            if (type.IsEnum)
            {
                return(TsTypeFamily.Enum);
            }

            if ((type.IsClass && type.FullName != "System.Object") || type.IsValueType /* structures */ || type.IsInterface)
            {
                return(TsTypeFamily.Class);
            }

            return(TsTypeFamily.Type);
        }
Esempio n. 6
0
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType.IsNullable())
                return CanConvertTo(context, Nullable.GetUnderlyingType(destinationType));

            return GoodTypes.Contains(destinationType) || base.CanConvertTo(context, destinationType);
        }
Esempio n. 7
0
        /// <summary>
        /// Initializes a new instance of the TsType class with the specific CLR type.
        /// </summary>
        /// <param name="type">The CLR type represented by this instance of the TsType.</param>
        public TsType(Type type)
        {
            if (type.IsNullable()) {
                type = type.GetNullableValueType();
            }

            this.Type = type;
        }
Esempio n. 8
0
        public static NpgsqlDbType ToDbType(Type type)
        {
            if (type.IsNullable()) return ToDbType(type.GetInnerTypeFromNullable());

            if (type == typeof (DateTime)) return NpgsqlDbType.Date;

            return (NpgsqlDbType) _getNgpsqlDbTypeMethod.Invoke(null, new object[] {type});
        }
Esempio n. 9
0
        internal static System.Type UnwrapIfNullable(this System.Type type)
        {
            if (type.IsNullable())
            {
                return(type.NullableOf());
            }

            return(type);
        }
        public bool IsPrimitiveType(Type type)
        {
            if (type == null)
                return false;

            if (type.IsNullable())
                type = Nullable.GetUnderlyingType(type);

            return type.IsPrimitive || type.IsEnum || primitiveTypes.Any(x => x.IsAssignableFrom(type));
        }
 /// <summary>
 /// Extension point. Try to find per-type <see cref="ReplicationBehavior"/> or
 /// return <c>null</c>, if current <see cref="IMetadataProvider"/> does not specify it.
 /// </summary>
 protected virtual ReplicationBehavior? TryGetPerTypeBehavior(Type entityType)
 {
     if (entityType.IsPrimitive || entityType.IsEnum || entityType == typeof (string))
         return ReplicationBehavior.Copy;
     if (entityType.IsNullable()) {
         Type underlyingType = entityType.GetNullableUnderlyingType();
         return GetPerTypeBehavior(underlyingType);
     }
     return null;
 }
Esempio n. 12
0
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType.IsNullable() && value != null)
                return ConvertTo(context, culture, value, Nullable.GetUnderlyingType(destinationType));

            if (GoodTypes.Contains(destinationType))
                return Convert.ChangeType(value, destinationType);

            return base.ConvertTo(context, culture, value, destinationType);
        }
 public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer ) {
     var jsonValue = serializer.Deserialize<JValue>(reader);
     switch ( jsonValue.Type ) {
         case JTokenType.Integer:
             var dto = DateTimeOffsetHelper.FromUnixTimeSeconds( jsonValue.Value<long>() );
             if ( objectType == DateTimeOffsetType || ( objectType.IsNullable() && Nullable.GetUnderlyingType( objectType ) == DateTimeOffsetType ) )
                 return dto;
             return dto.LocalDateTime;
         case JTokenType.Date:
             if ( objectType == DateTimeOffsetType || (objectType.IsNullable() && Nullable.GetUnderlyingType(objectType) == DateTimeOffsetType))
                 return jsonValue.Value<DateTimeOffset>();
             return jsonValue.Value<DateTime>();
         case JTokenType.Null:
             if ( objectType.IsNullable() )
                 return null;
             throw new JsonSerializationException( $"Can't deserialize null value to non-nullable type" );
         default:
             throw new JsonSerializationException( $"Unexpected token {jsonValue.Type} when parsing a date." );
     }
 }
        public static object ToType(this string origin, Type dest)
        {
            if (dest.IsNullable() && string.IsNullOrEmpty(origin))
                return null;

            var realType = dest.GetValueTypeIfNullable();
            if (typeof(IConvertible).IsAssignableFrom(realType))
                return Convert.ChangeType(origin, realType);

            throw new NotSupportedException("Cannot convert to type");
        }
Esempio n. 15
0
        public static DataType BuildDataType(Type type, Func<Type, MemberInfo, int> membersOrder = null)
        {
            if (DataType.IsPrimitiveType(type) || type.IsEnum || type == typeof(Guid) || type.IsKeyValuePair() || type.IsArray || type.IsList() || type.IsDictionary() || type.IsNullable())
                return BuildDataType(type, membersOrder, new HashSet<Type>());

            List<DataType> slots = new List<DataType>();
            foreach (var member in GetPublicMembers(type, membersOrder))
                slots.Add(BuildDataType(member.GetPropertyOrFieldType(), membersOrder, new HashSet<Type>()));

            return DataType.Slots(slots.ToArray());
        }
Esempio n. 16
0
        public static string GetPgType(Type memberType)
        {
            if (memberType.IsEnum) return "integer";

            if (memberType.IsNullable())
            {
                return GetPgType(memberType.GetInnerTypeFromNullable());
            }

            return PgTypes[memberType];
        }
        private static bool CheckIfIsImmutable(Type type, List<Type> checkedTypes)
        {
            bool result;
            if (ImmutableCheckedTypes.TryGetValue(type, out result))
            {
                return result;
            }

            if (type.IsNullable())
            {
                var underlyingType = Nullable.GetUnderlyingType(type);
                result = CheckIfIsImmutable(underlyingType, checkedTypes);
            }
            else if (type == typeof(bool))
            {
                result = true;
            }
            else if (type.IsEnum)
            {
                result = true;
            }
            else if (type.IsArray)
            {
                result = false;
            }
            else if (type.IsDelegate())
            {
                result = true;
            }
            else if (type.IsImmutableList() ||
                     type.IsImmutableArray() ||
                     type.IsImmutableHashSet())
            {
                var itemType = type.GetItemType();
                result = CheckIfIsImmutable(itemType, checkedTypes);
            }
            else if (type.IsKeyValuePair())
            {
                var genericArguments = type.GetGenericArguments();
                result = CheckIfIsImmutable(genericArguments[0], checkedTypes)
                         && CheckIfIsImmutable(genericArguments[1], checkedTypes);
            }
            else if (CanBeImmutable(type))
            {
                result = HasImmutableMembers(type, checkedTypes);
            }
            else
            {
                result = false;
            }

            ImmutableCheckedTypes.TryAdd(type, result);
            return result;
        }
 /// <summary>
 /// Returns a Expression reading a property from a IDataRecord, at the specified index
 /// The lambda parameters are:
 /// - IDataRecord
 /// - MappingContext
 /// - int (field index)
 /// </summary>
 /// <param name="returnType">The expected return type (to be mapped to the property)</param>
 /// <returns>An expression returning the field value</returns>
 public virtual LambdaExpression GetPropertyReader(Type returnType)
 {
     // if we have a nullable, then use its inner type
     if (returnType.IsNullable())
     {
         var nonNullableReturnType = returnType.GetNullableType();
         return GetNullablePropertyReader(nonNullableReturnType);
     }
     // otherwise, it's simple
     return GetNullablePropertyReader(returnType);
 }
Esempio n. 19
0
 public ClassMapper(Type fromType, Type toType)
     : base(fromType, toType)
 {
     if (!toType.IsAbstract)
     {
         if (toType.IsNullable())
             Ctor = DynamicMethodFactory.GetDefaultCreator(Nullable.GetUnderlyingType(toType));
         else
             Ctor = DynamicMethodFactory.GetDefaultCreator(toType);
     }
 }
Esempio n. 20
0
 public DataRowMapper(Type toType)
     : base(typeof(DataRow), toType)
 {
     if (!toType.IsAbstract)
     {
         if (toType.IsNullable())
             Ctor = DynamicMethodFactory.GetDefaultCreator(Nullable.GetUnderlyingType(toType));
         else
             Ctor = DynamicMethodFactory.GetDefaultCreator(toType);
     }
 }
Esempio n. 21
0
 /// <summary>
 /// 写入类型转换的 IL 指令。
 /// </summary>
 /// <param name="generator">IL 的指令生成器。</param>
 /// <param name="inputType">要转换的对象的类型。</param>
 /// <param name="outputType">要将输入对象转换到的类型。</param>
 /// <param name="isChecked">是否执行溢出检查。</param>
 public override void Emit(ILGenerator generator, Type inputType, Type outputType, bool isChecked)
 {
     Contract.Assume(inputType.IsNullable());
     Type inputUnderlyingType = Nullable.GetUnderlyingType(inputType);
     generator.EmitCall(inputType.GetMethod("get_Value"));
     if (inputUnderlyingType != outputType)
     {
         Conversion conversion = ConversionFactory.GetConversion(inputUnderlyingType, outputType);
         Contract.Assume(conversion != null);
         conversion.Emit(generator, inputUnderlyingType, outputType, isChecked);
     }
 }
Esempio n. 22
0
 /// <summary>
 /// Converts <paramref name="value"/> to the corresponding value of 
 /// type <paramref name="targetType"/>.  <paramref name="targetType"/>
 /// must be one of the following types: string, value type, and nullable type.
 /// </summary>
 /// <param name="value">The string to be converted.</param>
 /// <param name="targetType">The target type to convert <paramref name="value"/> to.</param>
 /// <returns>The corresponding value, in <paramref name="targetType"/>, of <paramref name="value"/>.</returns>
 /// <seealso cref="Convert.ChangeType(object,System.Type)"/>
 public static object ConvertToType(this string value, Type targetType)
 {
     if (value == null)
         return null;
     if (targetType == typeof(string))
         return value;
     if (targetType.IsEnum)
         return Enum.Parse(targetType, value, true);
     if (targetType.IsNullable())
         targetType = Nullable.GetUnderlyingType(targetType);
     return Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture);
 }
        public SimpleValueObjectContext(Type type, object value)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            if (value == null && type.IsValueType && !type.IsNullable())
                throw new ArgumentNullException("Specified type '" + type.Name + "' cannot be null.", "value");

            if (value != null && !type.IsInstanceOfType(value))
                throw new ArgumentException("Specified value '" + value + "' is not an instance of the specified type '" + type + "'.", "value");

            _value = value;
            _type = type;
        }
        public CommonReplicationStrategy(IMetadataProvider metadataProvider, Type entityType)
        {
            Guard.AgainstNull(metadataProvider, "metadataProvider");
            Guard.AgainstNull(entityType, "entityType");
            Guard.AgainstViolation(!entityType.IsNullable() && !entityType.IsArray,
                "CommonReplicationStrategy is not applicable to nullable or array types");

            this.entityType = entityType;

            memberDescriptions = metadataProvider.GetFieldsReplicationInfo(entityType)
                .Where(t => t.Behavior != ReplicationBehavior.Ignore)
                .Select(t => new MemberReplicationInfo(entityType, t))
                .ToArray();
        }
        public Func<string, object> ConverterFor(Type type)
        {
            if (!type.IsNullable()) return null;

            var innerType = type.GetGenericArguments().First();
            var inner = _conversions.FindConverter(innerType);

            return str =>
            {
                if (str == "NULL") return null;

                return inner(str);
            };
        }
Esempio n. 26
0
 /// <summary>
 /// 写入类型转换的 IL 指令。
 /// </summary>
 /// <param name="generator">IL 的指令生成器。</param>
 /// <param name="inputType">要转换的对象的类型。</param>
 /// <param name="outputType">要将输入对象转换到的类型。</param>
 /// <param name="isChecked">是否执行溢出检查。</param>
 public override void Emit(ILGenerator generator, Type inputType, Type outputType, bool isChecked)
 {
     Contract.Assume(outputType.IsNullable());
     Type outputUnderlyingType = Nullable.GetUnderlyingType(outputType);
     if (inputType != outputUnderlyingType)
     {
         Conversion conversion = ConversionFactory.GetConversion(inputType, outputUnderlyingType);
         Contract.Assume(conversion != null);
         conversion.Emit(generator, inputType, outputUnderlyingType, isChecked);
     }
     ConstructorInfo ctor = outputType.GetConstructor(new[] { outputUnderlyingType });
     Contract.Assume(ctor != null);
     generator.Emit(OpCodes.Newobj, ctor);
 }
 private List <Option> GetOptions(System.Type type)
 {
     return(type.IsEnum || (type.IsNullable() && Nullable.GetUnderlyingType(type).IsEnum) ?
            type.GetEnumOptions()
            .Where(x => !x.HasAttribute <HideAttribute>())
            .Select(x => {
         var option = _optionConvention.GetDescription(x);
         return _configuration.OptionOverrides.Apply(x, new Option {
             Name = option.WhenNotNull(y => y.Name).OtherwiseDefault(),
             Comments = option.WhenNotNull(y => y.Comments).OtherwiseDefault(),
             Value = _configuration.EnumValue == EnumValue.AsString ? x.Name : x.GetRawConstantValue().ToString()
         });
     }).OrderBy(x => x.Name ?? x.Value).ToList()
      : new List <Option>());
 }
Esempio n. 28
0
		public static object Evaluate (object a, object b, Type t, ExpressionType et)
		{
			TypeCode tc = Type.GetTypeCode (t);
			if (tc == TypeCode.Object) {
				if (!t.IsNullable ()) {
					throw new NotImplementedException (
						string.Format (
						"Expression with Node type {0} for type {1}",
						t.FullName,
						tc));

				}
				return EvaluateNullable (a, b, Type.GetTypeCode (t.GetGenericArguments () [0]), et);
			}
			return Evaluate (a, b, tc, et);
		}
Esempio n. 29
0
        public static bool IsAllPrimitive(Type type, Func<Type, MemberInfo, int> membersOrder = null)
        {
            if (DataType.IsPrimitiveType(type))
                return true;

            if (type.IsArray || type.IsList() || type.IsDictionary() || type.IsKeyValuePair() || type.IsNullable() || type == typeof(Guid))
                return false;

            foreach (var member in GetPublicMembers(type, membersOrder))
            {
                if (!DataType.IsPrimitiveType(member.GetPropertyOrFieldType()))
                    return false;
            }

            return true;
        }
Esempio n. 30
0
        internal static bool IsPrimitiveTypeMapping(Type fromType, Type toType)
        {
            if (fromType == null)
                return false;
            if (toType == null)
                return false;
            if (fromType.IsNullable())
                fromType = fromType.GetGenericArguments()[0];
            if (Type.GetTypeCode(fromType) == TypeCode.Object)
                return false;
            if (toType.IsNullable())
                toType = toType.GetGenericArguments()[0];
            if (Type.GetTypeCode(toType) == TypeCode.Object)
                return false;

            return true;
        }
Esempio n. 31
0
        public static string GetValueResponseWrapperTypeName(Type type)
        {
            var unwrappedType = type.GetUnwrappedNullableType();

            if (unwrappedType.IsNumericType(true) || unwrappedType == typeof(bool) || (unwrappedType.IsEnum && type.IsNullable()))
            {
                return "NumberValueResponse";
            }
            else if (unwrappedType is FickleListType)
            {
                return "ArrayValueResponse";
            }
            else
            {
                return TypeSystem.GetPrimitiveName(unwrappedType, true) + "ValueResponse";
            }
        }
        /// <inheritdoc />
        /// <exception cref="ArgumentNullException">The <paramref name="type"/> parameter is null.</exception>
        public override bool IsSupported(Type type, string referenceName, LinkedList<object> buildChain)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            if (type.IsNullable())
            {
                // Get the internal type
                var internalType = type.GetGenericArguments()[0];

                return Generator.IsSupported(internalType);
            }

            return Generator.IsSupported(type);
        }
Esempio n. 33
0
        private static bool SatisfiesConstraints(this Type genericVariable, SigTypeContext typeContextOfConstraintDeclarer, Type typeArg)
        {
            GenericParameterAttributes specialConstraints = genericVariable.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;

            if ((specialConstraints & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0)
            {
                if (!typeArg.IsValueType)
                    return false;
                else
                {
                    // the type argument is a value type, however if it is any kind of Nullable we want to fail
                    // as the constraint accepts any value type except Nullable types (Nullable itself is a value type)
                    if (typeArg.IsNullable())
                        return false;
                }
            }

            if ((specialConstraints & GenericParameterAttributes.ReferenceTypeConstraint) != 0)
            {
                if (typeArg.IsValueType)
                    return false;
            }

            if ((specialConstraints & GenericParameterAttributes.DefaultConstructorConstraint) != 0)
            {
                if (!typeArg.HasExplicitOrImplicitPublicDefaultConstructor())
                    return false;
            }

            // Now check general subtype constraints
            foreach (var constraint in genericVariable.GetGenericParameterConstraints())
            {
                Type instantiatedTypeConstraint = constraint.Instantiate(typeContextOfConstraintDeclarer);

                // System.Object constraint will be always satisfied - even if argList is empty
                if (instantiatedTypeConstraint.IsSystemObject())
                    continue;

                // if a concrete type can be cast to the constraint, then this constraint will be satisifed
                if (!AreTypesAssignable(typeArg, instantiatedTypeConstraint))
                    return false;
            }

            return true;
        }
Esempio n. 34
0
 public static bool IsPrimitive(this System.Type type)
 {
     return(type.IsValueType || type.IsNullable() || type == typeof(string));
 }
Esempio n. 35
0
 public static bool IsNullableOrReference(this System.Type type)
 {
     return(!type.IsValueType || type.IsNullable());
 }
        private ModelSpec CreateSpecFor(Type type, bool deferIfComplex, Dictionary<Type, ModelSpec> deferredMappings)
        {
            if (_customMappings.ContainsKey(type))
                return _customMappings[type];

            if (PrimitiveMappings.ContainsKey(type))
                return PrimitiveMappings[type];

            if (type.IsEnum)
                return new ModelSpec {Type = "string", Enum = type.GetEnumNames()};

            Type innerType;
            if (type.IsNullable(out innerType))
                return CreateSpecFor(innerType, deferIfComplex, deferredMappings);

            Type itemType;
            if (type.IsEnumerable(out itemType))
                return new ModelSpec { Type = "array", Items = CreateSpecFor(itemType, true, deferredMappings) };

            // Anthing else is complex

            if (deferIfComplex)
            {
                if (!deferredMappings.ContainsKey(type))
                    deferredMappings.Add(type, null);
                
                // Just return a reference for now
                return new ModelSpec {Ref = UniqueIdFor(type)};
            }

            return CreateComplexSpecFor(type, deferredMappings);
        }