Beispiel #1
0
        public void PackArray()
        {
            var date = MessagePackConvert.ToDateTime(1360370224238);
            var pack = _packer.MakePacket("test1", date, new[] { "hoge", "1234" });

            Utils.Unpack(pack).Is(@"[ ""test.test1"", 1360370224238, [ ""hoge"", ""1234"" ] ]");
        }
Beispiel #2
0
        public void PackNestedData()
        {
            var date = MessagePackConvert.ToDateTime(1360370224238);

            var parent = new Parent()
            {
                Name   = "Parent",
                Child1 = new Child {
                    Name = "Child1", Value = 1
                },
                Child2 = new Child {
                    Name = "Child2", Value = 2
                },
                Child3 = new Child {
                    Name = "Child3", Value = 3
                },
                Child4 = new Child {
                    Name = "Child4", Value = 4
                },
                Child5 = new Child {
                    Name = "Child5", Value = 5
                }
            };
            var pack = _packer.MakePacket("test1", date, parent);

            Utils.Unpack(pack).Is(@"[ ""test.test1"", 1360370224238, { ""Name"" : ""Parent"", ""Child1"" : { ""Name"" : ""Child1"", ""Value"" : 1 }, ""Child2"" : { ""Name"" : ""Child2"", ""Value"" : 2 }, ""Child3"" : { ""Name"" : ""Child3"", ""Value"" : 3 }, ""Child4"" : { ""Name"" : ""Child4"", ""Value"" : 4 }, ""Child5"" : { ""Name"" : ""Child5"", ""Value"" : 5 } } ]");
        }
Beispiel #3
0
        protected internal override DateTimeOffset UnpackFromCore(Unpacker unpacker)
        {
            if (unpacker.LastReadData.IsTypeOf <MessagePackExtendedTypeObject>().GetValueOrDefault())
            {
                return(Timestamp.Decode(unpacker.LastReadData.DeserializeAsMessagePackExtendedTypeObject()).ToDateTimeOffset());
            }
            else if (unpacker.IsArrayHeader)
            {
                if (UnpackHelpers.GetItemsCount(unpacker) != 2)
                {
                    SerializationExceptions.ThrowInvalidArrayItemsCount(unpacker, typeof(DateTimeOffset), 2);
                }

                long ticks;
                if (!unpacker.ReadInt64(out ticks))
                {
                    SerializationExceptions.ThrowUnexpectedEndOfStream(unpacker);
                }

                short offsetMinutes;
                if (!unpacker.ReadInt16(out offsetMinutes))
                {
                    SerializationExceptions.ThrowUnexpectedEndOfStream(unpacker);
                }

                return(new DateTimeOffset(DateTime.FromBinary(ticks), TimeSpan.FromMinutes(offsetMinutes)));
            }
            else
            {
                return(MessagePackConvert.ToDateTimeOffset(unpacker.LastReadData.DeserializeAsInt64()));
            }
        }
Beispiel #4
0
        public void PackSimpleAnonymousObject()
        {
            var date = MessagePackConvert.ToDateTime(1360370224238);
            var pack = _packer.MakePacket("test1", date, new { Message = "hoge", Value = 1234 });

            Utils.Unpack(pack).Is(@"[ ""test.test1"", 1360370224238, { ""Message"" : ""hoge"", ""Value"" : 1234 } ]");
        }
        protected internal override DateTimeOffset UnpackFromCore(Unpacker unpacker)
        {
            if (unpacker.IsArrayHeader)
            {
                if (UnpackHelpers.GetItemsCount(unpacker) != 2)
                {
                    throw new SerializationException("Invalid DateTimeOffset serialization.");
                }

                long ticks;
                if (!unpacker.ReadInt64(out ticks))
                {
                    throw SerializationExceptions.NewUnexpectedEndOfStream();
                }

                short offsetMinutes;
                if (!unpacker.ReadInt16(out offsetMinutes))
                {
                    throw SerializationExceptions.NewUnexpectedEndOfStream();
                }

                return(new DateTimeOffset(DateTime.FromBinary(ticks), TimeSpan.FromMinutes(offsetMinutes)));
            }
            else
            {
                return(MessagePackConvert.ToDateTimeOffset(unpacker.LastReadData.AsInt64()));
            }
        }
