コード例 #1
0
        public async Task XmlDataContractSerializerOutputFormatterWritesUTF16Output()
        {
            // Arrange
            var sampleInput = new DummyClass {
                SampleInt = 10
            };
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType(),
                                                                   "application/xml; charset=utf-16");
            var formatter = new XmlDataContractSerializerOutputFormatter(
                XmlOutputFormatter.GetDefaultXmlWriterSettings());

            formatter.WriterSettings.OmitXmlDeclaration = false;

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            Assert.NotNull(outputFormatterContext.ActionContext.HttpContext.Response.Body);
            outputFormatterContext.ActionContext.HttpContext.Response.Body.Position = 0;
            Assert.Equal("<?xml version=\"1.0\" encoding=\"utf-16\"?>" +
                         "<DummyClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                         "<SampleInt>10</SampleInt></DummyClass>",
                         new StreamReader(outputFormatterContext.ActionContext.HttpContext.Response.Body,
                                          Encodings.UTF16EncodingLittleEndian).ReadToEnd());
        }
コード例 #2
0
        public async Task WriteAsync_WritesOnModifiedWriterSettings()
        {
            // Arrange
            var expectedOutput =
                "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<DummyClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                "<SampleInt>10</SampleInt></DummyClass>";

            var sampleInput = new DummyClass {
                SampleInt = 10
            };
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());
            var formatter = new XmlDataContractSerializerOutputFormatter(
                new XmlWriterSettings
            {
                OmitXmlDeclaration = false,
                CloseOutput        = false
            });

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;

            body.Position = 0;

            var content = new StreamReader(body).ReadToEnd();

            XmlAssert.Equal(expectedOutput, content);
        }
コード例 #3
0
        public async Task XmlDataContractSerializerOutputFormatterWritesIndentedOutput()
        {
            // Arrange
            var sampleInput = new DummyClass {
                SampleInt = 10
            };
            var formatter = new XmlDataContractSerializerOutputFormatter(
                XmlOutputFormatter.GetDefaultXmlWriterSettings());

            formatter.WriterSettings.Indent = true;
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            Assert.NotNull(outputFormatterContext.ActionContext.HttpContext.Response.Body);
            outputFormatterContext.ActionContext.HttpContext.Response.Body.Position = 0;
            var outputString = new StreamReader(outputFormatterContext.ActionContext.HttpContext.Response.Body,
                                                Encoding.UTF8).ReadToEnd();

            Assert.Equal("<DummyClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                         "\r\n  <SampleInt>10</SampleInt>\r\n</DummyClass>",
                         outputString);
        }
コード例 #4
0
        public async Task XmlDataContractSerializerOutputFormatterWritesComplexTypes()
        {
            // Arrange
            var sampleInput = new TestLevelTwo
            {
                SampleString = "TestString",
                TestOne      = new TestLevelOne
                {
                    SampleInt    = 10,
                    sampleString = "TestLevelOne string"
                }
            };
            var formatter = new XmlDataContractSerializerOutputFormatter(
                XmlOutputFormatter.GetDefaultXmlWriterSettings());
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            Assert.NotNull(outputFormatterContext.ActionContext.HttpContext.Response.Body);
            outputFormatterContext.ActionContext.HttpContext.Response.Body.Position = 0;
            Assert.Equal("<TestLevelTwo xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                         "<SampleString>TestString</SampleString>" +
                         "<TestOne><SampleInt>10</SampleInt><sampleString>TestLevelOne string</sampleString>" +
                         "</TestOne></TestLevelTwo>",
                         new StreamReader(outputFormatterContext.ActionContext.HttpContext.Response.Body, Encoding.UTF8)
                         .ReadToEnd());
        }
コード例 #5
0
    /// <summary>
    /// Adds the data contract serializer formatters to <see cref="MvcOptions"/>.
    /// </summary>
    /// <param name="options">The <see cref="MvcOptions"/>.</param>
    public void Configure(MvcOptions options)
    {
        options.ModelMetadataDetailsProviders.Add(new DataMemberRequiredBindingMetadataProvider());

        var inputFormatter = new XmlDataContractSerializerInputFormatter(options);

        inputFormatter.WrapperProviderFactories.Add(new ProblemDetailsWrapperProviderFactory());
        options.InputFormatters.Add(inputFormatter);

        var outputFormatter = new XmlDataContractSerializerOutputFormatter(_loggerFactory);

        outputFormatter.WrapperProviderFactories.Add(new ProblemDetailsWrapperProviderFactory());
        options.OutputFormatters.Add(outputFormatter);

        // Do not override any user mapping
        var key     = "xml";
        var mapping = options.FormatterMappings.GetMediaTypeMappingForFormat(key);

        if (string.IsNullOrEmpty(mapping))
        {
            options.FormatterMappings.SetMediaTypeMappingForFormat(
                key,
                MediaTypeHeaderValues.ApplicationXml);
        }

        options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider("System.Xml.Linq.XObject"));
        options.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider("System.Xml.XmlNode"));
    }
