private static void ShouldBeSerializable(SerializationFormat format)
        {
            // Arrange.
            var category        = ApplicationEventCategory.Information;
            var verbosity       = ApplicationEventVerbosity.Normal;
            var description     = "description";
            var environmentName = "environmentName";
            var userInformation = "userInformation";
            var target          = new ApplicationEvent(category, verbosity, description, environmentName, userInformation);
            var serializer      = new DynamicSerializer <ApplicationEvent>(format);

            // Act.
            var serializedTarget   = serializer.Serialize(target);
            var deserializedResult = serializer.Deserialize(serializedTarget);

            // Assert.
            deserializedResult.Should().NotBeNull();
            deserializedResult.Category.Should().Be(target.Category);
            deserializedResult.Description.Should().Be(target.Description);
            deserializedResult.EnvironmentName.Should().Be(target.EnvironmentName);
            deserializedResult.OccurrenceDateTime.Should().Be(target.OccurrenceDateTime);
            deserializedResult.Summary.Should().Be(target.Summary);
            deserializedResult.UserInformation.Should().Be(target.UserInformation);
            deserializedResult.Verbosity.Should().Be(target.Verbosity);
        }
Example #2
0
        /// <summary>
        /// Serializes the specified message.
        /// </summary>
        /// <typeparam name="TMessage">
        /// The type of the message.
        /// </typeparam>
        /// <param name="message">
        /// The message to serialize.
        /// </param>
        /// <returns>
        /// The serialized result.
        /// </returns>
        /// <exception cref="SerializationException">
        /// <paramref name="message" /> is invalid or an error occurred during serialization.
        /// </exception>
        protected Byte[] SerializeMessage <TMessage>(TMessage message)
            where TMessage : class
        {
            var serializer = new DynamicSerializer <TMessage>(MessageSerializationFormat);

            return(serializer.Serialize(message));
        }
Example #3
0
 public NetContext()
 {
     Services   = new NetServiceCollection();
     Serializer = new DynamicSerializer();
     Packets    = new PacketRegistry();
     IsLocked   = false;
 }
Example #4
0
        public void DynamicSerializer_AddReaderWriter_CanReadWrite()
        {
            DynamicSerializer s = new DynamicSerializer();

            Assert.IsFalse(s.CanReadWrite(typeof(TestModelWithConstructor)));

            s.AddReaderWriter <TestModelWithConstructor>(
                new DataWriter(s, typeof(TestModelWithConstructor)),
                new DataReader(s, typeof(TestModelWithConstructor), () => new TestModelWithConstructor("")));

            Assert.IsTrue(s.CanReadWrite(typeof(TestModelWithConstructor)));

            TestModelWithConstructor m = new TestModelWithConstructor("Hello world");

            DataBuffer b = new DataBuffer();

            s.Write <TestModelWithConstructor>(b, m);

            b.Seek(0);
            var result = s.Read <TestModelWithConstructor>(b);

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.Data);
            Assert.AreEqual(result.Data, m.Data);
        }
Example #5
0
        public void DynamicSerializer_WriteReadCoveredType()
        {
            DynamicSerializer s = new DynamicSerializer();

            s.AddReaderWriter(typeof(ITestInterface),
                              new DataWriter(typeof(ITestInterface), WriteTestInterface),
                              new DataReader(typeof(ITestInterface), ReadTestInterface), true);

            Random         r = new Random();
            ITestInterface m = new TestImplemented();

            m.Data = "Hello world";

            DataBuffer b = new DataBuffer();

            s.Write(b, typeof(TestImplemented), m);

            b.Seek(0);
            var mresult = s.Read <ITestInterface>(b);

            Assert.IsNotNull(mresult);
            Assert.IsNotNull(mresult.Data);
            Assert.IsFalse(mresult.Data == "");
            Assert.AreEqual(m.Data, mresult.Data);
        }
Example #6
0
        private static void ShouldBeSerializable(SerializationFormat format)
        {
            // Arrange. Arrange.
            var target     = new TimeOfDay(TimeZoneInfo.Utc, 15, 32, 56, 490);
            var serializer = new DynamicSerializer <TimeOfDay>(format);

            // Act.
            var serializedTarget   = serializer.Serialize(target);
            var deserializedResult = serializer.Deserialize(serializedTarget);

            // Assert.
            deserializedResult.Should().Be(target);
        }
Example #7
0
		public void TestDynamicObject()
		{
			var reg = new MessageRegistry();
			var typeRegistry = TypeRegistry.CreateDefault();
			var ser = new DefaultSerializer<SubMessage>(reg, typeRegistry);
			var r = new DynamicSerializer(reg, typeRegistry);

			using (var buf = new ThreadSafeWriteQueue(1024))
			{
				dynamic src = new SubMessage { MessageId = ser.MessageId, A = 1, B = 2 };
				r.Serialize(buf, src);
				dynamic a = new { };
				r.Deserialize(buf, buf.ReadMessage(), a);
			}
		}
        private static void ShouldBeSerializable(SerializationFormat format)
        {
            // Arrange. Arrange.
            var start      = new DateTime(1997, 11, 6, 14, 7, 46, 482, DateTimeKind.Local);
            var end        = new DateTime(2024, 2, 29, 17, 41, 10, 193, DateTimeKind.Local);
            var target     = new DateTimeRange(start, end);
            var serializer = new DynamicSerializer <DateTimeRange>(format);

            // Act.
            var serializedTarget   = serializer.Serialize(target);
            var deserializedResult = serializer.Deserialize(serializedTarget);

            // Assert.
            deserializedResult.Should().Be(target);
        }
