Example #1
0
        public void AnonymousTypeTest()
        {
            var p = new Person
            {
                Name      = "John",
                Addresses = new[]
                {
                    new { Street = "St." },
                    new { Street = "Ave." }
                }
            };

            var result = defaultSerializer.Serialize(p);

            defaultSerializer.ConvertToJson(result).Is(@"{""Name"":""John"",""Addresses"":[{""Street"":""St.""},{""Street"":""Ave.""}]}");

            var p2 = defaultSerializer.Deserialize <Person>(result);

            p2.Name.Is("John");
            var addresses = p2.Addresses as IList;
            var d1        = addresses[0] as IDictionary;
            var d2        = addresses[1] as IDictionary;

            (d1["Street"] as string).Is("St.");
            (d2["Street"] as string).Is("Ave.");
        }
Example #2
0
        public void FooBar()
        {
            {
                var bin = serializer.Serialize(new MyClass {
                    MyProperty1 = 100, MyProperty2 = 9, MyProperty3 = "foo", MyProperty4 = "bar"
                });
                var json = serializer.ConvertToJson(bin);
                json.Is("[1000,9,\"foofoo\",\"bar\"]");

                var r2 = serializer.Deserialize <MyClass>(bin);
                r2.MyProperty1.Is(10000);
                r2.MyProperty2.Is(9);
                r2.MyProperty3.Is("foofoofoofoo");
                r2.MyProperty4.Is("bar");
            }
            {
                var bin = serializer.Serialize(new MyStruct {
                    MyProperty1 = 100, MyProperty2 = 9, MyProperty3 = "foo", MyProperty4 = "bar"
                });
                var json = serializer.ConvertToJson(bin);
                json.Is("[1000,9,\"foofoo\",\"bar\"]");

                var r2 = serializer.Deserialize <MyStruct>(bin);
                r2.MyProperty1.Is(10000);
                r2.MyProperty2.Is(9);
                r2.MyProperty3.Is("foofoofoofoo");
                r2.MyProperty4.Is("bar");
            }
        }
        public void EnumTest <T>(T x, T?y, string xName, string yName)
            where T : struct
        {
            var bin = serializer.Serialize(x, DynamicEnumAsStringResolver.Instance);

            serializer.ConvertToJson(bin).Trim('\"').Is(xName);
            serializer.Deserialize <T>(bin, DynamicEnumAsStringResolver.Instance).Is(x);

            var bin2 = serializer.Serialize(y, DynamicEnumAsStringResolver.Instance);

            serializer.ConvertToJson(bin2).Trim('\"').Is(yName);
            serializer.Deserialize <T?>(bin2, DynamicEnumAsStringResolver.Instance).Is(y);
        }
Example #4
0
        public void SerializeOrder()
        {
            var mc = new MyClass {
                MyProperty1 = 100, MyProperty2 = "foobar"
            };

            var bin = serializer.Serialize(mc);
            var mc2 = serializer.Deserialize <MyClass>(bin);

            mc.MyProperty1.Is(mc2.MyProperty1);
            mc.MyProperty2.Is(mc2.MyProperty2);

            serializer.ConvertToJson(bin).Is(@"[100,""foobar""]");
        }