コード例 #6
0
        public async Task WriteAsync_WritesUTF16Output()
        {
            // Arrange
            var expectedOutput =
                "<?xml version=\"1.0\" encoding=\"utf-16\"?>" +
                "<DummyClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                "<SampleInt>10</SampleInt></DummyClass>";

            var sampleInput = new DummyClass {
                SampleInt = 10
            };
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType(),
                                                                   "application/xml; charset=utf-16");
            var formatter = new XmlDataContractSerializerOutputFormatter();

            formatter.WriterSettings.OmitXmlDeclaration = false;

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;

            body.Position = 0;

            var content = new StreamReader(
                body,
                new UnicodeEncoding(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: true)).ReadToEnd();

            XmlAssert.Equal(expectedOutput, content);
        }
コード例 #7
0
        private static void Main()
        {
            var person = new Person {
                Title = Title.Mr, FirstName = "Matt", Age = 99, Income = 1234
            };

            // Serialize using XmlDataContractSerializerOutputFormatter - works
            var xmlFormatter = new XmlDataContractSerializerOutputFormatter();
            var result       = Serialize(person, xmlFormatter, ApplicationXml);

            Console.WriteLine("Xml: " + result);

            // Serialize using NewtonsoftJsonOutputFormatter - also works
            var newtonsoftFormatter = new NewtonsoftJsonOutputFormatter(new Newtonsoft.Json.JsonSerializerSettings(), ArrayPool <char> .Shared, new MvcOptions());

            result = Serialize(person, newtonsoftFormatter, ApplicationJson);
            Console.WriteLine("Newtonsoft Json: " + result);

            // Serialize using SystemTextJsonOutputFormatter - returns empty string :-(
            var systemTextJsonFormatter = new SystemTextJsonOutputFormatter(new System.Text.Json.JsonSerializerOptions());

            result = Serialize(person, systemTextJsonFormatter, ApplicationJson);
            Console.WriteLine("System.Text.Json: " + result);

            Console.ReadLine();
        }
コード例 #8
0
        // This method gets called by a runtime.
        // Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services)
        {
            XmlSerializerOutputFormatter xmlOutput;
            XmlSerializerInputFormatter  xmlInput;

            var xmlInputDc  = new XmlDataContractSerializerInputFormatter();
            var xmlOutputDc = new XmlDataContractSerializerOutputFormatter();

            services.AddMvc().ConfigureMvc(config => {
                config.InputFormatters.Add(xmlInputDc);
                config.OutputFormatters.Add(xmlOutputDc);

                var jsonInput  = config.InputFormatters.OfType <JsonInputFormatter>().FirstOrDefault();
                var jsonOutput = config.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault();

                jsonInput.SerializerSettings.ReferenceLoopHandling      = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                jsonInput.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;

                jsonOutput.SerializerSettings.ReferenceLoopHandling      = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                jsonOutput.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;
            });
            // Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers.
            // You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json.
            // services.AddWebApiConventions();
        }
コード例 #9
0
        public async Task WriteAsync_WritesSimpleTypes()
        {
            // Arrange
            var expectedOutput =
                "<DummyClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                "<SampleInt>10</SampleInt></DummyClass>";

            var sampleInput = new DummyClass {
                SampleInt = 10
            };
            var formatter = new XmlDataContractSerializerOutputFormatter();
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;

            body.Position = 0;

            var content = new StreamReader(body).ReadToEnd();

            XmlAssert.Equal(expectedOutput, content);
        }
コード例 #10
0
        public async Task SuppliedWriterSettings_TakeAffect()
        {
            // Arrange
            var writerSettings = FormattingUtilities.GetDefaultXmlWriterSettings();

            writerSettings.OmitXmlDeclaration = false;
            var sampleInput = new DummyClass {
                SampleInt = 10
            };
            var formatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());
            var formatter        = new XmlDataContractSerializerOutputFormatter(writerSettings);
            var expectedOutput   = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                   "<DummyClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                                   "<SampleInt>10</SampleInt></DummyClass>";

            // Act
            await formatter.WriteAsync(formatterContext);

            // Assert
            Assert.Same(writerSettings, formatter.WriterSettings);

            var body = formatterContext.HttpContext.Response.Body;

            body.Position = 0;

            var content = new StreamReader(body).ReadToEnd();

            XmlAssert.Equal(expectedOutput, content);
        }
