コード例 #1
0
        public async Task WriteAsyncEnumerableOfAsyncEnumerables <TElement>(IEnumerable <TElement> source, int delayInterval, int bufferSize)
        {
            if (StreamingSerializer?.IsAsyncSerializer != true)
            {
                return;
            }

            JsonSerializerOptions options = new JsonSerializerOptions
            {
                DefaultBufferSize = bufferSize
            };

            const int OuterEnumerableCount = 5;
            string    expectedJson         = JsonSerializer.Serialize(Enumerable.Repeat(source, OuterEnumerableCount));

            var innerAsyncEnumerable = new MockedAsyncEnumerable <TElement>(source, delayInterval);
            var outerAsyncEnumerable =
                new MockedAsyncEnumerable <IAsyncEnumerable <TElement> >(
                    Enumerable.Repeat(innerAsyncEnumerable, OuterEnumerableCount), delayInterval);

            using var stream = new Utf8MemoryStream();
            await StreamingSerializer.SerializeWrapper(stream, outerAsyncEnumerable, options);

            JsonTestHelper.AssertJsonEqual(expectedJson, stream.AsString());
            Assert.Equal(1, outerAsyncEnumerable.TotalCreatedEnumerators);
            Assert.Equal(1, outerAsyncEnumerable.TotalDisposedEnumerators);
            Assert.Equal(OuterEnumerableCount, innerAsyncEnumerable.TotalCreatedEnumerators);
            Assert.Equal(OuterEnumerableCount, innerAsyncEnumerable.TotalDisposedEnumerators);
        }
コード例 #2
0
        private List <TranscoderProfile> ParseAndMergeTranscoders(XElement oldFile)
        {
            // load all the transcoders from the old file
            var list = new List <TranscoderProfile>();

            foreach (var node in oldFile.Elements("transcoders").Elements("transcoder"))
            {
                var profile = new TranscoderProfile()
                {
                    Name        = node.Element("name").Value,
                    Description = node.Element("description").Value,
                    Bandwidth   = Int32.Parse(node.Element("bandwidth").Value),
                    Targets     = new List <string>()
                    {
                        node.Element("target").Value
                    },
                    Transport       = node.Element("transport").Value,
                    MaxOutputHeight = node.Element("maxOutputHeight") != null?Int32.Parse(node.Element("maxOutputHeight").Value) : 0,
                                          MaxOutputWidth                                           = node.Element("maxOutputWidth") != null?Int32.Parse(node.Element("maxOutputWidth").Value) : 0,
                                                                                    MIME           = node.Element("mime").Value,
                                                                                    HasVideoStream = node.Element("videoStream").Value == "true",
                                                                                    Transcoder     = (string)node.Element("transcoderConfiguration").Attribute("implementation")
                };

                foreach (var configNode in node.Elements("transcoderConfiguration").Descendants())
                {
                    profile.TranscoderParameters[configNode.Name.LocalName] = configNode.Value;
                }

                list.Add(profile);
            }

            // parse the new default file
            var       defaultSerializer = new StreamingSerializer();
            Streaming defaultModel;

            using (var file = File.OpenRead(DefaultPath))
            {
                defaultModel = (Streaming)defaultSerializer.Deserialize(file);
            }

            // merge the lists
            var finalList = defaultModel.Transcoders;

            foreach (var oldProfile in list)
            {
                if (!finalList.Any(x => x.Name == oldProfile.Name))
                {
                    finalList.Add(oldProfile);
                }
            }

            return(finalList);
        }
