Esempio n. 1
0
        public void TestFullMessageWithRichTypes()
        {
            TestXmlMessage message = TestXmlMessage.CreateBuilder()
                                     .SetValid(true)
                                     .SetText("text")
                                     .AddTextlines("a")
                                     .AddTextlines("b")
                                     .AddTextlines("c")
                                     .SetNumber(0x1010101010)
                                     .AddNumbers(1)
                                     .AddNumbers(2)
                                     .AddNumbers(3)
                                     .SetChild(TestXmlChild.CreateBuilder().AddOptions(EnumOptions.ONE).SetBinary(ByteString.CopyFrom(new byte[1])))
                                     .AddChildren(TestXmlMessage.Types.Children.CreateBuilder().AddOptions(EnumOptions.TWO).SetBinary(ByteString.CopyFrom(new byte[2])))
                                     .AddChildren(TestXmlMessage.Types.Children.CreateBuilder().AddOptions(EnumOptions.THREE).SetBinary(ByteString.CopyFrom(new byte[3])))
                                     .Build();

            StringWriter sw   = new StringWriter();
            XmlWriter    xwtr = XmlWriter.Create(sw, new XmlWriterSettings {
                Indent = true, IndentChars = "  "
            });

            XmlFormatWriter.CreateInstance(xwtr)
            .SetOptions(XmlWriterOptions.OutputNestedArrays | XmlWriterOptions.OutputEnumValues)
            .WriteMessage("root", message);

            string xml = sw.ToString();

            XmlFormatReader rdr = XmlFormatReader.CreateInstance(xml);

            rdr.Options = XmlReaderOptions.ReadNestedArrays;
            TestXmlMessage copy = rdr.Merge(TestXmlMessage.CreateBuilder()).Build();

            Assert.AreEqual(message, copy);
        }
Esempio n. 2
0
        public void TestXmlReadWriteWithoutRoot()
        {
            TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
            TestXmlMessage         message = builder.SetText("abc").SetNumber(123).Build();

            string xml;

            using (StringWriter sw = new StringWriter())
            {
                ICodedOutputStream output = XmlFormatWriter.CreateInstance(
                    XmlWriter.Create(sw, new XmlWriterSettings()
                {
                    ConformanceLevel = ConformanceLevel.Fragment
                }));

                message.WriteTo(output);
                output.Flush();
                xml = sw.ToString();
            }
            Assert.AreEqual("<text>abc</text><number>123</number>", xml);

            TestXmlMessage copy;

            using (XmlReader xr = XmlReader.Create(new StringReader(xml), new XmlReaderSettings()
            {
                ConformanceLevel = ConformanceLevel.Fragment
            }))
            {
                ICodedInputStream input = XmlFormatReader.CreateInstance(xr);
                copy = TestXmlMessage.CreateBuilder().MergeFrom(input).Build();
            }

            Assert.AreEqual(message, copy);
        }
Esempio n. 3
0
        /// <summary>
        /// Writes the message instance to the stream using the content type provided
        /// </summary>
        /// <param name="options">Options specific to writing this message and/or content type</param>
        /// <param name="contentType">The mime type of the content to be written</param>
        /// <param name="output">The stream to write the message to</param>
        /// <remarks> If you do not dispose of ICodedOutputStream some formats may yield incomplete output </remarks>
        public static ICodedOutputStream CreateOutputStream(MessageFormatOptions options, string contentType, Stream output)
        {
            ICodedOutputStream codedOutput = ContentTypeToOutputStream(contentType, options, output);

            if (codedOutput is JsonFormatWriter)
            {
                JsonFormatWriter writer = (JsonFormatWriter)codedOutput;
                if (options.FormattedOutput)
                {
                    writer.Formatted();
                }
            }
            else if (codedOutput is XmlFormatWriter)
            {
                XmlFormatWriter writer = (XmlFormatWriter)codedOutput;
                if (options.FormattedOutput)
                {
                    XmlWriterSettings settings = new XmlWriterSettings()
                    {
                        CheckCharacters    = false,
                        NewLineHandling    = NewLineHandling.Entitize,
                        OmitXmlDeclaration = true,
                        Encoding           = new UTF8Encoding(false),
                        Indent             = true,
                        IndentChars        = "    ",
                    };
                    // Don't know how else to change xml writer options?
                    codedOutput = writer = XmlFormatWriter.CreateInstance(XmlWriter.Create(output, settings));
                }
                writer.RootElementName = options.XmlWriterRootElementName;
                writer.Options         = options.XmlWriterOptions;
            }

            return(codedOutput);
        }