Example #9
0
        private static void ShouldBeSerializable(SerializationFormat format)
        {
            // Arrange. Arrange.
            var value      = Guid.Parse("4aaadf09-0a66-41dc-bfc8-f8520f4aeaf8");
            var identifier = new EnhancedReadabilityGuid(value);
            var target     = new EnhancedReadabilityGuidContainer(identifier);
            var serializer = new DynamicSerializer <EnhancedReadabilityGuidContainer>(format);

            // Act.
            var serializedTarget   = serializer.Serialize(target);
            var deserializedResult = serializer.Deserialize(serializedTarget);

            // Assert.
            deserializedResult.Identifier.Should().Be(identifier);
        }
Example #10
0
        /// <summary>
        /// Encode all values using the given serializer, and than decode them back.
        /// </summary>
        private static IEnumerable <T> RoundTrip <T>(DynamicSerializer <T> ds, CodecWriter codec, IEnumerable <T> values)
        {
            using (IEnumerator <T> enmr = values.GetEnumerator())
            {
                bool moveNext = enmr.MoveNext();
                var  buff     = new Buffer <T>(new T[4]);

                while (moveNext)
                {
                    try
                    {
                        codec.Count = 0;
                        moveNext    = ds.Serialize(codec, enmr);

                        codec.Count = 0;
                        buff.Count  = 0;
                        using (var cdcRdr = new CodecReader(codec.AsArraySegment()))
                            ds.DeSerialize(cdcRdr, buff, int.MaxValue);
                    }
                    catch (Exception x)
                    {
                        string msg = string.Format(
                            "codec.Count={0}, codec.Buffer[pos-1]={1}, enmr.Value={2}",
                            codec.Count,
                            codec.Count > 0
                                ? codec.Buffer[codec.Count - 1].ToString(CultureInfo.InvariantCulture)
                                : "n/a",
                            moveNext ? enmr.Current.ToString() : "none left");

                        if (x.GetType() == typeof(OverflowException))
                        {
                            throw new OverflowException(msg, x);
                        }

                        throw new SerializerException(x, msg);
                    }

                    ArraySegment <T> result = buff.AsArraySegment();
                    for (int i = result.Offset; i < result.Count; i++)
                    {
                        yield return(result.Array[i]);
                    }
                }
            }
        }
        private Task HandleReceiverException(ExceptionReceivedEventArgs exceptionReceivedArguments)
        {
            var receivedException = exceptionReceivedArguments.Exception;

            try
            {
                var exceptionRaisedMessage = new ExceptionRaisedMessage(receivedException);
                var serializer             = new DynamicSerializer <ExceptionRaisedMessage>(ExceptionRaisedMessageSerializationFormat);
                var messageBody            = serializer.Serialize(exceptionRaisedMessage);
                var azureServiceBusMessage = CreateAzureServiceBusMessage(messageBody, typeof(ExceptionRaisedMessage), ExceptionRaisedMessageSerializationFormat, exceptionRaisedMessage.Identifier, exceptionRaisedMessage.CorrelationIdentifier);
                var sendClient             = GetSendClient <ExceptionRaisedMessage>(ExceptionRaisedMessageEntityType);
                return(sendClient.SendAsync(azureServiceBusMessage));
            }
            catch (Exception exception)
            {
                throw new AggregateException("An exception was raised while trying to publish an ExceptionRaisedMessage.", exception, receivedException);
            }
        }