コード例 #11
0
        public async Task WriteAsync_WritesComplexTypes()
        {
            // Arrange
            var expectedOutput =
                "<TestLevelTwo xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                "<SampleString>TestString</SampleString>" +
                "<TestOne><SampleInt>10</SampleInt><sampleString>TestLevelOne string</sampleString>" +
                "</TestOne></TestLevelTwo>";

            var sampleInput = new TestLevelTwo
            {
                SampleString = "TestString",
                TestOne      = new TestLevelOne
                {
                    SampleInt    = 10,
                    sampleString = "TestLevelOne string"
                }
            };
            var formatter = new XmlDataContractSerializerOutputFormatter();
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;

            body.Position = 0;

            var content = new StreamReader(body).ReadToEnd();

            XmlAssert.Equal(expectedOutput, content);
        }
コード例 #12
0
        public async Task XmlDataContractSerializerOutputFormatterWritesOnModifiedWriterSettings()
        {
            // Arrange
            var sampleInput = new DummyClass {
                SampleInt = 10
            };
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());
            var formatter = new XmlDataContractSerializerOutputFormatter(
                new System.Xml.XmlWriterSettings
            {
                OmitXmlDeclaration = false,
                CloseOutput        = false
            });

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            Assert.NotNull(outputFormatterContext.ActionContext.HttpContext.Response.Body);
            outputFormatterContext.ActionContext.HttpContext.Response.Body.Position = 0;
            Assert.Equal("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                         "<DummyClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                         "<SampleInt>10</SampleInt></DummyClass>",
                         new StreamReader(outputFormatterContext.ActionContext.HttpContext.Response.Body, Encoding.UTF8).ReadToEnd());
        }
コード例 #13
0
ファイル: Startup.cs プロジェクト: jamsking/jamskingcore20EF
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <LinkStarApiDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("LSConnection")));
            services.AddDbContext <BaseApiDbContext>(options =>
                                                     options.UseSqlServer(Configuration.GetConnectionString("BAConnection")));

            services.AddMvc(options =>
            {
                options.ReturnHttpNotAcceptable = true;
                //options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
                //options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
                //options.InputFormatters.Add(new XmlDataContractSerializerInputFormatter());
                //options.FormatterMappings.SetMediaTypeMappingForFormat("xml", "application/xml");
                // Input formatters
                var xmlInputFormatting  = new XmlDataContractSerializerInputFormatter();
                var xmlOutputFormatting = new XmlDataContractSerializerOutputFormatter();
                //var jsonInputFormatting = new JsonInputFormatter();
                //jsonInputFormatting.SerializerSettings.Converters.Add(new BatchContentConverter());

                options.InputFormatters.Clear();
                //options.InputFormatters.Add(jsonInputFormatting);
                options.InputFormatters.Add(xmlInputFormatting);
                options.OutputFormatters.Add(xmlOutputFormatting);
                //options.FormatterMappings.SetMediaTypeMappingForFormat("xml", "application/xml");
            });
        }
コード例 #14
0
        public void XmlDataContractSerializer_CanWriteResult_ReturnsTrue_ForWritableType()
        {
            // Arrange
            var formatter = new XmlDataContractSerializerOutputFormatter(
                XmlOutputFormatter.GetDefaultXmlWriterSettings());
            var outputFormatterContext = GetOutputFormatterContext(null, typeof(Dictionary <string, string>));

            // Act & Assert
            Assert.True(formatter.CanWriteResult(outputFormatterContext, MediaTypeHeaderValue.Parse("application/xml")));
        }
コード例 #15
0
        public Task ExecuteAsync(ActionContext context, XmlResult result)
        {
            var serializerSettings = result.XmlSerializerSettings ?? FormattingUtilities.GetDefaultXmlWriterSettings();
            TextOutputFormatter formatter;

            // create the proper formatter
            formatter = new XmlDataContractSerializerOutputFormatter(serializerSettings);
            XmlResultExecutorBase xmlBase = new XmlResultExecutorBase(WriterFactory, LoggerFactory, formatter);

            return(xmlBase.ExecuteAsync(context, result));
        }
コード例 #16
0
        public void XmlDataContractSerializer_CanWriteResult(object input, Type declaredType, bool expectedOutput)
        {
            // Arrange
            var formatter = new XmlDataContractSerializerOutputFormatter();
            var outputFormatterContext = GetOutputFormatterContext(input, declaredType);

            // Act
            var result = formatter.CanWriteResult(outputFormatterContext, MediaTypeHeaderValue.Parse("application/xml"));

            // Assert
            Assert.Equal(expectedOutput, result);
        }
コード例 #17
0
        public void DoesNotThrow_OnNoLoggerAnd_WhenUnableToCreateSerializerForType()
        {
            // Arrange
            var formatter = new XmlDataContractSerializerOutputFormatter(); // no logger is being supplied here on purpose
            var outputFormatterContext = GetOutputFormatterContext(new Customer(10), typeof(Customer));

            // Act
            var canWriteResult = formatter.CanWriteResult(outputFormatterContext);

            // Assert
            Assert.False(canWriteResult);
        }