Esempio n. 4
0
        protected override object SerializeMessage <TMessage, TBuilder>(TMessage message)
        {
            StringWriter    text   = new StringWriter();
            XmlFormatWriter writer = XmlFormatWriter.CreateInstance(text);

            writer.WriteMessage("root", message);
            return(text.ToString());
        }
Esempio n. 5
0
        /// <summary>
        /// Serializes the message to XML text using the element name provided.
        /// This is a trivial wrapper around Serialization.XmlFormatWriter.WriteMessage.
        /// </summary>
        public static string ToXml(
#if !NOEXTENSIONS
            this
#endif
            IMessageLite message, string rootElementName)
        {
            StringWriter w = new StringWriter(new StringBuilder(4096));

            XmlFormatWriter.CreateInstance(w).WriteMessage(rootElementName, message);
            return(w.ToString());
        }
Esempio n. 6
0
        protected override object SerializeMessage <TMessage, TBuilder>(TMessage message)
        {
            StringWriter text = new StringWriter();
            XmlWriter    xwtr = XmlWriter.Create(text, new XmlWriterSettings {
                Indent = true, IndentChars = "  "
            });

            XmlFormatWriter writer = XmlFormatWriter.CreateInstance(xwtr).SetOptions(XmlWriterOptions.OutputNestedArrays);

            writer.WriteMessage("root", message);
            return(text.ToString());
        }
Esempio n. 7
0
        public void TestBooleanTypes()
        {
            TestXmlMessage message = TestXmlMessage.CreateBuilder()
                                     .SetValid(true)
                                     .Build();

            StringWriter sw = new StringWriter();

            XmlFormatWriter.CreateInstance(sw).WriteMessage("root", message);

            string          xml  = sw.ToString();
            XmlFormatReader rdr  = XmlFormatReader.CreateInstance(xml);
            TestXmlMessage  copy = rdr.Merge(TestXmlMessage.CreateBuilder()).Build();

            Assert.AreEqual(message, copy);
        }
Esempio n. 8
0
        public void TestNestedMessage()
        {
            TestXmlMessage message = TestXmlMessage.CreateBuilder()
                                     .SetChild(TestXmlChild.CreateBuilder().AddOptions(EnumOptions.TWO).Build())
                                     .Build();

            StringWriter sw = new StringWriter();

            XmlFormatWriter.CreateInstance(sw).WriteMessage("root", message);

            string          xml  = sw.ToString();
            XmlFormatReader rdr  = XmlFormatReader.CreateInstance(xml);
            TestXmlMessage  copy = rdr.Merge(TestXmlMessage.CreateBuilder()).Build();

            Assert.AreEqual(message, copy);
        }
Esempio n. 9
0
        public void TestMessageWithXmlText()
        {
            TestXmlMessage message = TestXmlMessage.CreateBuilder()
                                     .SetText("<text>").Build();

            StringWriter sw = new StringWriter();

            XmlFormatWriter.CreateInstance(sw).WriteMessage("root", message);

            string xml = sw.ToString();

            XmlFormatReader rdr  = XmlFormatReader.CreateInstance(xml);
            TestXmlMessage  copy = rdr.Merge(TestXmlMessage.CreateBuilder()).Build();

            Assert.AreEqual(message, copy);
        }
Esempio n. 10
0
        public void TestXmlWithWhitespace()
        {
            TestXmlMessage message = TestXmlMessage.CreateBuilder()
                                     .SetText(" \t <- leading space and trailing -> \r\n\t").Build();

            StringWriter sw = new StringWriter();

            XmlFormatWriter.CreateInstance(sw).WriteMessage("root", message);

            string xml = sw.ToString();

            XmlFormatReader rdr  = XmlFormatReader.CreateInstance(xml);
            TestXmlMessage  copy = rdr.Merge(TestXmlMessage.CreateBuilder()).Build();

            Assert.AreEqual(message, copy);
        }