Example #12
0
        public DynamicObjectFormatter(CerasSerializer serializer)
        {
            _ceras = serializer;

            var type = typeof(T);

            ThrowIfNonspecific(type);

            var members = GetSerializableMembers(type, _ceras.Config.DefaultTargets, _ceras.Config.ShouldSerializeMember);

            if (members.Count > 0)
            {
                _dynamicSerializer   = GenerateSerializer(members);
                _dynamicDeserializer = GenerateDeserializer(members);
            }
            else
            {
                _dynamicSerializer   = (ref byte[] buffer, ref int offset, T value) => { };
                _dynamicDeserializer = (byte[] buffer, ref int offset, ref T value) => { };
            }
        }
        private static void ShouldBeSerializable(SerializationFormat format)
        {
            // Arrange. Arrange.
            var correlationIdentifier = Guid.Parse("4aaadf09-0a66-41dc-bfc8-f8520f4aeaf8");
            var dateRange             = new DateTimeRange(DateTime.UtcNow, DateTime.UtcNow.AddDays(1));
            var target     = new SimulatedRequestMessage(correlationIdentifier, dateRange);
            var identifier = target.Identifier;
            var resultType = target.ResultType;
            var serializer = new DynamicSerializer <SimulatedRequestMessage>(format);

            // Act.
            var serializedTarget   = serializer.Serialize(target);
            var deserializedResult = serializer.Deserialize(serializedTarget);

            // Assert.
            deserializedResult.Should().NotBeNull();
            deserializedResult.CorrelationIdentifier.Should().Be(correlationIdentifier);
            deserializedResult.DateRange.Should().Be(dateRange);
            deserializedResult.Identifier.Should().Be(identifier);
            deserializedResult.ResultType.Should().Be(resultType);
        }
        private static void ShouldBeSerializable(SerializationFormat format)
        {
            // Arrange. Arrange.
            var requestMessageIdentifier = Guid.Parse("fab2812e-88f4-4a03-8723-6d285a98b149");
            var correlationIdentifier    = Guid.Parse("4aaadf09-0a66-41dc-bfc8-f8520f4aeaf8");
            var result     = TimeSpan.FromMilliseconds(99999);
            var target     = new SimulatedResponseMessage(requestMessageIdentifier, correlationIdentifier, result);
            var identifier = target.Identifier;
            var resultType = target.ResultType;
            var serializer = new DynamicSerializer <SimulatedResponseMessage>(format);

            // Act.
            var serializedTarget   = serializer.Serialize(target);
            var deserializedResult = serializer.Deserialize(serializedTarget);

            // Assert.
            deserializedResult.Should().NotBeNull();
            deserializedResult.CorrelationIdentifier.Should().Be(correlationIdentifier);
            deserializedResult.Identifier.Should().Be(identifier);
            deserializedResult.RequestMessageIdentifier.Should().Be(requestMessageIdentifier);
            deserializedResult.Result.Should().Be(result);
            deserializedResult.ResultType.Should().Be(resultType);
        }
Example #15
0
        /// <summary>
        /// Perform a round trip encoding/decoding test for the given sequence of values.
        /// </summary>
        protected void Run <T>(IEnumerable <T> values, string name = null,
                               Action <BaseField> set = null, Func <T, T, bool> comp = null)
        {
            using (var codec = new CodecWriter(10000))
            {
                var ds = new DynamicSerializer <T>(null);

                try
                {
                    if (set != null)
                    {
                        set(ds.RootField);
                    }

                    ds.MakeReadonly();

                    TestUtils.CollectionAssertEqual(
                        values, RoundTrip(ds, codec, values), comp, "{0} {1}", typeof(T).Name, name);
                }
                catch (Exception x)
                {
                    string msg = string.Format(
                        "Name={0}, codec.Count={1}, codec.Buffer[pos-1]={2}",
                        name,
                        codec.Count,
                        codec.Count > 0
                            ? codec.Buffer[codec.Count - 1].ToString(CultureInfo.InvariantCulture)
                            : "n/a");
                    if (x.GetType() == typeof(OverflowException))
                    {
                        throw new OverflowException(msg, x);
                    }

                    throw new SerializerException(x, msg);
                }
            }
        }
        private static void ShouldBeSerializable(SerializationFormat format)
        {
            // Arrange.
            var series     = new Double[] { 0d, 1d, 2d, 3d, 4d };
            var target     = series.ComputeDescriptives();
            var serializer = new DynamicSerializer <DescriptiveStatistics>(format);

            // Act.
            var serializedTarget   = serializer.Serialize(target);
            var deserializedResult = serializer.Deserialize(serializedTarget);

            // Assert.
            deserializedResult.Should().NotBeNull();
            deserializedResult.Maximum.Should().Be(target.Maximum);
            deserializedResult.Mean.Should().Be(target.Mean);
            deserializedResult.Median.Should().Be(target.Median);
            deserializedResult.Midrange.Should().Be(target.Midrange);
            deserializedResult.Minimum.Should().Be(target.Minimum);
            deserializedResult.Range.Should().Be(target.Range);
            deserializedResult.Size.Should().Be(target.Size);
            deserializedResult.StandardDeviation.Should().Be(target.StandardDeviation);
            deserializedResult.Sum.Should().Be(target.Sum);
            deserializedResult.Variance.Should().Be(target.Variance);
        }
Example #17
0
 public PacketsRegistry()
 {
     Serializer         = new DynamicSerializer();
     PacketsDeclaration = new Dictionary <string, FieldBase>();
 }
Example #18
0
 /// <summary>
 /// Serializes the given data to the provided TextWriter.
 ///
 /// Pass an Options object to configure the particulars (such as whitespace, and DateTime formats) of
 /// the produced JSON.  If omitted Options.Default is used, unless JSON.SetDefaultOptions(Options) has been
 /// called with a different Options object.
 ///
 /// Unlike Serialize, this method will inspect the Type of data to determine what serializer to invoke.
 /// This is not as fast as calling Serialize with a known type.
 ///
 /// Objects with participate in the DLR will be serialized appropriately, all other types
 /// will be serialized via reflection.
 /// </summary>
 public static void SerializeDynamic(dynamic data, TextWriter output, Options options = null)
 {
     DynamicSerializer.Serialize(output, (object)data, options ?? DefaultOptions, 0);
 }