Beispiel #6
0
        protected internal override async Task PackToAsyncCore(Packer packer, DateTimeOffset objectTree, CancellationToken cancellationToken)
        {
            if (this._conversion == DateTimeConversionMethod.Timestamp)
            {
                await packer.PackAsync(Timestamp.FromDateTimeOffset( objectTree ).Encode(), cancellationToken).ConfigureAwait(false);
            }
            else if (this._conversion == DateTimeConversionMethod.Native)
            {
                await packer.PackArrayHeaderAsync(2, cancellationToken).ConfigureAwait(false);

                await packer.PackAsync(objectTree.DateTime.ToBinary(), cancellationToken).ConfigureAwait(false);

                unchecked
                {
                    await packer.PackAsync(( short )(objectTree.Offset.Hours * 60 + objectTree.Offset.Minutes), cancellationToken).ConfigureAwait(false);
                }
            }
            else
            {
#if DEBUG
                Contract.Assert(this._conversion == DateTimeConversionMethod.UnixEpoc);
#endif // DEBUG
                await packer.PackAsync(MessagePackConvert.FromDateTimeOffset(objectTree), cancellationToken).ConfigureAwait(false);
            }
        }
Beispiel #7
0
        public void Verify(Stream stream)
        {
            stream.Position = 0;
            var data = Unpacking.UnpackObject(stream);

            NUnit.Framework.Assert.That(data, Is.Not.Null);
            if (data.IsDictionary)
            {
                var map = data.AsDictionary();
                NUnit.Framework.Assert.That(map.ContainsKey("Source"));
                NUnit.Framework.Assert.That(this.Source, Is.Not.Null);
                NUnit.Framework.Assert.That(map["Source"].AsString(), Is.EqualTo(this.Source.ToString()));
                NUnit.Framework.Assert.That(map.ContainsKey("TimeStamp"));
                NUnit.Framework.Assert.That(MessagePackConvert.ToDateTime(map["TimeStamp"].AsInt64()), Is.EqualTo(this.TimeStamp));
                NUnit.Framework.Assert.That(map.ContainsKey("Data"));
                NUnit.Framework.Assert.That(map["Data"].AsBinary(), Is.EqualTo(this.Data));
                NUnit.Framework.Assert.That(map.ContainsKey("History"));
                NUnit.Framework.Assert.That(map["History"].AsDictionary().Count, Is.EqualTo(this.History.Count));
            }
            else
            {
                var array = data.AsList();
                NUnit.Framework.Assert.That(this.Source, Is.Not.Null);
                NUnit.Framework.Assert.That(array[0].AsString(), Is.EqualTo(this.Source.ToString()));
                NUnit.Framework.Assert.That(MessagePackConvert.ToDateTime(array[2].AsInt64()), Is.EqualTo(this.TimeStamp));
                NUnit.Framework.Assert.That(array[1].AsBinary(), Is.EqualTo(this.Data));
                NUnit.Framework.Assert.That(array[3].AsDictionary().Count, Is.EqualTo(this.History.Count));
            }
        }
        private void TestEchoRequestContinuousCore(bool[] serverStatus, CountdownEvent waitHandle, int count, string message)
        {
            using (var client = new TcpClient())
            {
                client.Connect(new IPEndPoint(IPAddress.Loopback, CallbackServer.PortNumber));

                var    now           = MessagePackConvert.FromDateTime(DateTime.Now);
                bool[] resposeStatus = new bool[count];

                using (var stream = client.GetStream())
                    using (var packer = Packer.Create(stream))
                    {
                        for (int i = 0; i < count; i++)
                        {
                            this._trace.TraceInformation("---- Client sending request ----");
                            packer.PackArrayHeader(4);
                            packer.Pack(0);
                            packer.Pack(i);
                            packer.Pack("Echo");
                            packer.PackArrayHeader(2);
                            packer.Pack(message);
                            packer.Pack(now);
                            this._trace.TraceInformation("---- Client sent request ----");
                        }

                        if (Debugger.IsAttached)
                        {
                            waitHandle.Wait();
                        }
                        else
                        {
                            Assert.That(waitHandle.Wait(TimeSpan.FromSeconds(count * 3)));
                        }

                        for (int i = 0; i < count; i++)
                        {
                            this._trace.TraceInformation("---- Client receiving response ----");
                            var array = Unpacking.UnpackArray(stream);
                            Assert.That(array.Count, Is.EqualTo(4));
                            Assert.That(array[0] == 1, array[0].ToString());
                            Assert.That(array[1].IsTypeOf <int>().GetValueOrDefault());
                            resposeStatus[array[1].AsInt32()] = true;
                            Assert.That(array[2] == MessagePackObject.Nil, array[2].ToString());
                            Assert.That(array[3].IsArray, array[3].ToString());
                            var returnValue = array[3].AsList();
                            Assert.That(returnValue.Count, Is.EqualTo(2));
                            Assert.That(returnValue[0] == message, returnValue[0].ToString());
                            Assert.That(returnValue[1] == now, returnValue[1].ToString());
                            this._trace.TraceInformation("---- Client received response ----");
                        }

                        lock ( serverStatus )
                        {
                            Assert.That(serverStatus, Is.All.True, String.Join(", ", serverStatus));
                        }
                        Assert.That(resposeStatus, Is.All.True);
                    }
            }
        }
