// keep in sync with System.Core version internal static bool IsNumeric(Type type) { type = GetNonNullableType(type); if (!type.IsEnum()) { return IsNumeric(type.GetTypeCode()); } return false; }
public static void ArgumentTypeIsEnum(Type enumType, string parameterName) { ArgumentNotNull(enumType, "enumType"); if (!enumType.IsEnum()) throw new ArgumentException("Type {0} is not an Enum.".FormatWith(CultureInfo.InvariantCulture, enumType), parameterName); }
public static Instruction Create(Type type) { // Boxed enums can be unboxed as their underlying types: switch ((type.IsEnum() ? Enum.GetUnderlyingType(type) : type).GetTypeCode()) { case TypeCode.Boolean: return _Boolean ?? (_Boolean = new NotEqualBoolean()); case TypeCode.SByte: return _SByte ?? (_SByte = new NotEqualSByte()); case TypeCode.Byte: return _Byte ?? (_Byte = new NotEqualByte()); case TypeCode.Char: return _Char ?? (_Char = new NotEqualChar()); case TypeCode.Int16: return _Int16 ?? (_Int16 = new NotEqualInt16()); case TypeCode.Int32: return _Int32 ?? (_Int32 = new NotEqualInt32()); case TypeCode.Int64: return _Int64 ?? (_Int64 = new NotEqualInt64()); case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new NotEqualInt16()); case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new NotEqualInt32()); case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new NotEqualInt64()); case TypeCode.Single: return _Single ?? (_Single = new NotEqualSingle()); case TypeCode.Double: return _Double ?? (_Double = new NotEqualDouble()); case TypeCode.Object: if (!type.IsValueType()) { return _Reference ?? (_Reference = new NotEqualReference()); } // TODO: Nullable<T> throw new NotImplementedException(); default: throw new NotImplementedException(); } }
public static EnumMapping Create(Type enumType) { if (enumType == null) throw Error.ArgumentNull("enumType"); if (!enumType.IsEnum()) throw Error.Argument("enumType", "Type {0} is not an enumerated type", enumType.Name); var result = new EnumMapping(); result.Name = getEnumName(enumType); result.EnumType = enumType; result._enumToLiteral = new Dictionary<Enum, string>(); result._literalToEnum = new Dictionary<string, Enum>(); foreach(var enumValue in ReflectionHelper.FindEnumFields(enumType)) { var attr = ReflectionHelper.GetAttribute<EnumLiteralAttribute>(enumValue); string literal = enumValue.Name; if (attr != null) literal = attr.Literal; Enum value = (Enum)enumValue.GetValue(null); result._enumToLiteral.Add(value, literal); result._literalToEnum.Add(literal, value); } return result; }
private object read(Type nativeType) { object primitiveValue = _current.GetPrimitiveValue(); if (nativeType.IsEnum() && primitiveValue.GetType() == typeof(string)) { var enumMapping = _inspector.FindEnumMappingByType(nativeType); if (enumMapping != null) { var enumLiteral = (string)primitiveValue; if (enumMapping.ContainsLiteral(enumLiteral)) return enumMapping.ParseLiteral((string)primitiveValue); else throw Error.Format("Literal {0} is not a valid value for enumeration {1}", _current, enumLiteral, enumMapping.Name); } else throw Error.Format("Cannot find an enumeration mapping for enum " + nativeType.Name, _current); } try { return PrimitiveTypeConverter.ConvertTo(primitiveValue, nativeType); } catch (NotSupportedException exc) { // thrown when an unsupported conversion was required throw Error.Format(exc.Message, _current); } }
public static void AddModelType(Type type) { if (type.IsEnum()) Inspector.ImportEnum(type); else Inspector.ImportType(type); }
internal static Enum GetEnumValue(System.Type enumType, string s) { if (!enumType.IsEnum()) { throw new ArgumentException("Not an enumeration type", "enumType"); } // We only want to parse single named constants if (s.Length > 0 && char.IsLetter(s[0]) && s.IndexOf(',') < 0) { s = s.Replace('-', '_'); #if NETCF_1_0 FieldInfo field = enumType.GetField(s, BindingFlags.Static | BindingFlags.Public); if (field != null) { return((Enum)field.GetValue(null)); } #else return((Enum)Enum.Parse(enumType, s, false)); #endif } throw new ArgumentException(); }
public override object ExtractObject(Type requestedType) { if (requestedType == null) return m_value; if (requestedType.IsEnum()) return ConvertEnum(requestedType, m_value); object v = Convert.ChangeType(m_value, requestedType); return v; }
public static Type GetEnumerationType(Type enumType) { if (enumType.IsNullableType()) { enumType = enumType.GetTypeInfo().GenericTypeArguments[0]; } if (!enumType.IsEnum()) return null; return enumType; }
public static TypeCode GetTypeCode(Type type) { if (type == null) return TypeCode.Empty; TypeCode result; if (typeCodeLookup.TryGetValue(type, out result)) return result; if (type.IsEnum()) { type = Enum.GetUnderlyingType(type); if (typeCodeLookup.TryGetValue(type, out result)) return result; } return TypeCode.Object; }
public static Instruction Create(Type type) { Debug.Assert(!type.IsEnum()); switch (type.GetTypeCode()) { case TypeCode.Int16: return _Int16 ?? (_Int16 = new AddInt16()); case TypeCode.Int32: return _Int32 ?? (_Int32 = new AddInt32()); case TypeCode.Int64: return _Int64 ?? (_Int64 = new AddInt64()); case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new AddUInt16()); case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new AddUInt32()); case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new AddUInt64()); case TypeCode.Single: return _Single ?? (_Single = new AddSingle()); case TypeCode.Double: return _Double ?? (_Double = new AddDouble()); default: throw Assert.Unreachable; } }
// keep in sync with System.Core version internal static bool IsArithmetic(Type type) { type = GetNonNullableType(type); if (!type.IsEnum()) { switch (type.GetTypeCode()) { case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Double: case TypeCode.Single: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return true; } } return false; }
internal static NonGenericEnumInfo GetNonGenericEnumInfo(Type enumType) { Preconditions.NotNull(enumType, nameof(enumType)); var nonGenericEnumInfos = _nonGenericEnumInfos; NonGenericEnumInfo info; if (!nonGenericEnumInfos.TryGetValue(enumType, out info)) { if (enumType.IsEnum()) { var closedEnumsType = typeof(Enums<>).MakeGenericType(enumType); info = new NonGenericEnumInfo((IEnumInfo)closedEnumsType. #if TYPE_REFLECTION GetField("Info", BindingFlags.Static | BindingFlags.Public) #else GetTypeInfo().GetDeclaredField("Info") #endif .GetValue(null), false); } else { var nonNullableEnumType = Nullable.GetUnderlyingType(enumType); if (nonNullableEnumType?.IsEnum() != true) { throw new ArgumentException("must be an enum type", nameof(enumType)); } info = new NonGenericEnumInfo(GetInfo(nonNullableEnumType), true); } Dictionary<Type, NonGenericEnumInfo> oldNonGenericEnumInfos; do { NonGenericEnumInfo foundInfo; if (nonGenericEnumInfos.TryGetValue(enumType, out foundInfo)) { return foundInfo; } oldNonGenericEnumInfos = nonGenericEnumInfos; nonGenericEnumInfos = new Dictionary<Type, NonGenericEnumInfo>(nonGenericEnumInfos); nonGenericEnumInfos.Add(enumType, info); } while ((nonGenericEnumInfos = Interlocked.CompareExchange(ref _nonGenericEnumInfos, nonGenericEnumInfos, oldNonGenericEnumInfos)) != oldNonGenericEnumInfos); } return info; }
public static Instruction Create(Type type) { Debug.Assert(!type.IsEnum()); switch (type.GetTypeCode()) { case TypeCode.SByte: return _SByte ?? (_SByte = new LessThanSByte()); case TypeCode.Byte: return _Byte ?? (_Byte = new LessThanByte()); case TypeCode.Char: return _Char ?? (_Char = new LessThanChar()); case TypeCode.Int16: return _Int16 ?? (_Int16 = new LessThanInt16()); case TypeCode.Int32: return _Int32 ?? (_Int32 = new LessThanInt32()); case TypeCode.Int64: return _Int64 ?? (_Int64 = new LessThanInt64()); case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new LessThanUInt16()); case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new LessThanUInt32()); case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new LessThanUInt64()); case TypeCode.Single: return _Single ?? (_Single = new LessThanSingle()); case TypeCode.Double: return _Double ?? (_Double = new LessThanDouble()); default: throw Assert.Unreachable; } }
internal static Array GetEnumValues(System.Type enumType) { if (!enumType.IsEnum()) { throw new ArgumentException("Not an enumeration type", "enumType"); } #if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT IList result = Platform.CreateArrayList(); FieldInfo[] fields = enumType.GetFields(BindingFlags.Static | BindingFlags.Public); foreach (FieldInfo field in fields) { result.Add(field.GetValue(null)); } object[] arr = new object[result.Count]; result.CopyTo(arr, 0); return(arr); #else return(Enum.GetValues(enumType)); #endif }
public override string ToQuotedString(Type fieldType, object value) { var isEnumAsInt = fieldType.HasAttribute<EnumAsIntAttribute>(); if (isEnumAsInt) return this.ConvertNumber(Enum.GetUnderlyingType(fieldType), value).ToString(); var isEnumFlags = fieldType.IsEnumFlags() || (!fieldType.IsEnum() && fieldType.IsNumericType()); //i.e. is real int && not Enum long enumValue; if (!isEnumFlags && long.TryParse(value.ToString(), out enumValue)) value = Enum.ToObject(fieldType, enumValue); var enumString = DialectProvider.StringSerializer.SerializeToString(value); if (enumString == null || enumString == "null") enumString = value.ToString(); return !isEnumFlags ? DialectProvider.GetQuotedValue(enumString.Trim('"')) : enumString; }
private object read(Type nativeType) { object primitiveValue = _current.GetPrimitiveValue(); if (nativeType.IsEnum() && primitiveValue.GetType() == typeof(string)) { var enumMapping = _inspector.FindEnumMappingByType(nativeType); if (enumMapping != null) return enumMapping.ParseLiteral((string)primitiveValue); } try { return PrimitiveTypeConverter.Convert(primitiveValue, nativeType); } catch (NotSupportedException exc) { // thrown when an unsupported conversion was required throw Error.Format(exc.Message, _current); } }
public static string GetCoarseType(Type type) { Debug.Assert(type != null); if (type.IsTimeSpan()) return "timespan"; if (type.IsDateTime()) return "datetime"; if (type.IsEnum()) return "enumeration"; if (type.IsNumeric()) return "number"; if (type.IsString()) return "string"; if (type.IsBool()) return "bool"; if (type.IsGuid()) return "guid"; type = type.IsNullable() ? Nullable.GetUnderlyingType(type) : type; return type.Name.ToLowerInvariant(); }
public override object ToDbValue(Type fieldType, object value) { var isIntEnum = fieldType.IsEnumFlags() || fieldType.HasAttribute<EnumAsIntAttribute>() || (!fieldType.IsEnum() && fieldType.IsNumericType()); //i.e. is real int && not Enum if (isIntEnum && value.GetType().IsEnum()) return Convert.ChangeType(value, Enum.GetUnderlyingType(fieldType)); long enumValue; if (long.TryParse(value.ToString(), out enumValue)) { if (isIntEnum) return enumValue; value = Enum.ToObject(fieldType, enumValue); } var enumString = DialectProvider.StringSerializer.SerializeToString(value); return enumString != null && enumString != "null" ? enumString.Trim('"') : value.ToString(); }
public object GetValue(Type targetType) { var stringValue = _underlyingValue as string; if (_underlyingValue == null) { if (targetType.IsValueType() && !(targetType.IsGenericType() && targetType.GetGenericTypeDefinition() == typeof(Nullable<>))) { var valueAsString = string.IsNullOrEmpty(stringValue) ? "<null>" : string.Format("\"{0}\"", _underlyingValue); throw new ArgumentException(string.Format("Cannot convert {0} to {1} (Column: '{2}', Row: {3})", valueAsString, targetType.Name, Header, Row)); } ValueHasBeenUsed = true; return null; } ValueHasBeenUsed = true; if (targetType.IsInstanceOfType(_underlyingValue)) return _underlyingValue; if (targetType.IsEnum() && _underlyingValue is string) return Enum.Parse(targetType, (string)_underlyingValue); if (targetType == typeof(DateTime)) return DateTime.Parse(stringValue); try { return Convert.ChangeType(_underlyingValue, targetType); } catch (InvalidCastException ex) { throw new UnassignableExampleException(string.Format( "{0} cannot be assigned to {1} (Column: '{2}', Row: {3})", _underlyingValue == null ? "<null>" : _underlyingValue.ToString(), targetType.Name, Header, Row), ex, this); } }
/// <summary> /// Emits a load indirect opcode of the appropriate type for a value or object reference. /// Pops a pointer off the evaluation stack, dereferences it and loads /// a value of the specified type. /// </summary> /// <param name = "gen"></param> /// <param name = "type"></param> public static void EmitLoadIndirectOpCodeForType(ILGenerator gen, Type type) { if (type.IsEnum()) { EmitLoadIndirectOpCodeForType(gen, GetUnderlyingTypeOfEnum(type)); return; } if (type.IsByRef) { throw new NotSupportedException("Cannot load ByRef values"); } else if (type.IsPrimitive() && type != typeof(IntPtr)) { var opCode = LdindOpCodesDictionary.Instance[type]; if (opCode == LdindOpCodesDictionary.EmptyOpCode) { throw new ArgumentException("Type " + type + " could not be converted to a OpCode"); } gen.Emit(opCode); } else if (type.IsValueType()) { gen.Emit(OpCodes.Ldobj, type); } else if (type.IsGenericParameter) { gen.Emit(OpCodes.Ldobj, type); } else { gen.Emit(OpCodes.Ldind_Ref); } }
public static object ConvertFromReturnCode(this string returnCode, Type destinationType) { if (destinationType == typeof(int)) { return Convert.ToInt32(returnCode); } if (destinationType == typeof(short)) { return Convert.ToInt16(returnCode); } if (destinationType == typeof(long)) { return Convert.ToInt64(returnCode); } if (destinationType.IsEnum()) { return Enum.Parse(destinationType, returnCode); } throw new ArgumentException("The return code can only be an enum or an integer.", nameof(destinationType)); }
public override bool CanConvert(Type objectType) { return objectType.IsEnum() || (objectType.IsGenericType() && objectType.GetGenericTypeDefinition() == typeof(SafeEnum<>)); }
public static Instruction CreateLifted(Type type) { Debug.Assert(!type.IsEnum()); switch (type.GetTypeCode()) { case TypeCode.SByte: return _SByteLifted ?? (_SByteLifted = new LessThanSByte() { LiftedToNull = true }); case TypeCode.Byte: return _ByteLifted ?? (_ByteLifted = new LessThanByte() { LiftedToNull = true }); case TypeCode.Char: return _CharLifted ?? (_CharLifted = new LessThanChar() { LiftedToNull = true }); case TypeCode.Int16: return _Int16Lifted ?? (_Int16Lifted = new LessThanInt16() { LiftedToNull = true }); case TypeCode.Int32: return _Int32Lifted ?? (_Int32Lifted = new LessThanInt32() { LiftedToNull = true }); case TypeCode.Int64: return _Int64Lifted ?? (_Int64Lifted = new LessThanInt64() { LiftedToNull = true }); case TypeCode.UInt16: return _UInt16Lifted ?? (_UInt16Lifted = new LessThanUInt16() { LiftedToNull = true }); case TypeCode.UInt32: return _UInt32Lifted ?? (_UInt32Lifted = new LessThanUInt32() { LiftedToNull = true }); case TypeCode.UInt64: return _UInt64Lifted ?? (_UInt64Lifted = new LessThanUInt64() { LiftedToNull = true }); case TypeCode.Single: return _SingleLifted ?? (_SingleLifted = new LessThanSingle() { LiftedToNull = true }); case TypeCode.Double: return _DoubleLifted ?? (_DoubleLifted = new LessThanDouble() { LiftedToNull = true }); default: throw Assert.Unreachable; } }
internal JsonContract(Type underlyingType) { ValidationUtils.ArgumentNotNull(underlyingType, nameof(underlyingType)); UnderlyingType = underlyingType; IsNullable = ReflectionUtils.IsNullable(underlyingType); NonNullableUnderlyingType = (IsNullable && ReflectionUtils.IsNullableType(underlyingType)) ? Nullable.GetUnderlyingType(underlyingType) : underlyingType; CreatedType = NonNullableUnderlyingType; IsConvertable = ConvertUtils.IsConvertible(NonNullableUnderlyingType); IsEnum = NonNullableUnderlyingType.IsEnum(); InternalReadType = ReadType.Read; }
internal JsonContract(Type underlyingType) { ValidationUtils.ArgumentNotNull(underlyingType, "underlyingType"); UnderlyingType = underlyingType; IsNullable = ReflectionUtils.IsNullable(underlyingType); NonNullableUnderlyingType = (IsNullable && ReflectionUtils.IsNullableType(underlyingType)) ? Nullable.GetUnderlyingType(underlyingType) : underlyingType; CreatedType = NonNullableUnderlyingType; IsConvertable = ConvertUtils.IsConvertible(NonNullableUnderlyingType); IsEnum = NonNullableUnderlyingType.IsEnum(); if (NonNullableUnderlyingType == typeof(byte[])) { InternalReadType = ReadType.ReadAsBytes; } else if (NonNullableUnderlyingType == typeof(int)) { InternalReadType = ReadType.ReadAsInt32; } else if (NonNullableUnderlyingType == typeof(decimal)) { InternalReadType = ReadType.ReadAsDecimal; } else if (NonNullableUnderlyingType == typeof(string)) { InternalReadType = ReadType.ReadAsString; } else if (NonNullableUnderlyingType == typeof(DateTime)) { InternalReadType = ReadType.ReadAsDateTime; } #if !NET20 else if (NonNullableUnderlyingType == typeof(DateTimeOffset)) { InternalReadType = ReadType.ReadAsDateTimeOffset; } #endif else { InternalReadType = ReadType.Read; } }
// Helpers/Type private static IEnumerable <string> GetKeywords(this Type type) { if (!type.IsNested) { if (type.IsPublic) { yield return("public"); } else { yield return("internal"); } } else { if (type.IsNestedPublic) { yield return("public"); } if (type.IsNestedAssembly) { yield return("internal"); } if (type.IsNestedFamily) { yield return("protected"); } if (type.IsNestedFamORAssem) { yield return("protected internal"); // Can be accessed by any code in the assembly in which it's declared, or from within a derived class in another assembly. } if (type.IsNestedFamANDAssem) { yield return("private protected"); // Can be accessed only within its declaring assembly, by code in the same class or in a type that is derived from that class. } if (type.IsNestedPrivate) { yield return("private"); } } if (type.IsClass()) { if (type.IsStatic()) { yield return("static"); } if (type.IsAbstract()) { yield return("abstract"); } if (type.IsSealed()) { yield return("sealed"); } } if (type.IsInterface()) { yield return("interface"); } if (type.IsClass()) { yield return("class"); } if (type.IsStruct()) { yield return("struct"); } if (type.IsEnum()) { yield return("enum"); } if (type.IsDelegate()) { yield return("delegate"); } }
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required) { ValidationUtils.ArgumentNotNull(type, "type"); string resolvedId = GetTypeId(type, false); string explicitId = GetTypeId(type, true); if (!string.IsNullOrEmpty(resolvedId)) { JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId); if (resolvedSchema != null) { // resolved schema is not null but referencing member allows nulls // change resolved schema to allow nulls. hacky but what are ya gonna do? if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null)) resolvedSchema.Type |= JsonSchemaType.Null; if (required && resolvedSchema.Required != true) resolvedSchema.Required = true; return resolvedSchema; } } // test for unresolved circular reference if (_stack.Any(tc => tc.Type == type)) { throw new Exception("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type)); } JsonContract contract = ContractResolver.ResolveContract(type); JsonConverter converter; if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null) { JsonSchema converterSchema = converter.GetSchema(); if (converterSchema != null) return converterSchema; } Push(new TypeSchema(type, new JsonSchema())); if (explicitId != null) CurrentSchema.Id = explicitId; if (required) CurrentSchema.Required = true; CurrentSchema.Title = GetTitle(type); CurrentSchema.Description = GetDescription(type); if (converter != null) { // todo: Add GetSchema to JsonConverter and use here? CurrentSchema.Type = JsonSchemaType.Any; } else { switch (contract.ContractType) { case JsonContractType.Object: CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); CurrentSchema.Id = GetTypeId(type, false); GenerateObjectSchema(type, (JsonObjectContract) contract); break; case JsonContractType.Array: CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired); CurrentSchema.Id = GetTypeId(type, false); JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute; bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems); Type collectionItemType = ReflectionUtils.GetCollectionItemType(type); if (collectionItemType != null) { CurrentSchema.Items = new List<JsonSchema>(); CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false)); } break; case JsonContractType.Primitive: CurrentSchema.Type = GetJsonSchemaType(type, valueRequired); if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum() && !type.IsDefined(typeof (FlagsAttribute), true)) { CurrentSchema.Enum = new List<JToken>(); CurrentSchema.Options = new Dictionary<JToken, string>(); EnumValues<long> enumValues = EnumUtils.GetNamesAndValues<long>(type); foreach (EnumValue<long> enumValue in enumValues) { JToken value = JToken.FromObject(enumValue.Value); CurrentSchema.Enum.Add(value); CurrentSchema.Options.Add(value, enumValue.Name); } } break; case JsonContractType.String: JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType)) ? JsonSchemaType.String : AddNullType(JsonSchemaType.String, valueRequired); CurrentSchema.Type = schemaType; break; case JsonContractType.Dictionary: CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); Type keyType; Type valueType; ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType); if (keyType != null) { // can be converted to a string if (ConvertUtils.IsConvertible(keyType)) { CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false); } } break; #if !SILVERLIGHT && !PocketPC && !NETFX_CORE case JsonContractType.Serializable: CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); CurrentSchema.Id = GetTypeId(type, false); GenerateISerializableContract(type, (JsonISerializableContract) contract); break; #endif #if !(NET35 || NET20 || WINDOWS_PHONE) case JsonContractType.Dynamic: #endif case JsonContractType.Linq: CurrentSchema.Type = JsonSchemaType.Any; break; default: throw new Exception("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract)); } } return Pop().Schema; }
bool InnerTryConvert(Type returnType, out object result) { if (returnType == typeof(object)) { result = this; return true; } if (returnType.IsNullableType()) { returnType = Nullable.GetUnderlyingType(returnType); } switch (Type) { case JsonObjectType.False: result = false; return returnType == typeof(bool); case JsonObjectType.True: result = true; return returnType == typeof(bool); case JsonObjectType.FastNumber: if (returnType == typeof(double)) { double res; var ret = FastNumberToDouble(out res); result = res; return ret; } if (returnType == typeof(float)) { float res; var ret = FastNumberToFloat(out res); result = res; return ret; } if (returnType == typeof(decimal)) { decimal res; var ret = FastNumberToDecimal(out res); result = res; return ret; } if (returnType == typeof(byte)) { byte res; var ret = FastNumberToByte(out res); result = res; return ret; } if (returnType == typeof(sbyte)) { sbyte res; var ret = FastNumberToSByte(out res); result = res; return ret; } if (returnType == typeof(short)) { short res; var ret = FastNumberToShort(out res); result = res; return ret; } if (returnType == typeof(ushort)) { ushort res; var ret = FastNumberToUShort(out res); result = res; return ret; } if (returnType == typeof(int)) { int res; var ret = FastNumberToInt(out res); result = res; return ret; } if (returnType == typeof(uint)) { uint res; var ret = FastNumberToUInt(out res); result = res; return ret; } if (returnType == typeof(long)) { long res; var ret = FastNumberToLong(out res); result = res; return ret; } if (returnType == typeof(ulong)) { ulong res; var ret = FastNumberToULong(out res); result = res; return ret; } if (returnType == typeof(DateTime)) { long res; var ret = FastNumberToLong(out res); if (!ret) { result = null; return false; } switch(Options.UseDateTimeFormat) { case DateTimeFormat.MillisecondsSinceUnixEpoch: result = Methods.UnixEpoch + TimeSpan.FromMilliseconds(res); return true; case DateTimeFormat.SecondsSinceUnixEpoch: result = Methods.UnixEpoch + TimeSpan.FromSeconds(res); return true; default: result = null; return false; } } if(returnType == typeof(DateTimeOffset)) { long res; var ret = FastNumberToLong(out res); if (!ret) { result = null; return false; } switch (Options.UseDateTimeFormat) { case DateTimeFormat.MillisecondsSinceUnixEpoch: result = Methods.UnixEpochOffset + TimeSpan.FromMilliseconds(res); return true; case DateTimeFormat.SecondsSinceUnixEpoch: result = Methods.UnixEpochOffset + TimeSpan.FromSeconds(res); return true; default: result = null; return false; } } if(returnType == typeof(TimeSpan)) { const double TicksPerMillisecond = 10000; const double TicksPerSecond = 10000000; double res; var ret = FastNumberToDouble(out res); if (!ret) { result = null; return false; } switch (Options.UseDateTimeFormat) { case DateTimeFormat.MillisecondsSinceUnixEpoch: var msTicksDouble = res * TicksPerMillisecond; var msTicks = (long)msTicksDouble; if (msTicksDouble >= TimeSpan.MaxValue.Ticks) { msTicks = TimeSpan.MaxValue.Ticks; } if(msTicksDouble <= TimeSpan.MinValue.Ticks) { msTicks = TimeSpan.MinValue.Ticks; } result = new TimeSpan(msTicks); return true; case DateTimeFormat.SecondsSinceUnixEpoch: var sTicksDouble = res * TicksPerSecond; var sTicks = (long)sTicksDouble; if (sTicksDouble >= TimeSpan.MaxValue.Ticks) { sTicks = TimeSpan.MaxValue.Ticks; } if(sTicksDouble <= TimeSpan.MinValue.Ticks) { sTicks = TimeSpan.MinValue.Ticks; } result = new TimeSpan(sTicks); return true; default: result = null; return false; } } break; case JsonObjectType.Number: if (returnType == typeof(double)) { result = NumberValue; return true; } if (returnType == typeof(float)) { result = (float)NumberValue; return true; } if (returnType == typeof(decimal)) { result = (decimal)NumberValue; return true; } if (returnType == typeof(byte)) { result = (byte)NumberValue; return true; } if (returnType == typeof(sbyte)) { result = (sbyte)NumberValue; return true; } if (returnType == typeof(short)) { result = (short)NumberValue; return true; } if (returnType == typeof(ushort)) { result = (ushort)NumberValue; return true; } if (returnType == typeof(int)) { result = (int)NumberValue; return true; } if (returnType == typeof(uint)) { result = (uint)NumberValue; return true; } if (returnType == typeof(long)) { result = (long)NumberValue; return true; } if (returnType == typeof(ulong)) { result = (ulong)NumberValue; return true; } if (returnType == typeof(DateTime)) { var res = (long)NumberValue; switch (Options.UseDateTimeFormat) { case DateTimeFormat.MillisecondsSinceUnixEpoch: result = Methods.UnixEpoch + TimeSpan.FromMilliseconds(res); return true; case DateTimeFormat.SecondsSinceUnixEpoch: result = Methods.UnixEpoch + TimeSpan.FromSeconds(res); return true; default: result = null; return false; } } if (returnType == typeof(DateTimeOffset)) { var res = (long)NumberValue; switch (Options.UseDateTimeFormat) { case DateTimeFormat.MillisecondsSinceUnixEpoch: result = Methods.UnixEpochOffset + TimeSpan.FromMilliseconds(res); return true; case DateTimeFormat.SecondsSinceUnixEpoch: result = Methods.UnixEpochOffset + TimeSpan.FromSeconds(res); return true; default: result = null; return false; } } if (returnType == typeof(TimeSpan)) { const double TicksPerMillisecond = 10000; const double TicksPerSecond = 10000000; var res = NumberValue; switch (Options.UseDateTimeFormat) { case DateTimeFormat.MillisecondsSinceUnixEpoch: var msTicksDouble = res * TicksPerMillisecond; var msTicks = (long)msTicksDouble; if (msTicksDouble >= TimeSpan.MaxValue.Ticks) { msTicks = TimeSpan.MaxValue.Ticks; } if (msTicksDouble <= TimeSpan.MinValue.Ticks) { msTicks = TimeSpan.MinValue.Ticks; } result = new TimeSpan(msTicks); return true; case DateTimeFormat.SecondsSinceUnixEpoch: var sTicksDouble = res * TicksPerSecond; var sTicks = (long)sTicksDouble; if (sTicksDouble >= TimeSpan.MaxValue.Ticks) { sTicks = TimeSpan.MaxValue.Ticks; } if (sTicksDouble <= TimeSpan.MinValue.Ticks) { sTicks = TimeSpan.MinValue.Ticks; } result = new TimeSpan(sTicks); return true; default: result = null; return false; } } break; case JsonObjectType.String: if (returnType == typeof(string)) { result = StringValue; return true; } if (returnType.IsEnum()) { if (returnType.IsFlagsEnum()) { return ParseFlagsEnum(returnType, out result); } return EnumValues.TryParse(returnType, StringValue, out result); } if (returnType == typeof(Guid)) { Guid guid; if (!Guid.TryParseExact(StringValue, "D", out guid)) { result = null; return false; } result = guid; return true; } if (returnType == typeof(DateTime)) { DateTime res; bool ret; switch(Options.UseDateTimeFormat) { case DateTimeFormat.MicrosoftStyleMillisecondsSinceUnixEpoch: ret = Methods.ReadMicrosoftStyleDateTime(StringValue, out res); result = res; return ret; case DateTimeFormat.ISO8601: ret = Methods.ReadISO8601DateTime(StringValue, out res); result = res; return ret; case DateTimeFormat.RFC1123: ret = Methods.ReadRFC1123DateTime(StringValue, out res); result = res; return ret; default: result = null; return false; } } if (returnType == typeof(DateTimeOffset)) { DateTime dt; DateTimeOffset res; bool ret; switch (Options.UseDateTimeFormat) { case DateTimeFormat.MicrosoftStyleMillisecondsSinceUnixEpoch: ret = Methods.ReadMicrosoftStyleDateTime(StringValue, out dt); res = dt; result = res; return ret; case DateTimeFormat.ISO8601: ret = Methods.ReadISO8601DateWithOffset(StringValue, out res); result = res; return ret; default: result = null; return false; } } if(returnType == typeof(TimeSpan)) { TimeSpan ts; bool ret; switch (Options.UseDateTimeFormat) { case DateTimeFormat.MicrosoftStyleMillisecondsSinceUnixEpoch: ret = Methods.ReadMicrosoftStyleTimeSpan(StringValue, out ts); result = ts; return ret; case DateTimeFormat.ISO8601: ret = Methods.ReadISO8601TimeSpan(StringValue, out ts); result = ts; return ret; default: result = null; return false; } } break; case JsonObjectType.Object: if (returnType == typeof(System.Collections.IEnumerable)) { result = EnumerableObjectWrapper.MakeAsIEnumerable(ObjectMembers); return true; } if (returnType.IsGenericDictionary()) { var args = returnType.GetGenericArguments(); var keyType = args[0]; var valType = args[1]; var stringKeys = keyType == typeof(string); var enumKeys = keyType.IsEnum(); // only strings and enums can be keys if (!(stringKeys || enumKeys)) { result = null; return false; } var coerced = new Dictionary<object, object>(ObjectMembers.Count); foreach (var kv in ObjectMembers) { object innerResult = null; if (kv.Value != null && !kv.Value.InnerTryConvert(valType, out innerResult)) { result = null; return false; } if (stringKeys) { coerced[kv.Key] = innerResult; } else { object @enum = Enum.Parse(keyType, kv.Key, ignoreCase: true); coerced[@enum] = innerResult; } } if (stringKeys) { result = Utils.ProjectStringDictionary(coerced, valType); } else { // enum keys result = Utils.ProjectEnumDictionary(coerced, keyType, valType); } return true; } break; case JsonObjectType.Array: if (returnType == typeof(System.Collections.IEnumerable)) { result = EnumerableArrayWrapper.MakeAsIEnumerable(ArrayValue); return true; } if (returnType.IsGenericEnumerable()) { var castTo = returnType.GetGenericArguments()[0]; if (castTo == typeof(object)) { result = EnumerableArrayWrapper.MakeAsIEnumerableOfT(ArrayValue); return true; } bool bail = false; var dynamicProjection = ArrayValue.Select( val => { object innerResult; if (!val.InnerTryConvert(castTo, out innerResult)) { bail = true; return Activator.CreateInstance(castTo); } return innerResult; } ); result = Utils.DynamicProject(dynamicProjection, castTo); if (bail) { result = null; return false; } return true; } break; } result = null; return false; }
public override JsonSchema GetSchema(Type objectType) { if (!objectType.IsEnum()) return null; var schema = new JsonSchema { Type = JsonSchemaType.String }; schema.Enum = new List<JToken>(); var enumNames = EnumUtils.GetNames(objectType); foreach (var enumName in enumNames) { string resolvedEnumName = enumName; if (CamelCaseText) resolvedEnumName = StringUtils.ToCamelCase(resolvedEnumName); JToken value = JToken.FromObject(resolvedEnumName); schema.Enum.Add(value); } return schema; }
//public Type GetChoiceType(string choiceSuffix) //{ // string suffix = choiceSuffix.ToUpperInvariant(); // if(!HasChoices) return null; // return _choices // .Where(cattr => cattr.TypeName.ToUpperInvariant() == suffix) // .Select(cattr => cattr.Type) // .FirstOrDefault(); //} private static bool isAllowedNativeTypeForDataTypeValue(Type type) { // Special case, allow Nullable<enum> if (ReflectionHelper.IsNullableType(type)) type = ReflectionHelper.GetNullableArgument(type); return type.IsEnum(); // || PrimitiveTypeConverter.CanConvert(type); }
public static Instruction CreateLifted(Type type) { Debug.Assert(!type.IsEnum()); switch (type.GetTypeCode()) { case TypeCode.Int16: return _Int16Lifted ?? (_Int16Lifted = new NegateOvfInt16Lifted()); case TypeCode.Int32: return _Int32Lifted ?? (_Int32Lifted = new NegateOvfInt32Lifted()); case TypeCode.Int64: return _Int64Lifted ?? (_Int64Lifted = new NegateOvfInt64Lifted()); case TypeCode.UInt16: return _UInt16Lifted ?? (_UInt16Lifted = new NegateOvfUInt16Lifted()); case TypeCode.UInt32: return _UInt32Lifted ?? (_UInt32Lifted = new NegateOvfUInt32Lifted()); case TypeCode.Single: return _SingleLifted ?? (_SingleLifted = new NegateOvfSingleLifted()); case TypeCode.Double: return _DoubleLifted ?? (_DoubleLifted = new NegateOvfDoubleLifted()); default: throw Assert.Unreachable; } }
public MetadataType ToType(Type type) { if (type == null) return null; if (type.IsGenericType()) type = type.GetGenericTypeDefinition(); var metaType = new MetadataType { Name = type.GetOperationName(), Namespace = type.Namespace, GenericArgs = type.IsGenericType() ? GetGenericArgs(type) : null, Implements = ToInterfaces(type), Attributes = ToAttributes(type), Properties = ToProperties(type), IsNested = type.IsNested ? true : (bool?)null, IsEnum = type.IsEnum() ? true : (bool?)null, IsEnumInt = JsConfig.TreatEnumAsInteger || type.IsEnumFlags() ? true : (bool?)null, IsInterface = type.IsInterface() ? true : (bool?)null, IsAbstract = type.IsAbstract() ? true : (bool?)null, }; if (type.BaseType() != null && type.BaseType() != typeof(object) && !type.IsEnum() && !type.HasInterface(typeof(IService))) { metaType.Inherits = ToTypeName(type.BaseType()); } if (type.GetTypeWithInterfaceOf(typeof(IReturnVoid)) != null) { metaType.ReturnVoidMarker = true; } else { var genericMarker = type != typeof(IReturn<>) ? type.GetTypeWithGenericTypeDefinitionOf(typeof(IReturn<>)) : null; if (genericMarker != null) { var returnType = genericMarker.GetGenericArguments().First(); metaType.ReturnMarkerTypeName = ToTypeName(returnType); } } var routeAttrs = HostContext.AppHost.GetRouteAttributes(type).ToList(); if (routeAttrs.Count > 0) { metaType.Routes = routeAttrs.ConvertAll(x => new MetadataRoute { Path = x.Path, Notes = x.Notes, Summary = x.Summary, Verbs = x.Verbs, }); } metaType.Description = type.GetDescription(); var dcAttr = type.GetDataContract(); if (dcAttr != null) { metaType.DataContract = new MetadataDataContract { Name = dcAttr.Name, Namespace = dcAttr.Namespace, }; } if (type.IsEnum()) { metaType.EnumNames = new List<string>(); metaType.EnumValues = new List<string>(); var isDefaultLayout = true; var values = Enum.GetValues(type); for (var i = 0; i < values.Length; i++) { var value = values.GetValue(i); var name = value.ToString(); var enumValue = Convert.ToInt64(value).ToString(); if (enumValue != i.ToString()) isDefaultLayout = false; metaType.EnumNames.Add(name); metaType.EnumValues.Add(enumValue); } if (isDefaultLayout) metaType.EnumValues = null; } var innerTypes = type.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic); foreach (var innerType in innerTypes) { if (metaType.InnerTypes == null) metaType.InnerTypes = new List<MetadataTypeName>(); metaType.InnerTypes.Add(new MetadataTypeName { Name = innerType.GetOperationName(), Namespace = innerType.Namespace, GenericArgs = innerType.IsGenericType() ? innerType.GetGenericArguments().Select(x => x.GetOperationName()).ToArray() : null, }); } return metaType; }