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()); }
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); }
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); }
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()); }
/// <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")); }
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); }
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(); }
// 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(); }
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); }
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); }
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); }
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()); }
// 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"); }); }
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"))); }
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)); }
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); }
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); }
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)); }
// 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()); }); }
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); }
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); }
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); }
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); }
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); }
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); }
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); }
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); }
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()); }
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); }
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); }
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); }
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); }
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)); }
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); }
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); }
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); }
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)); }
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); }
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); }
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); } }