コード例 #18
0
        public async Task WriteAsync_ThrowsWhenNotConfiguredWithKnownTypes()
        {
            // Arrange
            var sampleInput = new SomeDummyClass {
                SampleInt = 1, SampleString = "TestString"
            };
            var formatter = new XmlDataContractSerializerOutputFormatter();
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, typeof(DummyClass));

            // Act & Assert
            await Assert.ThrowsAsync <SerializationException>(async() => await formatter.WriteAsync(outputFormatterContext));
        }
コード例 #19
0
ファイル: Startup.cs プロジェクト: praveencode8/MvcDotnet
        // Set up application services
        public void ConfigureServices(IServiceCollection services)
        {
            // Add MVC services to the services container
            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Latest);

            services.Configure <MvcOptions>(options =>
            {
                options.InputFormatters.Clear();
                options.OutputFormatters.Clear();

                // Since both XmlSerializer and DataContractSerializer based formatters
                // have supported media types of 'application/xml' and 'text/xml',  it
                // would be difficult for a test to choose a particular formatter based on
                // request information (Ex: Accept header).
                // So here we instead clear out the default supported media types and create new
                // ones which are distinguishable between formatters.
                var xmlSerializerInputFormatter = new XmlSerializerInputFormatter(new MvcOptions());
                xmlSerializerInputFormatter.SupportedMediaTypes.Clear();
                xmlSerializerInputFormatter.SupportedMediaTypes.Add(
                    new MediaTypeHeaderValue("application/xml-xmlser"));
                xmlSerializerInputFormatter.SupportedMediaTypes.Add(
                    new MediaTypeHeaderValue("text/xml-xmlser"));

                var xmlSerializerOutputFormatter = new XmlSerializerOutputFormatter();
                xmlSerializerOutputFormatter.SupportedMediaTypes.Clear();
                xmlSerializerOutputFormatter.SupportedMediaTypes.Add(
                    new MediaTypeHeaderValue("application/xml-xmlser"));
                xmlSerializerOutputFormatter.SupportedMediaTypes.Add(
                    new MediaTypeHeaderValue("text/xml-xmlser"));

                var dcsInputFormatter = new XmlDataContractSerializerInputFormatter(new MvcOptions());
                dcsInputFormatter.SupportedMediaTypes.Clear();
                dcsInputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml-dcs"));
                dcsInputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml-dcs"));

                var dcsOutputFormatter = new XmlDataContractSerializerOutputFormatter();
                dcsOutputFormatter.SupportedMediaTypes.Clear();
                dcsOutputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml-dcs"));
                dcsOutputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml-dcs"));

                options.InputFormatters.Add(dcsInputFormatter);
                options.InputFormatters.Add(xmlSerializerInputFormatter);
                options.OutputFormatters.Add(dcsOutputFormatter);
                options.OutputFormatters.Add(xmlSerializerOutputFormatter);

                xmlSerializerInputFormatter.WrapperProviderFactories.Add(new PersonWrapperProviderFactory());
                xmlSerializerOutputFormatter.WrapperProviderFactories.Add(new PersonWrapperProviderFactory());
                dcsInputFormatter.WrapperProviderFactories.Add(new PersonWrapperProviderFactory());
                dcsOutputFormatter.WrapperProviderFactories.Add(new PersonWrapperProviderFactory());
            });
        }
コード例 #20
0
        public async Task WriteAsync_WritesWhenConfiguredWithPreserveReferences()
        {
            // Arrange
            var sampleId               = 1;
            var sampleName             = "Parent";
            var InstanceNamespace      = "http://www.w3.org/2001/XMLSchema-instance";
            var SerializationNamespace = "http://schemas.microsoft.com/2003/10/Serialization/";

            var expectedOutput = string.Format(
                CultureInfo.InvariantCulture,
                "<Parent xmlns:i=\"{0}\" z:Id=\"{2}\" xmlns:z=\"{1}\">" +
                "<Children z:Id=\"2\" z:Size=\"1\">" +
                "<Child z:Id=\"3\"><Id>{2}</Id><Parent z:Ref=\"1\" i:nil=\"true\" />" +
                "</Child></Children><Name z:Id=\"4\">{3}</Name></Parent>",
                InstanceNamespace,
                SerializationNamespace,
                sampleId,
                sampleName);

            var child = new Child {
                Id = sampleId
            };
            var parent = new Parent {
                Name = sampleName, Children = new List <Child> {
                    child
                }
            };

            child.Parent = parent;

            var settings = new DataContractSerializerSettings
            {
                PreserveObjectReferences = true
            };
            var formatter = new XmlDataContractSerializerOutputFormatter
            {
                SerializerSettings = settings
            };
            var outputFormatterContext = GetOutputFormatterContext(parent, parent.GetType());

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;

            body.Position = 0;

            var content = new StreamReader(body).ReadToEnd();

            XmlAssert.Equal(expectedOutput, content);
        }