Example #5
0
        public void Versioning()
        {
            var v1 = new Version1
            {
                MyProperty1 = 100,
                MyProperty2 = 200,
                MyProperty3 = 300
            };

            var v2 = new Version2
            {
                MyProperty1 = 100,
                MyProperty2 = 200,
                MyProperty3 = 300,
                MyProperty5 = 500,
            };

            var v0 = new Version0
            {
                MyProperty1 = 100,
            };

            var v1Bytes = serializer.Serialize(v1);
            var v2Bytes = serializer.Serialize(v2);
            var v0Bytes = serializer.Serialize(v0);

            var a = serializer.ConvertToJson(v1Bytes);
            var b = serializer.ConvertToJson(v2Bytes);
            var c = serializer.ConvertToJson(v0Bytes);

            serializer.Deserialize <Version1>(v1Bytes).IsNotStructuralEqual(v1Bytes);
            serializer.Deserialize <Version2>(v2Bytes).IsNotStructuralEqual(v2Bytes);
            serializer.Deserialize <Version0>(v0Bytes).IsNotStructuralEqual(v0Bytes);

            // smaller than schema
            var v2_ = serializer.Deserialize <Version2>(v1Bytes);

            v2_.MyProperty1.Is(v1.MyProperty1);
            v2_.MyProperty2.Is(v1.MyProperty2);
            v2_.MyProperty3.Is(v1.MyProperty3);
            v2_.MyProperty5.Is(0);

            // larger than schema

            var v0_ = serializer.Deserialize <Version0>(v1Bytes);

            v0_.MyProperty1.Is(v1.MyProperty1);
        }
        public void AnonymousTypeTest()
        {
            var p = new Person
            {
                Name      = "John",
                Addresses = new[]
                {
                    new { Street = "St." },
                    new { Street = "Ave." },
                },
            };

            var result = MessagePackSerializer.Serialize(p, TypelessContractlessStandardResolver.Options);

            MessagePackSerializer.ConvertToJson(result, TypelessContractlessStandardResolver.Options).Is(@"{""Name"":""John"",""Addresses"":[{""Street"":""St.""},{""Street"":""Ave.""}]}");

            Person p2 = MessagePackSerializer.Deserialize <Person>(result, TypelessContractlessStandardResolver.Options);

            p2.Name.Is("John");
            var addresses = p2.Addresses as IList;
            var d1        = addresses[0] as IDictionary;
            var d2        = addresses[1] as IDictionary;

            (d1["Street"] as string).Is("St.");
            (d2["Street"] as string).Is("Ave.");
        }
        public void PreservingTimezoneInTypelessCollectionsTest()
        {
            var arr = new Dictionary <object, object>()
            {
                { (byte)1, "a" },
                { (byte)2, new object[] { "level2", new object[] { "level3", new Person()
                                                                   {
                                                                       Name = "Peter", Addresses = new object[] { new Address()
                                                                                                                  {
                                                                                                                      Street = "St."
                                                                                                                  }, new DateTime(2017, 6, 26, 14, 58, 0) }
                                                                   } } } },
            };
            var result = MessagePackSerializer.Serialize(arr, TypelessContractlessStandardResolver.Options);

            Dictionary <object, object> deser = MessagePackSerializer.Deserialize <Dictionary <object, object> >(result, TypelessContractlessStandardResolver.Options);

            deser.IsStructuralEqual(arr);

#if NETFRAMEWORK
            MessagePackSerializer.ConvertToJson(result, TypelessContractlessStandardResolver.Options).Is(@"{""1"":""a"",""2"":[""System.Object[], mscorlib"",""level2"",[""System.Object[], mscorlib"",""level3"",{""$type"":""MessagePack.Tests.TypelessContractlessStandardResolverTest+Person, MessagePack.Tests"",""Name"":""Peter"",""Addresses"":[{""$type"":""MessagePack.Tests.TypelessContractlessStandardResolverTest+Address, MessagePack.Tests"",""Street"":""St.""},{""$type"":""System.DateTime, mscorlib"",636340858800000000}]}]]}");
#else
            MessagePackSerializer.ConvertToJson(result, TypelessContractlessStandardResolver.Options).Is(@"{""1"":""a"",""2"":[""System.Object[], System.Private.CoreLib"",""level2"",[""System.Object[], System.Private.CoreLib"",""level3"",{""$type"":""MessagePack.Tests.TypelessContractlessStandardResolverTest+Person, MessagePack.Tests"",""Name"":""Peter"",""Addresses"":[{""$type"":""MessagePack.Tests.TypelessContractlessStandardResolverTest+Address, MessagePack.Tests"",""Street"":""St.""},{""$type"":""System.DateTime, System.Private.CoreLib"",636340858800000000}]}]]}");
#endif
        }
        public static T Convert <T>(T value)
        {
            var data = MessagePackSerializer.Serialize(value);

            Console.WriteLine(MessagePackSerializer.ConvertToJson(data));
            return(MessagePackSerializer.Deserialize <T>(data));
        }
        public static T TypelessConvert <T>(T value)
        {
            var data = MessagePackSerializer.Typeless.Serialize(value);

            Console.WriteLine(MessagePackSerializer.ConvertToJson(data));
            return((T)MessagePackSerializer.Typeless.Deserialize(data));
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            var headers     = string.Join("&", req.Headers.Select(x => x.Key + "=" + x.Value));
            var queryString = string.Join("&", req.Query.Select(x => x.Key + "=" + x.Value));
            var requestBody = "";

            using (var ms = new MemoryStream())
            {
                await req.Body.CopyToAsync(ms);

                ms.Position = 0;
                var raw = ms.ToArray();
                requestBody = MessagePackSerializer.ConvertToJson(raw);
            }

            var jo = new JObject();

            jo["Headers"]     = headers;
            jo["QueryString"] = queryString;
            jo["Body"]        = requestBody;

            return(new OkObjectResult(jo.ToString()));
        }
