public async Task XmlDataContractSerializerFormatterReadsSimpleTypes()
        {
            // Arrange
            var expectedInt = 10;
            var expectedString = "TestString";

            var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                                "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" +
                                "<sampleString>" + expectedString + "</sampleString></TestLevelOne>";

            var formatter = new XmlDataContractSerializerInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes(input);
            var context = GetInputFormatterContext(contentBytes, typeof(TestLevelOne));

            // Act
            await formatter.ReadAsync(context);

            // Assert
            Assert.NotNull(context.Model);
            Assert.IsType<TestLevelOne>(context.Model);

            var model = context.Model as TestLevelOne;
            Assert.Equal(expectedInt, model.SampleInt);
            Assert.Equal(expectedString, model.sampleString);
        }
Exemplo n.º 2
0
        public async Task XmlDataContractSerializerFormatterIgnoresBOMCharacters()
        {
            // Arrange
            var sampleString      = "Test";
            var sampleStringBytes = Encoding.UTF8.GetBytes(sampleString);
            var inputStart        = Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + Environment.NewLine +
                                                           "<TestLevelTwo><SampleString>" + sampleString);

            byte[] bom           = { 0xef, 0xbb, 0xbf };
            var    inputEnd      = Encoding.UTF8.GetBytes("</SampleString></TestLevelTwo>");
            var    expectedBytes = new byte[sampleString.Length + bom.Length];

            var contentBytes = new byte[inputStart.Length + bom.Length + inputEnd.Length];

            Buffer.BlockCopy(inputStart, 0, contentBytes, 0, inputStart.Length);
            Buffer.BlockCopy(bom, 0, contentBytes, inputStart.Length, bom.Length);
            Buffer.BlockCopy(inputEnd, 0, contentBytes, inputStart.Length + bom.Length, inputEnd.Length);

            var formatter = new XmlDataContractSerializerInputFormatter();
            var context   = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo));

            // Act
            await formatter.ReadAsync(context);

            // Assert
            Assert.NotNull(context.Model);
            var model = context.Model as TestLevelTwo;

            Buffer.BlockCopy(sampleStringBytes, 0, expectedBytes, 0, sampleStringBytes.Length);
            Buffer.BlockCopy(bom, 0, expectedBytes, sampleStringBytes.Length, bom.Length);
            Assert.Equal(expectedBytes, Encoding.UTF8.GetBytes(model.SampleString));
        }
Exemplo n.º 3
0
        public async Task XmlDataContractSerializerFormatterReadsSimpleTypes()
        {
            // Arrange
            var expectedInt    = 10;
            var expectedString = "TestString";

            var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                        "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" +
                        "<sampleString>" + expectedString + "</sampleString></TestLevelOne>";

            var formatter    = new XmlDataContractSerializerInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes(input);
            var context      = GetInputFormatterContext(contentBytes, typeof(TestLevelOne));

            // Act
            await formatter.ReadAsync(context);

            // Assert
            Assert.NotNull(context.Model);
            Assert.IsType <TestLevelOne>(context.Model);

            var model = context.Model as TestLevelOne;

            Assert.Equal(expectedInt, model.SampleInt);
            Assert.Equal(expectedString, model.sampleString);
        }
Exemplo n.º 4
0
        public async Task VerifyStreamIsOpenAfterRead()
        {
            // Arrange
            var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                        "<DummyClass><SampleInt>10</SampleInt></DummyClass>";
            var formatter    = new XmlDataContractSerializerInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes(input);
            var context      = GetInputFormatterContext(contentBytes, typeof(DummyClass));

            // Act
            await formatter.ReadAsync(context);

            // Assert
            Assert.NotNull(context.Model);
            Assert.True(context.HttpContext.Request.Body.CanRead);
        }
Exemplo n.º 5
0
        public async Task XmlDataContractSerializerFormatterThrowsOnInvalidCharacters()
        {
            // Arrange
            var inpStart = Encodings.UTF16EncodingLittleEndian.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                                                                        "<DummyClass><SampleInt>");

            byte[] inp    = { 192, 193 };
            var    inpEnd = Encodings.UTF16EncodingLittleEndian.GetBytes("</SampleInt></DummyClass>");

            var contentBytes = new byte[inpStart.Length + inp.Length + inpEnd.Length];

            Buffer.BlockCopy(inpStart, 0, contentBytes, 0, inpStart.Length);
            Buffer.BlockCopy(inp, 0, contentBytes, inpStart.Length, inp.Length);
            Buffer.BlockCopy(inpEnd, 0, contentBytes, inpStart.Length + inp.Length, inpEnd.Length);

            var formatter = new XmlDataContractSerializerInputFormatter();
            var context   = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo));

            // Act
            await Assert.ThrowsAsync(typeof(XmlException), async() => await formatter.ReadAsync(context));
        }