Esempio n. 11
0
        public void TestFullMessageWithUnknownFields()
        {
            TestXmlMessage origial = TestXmlMessage.CreateBuilder()
                                     .SetValid(true)
                                     .SetText("text")
                                     .AddTextlines("a")
                                     .AddTextlines("b")
                                     .AddTextlines("c")
                                     .SetNumber(0x1010101010)
                                     .AddNumbers(1)
                                     .AddNumbers(2)
                                     .AddNumbers(3)
                                     .SetChild(TestXmlChild.CreateBuilder().AddOptions(EnumOptions.ONE).SetBinary(ByteString.CopyFrom(new byte[1])))
                                     .AddChildren(TestXmlMessage.Types.Children.CreateBuilder().AddOptions(EnumOptions.TWO).SetBinary(ByteString.CopyFrom(new byte[2])))
                                     .AddChildren(TestXmlMessage.Types.Children.CreateBuilder().AddOptions(EnumOptions.THREE).SetBinary(ByteString.CopyFrom(new byte[3])))
                                     .Build();
            TestXmlNoFields message = TestXmlNoFields.CreateBuilder().MergeFrom(origial.ToByteArray()).Build();

            Assert.AreEqual(0, message.AllFields.Count);

            StringWriter sw = new StringWriter();

            XmlFormatWriter.CreateInstance(sw)
            .SetOptions(XmlWriterOptions.OutputNestedArrays | XmlWriterOptions.OutputEnumValues)
            .WriteMessage("root", message);

            string xml = sw.ToString();

            using (XmlReader x = XmlReader.Create(new StringReader(xml)))
            {
                x.MoveToContent();
                Assert.AreEqual(XmlNodeType.Element, x.NodeType);
                //should always be empty
                Assert.IsTrue(x.IsEmptyElement ||
                              (x.Read() && x.NodeType == XmlNodeType.EndElement)
                              );
            }

            XmlFormatReader rdr = XmlFormatReader.CreateInstance(xml);

            rdr.Options = XmlReaderOptions.ReadNestedArrays;
            TestXmlMessage copy = rdr.Merge(TestXmlMessage.CreateBuilder()).Build();

            Assert.AreEqual(TestXmlMessage.DefaultInstance, copy);
        }
Esempio n. 12
0
        public void TestRepeatedField()
        {
            TestXmlChild message = TestXmlChild.CreateBuilder()
                                   .AddOptions(EnumOptions.ONE)
                                   .AddOptions(EnumOptions.TWO)
                                   .Build();

            //Allow the writer to write the root element
            StringWriter sw = new StringWriter();

            XmlFormatWriter.CreateInstance(sw).WriteMessage("root", message);

            string          xml  = sw.ToString();
            XmlFormatReader rdr  = XmlFormatReader.CreateInstance(xml);
            TestXmlChild    copy = rdr.Merge(TestXmlChild.CreateBuilder()).Build();

            Assert.AreEqual(message, copy);
        }
Esempio n. 13
0
        public void Example_WriteXmlUsingICodedOutputStream()
        {
            TestXmlMessage message =
                TestXmlMessage.CreateBuilder()
                .SetValid(true)
                .Build();

            using (TextWriter output = new StringWriter())
            {
                ICodedOutputStream writer = XmlFormatWriter.CreateInstance(output);
                writer.WriteMessageStart();      //manually begin the message, output is '{'

                ICodedOutputStream stream = writer;
                message.WriteTo(stream);         //write the message normally

                writer.WriteMessageEnd();        //manually write the end message '}'
                Assert.AreEqual(@"<root><valid>true</valid></root>", output.ToString());
            }
        }
