public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return(null); } // get the request type property var request = JObject.Load(reader); var type = EnumSerializer.ToEnum <Card.CardType>(request.Value <string>("type")); // deserialize to the specified type switch (type) { case Card.CardType.Simple: return(request.ToObject <SimpleCard>()); case Card.CardType.Standard: return(request.ToObject <StandardCard>()); case Card.CardType.LinkAccount: return(request.ToObject <LinkAccountCard>()); default: throw new SerializationException($"Card type of \"{type}\" is invalid"); } }
public void Flags() { var w = new Writer(); var cs = new EnumSerializer(typeof(FlagsEnum)); w.BeginList(); w.BeginListValue(); Assert.True(cs.Write(w, FlagsEnum.One | FlagsEnum.Seven, null)); w.BeginListValue(); Assert.True(cs.Write(w, FlagsEnum.Four, null)); w.BeginListValue(); Assert.True(cs.Write(w, (FlagsEnum)0, null)); w.EndList(); Assert.True(w.IsValid()); Assert.AreEqual("[One|Seven,Four,0]", w.ToString()); var r = new Reader(w.ToString()); r.BeginList(); r.BeginListValue(); Assert.AreEqual(FlagsEnum.One | FlagsEnum.Seven, (FlagsEnum)cs.Read(r, null, null)); r.BeginListValue(); Assert.AreEqual(FlagsEnum.Four, (FlagsEnum)cs.Read(r, null, null)); r.BeginListValue(); Assert.AreEqual((FlagsEnum)0, (FlagsEnum)cs.Read(r, null, null)); r.EndList(); Assert.IsFalse(r.AnyLeft, "Any characters left."); }
public IEntitySerializer GetSerizliser(Type type) { if (_serializers.TryGetValue(type, out var serializer)) { return(serializer); } else if (type.IsEnum || Nullable.GetUnderlyingType(type)?.IsEnum == true) { if (_enumSerializers.TryGetValue(type, out var enumSerializer)) { return(enumSerializer); } if (type.IsEnum) { enumSerializer = new EnumSerializer(type); } else { enumSerializer = new NullableEntitySerializer(new EnumSerializer(Nullable.GetUnderlyingType(type))); } _enumSerializers[type] = enumSerializer; return(enumSerializer); } else { return(null); } }
private void ImportMatchesToContext() { using (var fileStream = new FileStream(filename, FileMode.Open)) { CsvSerializer.UseEncoding = Encoding.UTF8; CsvConfig.ItemSeperatorString = ";"; var rkiMatches = CsvSerializer.DeserializeFromStream <List <RkiMatchImportRecord> >(fileStream); foreach (var rkiMatch in rkiMatches.Where(r => r.klhi_nr.HasValue)) { var dbMatch = context.Sendings.SingleOrDefault(i => i.Isolate.StemNumber == rkiMatch.klhi_nr); if (dbMatch == null && rkiMatch.Jahr.HasValue && rkiMatch.LaufendeNummer.HasValue) { dbMatch = context.Sendings.SingleOrDefault(s => s.Isolate.YearlySequentialIsolateNumber == rkiMatch.LaufendeNummer && s.Isolate.Year == rkiMatch.Jahr); } if (dbMatch != null && dbMatch.ReceivingDate >= MinImportDate && rkiMatch.InterneRef.HasValue) { if (dbMatch.RkiMatchRecord == null) { dbMatch.RkiMatchRecord = new RkiMatchRecord { RkiStatus = (RkiStatus)(-1) }; } var status = EnumSerializer.DeserializeEnumStrict <RkiStatus>(rkiMatch.StatusName); if (dbMatch.RkiMatchRecord.RkiStatus <= status) { dbMatch.RkiMatchRecord.RkiReferenceId = rkiMatch.InterneRef.Value; dbMatch.RkiMatchRecord.RkiStatus = status; dbMatch.RkiMatchRecord.RkiReferenceNumber = rkiMatch.Aktenzeichen; } } } } }
/// <summary> /// Returns a serializer that can be used to serialize and object /// of type <paramref name="objectType"/>. /// <note> /// TODO: Add support for caching. /// </note> /// </summary> /// <param name="objectType">The type of object to be serialized.</param> /// <param name="ctx">The serialization context.</param> public virtual ISerializer Build(Type objectType, SerializationContext ctx) { if (objectType == null) { return(null); } ISerializer s; if (typeof(Calendar).IsAssignableFrom(objectType)) { s = new CalendarSerializer(ctx); } else if (typeof(ICalendarComponent).IsAssignableFrom(objectType)) { s = typeof(CalendarEvent).IsAssignableFrom(objectType) ? new EventSerializer(ctx) : new ComponentSerializer(ctx); } else if (typeof(ICalendarProperty).IsAssignableFrom(objectType)) { s = new PropertySerializer(ctx); } else if (typeof(CalendarParameter).IsAssignableFrom(objectType)) { s = new ParameterSerializer(ctx); } else if (typeof(string).IsAssignableFrom(objectType)) { s = new StringSerializer(ctx); } else if (objectType.GetTypeInfo().IsEnum) { s = new EnumSerializer(objectType, ctx); } else if (typeof(TimeSpan).IsAssignableFrom(objectType)) { s = new TimeSpanSerializer(ctx); } else if (typeof(int).IsAssignableFrom(objectType)) { s = new IntegerSerializer(ctx); } else if (typeof(Uri).IsAssignableFrom(objectType)) { s = new UriSerializer(ctx); } else if (typeof(ICalendarDataType).IsAssignableFrom(objectType)) { s = _mDataTypeSerializerFactory.Build(objectType, ctx); } // Default to a string serializer, which simply calls // ToString() on the value to serialize it. else { s = new StringSerializer(ctx); } return(s); }
public void constructor_with_no_arguments_should_return_expected_result <TEnum>( [ClassValues(typeof(EnumPrototypes))] TEnum _) where TEnum : struct, Enum { var subject = new EnumSerializer <TEnum>(); subject.Representation.Should().Be((BsonType)0); }
public void Deserialize_string_should_be_caseinsensitive(string json, CaseSensitiveEnum result) { var subject = new EnumSerializer <CaseSensitiveEnum>(BsonType.String); var deserialized = Deserialize(subject, ToBson(json)); deserialized.Should().Be(result); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return(null); } // get the request type property var request = JObject.Load(reader); var type = EnumSerializer.ToEnum <SpeechletRequest.RequestType>(request.Value <string>("type")); // convert it to an enum // deserialize to the specified type switch (type) { case SpeechletRequest.RequestType.LaunchRequest: return(request.ToObject <LaunchRequest>()); case SpeechletRequest.RequestType.IntentRequest: return(request.ToObject <IntentRequest>()); case SpeechletRequest.RequestType.SessionEndedRequest: return(request.ToObject <SessionEndedRequest>()); case SpeechletRequest.RequestType.PlaybackStarted: return(request.ToObject <PlaybackStartedRequest>()); case SpeechletRequest.RequestType.PlaybackFinished: return(request.ToObject <PlaybackFinishedRequest>()); case SpeechletRequest.RequestType.PlaybackStopped: return(request.ToObject <PlaybackStoppedRequest>()); case SpeechletRequest.RequestType.PlaybackNearlyFinished: return(request.ToObject <PlaybackNearlyFinishedRequest>()); case SpeechletRequest.RequestType.PlaybackFailed: return(request.ToObject <PlaybackFailedRequest>()); case SpeechletRequest.RequestType.NextCommandIssued: return(request.ToObject <NextCommandIssuedRequest>()); case SpeechletRequest.RequestType.PauseCommandIssued: return(request.ToObject <PauseCommandIssuedRequest>()); case SpeechletRequest.RequestType.PlayCommandIssued: return(request.ToObject <PlayCommandIssuedRequest>()); case SpeechletRequest.RequestType.PreviousCommandIssued: return(request.ToObject <PreviousCommandIssuedRequest>()); case SpeechletRequest.RequestType.SystemExceptionEncountered: return(request.ToObject <SystemExceptionEncounteredRequest>()); default: throw new SerializationException($"Request type of \"{type}\" is invalid"); } }
public void Deserialize_string_should_throw_when_enum_field_is_not_found() { var subject = new EnumSerializer <CaseSensitiveEnum>(BsonType.String); var json = "{ x : 'NotEnumField' }"; var exception = Record.Exception(() => Deserialize(subject, ToBson(json))); exception.Should().BeOfType <ArgumentException>(); }
[InlineData(EnumUInt64.Min, "{ x : { $numberDouble : '9223372036854775808.0' } }")] // (double)long.Max + 1 public void Deserialize_should_throw_on_overflow <TEnum>(TEnum _, string json) where TEnum : struct, Enum { var subject = new EnumSerializer <TEnum>(); var exception = Record.Exception(() => Deserialize(subject, ToBson(json))); exception.Should().BeOfType <OverflowException>(); }
public void constructor_with_representation_should_return_expected_result <TEnum>( [ClassValues(typeof(EnumPrototypes))] TEnum _, [Values((BsonType)0, BsonType.Int32, BsonType.Int64, BsonType.String)] BsonType representation) where TEnum : struct, Enum { var subject = new EnumSerializer <TEnum>(representation); subject.Representation.Should().Be(representation); }
public void Deserialize() { var serializer = new EnumSerializer(typeof(Country)); Assert.AreEqual(Country.America, serializer.Deserialize("America", null)); Assert.AreEqual(Country.America, serializer.Deserialize("0", null)); Assert.AreEqual(Country.Japan, serializer.Deserialize("JP", null)); Assert.ThrowsException <FormatException>(() => serializer.Deserialize("Japan", null)); Assert.ThrowsException <FormatException>(() => serializer.Deserialize("1", null)); }
private static bool TryTranslateDateTimeProperty(MemberExpression expression, AggregationExpression container, MemberInfo memberInfo, out AggregationExpression result) { result = null; if (container.Expression.Type == typeof(DateTime) && memberInfo is PropertyInfo propertyInfo) { AstExpression ast; IBsonSerializer serializer; if (propertyInfo.Name == "DayOfWeek") { ast = AstExpression.Subtract(AstExpression.DatePart(AstDatePart.DayOfWeek, container.Ast), 1); serializer = new EnumSerializer <DayOfWeek>(BsonType.Int32); } else { AstDatePart datePart; switch (propertyInfo.Name) { case "Day": datePart = AstDatePart.DayOfMonth; break; case "DayOfWeek": datePart = AstDatePart.DayOfWeek; break; case "DayOfYear": datePart = AstDatePart.DayOfYear; break; case "Hour": datePart = AstDatePart.Hour; break; case "Millisecond": datePart = AstDatePart.Millisecond; break; case "Minute": datePart = AstDatePart.Minute; break; case "Month": datePart = AstDatePart.Month; break; case "Second": datePart = AstDatePart.Second; break; case "Week": datePart = AstDatePart.Week; break; case "Year": datePart = AstDatePart.Year; break; default: return(false); } ast = AstExpression.DatePart(datePart, container.Ast); serializer = new Int32Serializer(); } result = new AggregationExpression(expression, ast, serializer); return(true); } return(false); }
public void Deserialize_should_throw_when_bson_type_is_invalid <TEnum>( [ClassValues(typeof(EnumPrototypes))] TEnum _, [Values("{ x : false }")] string json) where TEnum : struct, Enum { var subject = new EnumSerializer <TEnum>(); var bson = ToBson(json); var exception = Record.Exception(() => Deserialize(subject, bson)); exception.Should().BeOfType <FormatException>(); }
public void FlagsTest() { var value = TestFlags.B | TestFlags.D; using (var ms = new MemoryStream()) { var s = new EnumSerializer <TestFlags>(); Assert.True(s.CanSerialize(value, null)); using (var bw = new BinaryWriter(ms, Encoding.UTF8, true)) s.Serialize(value, bw, null); ms.Position = 0; using (var br = new BinaryReader(ms, Encoding.UTF8, true)) { var res = s.Deserialize(br, null); Assert.NotNull(res); Assert.Equal(value, res); } } }
private object SerializeDirective(JToken obj) { var type = EnumSerializer.ToEnum <Directive.DirectiveType>(obj.Value <string>("type")); // deserialize to the specified type switch (type) { case Directive.DirectiveType.Play: return(obj.ToObject <PlayDirective>()); case Directive.DirectiveType.Stop: return(obj.ToObject <StopDirective>()); case Directive.DirectiveType.ClearQueue: return(obj.ToObject <ClearQueueDirective>()); default: throw new SerializationException($"Directive type of \"{type}\" is invalid"); } }
public void WithRepresentation_should_return_expected_result <TEnum>( [ClassValues(typeof(EnumPrototypes))] TEnum _, [Values((BsonType)0, BsonType.Int32, BsonType.Int64, BsonType.String)] BsonType originalRepresentation, [Values((BsonType)0, BsonType.Int32, BsonType.Int64, BsonType.String)] BsonType newRepresentation) where TEnum : struct, Enum { var subject = new EnumSerializer <TEnum>(originalRepresentation); var result = subject.WithRepresentation(newRepresentation); if (newRepresentation == originalRepresentation) { result.Should().BeSameAs(subject); } else { result.Should().NotBeSameAs(subject); result.Representation.Should().Be(newRepresentation); } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return(null); } // get the request type property var request = JObject.Load(reader); var type = EnumSerializer.ToEnum <OutputSpeech.OutputType>(request.Value <string>("type")); // deserialize to the specified type switch (type) { case OutputSpeech.OutputType.PlainText: return(request.ToObject <PlainTextOutputSpeech>()); case OutputSpeech.OutputType.SSML: return(request.ToObject <SsmlOutputSpeech>()); default: throw new SerializationException($"Output Speech type of \"{type}\" is invalid"); } }
public void Simple() { var w = new Writer(); var cs = new EnumSerializer(typeof(SimpleEnum)); w.BeginList(); w.BeginListValue(); Assert.True(cs.Write(w, SimpleEnum.Third, null)); w.BeginListValue(); Assert.True(cs.Write(w, SimpleEnum.Fifth, null)); w.EndList(); Assert.True(w.IsValid()); Assert.AreEqual("[Third,Fifth]", w.ToString()); var r = new Reader(w.ToString()); r.BeginList(); r.BeginListValue(); Assert.AreEqual(SimpleEnum.Third, (SimpleEnum)cs.Read(r, null, null)); r.BeginListValue(); Assert.AreEqual(SimpleEnum.Fifth, (SimpleEnum)cs.Read(r, null, null)); r.EndList(); Assert.IsFalse(r.AnyLeft, "Any characters left."); }
public void Serialize_and_Deserialize_should_return_the_expected_result <TEnum>(TEnum value, BsonType representation, string expectedJson) where TEnum : struct, Enum { var subject = new EnumSerializer <TEnum>(representation); if (expectedJson == "overflow") { var exception = Record.Exception(() => Serialize(subject, value)); exception.Should().BeOfType <OverflowException>(); } else { var bson = Serialize(subject, value); var deserialized = Deserialize(subject, bson); if (!bson.SequenceEqual(ToBson(expectedJson))) { var message = $"Expected: {expectedJson} but found: {ToJson(bson)}."; throw new AssertionException(message); } deserialized.Should().Be(value); } }
public GenericClassSerializer GetTypeSerializer(Type fieldType) { GenericClassSerializer ret = null; if (serializerForClass.ContainsKey(fieldType)) { ret = serializerForClass[fieldType]; } else { if (typeof(Enum).IsAssignableFrom(fieldType)) { ret = new EnumSerializer(fieldType); serializerForClass.Add(fieldType, ret); } else { ret = serializerForClass[typeof(Object)]; } } return ret; }
public static object FromJson( JsonValue json, Type typeScope, DeserializationContext context = default(DeserializationContext) ) { // === Handle null === if (json.IsNull) { return(null); } // === Parse and validate arguments === if (typeScope == null) { throw new ArgumentNullException(nameof(typeScope)); } // context cannot be null, no need to check // === Guard insecure deserialization === if (!context.suppressInsecureDeserializationException) { if (typeScope == typeof(object)) { throw new InsecureDeserializationException( "You cannot deserialize unknown data to an 'object' " + "or 'dynamic' variable, as it poses a security risk. " + "Read the security section of the serialization " + "documentation to learn more." ); } } // === Determine deserialization type (the "$type" argument) === Type deserializationType = GetDeserializationType(json, typeScope); // === Call static constructor of the deserialized type === RuntimeHelpers.RunClassConstructor(deserializationType.TypeHandle); // === Deserialize === // .NET primitives if (typeScope.IsPrimitive) { return(DotNetPrimitivesSerializer.FromJson(json, typeScope)); } // string if (typeScope == typeof(string)) { return(json.AsString); } // enums if (typeScope.IsEnum) { return(EnumSerializer.FromJson(json, typeScope)); } // arrays if (typeScope.IsArray) { // binary data if (typeScope == typeof(byte[])) { return(BinarySerializer.FromJson(json, typeScope, context)); } return(ArraySerializer.FromJson(json, typeScope, context)); } // by what type value to search through ITypeSerializers var searchType = typeScope.IsGenericType ? typeScope.GetGenericTypeDefinition() : typeScope; // exact type serializers if (exactTypeSerializers.TryGetValue(searchType, out ITypeSerializer serializer)) { return(serializer.FromJson(json, deserializationType, context)); } // assignable type serializers foreach (var pair in assignableTypeSerializers) { if (pair.Key.IsAssignableFrom(searchType)) { return(pair.Value.FromJson(json, deserializationType, context)); } } // unisave serializable if (typeof(IUnisaveSerializable).IsAssignableFrom(deserializationType)) { return(UnisaveSerializableTypeSerializer.FromJson( json, deserializationType, context )); } // serializable if (typeof(ISerializable).IsAssignableFrom(deserializationType)) { return(SerializableTypeSerializer.FromJson( json, deserializationType, context )); } // other return(DefaultSerializer.FromJson( json, deserializationType, context )); }
private static JsonValue Serialize( object subject, Type typeScope, SerializationContext context ) { Type type = subject.GetType(); // .NET primitives if (type.IsPrimitive) { return(DotNetPrimitivesSerializer.ToJson(subject, type)); } // string if (type == typeof(string)) { return((string)subject); } // enums if (type.IsEnum) { return(EnumSerializer.ToJson(subject)); } // arrays if (type.IsArray) { // binary data if (type == typeof(byte[])) { return(BinarySerializer.ToJson(subject, typeScope, context)); } return(ArraySerializer.ToJson(subject, typeScope, context)); } // by what type value to search through ITypeSerializers var searchType = type.IsGenericType ? type.GetGenericTypeDefinition() : type; // exact type serializers if (exactTypeSerializers.TryGetValue(searchType, out ITypeSerializer serializer)) { return(serializer.ToJson(subject, typeScope, context)); } // assignable type serializers foreach (var pair in assignableTypeSerializers) { if (pair.Key.IsAssignableFrom(searchType)) { return(pair.Value.ToJson(subject, typeScope, context)); } } // unisave serializable if (typeof(IUnisaveSerializable).IsAssignableFrom(type)) { return(UnisaveSerializableTypeSerializer.ToJson( subject, typeScope, context )); } // serializable if (typeof(ISerializable).IsAssignableFrom(type)) { return(SerializableTypeSerializer.ToJson( subject, typeScope, context )); } // validate type scope if (!typeScope.IsAssignableFrom(type)) { throw new ArgumentException( $"Given subject is of type {type} that is not assignable " + $"to the given type scope {typeScope}" ); } // other return(DefaultSerializer.ToJson(subject, typeScope, context)); }
public override void SetUp() { base.SetUp(); _enumSerializer = new EnumSerializer(); }
/// <summary> /// Gets the object serializer corresponding to a specific type. /// </summary> /// <param name="Type">Type of object to serialize.</param> /// <returns>Object Serializer</returns> public async Task <IObjectSerializer> GetObjectSerializer(Type Type) { IObjectSerializer Result; TypeInfo TI = Type.GetTypeInfo(); lock (this.synchObj) { if (this.serializers.TryGetValue(Type, out Result)) { return(Result); } if (TI.IsEnum) { Result = new EnumSerializer(Type); } else if (Type.IsArray) { Type ElementType = Type.GetElementType(); Type T = Types.GetType(typeof(ByteArraySerializer).FullName.Replace("ByteArray", "Array")); Type SerializerType = T.MakeGenericType(new Type[] { ElementType }); Result = (IObjectSerializer)Activator.CreateInstance(SerializerType, this.context); } else if (TI.IsGenericType) { Type GT = Type.GetGenericTypeDefinition(); if (GT == typeof(Nullable <>)) { Type NullableType = Type.GenericTypeArguments[0]; if (NullableType.GetTypeInfo().IsEnum) { Result = new Serialization.NullableTypes.NullableEnumSerializer(NullableType); } else { Result = null; } } else { Result = null; } } else { Result = null; } if (!(Result is null)) { this.serializers[Type] = Result; this.serializerAdded.Set(); return(Result); } } try { #if NETSTANDARD1_5 Result = await ObjectSerializer.Create(Type, this.context, this.compiled); #else Result = await ObjectSerializer.Create(Type, this.context); #endif await Result.Init(); lock (this.synchObj) { this.serializers[Type] = Result; this.serializerAdded.Set(); } } catch (FileLoadException ex) { // Serializer in the process of being generated from another task or thread. while (true) { if (!this.serializerAdded.WaitOne(1000)) { ExceptionDispatchInfo.Capture(ex).Throw(); } lock (this.synchObj) { if (this.serializers.TryGetValue(Type, out Result)) { return(Result); } } } } return(Result); }
private void AvoidAot() { EnumSerializer <EntityType> e = new EnumSerializer <EntityType>(); }