Exemplo n.º 6
0
        public async Task XmlDataContractSerializerFormatterReadsWhenMaxDepthIsModified()
        {
            // Arrange
            var expectedInt = 10;

            var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                        "<DummyClass><SampleInt>" + expectedInt + "</SampleInt></DummyClass>";
            var formatter = new XmlDataContractSerializerInputFormatter();

            formatter.MaxDepth = 10;
            var contentBytes = Encoding.UTF8.GetBytes(input);
            var context      = GetInputFormatterContext(contentBytes, typeof(DummyClass));


            // Act
            await formatter.ReadAsync(context);

            // Assert
            Assert.NotNull(context.Model);
            Assert.IsType <DummyClass>(context.Model);
            var model = context.Model as DummyClass;

            Assert.Equal(expectedInt, model.SampleInt);
        }
        public async Task ReadAsync_AcceptsUTF16Characters()
        {
            // Arrange
            var expectedInt = 10;
            var expectedString = "TestString";

            var input = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>" +
                                "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" +
                                "<sampleString>" + expectedString + "</sampleString></TestLevelOne>";

            var formatter = new XmlDataContractSerializerInputFormatter();
            var contentBytes = Encoding.Unicode.GetBytes(input);

            var modelState = new ModelStateDictionary();
            var httpContext = GetHttpContext(contentBytes, contentType: "application/xml; charset=utf-16");

            var context = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: modelState,
                modelType: typeof(TestLevelOne));

            // Act
            var result = await formatter.ReadAsync(context);

            // Assert
            Assert.NotNull(result);
            Assert.False(result.HasError);
            var model = Assert.IsType<TestLevelOne>(result.Model);

            Assert.Equal(expectedInt, model.SampleInt);
            Assert.Equal(expectedString, model.sampleString);
        }
        public async Task ReadAsync_IgnoresBOMCharacters()
        {
            // Arrange
            var sampleString = "Test";
            var sampleStringBytes = Encoding.UTF8.GetBytes(sampleString);
            var inputStart = Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + Environment.NewLine +
                "<TestLevelTwo><SampleString>" + sampleString);
            byte[] bom = { 0xef, 0xbb, 0xbf };
            var inputEnd = Encoding.UTF8.GetBytes("</SampleString></TestLevelTwo>");
            var expectedBytes = new byte[sampleString.Length + bom.Length];

            var contentBytes = new byte[inputStart.Length + bom.Length + inputEnd.Length];
            Buffer.BlockCopy(inputStart, 0, contentBytes, 0, inputStart.Length);
            Buffer.BlockCopy(bom, 0, contentBytes, inputStart.Length, bom.Length);
            Buffer.BlockCopy(inputEnd, 0, contentBytes, inputStart.Length + bom.Length, inputEnd.Length);

            var formatter = new XmlDataContractSerializerInputFormatter();
            var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo));

            // Act
            var result = await formatter.ReadAsync(context);

            // Assert
            Assert.NotNull(result);
            Assert.False(result.HasError);
            var model = Assert.IsType<TestLevelTwo>(result.Model);
            Buffer.BlockCopy(sampleStringBytes, 0, expectedBytes, 0, sampleStringBytes.Length);
            Buffer.BlockCopy(bom, 0, expectedBytes, sampleStringBytes.Length, bom.Length);
            Assert.Equal(expectedBytes, Encoding.UTF8.GetBytes(model.SampleString));
        }
        public async Task ReadAsync_UsesContentTypeCharSet_ToReadStream()
        {
            // Arrange
            var expectedException = TestPlatformHelper.IsMono ? typeof(SerializationException) :
                                                                typeof(XmlException);
            var expectedMessage = TestPlatformHelper.IsMono ?
                "Expected element 'TestLevelTwo' in namespace '', but found Element node 'DummyClass' in namespace ''" :
                "The expected encoding 'utf-16LE' does not match the actual encoding 'utf-8'.";
            var inputBytes = Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<DummyClass><SampleInt>1000</SampleInt></DummyClass>");

            var formatter = new XmlDataContractSerializerInputFormatter();

            var modelState = new ModelStateDictionary();
            var httpContext = GetHttpContext(inputBytes, contentType: "application/xml; charset=utf-16");

            var context = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: modelState,
                modelType: typeof(TestLevelOne));

            // Act
            var ex = await Assert.ThrowsAsync(expectedException, () => formatter.ReadAsync(context));
            Assert.Equal(expectedMessage, ex.Message);
        }
        public async Task PostingModel_WithPropertySelfReferencingItself()
        {
            // Arrange
            var input = "<Employee xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.AspNet.Mvc.Xml\"" +
                " xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><Id>10</Id><Manager><Id>11</Id><Manager" +
                " i:nil=\"true\"/><Name>Mike</Name></Manager><Name>John</Name></Employee>";
            var formatter = new XmlDataContractSerializerInputFormatter();
            var contentBytes = Encodings.UTF8EncodingWithoutBOM.GetBytes(input);
            var context = GetInputFormatterContext(contentBytes, typeof(Employee));
            var expectedModel = new Employee()
            {
                Id = 10,
                Name = "John",
                Manager = new Employee()
                {
                    Id = 11,
                    Name = "Mike"
                }
            };

            // Act
            var model = await formatter.ReadAsync(context) as Employee;

            // Assert
            Assert.NotNull(model);
            Assert.Equal(expectedModel.Id, model.Id);
            Assert.Equal(expectedModel.Name, model.Name);
            Assert.NotNull(model.Manager);
            Assert.Equal(expectedModel.Manager.Id, model.Manager.Id);
            Assert.Equal(expectedModel.Manager.Name, model.Manager.Name);
            Assert.Null(model.Manager.Manager);

            Assert.Equal(1, context.ActionContext.ModelState.Keys.Count);
            AssertModelStateErrorMessages(
                typeof(Employee).FullName,
                context.ActionContext,
                expectedErrorMessages: new[]
                {
                    string.Format(requiredErrorMessageFormat, nameof(Employee.Id), typeof(Employee).FullName)
                });
        }
        public async Task PostingModel_WithDictionaryProperty_HasValidationErrorsOnKeyAndValue()
        {
            // Arrange
            var input = "<FavoriteLocations " +
                "i:nil=\"true\" xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.AspNet.Mvc.Xml\"" +
                " xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"/>";

            var formatter = new XmlDataContractSerializerInputFormatter();
            var contentBytes = Encodings.UTF8EncodingWithoutBOM.GetBytes(input);
            var context = GetInputFormatterContext(contentBytes, typeof(FavoriteLocations));

            // Act
            var model = await formatter.ReadAsync(context);

            // Assert
            Assert.Null(model);

            Assert.Equal(2, context.ActionContext.ModelState.Keys.Count);
            AssertModelStateErrorMessages(
                typeof(Point).FullName,
                context.ActionContext,
                expectedErrorMessages: new[]
                {
                    string.Format(requiredErrorMessageFormat, nameof(Point.X), typeof(Point).FullName),
                    string.Format(requiredErrorMessageFormat, nameof(Point.Y), typeof(Point).FullName)
                });
            AssertModelStateErrorMessages(
                typeof(Address).FullName,
                context.ActionContext,
                expectedErrorMessages: new[]
                {
                    string.Format(requiredErrorMessageFormat, nameof(Address.IsResidential), typeof(Address).FullName),
                    string.Format(requiredErrorMessageFormat, nameof(Address.Zipcode), typeof(Address).FullName)
                });
        }
        public async Task ReadAsync_ThrowsWhenNotConfiguredWithKnownTypes()
        {
            // Arrange
            var KnownTypeName = "SomeDummyClass";
            var InstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";

            var input = string.Format(
                    "<DummyClass i:type=\"{0}\" xmlns:i=\"{1}\"><SampleInt>1</SampleInt>"
                    + "<SampleString>Some text</SampleString></DummyClass>",
                    KnownTypeName,
                    InstanceNamespace);
            var formatter = new XmlDataContractSerializerInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes(input);
            var context = GetInputFormatterContext(contentBytes, typeof(DummyClass));

            // Act & Assert
            await Assert.ThrowsAsync(typeof(SerializationException), async () => await formatter.ReadAsync(context));
        }
        public async Task ReadAsync_ThrowsOnExceededMaxDepth()
        {
            if (TestPlatformHelper.IsMono)
            {
                // ReaderQuotas are not honored on Mono
                return;
            }

            // Arrange
            var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                        "<TestLevelTwo><SampleString>test</SampleString>" +
                        "<TestOne><SampleInt>10</SampleInt>" +
                        "<sampleString>test</sampleString></TestOne></TestLevelTwo>";
            var formatter = new XmlDataContractSerializerInputFormatter();
            formatter.MaxDepth = 1;
            var contentBytes = Encoding.UTF8.GetBytes(input);
            var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo));

            // Act & Assert
            await Assert.ThrowsAsync(typeof(SerializationException), async () => await formatter.ReadAsync(context));
        }
        public async Task ReadAsync_ReadsComplexTypes()
        {
            // Arrange
            var expectedInt = 10;
            var expectedString = "TestString";
            var expectedLevelTwoString = "102";

            var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                        "<TestLevelTwo><SampleString>" + expectedLevelTwoString + "</SampleString>" +
                        "<TestOne><SampleInt>" + expectedInt + "</SampleInt>" +
                        "<sampleString>" + expectedString + "</sampleString></TestOne></TestLevelTwo>";

            var formatter = new XmlDataContractSerializerInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes(input);
            var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo));

            // Act
            var result = await formatter.ReadAsync(context);

            // Assert
            Assert.NotNull(result);
            Assert.False(result.HasError);
            var model = Assert.IsType<TestLevelTwo>(result.Model);

            Assert.Equal(expectedLevelTwoString, model.SampleString);
            Assert.Equal(expectedInt, model.TestOne.SampleInt);
            Assert.Equal(expectedString, model.TestOne.sampleString);
        }
        public async Task PostingModelOfStructs_WithDeeperHierarchy_HasValidationErrors()
        {
            // Arrange
            var input = "<School i:nil=\"true\" " +
                "xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.AspNet.Mvc.Xml\" " +
                "xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"/>";

            var formatter = new XmlDataContractSerializerInputFormatter();
            var contentBytes = Encodings.UTF8EncodingWithoutBOM.GetBytes(input);
            var context = GetInputFormatterContext(contentBytes, typeof(School));

            // Act
            var model = await formatter.ReadAsync(context);

            // Assert
            Assert.Null(model);

            Assert.Equal(3, context.ActionContext.ModelState.Keys.Count);
            AssertModelStateErrorMessages(
                typeof(School).FullName,
                context.ActionContext,
                expectedErrorMessages: new[]
                {
                    string.Format(requiredErrorMessageFormat, nameof(School.Id), typeof(School).FullName)
                });
            AssertModelStateErrorMessages(
                typeof(Website).FullName,
                context.ActionContext,
                expectedErrorMessages: new[]
                {
                    string.Format(requiredErrorMessageFormat, nameof(Website.Id), typeof(Website).FullName)
                });

            AssertModelStateErrorMessages(
                typeof(Student).FullName,
                context.ActionContext,
                expectedErrorMessages: new[]
                {
                    string.Format(requiredErrorMessageFormat, nameof(Student.Id), typeof(Student).FullName)
                });
        }
        public async Task ReadAsync_AcceptsUTF16Characters()
        {
            // Arrange
            var expectedInt = 10;
            var expectedString = "TestString";

            var input = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>" +
                                "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" +
                                "<sampleString>" + expectedString + "</sampleString></TestLevelOne>";

            var formatter = new XmlDataContractSerializerInputFormatter();
            var contentBytes = Encodings.UTF16EncodingLittleEndian.GetBytes(input);

            var modelState = new ModelStateDictionary();
            var httpContext = GetHttpContext(contentBytes, contentType: "application/xml; charset=utf-16");

            var context = new InputFormatterContext(httpContext, modelState, typeof(TestLevelOne));
            
            // Act
            var model = await formatter.ReadAsync(context);

            // Assert
            Assert.NotNull(model);
            Assert.IsType<TestLevelOne>(model);

            var levelOneModel = model as TestLevelOne;
            Assert.Equal(expectedInt, levelOneModel.SampleInt);
            Assert.Equal(expectedString, levelOneModel.sampleString);
        }
        public async Task PostingModel_WithDeeperHierarchy_HasValidationErrors()
        {
            // Arrange
            var input = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                        "<Store xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.AspNet.Mvc.Xml\"" +
                        " xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" i:nil=\"true\" />";
            var formatter = new XmlDataContractSerializerInputFormatter();
            var contentBytes = Encodings.UTF8EncodingWithoutBOM.GetBytes(input);
            var context = GetInputFormatterContext(contentBytes, typeof(Store));

            // Act
            var model = await formatter.ReadAsync(context) as Store;

            // Assert
            Assert.Null(model);

            Assert.Equal(3, context.ActionContext.ModelState.Keys.Count);
            AssertModelStateErrorMessages(
                typeof(Address).FullName,
                context.ActionContext,
                expectedErrorMessages: new[]
                {
                    string.Format(requiredErrorMessageFormat, nameof(Address.IsResidential), typeof(Address).FullName),
                    string.Format(requiredErrorMessageFormat, nameof(Address.Zipcode), typeof(Address).FullName)
                });

            AssertModelStateErrorMessages(
                typeof(Employee).FullName,
                context.ActionContext,
                expectedErrorMessages: new[]
                {
                    string.Format(requiredErrorMessageFormat, nameof(Employee.Id), typeof(Employee).FullName)
                });

            AssertModelStateErrorMessages(
                typeof(Product).FullName,
                context.ActionContext,
                expectedErrorMessages: new[]
                {
                    string.Format(requiredErrorMessageFormat, nameof(Product.Id), typeof(Product).FullName)
                });
        }
        public async Task PostingListOfModels_WithRequiredAndDataMemberNoRequired_HasValidationErrors()
        {
            // Arrange
            var input = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                        "<ArrayOfProduct xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.AspNet.Mvc.Xml\"" +
                        " xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><Product><Id>" +
                        "10</Id><Name>Phone</Name></Product></ArrayOfProduct>";
            var formatter = new XmlDataContractSerializerInputFormatter();
            var contentBytes = Encodings.UTF8EncodingWithoutBOM.GetBytes(input);
            var context = GetInputFormatterContext(contentBytes, typeof(List<Product>));

            // Act
            var model = await formatter.ReadAsync(context) as List<Product>;

            // Assert
            Assert.NotNull(model);
            Assert.Equal(1, model.Count);
            Assert.Equal(10, model[0].Id);
            Assert.Equal("Phone", model[0].Name);

            Assert.Equal(2, context.ActionContext.ModelState.Keys.Count);
            AssertModelStateErrorMessages(
                typeof(Product).FullName,
                context.ActionContext,
                expectedErrorMessages: new[]
                {
                    string.Format(requiredErrorMessageFormat, nameof(Product.Id), typeof(Product).FullName)
                });

            AssertModelStateErrorMessages(
                typeof(Address).FullName,
                context.ActionContext,
                expectedErrorMessages: new[]
                {
                    string.Format(requiredErrorMessageFormat, nameof(Address.Zipcode), typeof(Address).FullName),
                    string.Format(requiredErrorMessageFormat, nameof(Address.IsResidential), typeof(Address).FullName)
                });
        }
        public async Task PostingListofModels_WithBothRequiredAndDataMemberRequired_NoValidationErrors()
        {
            // Arrange
            var input = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                        "<ArrayOfLaptop xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.AspNet.Mvc.Xml\"" +
                        " xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><Laptop><Id>" +
                        "10</Id><SupportsVirtualization>true</SupportsVirtualization></Laptop></ArrayOfLaptop>";
            var formatter = new XmlDataContractSerializerInputFormatter();
            var contentBytes = Encodings.UTF8EncodingWithoutBOM.GetBytes(input);
            var context = GetInputFormatterContext(contentBytes, typeof(List<Laptop>));

            // Act
            var model = await formatter.ReadAsync(context) as List<Laptop>;

            // Assert
            Assert.NotNull(model);
            Assert.Equal(1, model.Count);
            Assert.Equal(10, model[0].Id);
            Assert.Equal(true, model[0].SupportsVirtualization);
            Assert.Empty(context.ActionContext.ModelState);
        }
        public async Task ReadAsync_ThrowsWhenNotConfiguredWithRootName()
        {
            // Arrange
            var SubstituteRootName = "SomeOtherClass";
            var SubstituteRootNamespace = "http://tempuri.org";

            var input = string.Format(
                "<{0} xmlns=\"{1}\"><SampleInt xmlns=\"\">1</SampleInt></{0}>",
                SubstituteRootName,
                SubstituteRootNamespace);
            var formatter = new XmlDataContractSerializerInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes(input);
            var context = GetInputFormatterContext(contentBytes, typeof(DummyClass));

            // Act & Assert
            await Assert.ThrowsAsync(typeof(SerializationException), async () => await formatter.ReadAsync(context));
        }
        public async Task PostingModelInheritingType_HasRequiredAttributeValidationErrors()
        {
            // Arrange
            var input = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<ModelInheritingTypeHavingRequiredAttributeValidationErrors" +
                " xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.AspNet.Mvc.Xml\"" +
                " xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                "<IsResidential>true</IsResidential><Zipcode>98052</Zipcode>" +
                "</ModelInheritingTypeHavingRequiredAttributeValidationErrors>";
            var formatter = new XmlDataContractSerializerInputFormatter();
            var contentBytes = Encodings.UTF8EncodingWithoutBOM.GetBytes(input);
            var context = GetInputFormatterContext(
                contentBytes,
                typeof(ModelInheritingTypeHavingRequiredAttributeValidationErrors));

            // Act
            var model = await formatter.ReadAsync(context)
                as ModelInheritingTypeHavingRequiredAttributeValidationErrors;

            // Assert
            Assert.NotNull(model);
            Assert.Equal(98052, model.Zipcode);
            Assert.Equal(true, model.IsResidential);

            Assert.Equal(1, context.ActionContext.ModelState.Keys.Count);
            AssertModelStateErrorMessages(
                typeof(Address).FullName,
                context.ActionContext,
                expectedErrorMessages: new[]
                {
                    string.Format(requiredErrorMessageFormat, nameof(Address.Zipcode), typeof(Address).FullName),
                    string.Format(requiredErrorMessageFormat, nameof(Address.IsResidential), typeof(Address).FullName)
                });
        }
        public async Task ReadAsync_ReadsWhenConfiguredWithRootName()
        {
            // Arrange
            var expectedInt = 10;
            var SubstituteRootName = "SomeOtherClass";
            var SubstituteRootNamespace = "http://tempuri.org";

            var input = string.Format(
                "<{0} xmlns=\"{1}\"><SampleInt xmlns=\"\">{2}</SampleInt></{0}>",
                SubstituteRootName,
                SubstituteRootNamespace,
                expectedInt);

            var dictionary = new XmlDictionary();
            var settings = new DataContractSerializerSettings
            {
                RootName = dictionary.Add(SubstituteRootName),
                RootNamespace = dictionary.Add(SubstituteRootNamespace)
            };
            var formatter = new XmlDataContractSerializerInputFormatter
            {
                SerializerSettings = settings
            };
            var contentBytes = Encoding.UTF8.GetBytes(input);
            var context = GetInputFormatterContext(contentBytes, typeof(DummyClass));

            // Act
            var result = await formatter.ReadAsync(context);

            // Assert
            Assert.NotNull(result);
            Assert.False(result.HasError);
            var model = Assert.IsType<DummyClass>(result.Model);
            Assert.Equal(expectedInt, model.SampleInt);
        }
        public async Task PostingModel_WithDifferentValueTypeProperties_HasValidationErrors()
        {
            // Arrange
            var input = "<ValueTypePropertiesModel i:nil=\"true\" " +
                "xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.AspNet.Mvc.Xml\" " +
                "xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"/>";

            var formatter = new XmlDataContractSerializerInputFormatter();
            var contentBytes = Encodings.UTF8EncodingWithoutBOM.GetBytes(input);
            var context = GetInputFormatterContext(contentBytes, typeof(ValueTypePropertiesModel));

            // Act
            var model = await formatter.ReadAsync(context);

            // Assert
            Assert.Null(model);

            Assert.Equal(3, context.ActionContext.ModelState.Keys.Count);
            AssertModelStateErrorMessages(
                typeof(Point).FullName,
                context.ActionContext,
                expectedErrorMessages: new[]
                {
                    string.Format(requiredErrorMessageFormat, nameof(Point.X), typeof(Point).FullName),
                    string.Format(requiredErrorMessageFormat, nameof(Point.X), typeof(Point).FullName)
                });
            AssertModelStateErrorMessages(
                typeof(GpsCoordinate).FullName,
                context.ActionContext,
                expectedErrorMessages: new[]
                {
                    string.Format(
                        requiredErrorMessageFormat, 
                        nameof(GpsCoordinate.Latitude), 
                        typeof(GpsCoordinate).FullName),
                    string.Format(
                        requiredErrorMessageFormat, 
                        nameof(GpsCoordinate.Longitude), 
                        typeof(GpsCoordinate).FullName)
                });
            AssertModelStateErrorMessages(
                typeof(ValueTypePropertiesModel).FullName,
                context.ActionContext,
                expectedErrorMessages: new[]
                {
                    string.Format(
                        requiredErrorMessageFormat, 
                        nameof(ValueTypePropertiesModel.IntProperty), 
                        typeof(ValueTypePropertiesModel).FullName),
                    string.Format(
                        requiredErrorMessageFormat,
                        nameof(ValueTypePropertiesModel.DateTimeProperty),
                        typeof(ValueTypePropertiesModel).FullName),
                    string.Format(
                        requiredErrorMessageFormat,
                        nameof(ValueTypePropertiesModel.PointProperty),
                        typeof(ValueTypePropertiesModel).FullName),
                    string.Format(
                        requiredErrorMessageFormat,
                        nameof(ValueTypePropertiesModel.GpsCoordinateProperty),
                        typeof(ValueTypePropertiesModel).FullName)
                });
        }
        public async Task ReadAsync_ReadsWhenConfiguredWithKnownTypes()
        {
            // Arrange
            var expectedInt = 10;
            var expectedString = "TestString";
            var KnownTypeName = "SomeDummyClass";
            var InstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";

            var input = string.Format(
                    "<DummyClass i:type=\"{0}\" xmlns:i=\"{1}\"><SampleInt>{2}</SampleInt>"
                    + "<SampleString>{3}</SampleString></DummyClass>",
                    KnownTypeName,
                    InstanceNamespace,
                    expectedInt,
                    expectedString);
            var settings = new DataContractSerializerSettings
            {
                KnownTypes = new[] { typeof(SomeDummyClass) }
            };
            var formatter = new XmlDataContractSerializerInputFormatter
            {
                SerializerSettings = settings
            };
            var contentBytes = Encoding.UTF8.GetBytes(input);
            var context = GetInputFormatterContext(contentBytes, typeof(DummyClass));

            // Act
            var result = await formatter.ReadAsync(context);

            // Assert
            Assert.NotNull(result);
            Assert.False(result.HasError);
            var model = Assert.IsType<SomeDummyClass>(result.Model);
            Assert.Equal(expectedInt, model.SampleInt);
            Assert.Equal(expectedString, model.SampleString);
        }
        public async Task ReadAsync_VerifyStreamIsOpenAfterRead()
        {
            // Arrange
            var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<DummyClass><SampleInt>10</SampleInt></DummyClass>";
            var formatter = new XmlDataContractSerializerInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes(input);
            var context = GetInputFormatterContext(contentBytes, typeof(DummyClass));

            // Act
            var result = await formatter.ReadAsync(context);

            // Assert
            Assert.NotNull(result);
            Assert.False(result.HasError);
            Assert.NotNull(result.Model);
            Assert.True(context.HttpContext.Request.Body.CanRead);
        }