Esempio n. 14
0
        public void TestEmptyMessage()
        {
            TestXmlChild message = TestXmlChild.CreateBuilder()
                                   .Build();

            StringWriter sw = new StringWriter();
            XmlWriter    xw = XmlWriter.Create(sw);

            //When we call message.WriteTo, we are responsible for the root element
            xw.WriteStartElement("root");
            message.WriteTo(XmlFormatWriter.CreateInstance(xw));
            xw.WriteEndElement();
            xw.Flush();

            string          xml  = sw.ToString();
            XmlFormatReader rdr  = XmlFormatReader.CreateInstance(xml);
            TestXmlChild    copy = rdr.Merge(TestXmlChild.CreateBuilder()).Build();

            Assert.AreEqual(message, copy);
        }
        public void TestXmlWithExtensionMessage()
        {
            TestXmlMessage message = TestXmlMessage.CreateBuilder()
                                     .SetExtension(UnitTestXmlSerializerTestProtoFile.ExtensionMessage,
                                                   new TestXmlExtension.Builder().SetNumber(42).Build()).Build();

            StringWriter sw = new StringWriter();

            XmlFormatWriter.CreateInstance(sw).WriteMessage("root", message);

            string xml = sw.ToString();

            ExtensionRegistry registry = ExtensionRegistry.CreateInstance();

            UnitTestXmlSerializerTestProtoFile.RegisterAllExtensions(registry);

            XmlFormatReader rdr  = XmlFormatReader.CreateInstance(xml);
            TestXmlMessage  copy = rdr.Merge(TestXmlMessage.CreateBuilder(), registry).Build();

            Assert.AreEqual(message, copy);
        }
Esempio n. 16
0
        public void TestXmlWithExtensionEnum()
        {
            TestXmlMessage message = TestXmlMessage.CreateBuilder()
                                     .SetExtension(UnittestExtrasXmltest.ExtensionEnum, EnumOptions.ONE)
                                     .Build();

            StringWriter sw = new StringWriter();

            XmlFormatWriter.CreateInstance(sw).WriteMessage("root", message);

            string xml = sw.ToString();

            ExtensionRegistry registry = ExtensionRegistry.CreateInstance();

            UnittestExtrasXmltest.RegisterAllExtensions(registry);

            XmlFormatReader rdr  = XmlFormatReader.CreateInstance(xml);
            TestXmlMessage  copy = rdr.Merge(TestXmlMessage.CreateBuilder(), registry).Build();

            Assert.AreEqual(message, copy);
        }
Esempio n. 17
0
        public void TestXmlReaderOptions()
        {
            MemoryStream ms = new MemoryStream();

            XmlFormatWriter.CreateInstance(ms)
            .SetOptions(XmlWriterOptions.OutputNestedArrays)
            .WriteMessage("my-root-node", TestXmlMessage.CreateBuilder().SetText("a").AddNumbers(1).AddNumbers(2).Build());
            ms.Position = 0;

            MessageFormatOptions options = new MessageFormatOptions()
            {
                XmlReaderOptions         = XmlReaderOptions.ReadNestedArrays,
                XmlReaderRootElementName = "my-root-node"
            };

            TestXmlMessage msg = Extensions.MergeFrom(new TestXmlMessage.Builder(),
                                                      options, "application/xml", ms)
                                 .Build();

            Assert.AreEqual("a", msg.Text);
            Assert.AreEqual(1, msg.NumbersList[0]);
            Assert.AreEqual(2, msg.NumbersList[1]);
        }