Example #11
0
        public void EmptyAnonymousType()
        {
            var testData = new { };
            var data     = MessagePackSerializer.Serialize(testData, ContractlessStandardResolver.Options);

            MessagePackSerializer.ConvertToJson(data).Is(@"{}");
        }
        public void ObjectRuntimeTypeTest()
        {
            var p = new Person
            {
                Name      = "John",
                Addresses = new object[]
                {
                    new object(),
                    new Address {
                        Street = "Ave."
                    },
                },
            };

            var result = MessagePackSerializer.Serialize(p, TypelessContractlessStandardResolver.Options);

            Person p2 = MessagePackSerializer.Deserialize <Person>(result, TypelessContractlessStandardResolver.Options);

            p.IsStructuralEqual(p2);

#if NETFRAMEWORK
            MessagePackSerializer.ConvertToJson(result, TypelessContractlessStandardResolver.Options).Is(@"{""Name"":""John"",""Addresses"":[{""$type"":""""System.Object, mscorlib""},{""$type"":""MessagePack.Tests.TypelessContractlessStandardResolverTest+Address, MessagePack.Tests"",""Street"":""Ave.""}]}");
#else
            MessagePackSerializer.ConvertToJson(result, TypelessContractlessStandardResolver.Options).Is(@"{""Name"":""John"",""Addresses"":[{""$type"":""""System.Object, System.Private.CoreLib""},{""$type"":""MessagePack.Tests.TypelessContractlessStandardResolverTest+Address, MessagePack.Tests"",""Street"":""Ave.""}]}");
#endif
        }
Example #13
0
        public bool TryTransform(HttpRequestRecord record, ReadOnlySpan <byte> body, StringValues contentTypeHeaderValues, out BodyDataTransformResult result)
        {
            var json = MessagePackSerializer.ConvertToJson(body.ToArray(), MessagePack.Resolvers.ContractlessStandardResolver.Options);

            result = new BodyDataTransformResult(Encoding.UTF8.GetBytes(json), contentTypeHeaderValues.ToString(), "application/json");
            return(true);
        }
Example #14
0
        public async Task GetState([QueryField] bool?json, string tokenArg)
        {
            (ChatId, UserId)? token = ApiMessenger.ParseToken(tokenArg);
            if (token == null)
            {
                throw HttpException.Forbidden();
            }

            var(_, user) = ((ChatId, UserId))token;

            using var context = new UserContext(user);
            var publicUser = new PublicUser(context.User);
            var bytes      = MessagePackSerializer.Serialize(publicUser);

            if (json ?? false)
            {
                var response = MessagePackSerializer.ConvertToJson(bytes);
                HttpContext.Response.ContentType = "application/json";
                bytes = Encoding.UTF8.GetBytes(response);
            }
            else
            {
                HttpContext.Response.ContentType = "application/x-msgpack";
            }
            using (var stream = HttpContext.OpenResponseStream())
            {
                await stream.WriteAsync(bytes, 0, bytes.Length);
            }
        }
        public void SimpleTest()
        {
            var p = new Person
            {
                Name      = "John",
                Addresses = new[]
                {
                    new Address {
                        Street = "St."
                    },
                    new Address {
                        Street = "Ave."
                    }
                }
            };

            var result = serializer.Serialize(p, MessagePack.Resolvers.ContractlessStandardResolver.Instance);

            serializer.ConvertToJson(result).Is(@"{""Name"":""John"",""Addresses"":[{""Street"":""St.""},{""Street"":""Ave.""}]}");

            var p2 = serializer.Deserialize <Person>(result, MessagePack.Resolvers.ContractlessStandardResolver.Instance);

            p2.Name.Is("John");
            var addresses = p2.Addresses as IList;
            var d1        = addresses[0] as IDictionary;
            var d2        = addresses[1] as IDictionary;

            (d1["Street"] as string).Is("St.");
            (d2["Street"] as string).Is("Ave.");
        }