Exemplo n.º 26
0
        public async Task XmlDataContractSerializerFormatterThrowsWhenReaderQuotasAreChanged()
        {
            // Arrange
            var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                        "<TestLevelTwo><SampleString>test</SampleString>" +
                        "<TestOne><SampleInt>10</SampleInt>" +
                        "<sampleString>test</sampleString></TestOne></TestLevelTwo>";
            var formatter = new XmlDataContractSerializerInputFormatter();

            formatter.XmlDictionaryReaderQuotas.MaxStringContentLength = 2;
            var contentBytes = Encoding.UTF8.GetBytes(input);
            var context      = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo));

            // Act & Assert
            await Assert.ThrowsAsync(typeof(SerializationException), async() => await formatter.ReadAsync(context));
        }
        public async Task ReadAsync_FallsbackToUTF8_WhenCharSet_NotInContentType()
        {
            // Arrange
            var expectedException = TestPlatformHelper.IsMono ? typeof(SerializationException) :
                                                                typeof(XmlException);
            var expectedMessage = TestPlatformHelper.IsMono ?
                "Expected element 'TestLevelTwo' in namespace '', but found Element node 'DummyClass' in namespace ''" :
                "The expected encoding 'utf-8' does not match the actual encoding 'utf-16LE'.";
            var inpStart = Encoding.Unicode.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-16\"?>" +
                "<DummyClass><SampleInt>");
            byte[] inp = { 192, 193 };
            var inpEnd = Encoding.Unicode.GetBytes("</SampleInt></DummyClass>");

            var contentBytes = new byte[inpStart.Length + inp.Length + inpEnd.Length];
            Buffer.BlockCopy(inpStart, 0, contentBytes, 0, inpStart.Length);
            Buffer.BlockCopy(inp, 0, contentBytes, inpStart.Length, inp.Length);
            Buffer.BlockCopy(inpEnd, 0, contentBytes, inpStart.Length + inp.Length, inpEnd.Length);

            var formatter = new XmlDataContractSerializerInputFormatter();
            var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo));

            // Act
            var ex = await Assert.ThrowsAsync(expectedException, () => formatter.ReadAsync(context));
            Assert.Equal(expectedMessage, ex.Message);
        }
        public async Task ReadAsync_ReadsWhenMaxDepthIsModified()
        {
            // Arrange
            var expectedInt = 10;

            var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<DummyClass><SampleInt>" + expectedInt + "</SampleInt></DummyClass>";
            var formatter = new XmlDataContractSerializerInputFormatter();
            formatter.MaxDepth = 10;
            var contentBytes = Encoding.UTF8.GetBytes(input);
            var context = GetInputFormatterContext(contentBytes, typeof(DummyClass));


            // Act
            var result = await formatter.ReadAsync(context);

            // Assert
            Assert.NotNull(result);
            Assert.False(result.HasError);
            var model = Assert.IsType<DummyClass>(result.Model);
            Assert.Equal(expectedInt, model.SampleInt);
        }
        public async Task PostingModel_WithPropertyHavingNullableValueTypes_NoRequiredAttributeValidationErrors()
        {
            // Arrange
            var input = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<ModelWithPropertyHavingTypeWithNullableProperties " +
                "xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.AspNet.Mvc.Xml\" " +
                "xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><CarInfoProperty>" +
                "<ServicedYears xmlns:a=\"http://schemas.datacontract.org/2004/07/System\"><a:int>2006</a:int>" +
                "<a:int>2007</a:int></ServicedYears><Year>2005</Year></CarInfoProperty>" +
                "</ModelWithPropertyHavingTypeWithNullableProperties>";
            var formatter = new XmlDataContractSerializerInputFormatter();
            var contentBytes = Encodings.UTF8EncodingWithoutBOM.GetBytes(input);
            var context = GetInputFormatterContext(
                contentBytes,
                typeof(ModelWithPropertyHavingTypeWithNullableProperties));
            var expectedModel = new ModelWithPropertyHavingTypeWithNullableProperties()
            {
                CarInfoProperty = new CarInfo() { Year = 2005, ServicedYears = new List<int?>() }
            };

            expectedModel.CarInfoProperty.ServicedYears.Add(2006);
            expectedModel.CarInfoProperty.ServicedYears.Add(2007);

            // Act
            var model = await formatter.ReadAsync(context) as ModelWithPropertyHavingTypeWithNullableProperties;

            // Assert
            Assert.NotNull(model);
            Assert.NotNull(model.CarInfoProperty);
            Assert.Equal(expectedModel.CarInfoProperty.Year, model.CarInfoProperty.Year);
            Assert.Equal(expectedModel.CarInfoProperty.ServicedYears, model.CarInfoProperty.ServicedYears);
            Assert.Empty(context.ActionContext.ModelState);
        }
        public async Task ReadAsync_ThrowsWhenReaderQuotasAreChanged()
        {
            // Arrange
            var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                        "<TestLevelTwo><SampleString>test</SampleString>" +
                        "<TestOne><SampleInt>10</SampleInt>" +
                        "<sampleString>test</sampleString></TestOne></TestLevelTwo>";
            var formatter = new XmlDataContractSerializerInputFormatter();
            formatter.XmlDictionaryReaderQuotas.MaxStringContentLength = 2;
            var contentBytes = Encoding.UTF8.GetBytes(input);
            var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo));

            // Act & Assert
            await Assert.ThrowsAsync(typeof(SerializationException), async () => await formatter.ReadAsync(context));
        }
        public async Task XmlDataContractSerializerFormatterThrowsOnInvalidCharacters()
        {
            // Arrange
            var inpStart = Encodings.UTF16EncodingLittleEndian.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<DummyClass><SampleInt>");
            byte[] inp = { 192, 193 };
            var inpEnd = Encodings.UTF16EncodingLittleEndian.GetBytes("</SampleInt></DummyClass>");

            var contentBytes = new byte[inpStart.Length + inp.Length + inpEnd.Length];
            Buffer.BlockCopy(inpStart, 0, contentBytes, 0, inpStart.Length);
            Buffer.BlockCopy(inp, 0, contentBytes, inpStart.Length, inp.Length);
            Buffer.BlockCopy(inpEnd, 0, contentBytes, inpStart.Length + inp.Length, inpEnd.Length);

            var formatter = new XmlDataContractSerializerInputFormatter();
            var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo));

            // Act
            await Assert.ThrowsAsync(typeof(XmlException), async () => await formatter.ReadAsync(context));
        }