Esempio n. 18
0
        /// <summary>
        /// Runs a single test. Error messages are displayed to Console.Error, and the return value indicates
        /// general success/failure.
        /// </summary>
        public static bool RunTest(string typeName, string file, byte[] inputData)
        {
            WriteLine("Benchmarking {0} with file {1}", typeName, file);
            IMessage defaultMessage;

            try
            {
                defaultMessage = MessageUtil.GetDefaultMessage(typeName);
            }
            catch (ArgumentException e)
            {
                Console.Error.WriteLine(e.Message);
                return(false);
            }
            try
            {
                ExtensionRegistry registry = ExtensionRegistry.Empty;
                inputData = inputData ?? File.ReadAllBytes(file);
                MemoryStream inputStream   = new MemoryStream(inputData);
                ByteString   inputString   = ByteString.CopyFrom(inputData);
                IMessage     sampleMessage =
                    defaultMessage.WeakCreateBuilderForType().WeakMergeFrom(inputString, registry).WeakBuild();

                IDictionary <string, object> dictionary = null;
                byte[] jsonBytes = null, xmlBytes = null; /*no pun intended, well... maybe for xml*/
                if (OtherFormats)
                {
                    using (MemoryStream temp = new MemoryStream())
                    {
                        XmlFormatWriter.CreateInstance(temp).WriteMessage(sampleMessage);
                        xmlBytes = temp.ToArray();
                    }
                    using (MemoryStream temp = new MemoryStream())
                    {
                        JsonFormatWriter.CreateInstance(temp).WriteMessage(sampleMessage);
                        jsonBytes = temp.ToArray();
                    }
                    dictionary = new Dictionary <string, object>(StringComparer.Ordinal);
                    new DictionaryWriter(dictionary).WriteMessage(sampleMessage);
                }

                //Serializers
                if (!FastTest)
                {
                    RunBenchmark("Serialize to byte string", inputData.Length, () => sampleMessage.ToByteString());
                }
                RunBenchmark("Serialize to byte array", inputData.Length, () => sampleMessage.ToByteArray());
                if (!FastTest)
                {
                    RunBenchmark("Serialize to memory stream", inputData.Length,
                                 () => sampleMessage.WriteTo(new MemoryStream()));
                }

                if (OtherFormats)
                {
                    RunBenchmark("Serialize to xml", xmlBytes.Length,
                                 () =>
                    {
                        XmlFormatWriter.CreateInstance(new MemoryStream(), Encoding.UTF8).WriteMessage(sampleMessage);
                    });
                    RunBenchmark("Serialize to json", jsonBytes.Length,
                                 () => { JsonFormatWriter.CreateInstance().WriteMessage(sampleMessage); });
                    RunBenchmark("Serialize to json via xml", jsonBytes.Length,
                                 () =>
                                 XmlFormatWriter.CreateInstance(
                                     JsonReaderWriterFactory.CreateJsonWriter(new MemoryStream(), Encoding.UTF8))
                                 .SetOptions(XmlWriterOptions.OutputJsonTypes)
                                 .WriteMessage(sampleMessage)
                                 );

                    RunBenchmark("Serialize to dictionary", sampleMessage.SerializedSize,
                                 () => new DictionaryWriter().WriteMessage(sampleMessage));
                }
                //Deserializers
                if (!FastTest)
                {
                    RunBenchmark("Deserialize from byte string", inputData.Length,
                                 () => defaultMessage.WeakCreateBuilderForType()
                                 .WeakMergeFrom(inputString, registry)
                                 .WeakBuild()
                                 );
                }

                RunBenchmark("Deserialize from byte array", inputData.Length,
                             () => defaultMessage.WeakCreateBuilderForType()
                             .WeakMergeFrom(CodedInputStream.CreateInstance(inputData), registry)
                             .WeakBuild()
                             );
                if (!FastTest)
                {
                    RunBenchmark("Deserialize from memory stream", inputData.Length,
                                 () =>
                    {
                        inputStream.Position = 0;
                        defaultMessage.WeakCreateBuilderForType().WeakMergeFrom(
                            CodedInputStream.CreateInstance(inputStream), registry)
                        .WeakBuild();
                    });
                }

                if (OtherFormats)
                {
                    RunBenchmark("Deserialize from xml", xmlBytes.Length,
                                 () =>
                                 XmlFormatReader.CreateInstance(xmlBytes).Merge(
                                     defaultMessage.WeakCreateBuilderForType()).WeakBuild());
                    RunBenchmark("Deserialize from json", jsonBytes.Length,
                                 () =>
                                 JsonFormatReader.CreateInstance(jsonBytes).Merge(
                                     defaultMessage.WeakCreateBuilderForType()).WeakBuild());
                    RunBenchmark("Deserialize from json via xml", jsonBytes.Length,
                                 () =>
                                 XmlFormatReader.CreateInstance(JsonReaderWriterFactory.CreateJsonReader(jsonBytes, XmlDictionaryReaderQuotas.Max))
                                 .SetOptions(XmlReaderOptions.ReadNestedArrays).Merge(
                                     defaultMessage.WeakCreateBuilderForType()).WeakBuild());

                    RunBenchmark("Deserialize from dictionary", sampleMessage.SerializedSize,
                                 () =>
                                 new DictionaryReader(dictionary).Merge(defaultMessage.WeakCreateBuilderForType()).
                                 WeakBuild());
                }
                WriteLine(String.Empty);
                return(true);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error: {0}", e.Message);
                Console.Error.WriteLine();
                Console.Error.WriteLine("Detailed exception information: {0}", e);
                return(false);
            }
        }