Beispiel #9
0
        protected internal override FILETIME UnpackFromCore(Unpacker unpacker)
        {
            var value = MessagePackConvert.ToDateTime(unpacker.LastReadData.AsInt64()).ToFileTimeUtc();

            return(new FILETIME {
                dwHighDateTime = unchecked (( int )(value >> 32)), dwLowDateTime = unchecked (( int )(value & 0xffffffff))
            });
        }
        public static void PackCharArraySegmentTo(Packer packer, object obj, IMessagePackSingleObjectSerializer itemSerializer)
        {
            var objectTree = (ArraySegment <char>)obj;
#endif // !UNITY
            // TODO: More efficient
            packer.PackStringHeader(objectTree.Count);
            packer.PackRawBody(MessagePackConvert.EncodeString(new string( objectTree.Array.Skip(objectTree.Offset).Take(objectTree.Count).ToArray())));
        }
Beispiel #11
0
 protected internal override void PackToCore(Packer packer, FILETIME objectTree)
 {
     packer.Pack(
         MessagePackConvert.FromDateTime(
             objectTree.ToDateTime()
             )
         );
 }
 public void TestDateTimeOffset()
 {
     TestCore(
         DateTimeOffset.UtcNow,
         stream => MessagePackConvert.ToDateTimeOffset(Unpacking.UnpackInt64(stream)),
         (x, y) => CompareDateTime(x.DateTime.ToUniversalTime(), y.DateTime.ToUniversalTime())
         );
 }
 public void TestDateTime()
 {
     TestCore(
         DateTime.UtcNow,
         stream => MessagePackConvert.ToDateTime(Unpacking.UnpackInt64(stream)),
         CompareDateTime
         );
 }
Beispiel #14
0
        protected internal sealed override FILETIME UnpackFromCore(Unpacker unpacker)
        {
            long num = MessagePackConvert.ToDateTime(unpacker.Data.Value.AsInt64()).ToFileTimeUtc();

            return(new FILETIME {
                dwHighDateTime = (int)(num >> 0x20), dwLowDateTime = (int)(((ulong)num) & 0xffffffffL)
            });
        }
        public void PackList()
        {
            var date = MessagePackConvert.ToDateTime(1360370224238);
            var pack = _packer.MakePacket("test1", date, new List <string> {
                "hoge", "1234"
            });

            Utils.Unpack(pack).Is(@"[ ""test.test1"", [ [ 1360370224.238, [ ""hoge"", ""1234"" ] ] ] ]");
        }