コード例 #3
0
        public async Task ReadSimpleObjectWithTrailingTriviaAsync()
        {
            if (StreamingSerializer is null)
            {
                return;
            }

            async Task RunTestAsync <T>(string testData)
            {
                byte[] data = Encoding.UTF8.GetBytes(testData + " /* Multi\r\nLine Comment */\t");
                using (MemoryStream stream = new MemoryStream(data))
                {
                    JsonSerializerOptions options = new JsonSerializerOptions
                    {
                        DefaultBufferSize   = 1,
                        ReadCommentHandling = JsonCommentHandling.Skip,
                    };

                    var obj = await StreamingSerializer.DeserializeWrapper <T>(stream, options);

                    ((ITestClass)obj).Verify();
                }
            }

            // TODO: should be refactored to a theory
            // Array size is the count of the following tests.
            Task[] tasks = new Task[14];

            // Simple models can be deserialized.
            tasks[0] = Task.Run(async() => await RunTestAsync <Parameterized_IndexViewModel_Immutable>(Parameterized_IndexViewModel_Immutable.s_json));
            // Complex models can be deserialized.
            tasks[1] = Task.Run(async() => await RunTestAsync <ObjWCtorMixedParams>(ObjWCtorMixedParams.s_json));
            tasks[2] = Task.Run(async() => await RunTestAsync <Parameterized_Class_With_ComplexTuple>(Parameterized_Class_With_ComplexTuple.s_json));
            // JSON that doesn't bind to ctor args are matched with properties or ignored (as appropriate).
            tasks[3] = Task.Run(async() => await RunTestAsync <Person_Class>(Person_Class.s_json));
            tasks[4] = Task.Run(async() => await RunTestAsync <Person_Struct>(Person_Struct.s_json));
            // JSON that doesn't bind to ctor args or properties are sent to ext data if avaiable.
            tasks[5] = Task.Run(async() => await RunTestAsync <Parameterized_Person>(Parameterized_Person.s_json));
            tasks[6] = Task.Run(async() => await RunTestAsync <Parameterized_Person_ObjExtData>(Parameterized_Person_ObjExtData.s_json));
            // Up to 64 ctor args are supported.
            tasks[7] = Task.Run(async() => await RunTestAsync <Class_With_Ctor_With_64_Params>(Encoding.UTF8.GetString(Class_With_Ctor_With_64_Params.Data)));
            // Arg8deserialization honors attributes on matching property.
            tasks[8]  = Task.Run(async() => await RunTestAsync <Point_MembersHave_JsonPropertyName>(Point_MembersHave_JsonPropertyName.s_json));
            tasks[9]  = Task.Run(async() => await RunTestAsync <Point_MembersHave_JsonConverter>(Point_MembersHave_JsonConverter.s_json));
            tasks[10] = Task.Run(async() => await RunTestAsync <Point_MembersHave_JsonIgnore>(Point_MembersHave_JsonIgnore.s_json));
            // Complex JSON as last argument works
            tasks[11] = Task.Run(async() => await RunTestAsync <Point_With_Array>(Point_With_Array.s_json));
            tasks[12] = Task.Run(async() => await RunTestAsync <Point_With_Dictionary>(Point_With_Dictionary.s_json));
            tasks[13] = Task.Run(async() => await RunTestAsync <Point_With_Object>(Point_With_Object.s_json));

            await Task.WhenAll(tasks);
        }