Example #16
0
        public void SimpleTest()
        {
            var p = new Person
            {
                Name      = "John",
                Addresses = new[]
                {
                    new Address {
                        Street = "St."
                    },
                    new Address {
                        Street = "Ave."
                    },
                },
            };

            var result = MessagePackSerializer.Serialize(p, Resolvers.ContractlessStandardResolver.Options);

            MessagePackSerializer.ConvertToJson(result).Is(@"{""Name"":""John"",""Addresses"":[{""Street"":""St.""},{""Street"":""Ave.""}]}");

            Person p2 = MessagePackSerializer.Deserialize <Person>(result, Resolvers.ContractlessStandardResolver.Options);

            p2.Name.Is("John");
            var addresses = (IList)p2.Addresses;
            var d1        = (IDictionary)addresses[0];
            var d2        = (IDictionary)addresses[1];

            ((string)d1["Street"]).Is("St.");
            ((string)d2["Street"]).Is("Ave.");
        }
Example #17
0
        public void Serialize_WithVariousAttributes()
        {
            var mc = new ClassWithPublicMembersWithoutAttributes
            {
                AttributedProperty   = 1,
                UnattributedProperty = 2,
                IgnoredProperty      = 3,
                AttributedField      = 4,
                UnattributedField    = 5,
                IgnoredField         = 6,
            };

            var bin = MessagePackSerializer.Serialize(mc);
            ClassWithPublicMembersWithoutAttributes mc2 = MessagePackSerializer.Deserialize <ClassWithPublicMembersWithoutAttributes>(bin);

            mc2.AttributedProperty.Is(mc.AttributedProperty);
            mc2.AttributedField.Is(mc.AttributedField);

            mc2.UnattributedProperty.Is(0);
            mc2.IgnoredProperty.Is(0);
            mc2.UnattributedField.Is(0);
            mc2.IgnoredField.Is(0);

            MessagePackSerializer.ConvertToJson(bin).Is(@"{""AttributedProperty"":1,""AttributedField"":4}");
        }
Example #18
0
        private void CheckConnection()
        {
            client = new TCP();

            Debug.WriteLine("Thread is running");

            while (!DroneStatus.IsConnected)
            {
                Debug.WriteLine("Checking connection");

                try
                {
                    byte[] response = client.Send(new GetServerVersion().GetCommand(), 32);
                    Debug.WriteLine(MessagePackSerializer.ConvertToJson(response));

                    if (response.Length > 0)
                    {
                        Debug.WriteLine("We're connected!");
                        DroneStatus.IsConnected = true;


                        mainPage.UpdateButton("Connected!");

                        client.Close();
                    }
                } catch (Exception e)
                {
                    Debug.WriteLine("Error: " + e.Message);
                }

                // Check connection every 3 seconds
                Thread.Sleep(3000);
            }
        }
Example #19
0
        public void DynamicObject()
        {
            var testData = new object[]
            {
                new DynamicObjectFallbackTestContainer
                {
                    MyProperty = 100,
                    MoreObject = new string[] { "a", "b", "c" },
                },

                new DynamicObjectFallbackTestContainer
                {
                    MyProperty = 300,
                    MoreObject = new SharedData.SimpleStringKeyData
                    {
                        Prop1 = 10,
                        Prop2 = SharedData.ByteEnum.C,
                        Prop3 = 99999,
                    },
                },
            };

            var data1 = MessagePackSerializer.Serialize(testData);

            var json = MessagePackSerializer.ConvertToJson(data1);

            json.Is(@"[[100,[""a"",""b"",""c""]],[300,{""Prop1"":10,""Prop2"":2,""Prop3"":99999}]]");
        }
    public void UpdateOutput(SignaledPeer.Offer offer)
    {
        var offerPacket = MessagePackSerializer.Serialize(offer);

        OutputField.Text = MessagePackSerializer.ConvertToJson(offerPacket);
        Log.Information("Updated output; {UID}, {L}", offer.assignedUID, OutputField.Text.Length);
    }