Beispiel #16
0
 protected internal override void PackToCore(Packer packer, FILETIME value)
 {
     packer.Pack(
         MessagePackConvert.FromDateTime(
             // DateTime.FromFileTimeUtc in Mono 2.10.x does not return Utc DateTime (Mono issue #2936), so do convert manually to ensure returned DateTime is UTC.
             _fileTimeEpocUtc.AddTicks(unchecked ((( long )value.dwHighDateTime << 32) | (value.dwLowDateTime & 0xffffffff)))
             )
         );
 }
        public void PackStruct()
        {
            var date = MessagePackConvert.ToDateTime(1360370224238);
            var s    = new StructData {
                Name = "Struct", Value = 112233445566778899
            };
            var pack = _packer.MakePacket("test1", date, s);

            Utils.Unpack(pack).Is(@"[ ""test.test1"", [ [ 1360370224.238, { ""Name"" : ""Struct"", ""Value"" : 112233445566778899 } ] ] ]");
        }
        public void PackSimpleDictionary()
        {
            var date = MessagePackConvert.ToDateTime(1360370224238);
            var msg  = new Dictionary <string, object>()
            {
                { "Message", "hoge" }, { "Value", 1234 }
            };
            var pack = _packer.MakePacket("test1", date, msg);

            Utils.Unpack(pack).Is(@"[ ""test.test1"", [ [ 1360370224.238, { ""Message"" : ""hoge"", ""Value"" : 1234 } ] ] ]");
        }
        public void PackSimpleDynamicObject()
        {
            var     date = MessagePackConvert.ToDateTime(1360370224238);
            dynamic msg  = new ExpandoObject();

            msg.Message = "hoge";
            msg.Value   = 1234;
            var pack = _packer.MakePacket("test1", date, msg);

            ((string)Utils.Unpack(pack)).Is(@"[ ""test.test1"", [ [ 1360370224.238, { ""Message"" : ""hoge"", ""Value"" : 1234 } ] ] ]");
        }
        public void SendMessage()
        {
            var server = new DummyServer();
            var task   = server.Run(24224);
            var date   = MessagePackConvert.ToDateTime(1360370224238);

            using (var sender = FluentSender.CreateSync("app").Result)
            {
                sender.EmitWithTimeAsync("hoge", date, new { message = "hoge" });
            }
            var ret = task.Result;

            Utils.Unpack(ret).Is(@"[ ""app.hoge"", [ [ 1360370224.238, { ""message"" : ""hoge"" } ] ] ]");
        }
 protected internal sealed override System.DateTimeOffset UnpackFromCore(Unpacker unpacker)
 {
     try
     {
         return(MessagePackConvert.ToDateTimeOffset(unpacker.Data.Value.AsInt64()));
     }
     catch (ArgumentException ex)
     {
         throw new SerializationException(String.Format(CultureInfo.CurrentCulture, "The unpacked value is not expected type. {0}", ex.Message), ex);
     }
     catch (InvalidOperationException ex)
     {
         throw new SerializationException(String.Format(CultureInfo.CurrentCulture, "The unpacked value is not expected type. {0}", ex.Message), ex);
     }
 }
Beispiel #22
0
 protected internal override Timestamp UnpackFromCore(Unpacker unpacker)
 {
     if (unpacker.LastReadData.IsTypeOf <MessagePackExtendedTypeObject>().GetValueOrDefault())
     {
         return(Timestamp.Decode(unpacker.LastReadData.AsMessagePackExtendedTypeObject()));
     }
     else if (this._conversion == DateTimeConversionMethod.UnixEpoc)
     {
         return(MessagePackConvert.ToDateTimeOffset(unpacker.LastReadData.DeserializeAsInt64()));
     }
     else
     {
         return(new DateTimeOffset(DateTime.FromBinary(unpacker.LastReadData.DeserializeAsInt64()), TimeSpan.Zero));
     }
 }
        public void PackLoopRefType()
        {
            var date  = MessagePackConvert.ToDateTime(1360370224238);
            var child = new Node {
                Name = "Child"
            };
            var node = new Node {
                Name = "Parent", Child = child
            };

            child.Child = node;

            var ex = AssertEx.Throws <InvalidOperationException>(() => _packer.MakePacket("test1", date, node));

            ex.Message.Is("nest counter is over the maximum. counter = 11");
        }
        protected internal sealed override DateTime UnpackFromCore(Unpacker unpacker)
        {
            DateTime time;

            try
            {
                time = MessagePackConvert.ToDateTime(unpacker.Data.Value.AsInt64());
            }
            catch (ArgumentException exception)
            {
                throw new SerializationException(string.Format(CultureInfo.CurrentCulture, "The unpacked value is not expected type. {0}", new object[] { exception.Message }), exception);
            }
            catch (InvalidOperationException exception2)
            {
                throw new SerializationException(string.Format(CultureInfo.CurrentCulture, "The unpacked value is not expected type. {0}", new object[] { exception2.Message }), exception2);
            }
            return(time);
        }