コード例 #4
0
        public async Task WriteAsyncEnumerable_ElementSerializationThrows_ShouldDisposeEnumerator()
        {
            if (StreamingSerializer?.IsAsyncSerializer != true)
            {
                return;
            }

            using var stream = new Utf8MemoryStream();
            var asyncEnumerable = new MockedAsyncEnumerable <IEnumerable <int> >(Enumerable.Repeat(ThrowingEnumerable(), 2));

            await Assert.ThrowsAsync <DivideByZeroException>(async() => await StreamingSerializer.SerializeWrapper(stream, new { Data = asyncEnumerable }));

            Assert.Equal(1, asyncEnumerable.TotalCreatedEnumerators);
            Assert.Equal(1, asyncEnumerable.TotalDisposedEnumerators);
コード例 #5
0
        public async Task PreserveReferenceOfTypeObjectAsync()
        {
            if (StreamingSerializer is null)
            {
                return;
            }

            var root = new ClassWithObjectProperty();

            root.Child   = new ClassWithObjectProperty();
            root.Sibling = root.Child;

            Assert.Same(root.Child, root.Sibling);

            string json = await StreamingSerializer.SerializeWrapper(root, s_serializerOptionsPreserve);

            ClassWithObjectProperty rootCopy = await StreamingSerializer.DeserializeWrapper <ClassWithObjectProperty>(json, s_serializerOptionsPreserve);

            Assert.Same(rootCopy.Child, rootCopy.Sibling);
        }
コード例 #6
0
        public async Task WriteRootLevelAsyncEnumerable <TElement>(IEnumerable <TElement> source, int delayInterval, int bufferSize)
        {
            if (StreamingSerializer?.IsAsyncSerializer != true)
            {
                return;
            }

            JsonSerializerOptions options = new JsonSerializerOptions
            {
                DefaultBufferSize = bufferSize
            };

            string expectedJson = JsonSerializer.Serialize(source);

            using var stream = new Utf8MemoryStream();
            var asyncEnumerable = new MockedAsyncEnumerable <TElement>(source, delayInterval);
            await StreamingSerializer.SerializeWrapper(stream, asyncEnumerable, options);

            JsonTestHelper.AssertJsonEqual(expectedJson, stream.AsString());
            Assert.Equal(1, asyncEnumerable.TotalCreatedEnumerators);
            Assert.Equal(1, asyncEnumerable.TotalDisposedEnumerators);
        }
コード例 #7
0
        public async Task WriteSequentialNestedAsyncEnumerables <TElement>(IEnumerable <TElement> source, int delayInterval, int bufferSize)
        {
            if (StreamingSerializer?.IsAsyncSerializer != true)
            {
                return;
            }

            JsonSerializerOptions options = new JsonSerializerOptions
            {
                DefaultBufferSize = bufferSize
            };

            string expectedJson = JsonSerializer.Serialize(new { Data1 = source, Data2 = source });

            using var stream = new Utf8MemoryStream();
            var asyncEnumerable = new MockedAsyncEnumerable <TElement>(source, delayInterval);
            await StreamingSerializer.SerializeWrapper(stream, new AsyncEnumerableDtoWithTwoProperties <TElement> {
                Data1 = asyncEnumerable, Data2 = asyncEnumerable
            }, options);

            JsonTestHelper.AssertJsonEqual(expectedJson, stream.AsString());
            Assert.Equal(2, asyncEnumerable.TotalCreatedEnumerators);
            Assert.Equal(2, asyncEnumerable.TotalDisposedEnumerators);
        }
コード例 #8
0
        public async Task Cannot_DeserializeAsync_ObjectWith_Ctor_With_65_Params()
        {
            if (StreamingSerializer is null)
            {
                return;
            }

            async Task RunTestAsync <T>()
            {
                StringBuilder sb = new StringBuilder();

                sb.Append("{");
                for (int i = 0; i < 64; i++)
                {
                    sb.Append($@"""Int{i}"":{i},");
                }
                sb.Append($@"""Int64"":64");
                sb.Append("}");

                string input = sb.ToString();

                using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(input)))
                {
                    JsonSerializerOptions options = new JsonSerializerOptions
                    {
                        DefaultBufferSize = 1
                    };

                    await Assert.ThrowsAsync <NotSupportedException>(async() => await StreamingSerializer.DeserializeWrapper <T>(stream, options));
                }

                using (MemoryStream stream = new MemoryStream("{}" u8.ToArray()))
                {
                    JsonSerializerOptions options = new JsonSerializerOptions
                    {
                        DefaultBufferSize = 1
                    };

                    await Assert.ThrowsAsync <NotSupportedException>(async() => await StreamingSerializer.DeserializeWrapper <T>(stream, options));
                }
            }

            Task[] tasks = new Task[2];

            tasks[0] = Task.Run(async() => await RunTestAsync <Class_With_Ctor_With_65_Params>());
            tasks[1] = Task.Run(async() => await RunTestAsync <Struct_With_Ctor_With_65_Params>());

            await Task.WhenAll(tasks);
        }