コード例 #21
0
        public void DefaultConstructor_ExpectedWriterSettings_Created()
        {
            // Arrange and Act
            var formatter = new XmlDataContractSerializerOutputFormatter();

            // Assert
            var writerSettings = formatter.WriterSettings;

            Assert.NotNull(writerSettings);
            Assert.True(writerSettings.OmitXmlDeclaration);
            Assert.False(writerSettings.CloseOutput);
            Assert.False(writerSettings.CheckCharacters);
        }
コード例 #22
0
        public static MvcOptions AddCustomOutputFormatters <TJsonOutputFormatter>(this MvcOptions options) where TJsonOutputFormatter : OutputFormatter
        {
            var xmlOutputFormatter = new XmlDataContractSerializerOutputFormatter();

            options.OutputFormatters.Add(xmlOutputFormatter);
            var jsonOutputFormatter = options.OutputFormatters
                                      .OfType <TJsonOutputFormatter>()
                                      .First();
            var customMediaType = new string[] { };

            customMediaType.Execute(e => jsonOutputFormatter.SupportedMediaTypes.Add(e));
            return(options);
        }
コード例 #23
0
        public void CanWriteResult_ReturnsExpectedValueForObjectType(object input, Type declaredType, bool expectedOutput)
        {
            // Arrange
            var formatter = new XmlDataContractSerializerOutputFormatter();
            var outputFormatterContext = GetOutputFormatterContext(input, declaredType);

            outputFormatterContext.ContentType = new StringSegment("application/xml");

            // Act
            var result = formatter.CanWriteResult(outputFormatterContext);

            // Assert
            Assert.Equal(expectedOutput, result);
        }
コード例 #24
0
        public async Task VerifyBodyIsNotClosedAfterOutputIsWritten()
        {
            // Arrange
            var sampleInput = new DummyClass {
                SampleInt = 10
            };
            var formatter = new XmlDataContractSerializerOutputFormatter();
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            Assert.NotNull(outputFormatterContext.ActionContext.HttpContext.Response.Body);
            Assert.True(outputFormatterContext.ActionContext.HttpContext.Response.Body.CanRead);
        }
コード例 #25
0
        public async Task WriteAsync_DoesntFlushOutputStream()
        {
            // Arrange
            var sampleInput = new DummyClass {
                SampleInt = 10
            };
            var formatter = new XmlDataContractSerializerOutputFormatter();
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());

            var response = outputFormatterContext.HttpContext.Response;

            response.Body = FlushReportingStream.GetThrowingStream();

            // Act & Assert
            await formatter.WriteAsync(outputFormatterContext);
        }
コード例 #26
0
        public async Task XmlDataContractSerializerOutputFormatterCanWriteBasicTypes(object input, string expectedOutput)
        {
            // Arrange
            var formatter = new XmlDataContractSerializerOutputFormatter();
            var outputFormatterContext = GetOutputFormatterContext(input, typeof(object));

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            Assert.NotNull(outputFormatterContext.ActionContext.HttpContext.Response.Body);
            outputFormatterContext.ActionContext.HttpContext.Response.Body.Position = 0;
            Assert.Equal(expectedOutput,
                         new StreamReader(outputFormatterContext.ActionContext.HttpContext.Response.Body, Encoding.UTF8)
                         .ReadToEnd());
            Assert.True(outputFormatterContext.ActionContext.HttpContext.Response.Body.CanRead);
        }
コード例 #27
0
        public async Task WriteAsync_WritesWhenConfiguredWithKnownTypes()
        {
            // Arrange
            var sampleInt         = 10;
            var sampleString      = "TestString";
            var KnownTypeName     = "SomeDummyClass";
            var InstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";

            var expectedOutput = string.Format(
                CultureInfo.InvariantCulture,
                "<DummyClass xmlns:i=\"{1}\" xmlns=\"\" i:type=\"{0}\"><SampleInt>{2}</SampleInt>"
                + "<SampleString>{3}</SampleString></DummyClass>",
                KnownTypeName,
                InstanceNamespace,
                sampleInt,
                sampleString);

            var sampleInput = new SomeDummyClass
            {
                SampleInt    = sampleInt,
                SampleString = sampleString
            };

            var settings = new DataContractSerializerSettings
            {
                KnownTypes = new[] { typeof(SomeDummyClass) }
            };
            var formatter = new XmlDataContractSerializerOutputFormatter
            {
                SerializerSettings = settings
            };
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, typeof(DummyClass));

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;

            body.Position = 0;

            var content = new StreamReader(body).ReadToEnd();

            XmlAssert.Equal(expectedOutput, content);
        }