Beispiel #25
0
        protected internal override async Task PackToAsyncCore(Packer packer, Timestamp objectTree, CancellationToken cancellationToken)
        {
            if (this._conversion == DateTimeConversionMethod.Timestamp)
            {
                await packer.PackAsync(objectTree.Encode(), cancellationToken).ConfigureAwait(false);
            }
            else if (this._conversion == DateTimeConversionMethod.Native)
            {
                await packer.PackAsync(objectTree.ToDateTime().ToBinary(), cancellationToken).ConfigureAwait(false);
            }
            else
            {
#if DEBUG
                Contract.Assert(this._conversion == DateTimeConversionMethod.UnixEpoc);
#endif // DEBUG
                await packer.PackAsync(MessagePackConvert.FromDateTimeOffset(objectTree.ToDateTimeOffset()), cancellationToken).ConfigureAwait(false);
            }
        }
Beispiel #26
0
        protected internal override void PackToCore(Packer packer, Timestamp objectTree)
        {
            if (this._conversion == DateTimeConversionMethod.Timestamp)
            {
                packer.Pack(objectTree.Encode());
            }
            else if (this._conversion == DateTimeConversionMethod.Native)
            {
                packer.Pack(objectTree.ToDateTime().ToBinary());
            }
            else
            {
#if DEBUG
                Contract.Assert(this._conversion == DateTimeConversionMethod.UnixEpoc);
#endif // DEBUG
                packer.Pack(MessagePackConvert.FromDateTimeOffset(objectTree.ToDateTimeOffset()));
            }
        }