Example #21
0
        static bool DecryptMaster(FileInfo inputFile, byte[] decrypted)
        {
            var typeName   = inputFile.Name.Replace(".msgpack.enc", "");
            var targetType = MasterTypes.GetDeserializeType(typeName);

            var options = MessagePackSerializerOptions.Standard.WithCompression(MessagePackCompression.Lz4Block);

            if (targetType == null)
            {
                Console.WriteLine($"Not supported master {typeName}.");
                File.WriteAllText(
                    inputFile.FullName.Replace(".msgpack.enc", ".json"),
                    MessagePackSerializer.ConvertToJson(decrypted, options)
                    );
            }
            else
            {
                var result = MessagePackSerializer.Deserialize(targetType, decrypted, options);
                File.WriteAllText(
                    inputFile.FullName.Replace(".msgpack.enc", ".json"),
                    DumpToJson(result)
                    );
            }

            return(true);
        }
Example #22
0
    public void SerializationOfSystemType()
    {
        Type type = typeof(string);

        byte[] msgpack = MessagePackSerializer.Typeless.Serialize(type);
        this.logger.WriteLine(MessagePackSerializer.ConvertToJson(msgpack));
        Assert.Equal(type, MessagePackSerializer.Typeless.Deserialize(msgpack));
    }
        public void SerializeAndConvertToJson()
        {
            var testData = new { Hoge = 100, Huga = true, Yaki = new { Rec = 1, T = 10 }, Nano = "nanoanno" };

            var data = serializer.Serialize(testData, ContractlessStandardResolver.Instance);

            serializer.ConvertToJson(data).Is(@"{""Hoge"":100,""Huga"":true,""Yaki"":{""Rec"":1,""T"":10},""Nano"":""nanoanno""}");
        }
Example #24
0
        public void FloatJson()
        {
            var f    = 3.33f;
            var xs   = MessagePackSerializer.Serialize(f);
            var json = MessagePackSerializer.ConvertToJson(xs);

            json.Is("3.33");
        }
Example #25
0
        public void DateTimeJson()
        {
            var now  = new DateTime(1999, 12, 19, 11, 19, 19, DateTimeKind.Utc);
            var bin  = MessagePackSerializer.Serialize(now);
            var json = MessagePackSerializer.ConvertToJson(bin);

            json.Is(@"""1999-12-19T11:19:19.0000000Z""");
        }
Example #26
0
        private string JsonConvert(string json, MessagePackSerializerOptions options)
        {
            var sequence       = new Sequence <byte>();
            var sequenceWriter = new MessagePackWriter(sequence);

            MessagePackSerializer.ConvertFromJson(json, ref sequenceWriter, options);
            sequenceWriter.Flush();
            return(MessagePackSerializer.ConvertToJson(sequence.AsReadOnlySequence, options));
        }
Example #27
0
        public void ItShouldConvertToJson()
        {
            string expected = "10.5";
            var    a        = CreateDataType();
            var    data     = MessagePackSerializer.Serialize(a);
            var    actual   = MessagePackSerializer.ConvertToJson(data);

            Assert.AreEqual(expected, actual);
        }
Example #28
0
        private static string SerializeAndDeserialize <T>(T input)
        {
            var bytes        = MessagePackSerializer.Serialize(input);
            var deserialized = MessagePackSerializer.Deserialize <T>(bytes);

            var json = MessagePackSerializer.ConvertToJson(bytes);

            return(json);
        }
        string JsonConvert(string json, MessagePackSerializer serializer)
        {
            var sequence       = new Sequence <byte>();
            var sequenceWriter = new MessagePackWriter(sequence);

            serializer.ConvertFromJson(json, ref sequenceWriter);
            sequenceWriter.Flush();
            return(serializer.ConvertToJson(sequence.AsReadOnlySequence));
        }
        private static void AssertConvertToJsonRecursionCheckThrows(ReadOnlySequence <byte> sequence, MessagePackSerializerOptions options)
        {
            var ex = Assert.Throws <MessagePackSerializationException>(() =>
            {
                var reader = new MessagePackReader(sequence);
                MessagePackSerializer.ConvertToJson(ref reader, new StringWriter(), options);
            });

            Assert.IsType <InsufficientExecutionStackException>(ex.InnerException);
        }