コード例 #28
0
        public void CannotCreateSerializer_LogsWarning(
            XmlDataContractSerializerOutputFormatter formatter,
            TestSink sink)
        {
            // Arrange
            var outputFormatterContext = GetOutputFormatterContext(new Customer(10), typeof(Customer));

            // Act
            var result = formatter.CanWriteResult(outputFormatterContext);

            // Assert
            Assert.False(result);
            var write = Assert.Single(sink.Writes);

            Assert.Equal(LogLevel.Warning, write.LogLevel);
            Assert.Equal($"An error occurred while trying to create a DataContractSerializer for the type '{typeof(Customer).FullName}'.",
                         write.State.ToString());
        }
コード例 #29
0
        public async Task WriteAsync_CanWriteBasicTypes(object input, string expectedOutput)
        {
            // Arrange
            var formatter = new XmlDataContractSerializerOutputFormatter();
            var outputFormatterContext = GetOutputFormatterContext(input, input.GetType());

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;

            body.Position = 0;

            var content = new StreamReader(body).ReadToEnd();

            XmlAssert.Equal(expectedOutput, content);
        }
コード例 #30
0
        public async Task WriteAsync_WritesWhenConfiguredWithRootName()
        {
            // Arrange
            var sampleInt               = 10;
            var SubstituteRootName      = "SomeOtherClass";
            var SubstituteRootNamespace = "http://tempuri.org";
            var InstanceNamespace       = "http://www.w3.org/2001/XMLSchema-instance";

            var expectedOutput = string.Format(
                CultureInfo.InvariantCulture,
                "<{0} xmlns:i=\"{2}\" xmlns=\"{1}\"><SampleInt xmlns=\"\">{3}</SampleInt></{0}>",
                SubstituteRootName,
                SubstituteRootNamespace,
                InstanceNamespace,
                sampleInt);

            var sampleInput = new DummyClass {
                SampleInt = sampleInt
            };

            var dictionary = new XmlDictionary();
            var settings   = new DataContractSerializerSettings
            {
                RootName      = dictionary.Add(SubstituteRootName),
                RootNamespace = dictionary.Add(SubstituteRootNamespace)
            };
            var formatter = new XmlDataContractSerializerOutputFormatter
            {
                SerializerSettings = settings
            };
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;

            body.Position = 0;

            var content = new StreamReader(body).ReadToEnd();

            XmlAssert.Equal(expectedOutput, content);
        }