Beispiel #27
0
        protected internal override void PackToCore(Packer packer, DateTimeOffset objectTree)
        {
            if (this._conversion == DateTimeConversionMethod.Native)
            {
                packer.PackArrayHeader(2);
                packer.Pack(objectTree.DateTime.ToBinary());
                unchecked
                {
                    packer.Pack(( short )(objectTree.Offset.Hours * 60 + objectTree.Offset.Minutes));
                }
            }
            else
            {
#if DEBUG
                Contract.Assert(this._conversion == DateTimeConversionMethod.UnixEpoc);
#endif // DEBUG
                packer.Pack(MessagePackConvert.FromDateTimeOffset(objectTree));
            }
        }
        private static void TestDeserializationCore(DateTimeConversionMethod kind)
        {
            var now         = Timestamp.UtcNow;
            var dateTimeNow = now.ToDateTimeOffset();

            using (var buffer = new MemoryStream())
                using (var packer = Packer.Create(buffer, PackerCompatibilityOptions.None))
                {
                    packer.PackArrayHeader(ClassHasTimestamp.MemberCount);
                    for (var i = 0; i < ClassHasTimestamp.MemberCount; i++)
                    {
                        switch (kind)
                        {
                        case DateTimeConversionMethod.Native:
                        {
                            if (i == 2)
                            {
                                // DateTimeOffset -> [long, shourt]
                                packer.PackArrayHeader(2);
                                packer.Pack(dateTimeNow.AddSeconds(i).Ticks);
                                packer.Pack(( short )0);
                            }
                            else
                            {
                                packer.Pack(dateTimeNow.AddSeconds(i).Ticks);
                            }

                            break;
                        }

                        case DateTimeConversionMethod.UnixEpoc:
                        {
                            packer.Pack(MessagePackConvert.FromDateTimeOffset(dateTimeNow.AddSeconds(i)));
                            break;
                        }

                        case DateTimeConversionMethod.Timestamp:
                        {
                            packer.PackExtendedTypeValue((now.Add(TimeSpan.FromSeconds(i)).Encode()));
                            break;
                        }

                        default:
                        {
                            Assert.Fail("Unexpected Kind");
                            break;
                        }
                        }
                    }

                    var context = new SerializationContext();
                    context.DefaultDateTimeConversionMethod = kind;

                    var serializer = context.GetSerializer <ClassHasTimestamp>();
                    buffer.Position = 0;

                    var result = serializer.Unpack(buffer);
                    switch (kind)
                    {
                    case DateTimeConversionMethod.Native:
                    {
                        Assert.That(result.Timestamp, Is.EqualTo(new Timestamp(now.UnixEpochSecondsPart, now.NanosecondsPart / 100 * 100)));
                        Assert.That(result.DateTime, Is.EqualTo(now.ToDateTime().AddSeconds(1)));
                        Assert.That(result.DateTimeOffset, Is.EqualTo(now.ToDateTimeOffset().AddSeconds(2)));
#if (!SILVERLIGHT || WINDOWS_PHONE) && !XAMARIN && !UNITY && !UNITY
                        Assert.That(result.FileTime, Is.EqualTo(now.Add(TimeSpan.FromSeconds(3).Subtract(TimeSpan.FromTicks(now.NanosecondsPart % 100))).ToDateTime().ToWin32FileTimeUtc()));
#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY && !UNITY
                        break;
                    }

                    case DateTimeConversionMethod.UnixEpoc:
                    {
                        Assert.That(result.Timestamp, Is.EqualTo(new Timestamp(now.UnixEpochSecondsPart, now.NanosecondsPart / 1000000 * 1000000)));
                        Assert.That(result.DateTime, Is.EqualTo(now.ToDateTime().AddSeconds(1).Subtract(TimeSpan.FromTicks(now.NanosecondsPart / 100 % 10000))));
                        Assert.That(result.DateTimeOffset, Is.EqualTo(now.ToDateTimeOffset().AddSeconds(2).Subtract(TimeSpan.FromTicks(now.NanosecondsPart / 100 % 10000))));
#if (!SILVERLIGHT || WINDOWS_PHONE) && !XAMARIN && !UNITY && !UNITY
                        Assert.That(result.FileTime, Is.EqualTo(now.Add(TimeSpan.FromSeconds(3).Subtract(TimeSpan.FromTicks(now.NanosecondsPart / 100 % 10000))).ToDateTime().ToWin32FileTimeUtc()));
#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY && !UNITY
                        break;
                    }

                    case DateTimeConversionMethod.Timestamp:
                    {
                        Assert.That(result.Timestamp, Is.EqualTo(now));
                        Assert.That(result.DateTime, Is.EqualTo(now.ToDateTime().AddSeconds(1)));
                        Assert.That(result.DateTimeOffset, Is.EqualTo(now.ToDateTimeOffset().AddSeconds(2)));
#if (!SILVERLIGHT || WINDOWS_PHONE) && !XAMARIN && !UNITY && !UNITY
                        Assert.That(result.FileTime, Is.EqualTo(now.Add(TimeSpan.FromSeconds(3)).ToDateTime().ToWin32FileTimeUtc()));
#endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !XAMARIN && !UNITY && !UNITY
                        break;
                    }
                    }
                }
        }
 protected internal sealed override void PackToCore(Packer packer, System.DateTimeOffset value)
 {
     packer.Pack(MessagePackConvert.FromDateTimeOffset(value));
 }
Beispiel #30
0
 protected internal override FILETIME UnpackFromCore(Unpacker unpacker)
 {
     return(MessagePackConvert.ToDateTime(unpacker.LastReadData.AsInt64()).ToWin32FileTimeUtc());
 }