コード例 #31
0
        public async Task WriteAsync_SerializesObjectWhenDeclaredTypeIsDifferentFromActualType()
        {
            // Arrange
            var expected = @"<DummyClass xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns="""" " +
                @"i:type=""SomeDummyClass""><SampleInt>1</SampleInt><SampleString>Test</SampleString></DummyClass>";
            var sampleInput = new SomeDummyClass { SampleInt = 1, SampleString = "Test" };
            var formatter = new XmlDataContractSerializerOutputFormatter();
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, typeof(DummyClass));

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;
            body.Position = 0;
            var actual = new StreamReader(body).ReadToEnd();
            XmlAssert.Equal(expected, actual);
        }
コード例 #32
0
        public async Task WriteAsync_WritesOnModifiedWriterSettings()
        {
            // Arrange
            var expectedOutput =
                "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<DummyClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                "<SampleInt>10</SampleInt></DummyClass>";

            var sampleInput = new DummyClass { SampleInt = 10 };
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());
            var formatter = new XmlDataContractSerializerOutputFormatter(
                new XmlWriterSettings
                {
                    OmitXmlDeclaration = false,
                    CloseOutput = false
                });

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;
            body.Position = 0;

            var content = new StreamReader(body).ReadToEnd();
            XmlAssert.Equal(expectedOutput, content);
        }
コード例 #33
0
        public async Task WriteAsync_WritesWhenConfiguredWithRootName()
        {
            // Arrange
            var sampleInt = 10;
            var SubstituteRootName = "SomeOtherClass";
            var SubstituteRootNamespace = "http://tempuri.org";
            var InstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";

            var expectedOutput = string.Format(
                "<{0} xmlns:i=\"{2}\" xmlns=\"{1}\"><SampleInt xmlns=\"\">{3}</SampleInt></{0}>",
                SubstituteRootName,
                SubstituteRootNamespace,
                InstanceNamespace,
                sampleInt);

            var sampleInput = new DummyClass { SampleInt = sampleInt };

            var dictionary = new XmlDictionary();
            var settings = new DataContractSerializerSettings
            {
                RootName = dictionary.Add(SubstituteRootName),
                RootNamespace = dictionary.Add(SubstituteRootNamespace)
            };
            var formatter = new XmlDataContractSerializerOutputFormatter
            {
                SerializerSettings = settings
            };
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;
            body.Position = 0;

            var content = new StreamReader(body).ReadToEnd();
            XmlAssert.Equal(expectedOutput, content);
        }
コード例 #34
0
        public async Task WriteAsync_ThrowsWhenNotConfiguredWithPreserveReferences()
        {
            // Arrange
            var child = new Child { Id = 1 };
            var parent = new Parent { Name = "Parent", Children = new List<Child> { child } };
            child.Parent = parent;

            var formatter = new XmlDataContractSerializerOutputFormatter();
            var outputFormatterContext = GetOutputFormatterContext(parent, parent.GetType());

            // Act & Assert
            await Assert.ThrowsAsync(typeof(SerializationException),
                async () => await formatter.WriteAsync(outputFormatterContext));
        }
コード例 #35
0
        public async Task WriteAsync_CanWriteBasicTypes(object input, string expectedOutput)
        {
            // Arrange
            var formatter = new XmlDataContractSerializerOutputFormatter();
            var outputFormatterContext = GetOutputFormatterContext(input, input.GetType());

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;
            body.Position = 0;

            var content = new StreamReader(body).ReadToEnd();
            XmlAssert.Equal(expectedOutput, content);
        }
コード例 #36
0
        public async Task WriteAsync_WritesWhenConfiguredWithKnownTypes()
        {
            // Arrange
            var sampleInt = 10;
            var sampleString = "TestString";
            var KnownTypeName = "SomeDummyClass";
            var InstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";

            var expectedOutput = string.Format(
                    "<DummyClass xmlns:i=\"{1}\" xmlns=\"\" i:type=\"{0}\"><SampleInt>{2}</SampleInt>"
                    + "<SampleString>{3}</SampleString></DummyClass>",
                    KnownTypeName,
                    InstanceNamespace,
                    sampleInt,
                    sampleString);

            var sampleInput = new SomeDummyClass
            {
                SampleInt = sampleInt,
                SampleString = sampleString
            };

            var settings = new DataContractSerializerSettings
            {
                KnownTypes = new[] { typeof(SomeDummyClass) }
            };
            var formatter = new XmlDataContractSerializerOutputFormatter
            {
                SerializerSettings = settings
            };
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, typeof(DummyClass));

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;
            body.Position = 0;

            var content = new StreamReader(body).ReadToEnd();
            XmlAssert.Equal(expectedOutput, content);
        }
コード例 #37
0
        public async Task WriteAsync_DoesntFlushOutputStream()
        {
            // Arrange
            var sampleInput = new DummyClass { SampleInt = 10 };
            var formatter = new XmlDataContractSerializerOutputFormatter();
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());

            var response = outputFormatterContext.HttpContext.Response;
            response.Body = FlushReportingStream.GetThrowingStream();

            // Act & Assert
            await formatter.WriteAsync(outputFormatterContext);
        }
コード例 #38
0
        public void CanWriteResult_ReturnsExpectedOutput(object input, Type declaredType, bool expectedOutput)
        {
            // Arrange
            var formatter = new XmlDataContractSerializerOutputFormatter();
            var outputFormatterContext = GetOutputFormatterContext(input, declaredType);
            outputFormatterContext.ContentType = new StringSegment("application/xml");

            // Act
            var result = formatter.CanWriteResult(outputFormatterContext);

            // Assert
            Assert.Equal(expectedOutput, result);
        }
コード例 #39
0
        public async Task WriteAsync_VerifyBodyIsNotClosedAfterOutputIsWritten()
        {
            // Arrange
            var sampleInput = new DummyClass { SampleInt = 10 };
            var formatter = new XmlDataContractSerializerOutputFormatter();
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;
            Assert.True(body.CanRead);
        }
コード例 #40
0
        public void DefaultConstructor_ExpectedWriterSettings_Created()
        {
            // Arrange and Act
            var formatter = new XmlDataContractSerializerOutputFormatter();

            // Assert
            var writerSettings = formatter.WriterSettings;
            Assert.NotNull(writerSettings);
            Assert.True(writerSettings.OmitXmlDeclaration);
            Assert.False(writerSettings.CloseOutput);
            Assert.False(writerSettings.CheckCharacters);
        }
コード例 #41
0
        public async Task WriteAsync_ThrowsWhenNotConfiguredWithKnownTypes()
        {
            // Arrange
            var sampleInput = new SomeDummyClass { SampleInt = 1, SampleString = "TestString" };
            var formatter = new XmlDataContractSerializerOutputFormatter();
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, typeof(DummyClass));

            // Act & Assert
            await Assert.ThrowsAsync(typeof(SerializationException),
                async () => await formatter.WriteAsync(outputFormatterContext));
        }
コード例 #42
0
        public async Task WriteAsync_WritesIndentedOutput()
        {
            // Arrange
            var expectedOutput =
                "<DummyClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                "\r\n  <SampleInt>10</SampleInt>\r\n</DummyClass>";

            var sampleInput = new DummyClass { SampleInt = 10 };
            var formatter = new XmlDataContractSerializerOutputFormatter();
            formatter.WriterSettings.Indent = true;
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;
            body.Position = 0;

            var content = new StreamReader(body).ReadToEnd();
            XmlAssert.Equal(expectedOutput, content);
        }
コード例 #43
0
        public async Task WriteAsync_WritesUTF16Output()
        {
            // Arrange
            var expectedOutput =
                "<?xml version=\"1.0\" encoding=\"utf-16\"?>" +
                "<DummyClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                "<SampleInt>10</SampleInt></DummyClass>";

            var sampleInput = new DummyClass { SampleInt = 10 };
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType(),
                "application/xml; charset=utf-16");
            var formatter = new XmlDataContractSerializerOutputFormatter();
            formatter.WriterSettings.OmitXmlDeclaration = false;

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;
            body.Position = 0;

            var content = new StreamReader(
                body,
                new UnicodeEncoding(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: true)).ReadToEnd();
            XmlAssert.Equal(expectedOutput, content);
        }
コード例 #44
0
        public async Task WriteAsync_WritesComplexTypes()
        {
            // Arrange
            var expectedOutput =
                "<TestLevelTwo xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                "<SampleString>TestString</SampleString>" +
                "<TestOne><SampleInt>10</SampleInt><sampleString>TestLevelOne string</sampleString>" +
                "</TestOne></TestLevelTwo>";

            var sampleInput = new TestLevelTwo
            {
                SampleString = "TestString",
                TestOne = new TestLevelOne
                {
                    SampleInt = 10,
                    sampleString = "TestLevelOne string"
                }
            };
            var formatter = new XmlDataContractSerializerOutputFormatter();
            var outputFormatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;
            body.Position = 0;

            var content = new StreamReader(body).ReadToEnd();
            XmlAssert.Equal(expectedOutput, content);
        }
コード例 #45
0
        public async Task SuppliedWriterSettings_TakeAffect()
        {
            // Arrange
            var writerSettings = FormattingUtilities.GetDefaultXmlWriterSettings();
            writerSettings.OmitXmlDeclaration = false;
            var sampleInput = new DummyClass { SampleInt = 10 };
            var formatterContext = GetOutputFormatterContext(sampleInput, sampleInput.GetType());
            var formatter = new XmlDataContractSerializerOutputFormatter(writerSettings);
            var expectedOutput = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                "<DummyClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                                "<SampleInt>10</SampleInt></DummyClass>";

            // Act
            await formatter.WriteAsync(formatterContext);

            // Assert
            Assert.Same(writerSettings, formatter.WriterSettings);

            var body = formatterContext.HttpContext.Response.Body;
            body.Position = 0;

            var content = new StreamReader(body).ReadToEnd();
            XmlAssert.Equal(expectedOutput, content);
        }
コード例 #46
0
        public async Task WriteAsync_WritesWhenConfiguredWithPreserveReferences()
        {
            // Arrange
            var sampleId = 1;
            var sampleName = "Parent";
            var InstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";
            var SerializationNamespace = "http://schemas.microsoft.com/2003/10/Serialization/";

            var expectedOutput = string.Format(
                    "<Parent xmlns:i=\"{0}\" z:Id=\"{2}\" xmlns:z=\"{1}\">" +
                    "<Children z:Id=\"2\" z:Size=\"1\">" +
                    "<Child z:Id=\"3\"><Id>{2}</Id><Parent z:Ref=\"1\" i:nil=\"true\" />" +
                    "</Child></Children><Name z:Id=\"4\">{3}</Name></Parent>",
                    InstanceNamespace,
                    SerializationNamespace,
                    sampleId,
                    sampleName);

            var child = new Child { Id = sampleId };
            var parent = new Parent { Name = sampleName, Children = new List<Child> { child } };
            child.Parent = parent;

            var settings = new DataContractSerializerSettings
            {
                PreserveObjectReferences = true
            };
            var formatter = new XmlDataContractSerializerOutputFormatter
            {
                SerializerSettings = settings
            };
            var outputFormatterContext = GetOutputFormatterContext(parent, parent.GetType());

            // Act
            await formatter.WriteAsync(outputFormatterContext);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;
            body.Position = 0;

            var content = new StreamReader(body).ReadToEnd();
            XmlAssert.Equal(expectedOutput, content);
        }
コード例 #47
0
        public void GetSupportedContentTypes_ReturnsSupportedTypes(Type type, object expectedOutput)
        {
            // Arrange
            var formatter = new XmlDataContractSerializerOutputFormatter();

            // Act
            var result = formatter.GetSupportedContentTypes(
                "application/xml",
                type);

            // Assert
            if (expectedOutput != null)
            {
                Assert.Equal(expectedOutput, Assert.Single(result).ToString());
            }
            else
            {
                Assert.Equal(expectedOutput, result);
            }
        }