예제 #1
0
        /// <summary>
        /// Asserts that the results of an XSL transform on some XML are the expected result
        /// </summary>
        /// <param name="xslTransform">The XSL transform.</param>
        /// <param name="xmlToTransform">The XML to transform.</param>
        /// <param name="expectedResult">The expected result.</param>
        public static void XslTransformResults(XmlInput xslTransform, XmlInput xmlToTransform, XmlInput expectedResult)
        {
            Xslt      xslt   = new Xslt(xslTransform);
            XmlOutput output = xslt.Transform(xmlToTransform);

            XmlEquals(expectedResult, output.AsXml());
        }
예제 #2
0
        [Test] public void StringInputTranslatesToXmlReader()
        {
            XmlInput input  = new XmlInput(INPUT);
            string   actual = ReadOuterXml(input.CreateXmlReader());

            Assertion.AssertEquals(_expected, actual);
        }
예제 #3
0
        public override bool Execute()
        {
            XmlInput       xmlInput       = new XmlInput(XmlInputPaths, XmlContent);
            XslInput       xslInput       = new XslInput(XslInputPaths, XslContent);
            ParameterInput parameterInput = new ParameterInput(ParameterPaths, ParameterContents);
            Output         output         = new Output(OutputPaths);

            int maxCount = 0;

            maxCount = Math.Max(maxCount, xmlInput.Count);
            maxCount = Math.Max(maxCount, xslInput.Count);
            maxCount = Math.Max(maxCount, parameterInput.Count);
            maxCount = Math.Max(maxCount, output.Count);

            for (int i = 0; i < maxCount; i++)
            {
                XslCompiledTransform transform = xslInput.CreateTransform(Math.Min(xslInput.Count - 1, i));

                using (XmlWriter writer = output.CreateWriter(Math.Min(output.Count - 1, i), transform.OutputSettings))
                    using (XmlReader reader = xmlInput.CreateReader(Math.Min(xmlInput.Count - 1, i)))
                        transform.Transform(reader, parameterInput.CreateArgumentList(Math.Min(parameterInput.Count - 1, i)), writer);
            }

            OutputContent = output.Content.ToString();
            return(true);
        }
예제 #4
0
        public void Load()
        {
            UndoMgr undomgr = new UndoMgr(5);
            ObjectStore <TestObject> objstore = new ObjectStore <TestObject>(undomgr);

            string xmlText =
                @"<?xml version=""1.0"" encoding=""utf-16""?>
<testobjects>
  <testobject id=""2"" x=""8"" f=""9.4"">goodbye</testobject>
  <testobject id=""3"" x=""9"" f=""9.9"">bat</testobject>
  <testobject id=""4"" x=""11"" f=""1.4"">foo</testobject>
</testobjects>";

            XmlInput xmlinput = new XmlInput(new StringReader(xmlText), "testfile");

            xmlinput.CheckElement("testobjects");
            xmlinput.Read();

            objstore.Load(xmlinput);
            xmlinput.Dispose();

            TestUtil.TestEnumerableAnyOrder(objstore.AllPairs,
                                            new KeyValuePair <Id <TestObject>, TestObject>[] {
                new KeyValuePair <Id <TestObject>, TestObject>(new Id <TestObject>(3), new TestObject(9, "bat", 9.9F)),
                new KeyValuePair <Id <TestObject>, TestObject>(new Id <TestObject>(4), new TestObject(11, "foo", 1.4F)),
                new KeyValuePair <Id <TestObject>, TestObject>(new Id <TestObject>(2), new TestObject(8, "goodbye", 9.4F))
            });
        }
예제 #5
0
        /// <summary>
        /// Asserts that the flattened String obtained by executing an Xpath on some XML is a particular value
        /// </summary>
        /// <param name="anXPathExpression">An X path expression.</param>
        /// <param name="inXml">The XML to test.</param>
        /// <param name="expectedValue">The expected value.</param>
        public static void XPathEvaluatesTo(string anXPathExpression, XmlInput inXml,
                                            string expectedValue)
        {
            XPath xpath = new XPath(anXPathExpression);

            OldAssert.AreEqual(expectedValue, xpath.EvaluateXPath(inXml));
        }
예제 #6
0
        public void TestXPointerIndentationBug()
        {
            XmlUrlResolver resolver = new XmlUrlResolver();

            resolver.Credentials = CredentialCache.DefaultCredentials;
            XsltSettings xsltSettings = new XsltSettings();

            xsltSettings.EnableDocumentFunction = true;
            XmlReaderSettings settings = new XmlReaderSettings();

            settings.ProhibitDtd = false;
            XmlReader        reader       = XmlReader.Create("../../XInclude/tests/Transform.xsl", settings);
            XIncludingReader xInputReader = new XIncludingReader("../../XInclude/tests/FileA.xml");

            try
            {
                MvpXslTransform processor = new MvpXslTransform(false);
                processor.Load(reader, xsltSettings, resolver);
                //xInputReader.XmlResolver = new XMLBase();
                XmlDocument xInputDoc = new XmlDocument();
                xInputDoc.Load(xInputReader);
                XmlInput     xInput  = new XmlInput(xInputDoc);
                StringWriter stringW = new StringWriter();
                XmlOutput    xOutput = new XmlOutput(stringW);
                processor.Transform(xInput, null, xOutput);
                processor.TemporaryFiles.Delete();
                Assert.AreEqual("<?xml version=\"1.0\" encoding=\"utf-16\"?>NodeA Content", stringW.ToString());
            }
            finally
            {
                reader.Close();
                xInputReader.Close();
            }
        }
예제 #7
0
        [Test] public void TextReaderInputTranslatesToXmlReader()
        {
            XmlInput input  = new XmlInput(new StringReader(INPUT));
            string   actual = ReadOuterXml(input.CreateXmlReader());

            Assert.AreEqual(_expected, actual);
        }
예제 #8
0
        /// <summary>
        /// Asserts that the results of an XSL transform on some XML are the expected result
        /// </summary>
        /// <param name="xslTransform">The XSL transform.</param>
        /// <param name="xmlToTransform">The XML to transform.</param>
        /// <param name="expectedResult">The expected result.</param>
        public static void XslTransformResults(string xslTransform, string xmlToTransform, string expectedResult)
        {
            XmlInput xsl   = new XmlInput(xslTransform);
            XmlInput xml2  = new XmlInput(xmlToTransform);
            XmlInput xmlEx = new XmlInput(expectedResult);

            XslTransformResults(xsl, xml2, xmlEx);
        }
예제 #9
0
        public void TestTextReaderInput()
        {
            MvpXslTransform xslt  = GetMvpXslTransform();
            XmlInput        input = new XmlInput(new StreamReader("../../../Common/northwind.xml", Encoding.GetEncoding("windows-1252")));
            MemoryStream    ms    = new MemoryStream();

            xslt.Transform(input, Arguments, new XmlOutput(ms));
            CompareResults(standardResult, ms.ToArray());
        }
예제 #10
0
        public void TestXmlReaderInput()
        {
            MvpXslTransform xslt  = GetMvpXslTransform();
            XmlInput        input = new XmlInput(XmlReader.Create("../../../Common/northwind.xml"));
            MemoryStream    ms    = new MemoryStream();

            xslt.Transform(input, Arguments, new XmlOutput(ms));
            CompareResults(standardResult, ms.ToArray());
        }
예제 #11
0
        public void TestIXPathNavigableInput()
        {
            MvpXslTransform xslt  = GetMvpXslTransform();
            XmlInput        input = new XmlInput(new XPathDocument("../../../Common/northwind.xml", XmlSpace.Preserve));
            MemoryStream    ms    = new MemoryStream();

            xslt.Transform(input, Arguments, new XmlOutput(ms));
            CompareResults(standardResult, ms.ToArray());
        }
예제 #12
0
        public void ResolverTestIXPathNavigableInput()
        {
            MvpXslTransform xslt  = GetMvpXslTransform2();
            XmlInput        input = new XmlInput(new XPathDocument("../../../Common/MvpXslTransformTests/test.xml"), new MyXmlResolver());
            MemoryStream    ms    = new MemoryStream();

            xslt.Transform(input, Arguments, new XmlOutput(ms));
            CompareResults(resolverTestStandardResult, ms.ToArray());
        }
예제 #13
0
        public void CompareExpectedXMLs()
        {
            Dictionary <string, string> expected = new Dictionary <string, string>();
            Dictionary <string, string> actual   = new Dictionary <string, string>();

            RunReport(mValidTrxFile);

            XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(new NameTable());

            xmlNamespaceManager.AddNamespace("prefix", "urn:model.allure.qatools.yandex.ru");

            DiffConfiguration diffConfiguration = new DiffConfiguration(String.Empty, false, WhitespaceHandling.None, true);

            FillCategoryToXmlMap("sample-output", expected);
            FillCategoryToXmlMap(mTargetDir, actual);

            if (expected.Keys.Count != actual.Keys.Count)
            {
                Assert.Fail("Expected {0} categories but found {1}.", expected.Keys.Count, actual.Keys.Count);
            }

            foreach (string category in actual.Keys)
            {
                if (!expected.ContainsKey(category))
                {
                    Assert.Fail("The category " + category + " was not expected.");
                }

                string expectedFile = expected[category];
                string actualFile   = actual[category];

                string expectedFileText = File.ReadAllText(expectedFile);
                string actualFileText   = File.ReadAllText(actualFile);

                XmlInput control = new XmlInput(expectedFileText);
                XmlInput test    = new XmlInput(actualFileText);

                XmlDiff xmlDiff = new XmlDiff(control, test, diffConfiguration);

                DiffResult diffResult = xmlDiff.Compare();
                if (!diffResult.Identical)
                {
                    string failureMessage = String.Format("The expected file {0} was different from the actual file {1}", expectedFile, actualFile);
                    failureMessage += Environment.NewLine;
                    failureMessage += "Expected XML: ";
                    failureMessage += expectedFileText;
                    failureMessage += Environment.NewLine;
                    failureMessage += "Actual XML: ";
                    failureMessage += actualFileText;
                    failureMessage += Environment.NewLine;
                    failureMessage += "Difference: ";
                    failureMessage += diffResult.Difference;

                    Assert.Fail(failureMessage);
                }
            }
        }
예제 #14
0
        public void LoadModifySave()
        {
            Id <TestObject>          id;
            UndoMgr                  undomgr  = new UndoMgr(5);
            ObjectStore <TestObject> objstore = new ObjectStore <TestObject>(undomgr);

            string xmlText =
                @"<?xml version=""1.0"" encoding=""utf-16""?>
<testobjects>
  <testobject id=""2"" x=""8"" f=""9.4"">goodbye</testobject>
  <testobject id=""4"" x=""11"" f=""1.4"">foo</testobject>
</testobjects>";

            XmlInput xmlinput = new XmlInput(new StringReader(xmlText), "testfile");

            xmlinput.CheckElement("testobjects");
            xmlinput.Read();

            objstore.Load(xmlinput);
            xmlinput.Dispose();

            undomgr.BeginCommand(57, "Command1");
            id = objstore.Add(new TestObject(5, "hello", 5.4F));
            Assert.AreEqual(5, id.id);
            id = objstore.Add(new TestObject(9, "bat", 9.9F));
            Assert.AreEqual(6, id.id);
            undomgr.EndCommand(57);

            undomgr.BeginCommand(58, "Command2");
            objstore.Replace(new Id <TestObject>(2), new TestObject(-9, "elvis", 9.1F));
            objstore.Remove(new Id <TestObject>(4));
            undomgr.EndCommand(58);

            TextWriter    writer    = new StringWriter();
            XmlTextWriter xmloutput = new XmlTextWriter(writer);

            xmloutput.Formatting = Formatting.Indented;
            xmloutput.Namespaces = false;

            xmloutput.WriteStartDocument();
            xmloutput.WriteStartElement("testobjects");

            objstore.Save(xmloutput);

            xmloutput.WriteEndElement();
            xmloutput.WriteEndDocument();
            xmloutput.Close();

            Assert.AreEqual(
                @"<?xml version=""1.0"" encoding=""utf-16""?>
<testobjects>
  <testobject id=""2"" x=""-9"" f=""9.1"">elvis</testobject>
  <testobject id=""5"" x=""5"" f=""5.4"">hello</testobject>
  <testobject id=""6"" x=""9"" f=""9.9"">bat</testobject>
</testobjects>",
                writer.ToString());
        }
예제 #15
0
        public void ResolverTestXmlReaderInput()
        {
            MvpXslTransform xslt  = GetMvpXslTransform2();
            XmlInput        input = new XmlInput(XmlReader.Create("../../MvpXslTransformTests/test.xml"), new MyXmlResolver());
            MemoryStream    ms    = new MemoryStream();

            xslt.Transform(input, Arguments, new XmlOutput(ms));
            CompareResults(resolverTestStandardResult, ms.ToArray());
        }
예제 #16
0
        private void RunLoopClicked(object sender, EventArgs e)
        {
            var          sb   = new StringBuilder();
            const string data = "<element />";

            var bytesTimer = new Stopwatch();
            var ourBytes   = Encoding.UTF8.GetBytes(data);
            var theirBytes = Encoding.UTF8.GetBytes(data);

            bytesTimer.Start();
            for (var i = 0; i < 100000; ++i)
            {
                XmlUtilities.AreXmlElementsEqual(ourBytes, theirBytes);
            }
            bytesTimer.Stop();
            sb.AppendFormat("Time to check (as bytes): {0}ms; {1}ticks.", bytesTimer.ElapsedMilliseconds, bytesTimer.ElapsedTicks);
            sb.AppendLine();

            var stringTimer = new Stopwatch();

            stringTimer.Start();
            for (var i = 0; i < 100000; ++i)
            {
                XmlUtilities.AreXmlElementsEqual(data, data);
            }
            stringTimer.Stop();
            sb.AppendFormat("Time to check (as string): {0}ms; {1}ticks.", stringTimer.ElapsedMilliseconds, stringTimer.ElapsedTicks);
            sb.AppendLine();

            var doc          = new XmlDocument();
            var ourNode      = XmlUtilities.GetDocumentNodeFromRawXml(data, doc);
            var theirNode    = XmlUtilities.GetDocumentNodeFromRawXml(data, doc);
            var xmlNodeTimer = new Stopwatch();

            xmlNodeTimer.Start();
            for (var i = 0; i < 100000; ++i)
            {
                XmlUtilities.AreXmlElementsEqual(ourNode, theirNode);
            }
            xmlNodeTimer.Stop();
            sb.AppendFormat("Time to check (as XmlNode): {0}ms; {1}ticks.", xmlNodeTimer.ElapsedMilliseconds, xmlNodeTimer.ElapsedTicks);
            sb.AppendLine();

            var ourInput      = new XmlInput(data);
            var theirInput    = new XmlInput(data);
            var xmlInputTimer = new Stopwatch();

            xmlInputTimer.Start();
            for (var i = 0; i < 100000; ++i)
            {
                XmlUtilities.AreXmlElementsEqual(ourInput, theirInput);
            }
            xmlInputTimer.Stop();
            sb.AppendFormat("Time to check (as XmlInput): {0}ms; {1}ticks.", xmlInputTimer.ElapsedMilliseconds, xmlInputTimer.ElapsedTicks);

            MessageBox.Show(sb.ToString());
        }
예제 #17
0
 public void CloseFile()
 {
     // Make sure that Dispose really closes the underlying file.
     File.Copy(TestUtil.GetTestFile("xmlinput.xml"), TestUtil.GetTestFile("temp.xml"));
     XmlInput xmlinput = new XmlInput(TestUtil.GetTestFile("temp.xml"));
     xmlinput.CheckElement("rootsym");
     xmlinput.Dispose();
     File.Delete(TestUtil.GetTestFile("temp.xml"));
 }
예제 #18
0
        public void AssertXslTransformResultsWorksWithXmlInput()
        {
            StreamReader xsl            = ValidatorTests.GetTestReader("animal.xsl");
            XmlInput     xslt           = new XmlInput(xsl);
            StreamReader xml            = ValidatorTests.GetTestReader("testAnimal.xml");
            XmlInput     xmlToTransform = new XmlInput(xml);
            XmlInput     expectedXml    = new XmlInput("<dog/>");

            OldXmlAssert.XslTransformResults(xslt, xmlToTransform, expectedXml);
        }
예제 #19
0
        [Test] public void AssertXslTransformResultsWorksWithXmlInput()
        {
            StreamReader xsl            = GetStreamReader(".\\..\\tests\\etc\\animal.xsl");
            XmlInput     xslt           = new XmlInput(xsl);
            StreamReader xml            = GetStreamReader(".\\..\\tests\\etc\\testAnimal.xml");
            XmlInput     xmlToTransform = new XmlInput(xml);
            XmlInput     expectedXml    = new XmlInput("<dog/>");

            XmlAssertion.AssertXslTransformResults(xslt, xmlToTransform, expectedXml);
        }
예제 #20
0
        public void CloseFile()
        {
            // Make sure that Dispose really closes the underlying file.
            File.Copy(TestUtil.GetTestFile("xmlinput.xml"), TestUtil.GetTestFile("temp.xml"));
            XmlInput xmlinput = new XmlInput(TestUtil.GetTestFile("temp.xml"));

            xmlinput.CheckElement("rootsym");
            xmlinput.Dispose();
            File.Delete(TestUtil.GetTestFile("temp.xml"));
        }
예제 #21
0
        public static bool AreXmlElementsEqual(XmlInput ours, XmlInput theirs)
        {
            // Must use 'config', or whitespace only differences will make the elements different.
            // cf. diffing changeset 240 and 241 in the Tok Pisin project for such whitespace differences.
            var config     = new DiffConfiguration(WhitespaceHandling.None);
            var diff       = new XmlDiff(ours, theirs, config);
            var diffResult = diff.Compare();

            return(diffResult == null || diffResult.Difference == null || !diffResult.Difference.MajorDifference);
        }
예제 #22
0
        /// <summary>
        /// Runs the sample.
        /// </summary>
        public static void RunFromConfigurationFileSample()
        {
            Console.WriteLine(Header);
            Console.WriteLine(FirstSampleStepText);

            var inputDataFile = new Uri(Settings.Default.InvoiceXmlInput, UriKind.Relative);
            var input = new XmlInput(inputDataFile);

            var configuration = new Uri(Settings.Default.ExportEngineSample07Configuration, UriKind.Relative);
            input.Export(ExportSettings.ImportFrom(configuration));
        }
예제 #23
0
        public void CharMapTest4()
        {
            MvpXslTransform xslt = new MvpXslTransform();

            xslt.Load(XmlReader.Create("../../Common/MvpXslTransformTests/char-map.xslt"));
            XmlInput     input = new XmlInput(new StringReader("<foo attr=\"{data}\">text {%= fff() %} and more&#xA0;text.</foo>"));
            StringWriter sw    = new StringWriter();

            xslt.Transform(input, Arguments, new XmlOutput(sw));
            Assert.IsTrue(sw.ToString() == "<out attr=\"a&nbsp;b\"><text>Some&nbsp;text, now ASP.NET <%# Eval(\"foo\") %> and more&nbsp;text.</text><foo attr=\"<data>\">text <%= fff() %> and more&nbsp;text.</foo></out>");
        }
예제 #24
0
        public void TestXmlReaderInput2()
        {
            MvpXslTransform xslt  = GetMvpXslTransform();
            XmlInput        input = new XmlInput(XmlReader.Create("../../../Common/northwind.xml"));
            MemoryStream    ms    = new MemoryStream();
            XmlReader       r     = xslt.Transform(input, Arguments);
            XmlWriter       w     = XmlWriter.Create(ms);

            w.WriteNode(r, false);
            w.Close();
            CompareResults(standardResult, ms.ToArray());
        }
예제 #25
0
        public void TestIXPathNavigableInput2()
        {
            MvpXslTransform xslt  = GetMvpXslTransform();
            XmlInput        input = new XmlInput(new XPathDocument("../../../Common/northwind.xml", XmlSpace.Preserve));
            MemoryStream    ms    = new MemoryStream();
            XmlReader       r     = xslt.Transform(input, Arguments);
            XmlWriter       w     = XmlWriter.Create(ms);

            w.WriteNode(r, false);
            w.Close();
            CompareResults(standardResult, ms.ToArray());
        }
예제 #26
0
        public void ResolverTestStreamInput()
        {
            MvpXslTransform xslt = GetMvpXslTransform2();

            using (FileStream fs = File.OpenRead("../../../Common/MvpXslTransformTests/test.xml"))
            {
                XmlInput     input = new XmlInput(fs, new MyXmlResolver());
                MemoryStream ms    = new MemoryStream();
                xslt.Transform(input, Arguments, new XmlOutput(ms));
                CompareResults(resolverTestStandardResult, ms.ToArray());
            }
        }
예제 #27
0
        public void TestTextReaderInput2()
        {
            MvpXslTransform xslt  = GetMvpXslTransform();
            XmlInput        input = new XmlInput(new StreamReader("../../northwind.xml", Encoding.GetEncoding("windows-1252")));
            MemoryStream    ms    = new MemoryStream();
            XmlReader       r     = xslt.Transform(input, Arguments);
            XmlWriter       w     = XmlWriter.Create(ms);

            w.WriteNode(r, false);
            w.Close();
            CompareResults(standardResult, ms.ToArray());
        }
예제 #28
0
        public void TestStreamInput()
        {
            MvpXslTransform xslt = GetMvpXslTransform();

            using (FileStream fs = File.OpenRead("../../../Common/northwind.xml"))
            {
                XmlInput     input = new XmlInput(fs);
                MemoryStream ms    = new MemoryStream();
                xslt.Transform(input, Arguments, new XmlOutput(ms));
                CompareResults(standardResult, ms.ToArray());
            }
        }
        /// <summary>
        /// Runs the sample.
        /// </summary>
        public static void RunFromCodeSample()
        {
            Console.WriteLine(Header);
            Console.WriteLine(FirstSampleStepText);

            var inputDataFile = new Uri(Settings.Default.InventoryXmlInput, UriKind.Relative);
            var input         = new XmlInput(inputDataFile);

            var configurationModel = CreateModel();

            input.Export(ExportSettings.CreateFromModels(configurationModel, "Sample01"));
        }
예제 #30
0
        public void ExsltTest()
        {
            MvpXslTransform xslt = new MvpXslTransform();

            xslt.Load("../../../Common/MvpXslTransformTests/exslt-test.xslt");
            XmlInput     input = new XmlInput("../../../Common/MvpXslTransformTests/test.xml");
            MemoryStream ms    = new MemoryStream();

            xslt.Transform(input, Arguments, new XmlOutput(ms));
            string expected = "<out>3</out>";

            CompareResults(Encoding.ASCII.GetBytes(expected), ms.ToArray());
        }
예제 #31
0
        public void TestStringOutput()
        {
            MvpXslTransform xslt  = GetMvpXslTransform();
            XmlInput        input = new XmlInput("../../../Common/northwind.xml");

            xslt.Transform(input, Arguments, new XmlOutput("../../../Common/MvpXslTransformTests/out.xml"));
            using (FileStream fs = File.OpenRead("../../../Common/MvpXslTransformTests/out.xml"))
            {
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                CompareResults(standardResult, bytes);
            }
        }
예제 #32
0
 public void StreamInputTranslatesToXmlReader()
 {
     MemoryStream stream = new MemoryStream();
     StreamWriter writer = new StreamWriter(stream, Encoding.Default);
     writer.WriteLine(INPUT);
     writer.Flush();
     stream.Seek(0, SeekOrigin.Begin);
     XmlInput input = new XmlInput(stream);
     string actual = ReadOuterXml(input.CreateXmlReader());
     try {
         Assert.AreEqual(_expected, actual);
     } finally {
         writer.Close();
     }
 }
 public void AssertXslTransformResultsWorksWithXmlInput()
 {
     StreamReader xsl = ValidatorTests.GetTestReader("animal.xsl");
     XmlInput xslt = new XmlInput(xsl);
     StreamReader xml = ValidatorTests.GetTestReader("testAnimal.xml");
     XmlInput xmlToTransform = new XmlInput(xml);
     XmlInput expectedXml = new XmlInput("<dog/>");
     XmlAssert.XslTransformResults(xslt, xmlToTransform, expectedXml);
 }
예제 #34
0
 public void TextReaderInputTranslatesToXmlReader()
 {
     XmlInput input = new XmlInput(new StringReader(INPUT));
     string actual = ReadOuterXml(input.CreateXmlReader());
     Assert.AreEqual(_expected, actual);
 }
예제 #35
0
 public void HashCodeEqualsHashCodeOfInput()
 {
     XmlInput input = new XmlInput(INPUT);
     Assert.AreEqual(INPUT.GetHashCode(), input.GetHashCode());
 }
예제 #36
0
 public void NotEqualsNull()
 {
     XmlInput input = new XmlInput(INPUT);
     Assert.AreEqual(false, input.Equals(null));
 }
예제 #37
0
        public void LoadModifySave()
        {
            Id<TestObject> id;
            UndoMgr undomgr = new UndoMgr(5);
            ObjectStore<TestObject> objstore = new ObjectStore<TestObject>(undomgr);

            string xmlText =
            @"<?xml version=""1.0"" encoding=""utf-16""?>
            <testobjects>
              <testobject id=""2"" x=""8"" f=""9.4"">goodbye</testobject>
              <testobject id=""4"" x=""11"" f=""1.4"">foo</testobject>
            </testobjects>";

            XmlInput xmlinput = new XmlInput(new StringReader(xmlText), "testfile");

            xmlinput.CheckElement("testobjects");
            xmlinput.Read();

            objstore.Load(xmlinput);
            xmlinput.Dispose();

            undomgr.BeginCommand(57, "Command1");
            id = objstore.Add(new TestObject(5, "hello", 5.4F));
            Assert.AreEqual(5, id.id);
            id = objstore.Add(new TestObject(9, "bat", 9.9F));
            Assert.AreEqual(6, id.id);
            undomgr.EndCommand(57);

            undomgr.BeginCommand(58, "Command2");
            objstore.Replace(new Id<TestObject>(2), new TestObject(-9, "elvis", 9.1F));
            objstore.Remove(new Id<TestObject>(4));
            undomgr.EndCommand(58);

            TextWriter writer = new StringWriter();
            XmlTextWriter xmloutput = new XmlTextWriter(writer);
            xmloutput.Formatting = Formatting.Indented;
            xmloutput.Namespaces = false;

            xmloutput.WriteStartDocument();
            xmloutput.WriteStartElement("testobjects");

            objstore.Save(xmloutput);

            xmloutput.WriteEndElement();
            xmloutput.WriteEndDocument();
            xmloutput.Close();

            Assert.AreEqual(
            @"<?xml version=""1.0"" encoding=""utf-16""?>
            <testobjects>
              <testobject id=""2"" x=""-9"" f=""9.1"">elvis</testobject>
              <testobject id=""5"" x=""5"" f=""5.4"">hello</testobject>
              <testobject id=""6"" x=""9"" f=""9.9"">bat</testobject>
            </testobjects>",
            writer.ToString());
        }
예제 #38
0
        /// <summary>
        /// Executes the XslTransform task.
        /// </summary>
        /// <returns>true if transformation succeeds.</returns>
        public override bool Execute()
        {
            XmlInput xmlinput;
            XsltInput xsltinput;
            ErrorUtilities.VerifyThrowArgumentNull(_outputPaths, "OutputPath");

            // Load XmlInput, XsltInput parameters
            try
            {
                xmlinput = new XmlInput(_xmlInputPaths, _xmlString);
                xsltinput = new XsltInput(_xsltFile, _xsltString, _xsltCompiledDll, Log);
            }
            catch (Exception e)
            {
                if (ExceptionHandling.IsCriticalException(e))
                {
                    throw;
                }

                Log.LogErrorWithCodeFromResources("XslTransform.ArgumentError", e.Message);
                return false;
            }

            // Check if OutputPath has same number of parameters as xmlInputPaths.
            if (_xmlInputPaths != null && _xmlInputPaths.Length != _outputPaths.Length)
            {
                Log.LogErrorWithCodeFromResources("General.TwoVectorsMustHaveSameLength", _outputPaths.Length, _xmlInputPaths.Length, "XmlContent", "XmlInputPaths");
                return false;
            }

            // Check if OutputPath has 1 parameter if xmlString is specified.
            if (_xmlString != null && _outputPaths.Length != 1)
            {
                Log.LogErrorWithCodeFromResources("General.TwoVectorsMustHaveSameLength", _outputPaths.Length, 1, "XmlContent", "OutputPaths");
                return false;
            }

            XsltArgumentList arguments;

            // Arguments parameters
            try
            {
                arguments = ProcessXsltArguments(_parameters);
            }
            catch (Exception e)
            {
                if (ExceptionHandling.IsCriticalException(e))
                {
                    throw;
                }

                Log.LogErrorWithCodeFromResources("XslTransform.XsltArgumentsError", e.Message);
                return false;
            }

            XslCompiledTransform xslct;

            // Load the XSLT
            try
            {
                xslct = xsltinput.LoadXslt(UseTrustedSettings);
            }
            catch (Exception e)
            {
                if (ExceptionHandling.IsCriticalException(e))
                {
                    throw;
                }

                Log.LogErrorWithCodeFromResources("XslTransform.XsltLoadError", e.Message);
                return false;
            }

            // Do the transformation.
            try
            {
                for (int i = 0; i < xmlinput.Count; i++)
                {
                    using (XmlWriter xmlWriter = XmlWriter.Create(_outputPaths[i].ItemSpec, xslct.OutputSettings))
                    {
                        using (XmlReader xr = xmlinput.CreateReader(i))
                        {
                            xslct.Transform(xr, arguments, xmlWriter);
                        }

                        xmlWriter.Close();
                    }
                }
            }
            catch (Exception e)
            {
                if (ExceptionHandling.IsCriticalException(e))
                {
                    throw;
                }

                Log.LogErrorWithCodeFromResources("XslTransform.TransformError", e.Message);
                return false;
            }

            // Copy Metadata
            if (xmlinput.XmlMode == XmlInput.XmlModes.XmlFile)
            {
                for (int i = 0; i < _xmlInputPaths.Length; i++)
                {
                    _xmlInputPaths[i].CopyMetadataTo(_outputPaths[i]);
                }
            }

            return true;
        }
 public override bool Execute()
 {
     XmlInput input;
     XsltInput input2;
     XsltArgumentList list;
     XslCompiledTransform transform;
     Microsoft.Build.Shared.ErrorUtilities.VerifyThrowArgumentNull(this.outputPaths, "OutputPath");
     try
     {
         input = new XmlInput(this.xmlInputPaths, this.xmlString);
         input2 = new XsltInput(this.xsltFile, this.xsltString, this.xsltCompiledDll);
     }
     catch (Exception exception)
     {
         if (Microsoft.Build.Shared.ExceptionHandling.IsCriticalException(exception))
         {
             throw;
         }
         base.Log.LogErrorWithCodeFromResources("XslTransform.ArgumentError", new object[] { exception.Message });
         return false;
     }
     if ((this.xmlInputPaths != null) && (this.xmlInputPaths.Length != this.outputPaths.Length))
     {
         base.Log.LogErrorWithCodeFromResources("General.TwoVectorsMustHaveSameLength", new object[] { this.outputPaths.Length, this.xmlInputPaths.Length, "XmlContent", "XmlInputPaths" });
         return false;
     }
     if ((this.xmlString != null) && (this.outputPaths.Length != 1))
     {
         base.Log.LogErrorWithCodeFromResources("General.TwoVectorsMustHaveSameLength", new object[] { this.outputPaths.Length, 1, "XmlContent", "OutputPaths" });
         return false;
     }
     try
     {
         list = ProcessXsltArguments(this.parameters);
     }
     catch (Exception exception2)
     {
         if (Microsoft.Build.Shared.ExceptionHandling.IsCriticalException(exception2))
         {
             throw;
         }
         base.Log.LogErrorWithCodeFromResources("XslTransform.XsltArgumentsError", new object[] { exception2.Message });
         return false;
     }
     try
     {
         transform = input2.LoadXslt();
     }
     catch (Exception exception3)
     {
         if (Microsoft.Build.Shared.ExceptionHandling.IsCriticalException(exception3))
         {
             throw;
         }
         base.Log.LogErrorWithCodeFromResources("XslTransform.XsltLoadError", new object[] { exception3.Message });
         return false;
     }
     try
     {
         for (int i = 0; i < input.Count; i++)
         {
             using (XmlWriter writer = XmlWriter.Create(this.outputPaths[i].ItemSpec, transform.OutputSettings))
             {
                 using (XmlReader reader = input.CreateReader(i))
                 {
                     transform.Transform(reader, list, writer);
                 }
                 writer.Close();
             }
         }
     }
     catch (Exception exception4)
     {
         if (Microsoft.Build.Shared.ExceptionHandling.NotExpectedException(exception4))
         {
             throw;
         }
         base.Log.LogErrorWithCodeFromResources("XslTransform.TransformError", new object[] { exception4.Message });
         return false;
     }
     if (input.XmlMode == XmlInput.XmlModes.XmlFile)
     {
         for (int j = 0; j < this.xmlInputPaths.Length; j++)
         {
             this.xmlInputPaths[j].CopyMetadataTo(this.outputPaths[j]);
         }
     }
     return true;
 }
 public override bool Execute()
 {
     XmlInput input;
     XPathDocument document;
     Microsoft.Build.Shared.ErrorUtilities.VerifyThrowArgumentNull(this.query, "Query");
     try
     {
         input = new XmlInput(this.xmlInputPath, this.xmlContent);
     }
     catch (Exception exception)
     {
         if (Microsoft.Build.Shared.ExceptionHandling.IsCriticalException(exception))
         {
             throw;
         }
         base.Log.LogErrorWithCodeFromResources("XmlPeek.ArgumentError", new object[] { exception.Message });
         return false;
     }
     try
     {
         using (XmlReader reader = input.CreateReader())
         {
             document = new XPathDocument(reader);
             reader.Close();
         }
     }
     catch (Exception exception2)
     {
         if (Microsoft.Build.Shared.ExceptionHandling.IsCriticalException(exception2))
         {
             throw;
         }
         base.Log.LogErrorWithCodeFromResources("XmlPeekPoke.InputFileError", new object[] { this.xmlInputPath.ItemSpec, exception2.Message });
         return false;
     }
     finally
     {
         input.CloseReader();
     }
     XPathNavigator navigator = document.CreateNavigator();
     XPathExpression expr = null;
     try
     {
         expr = navigator.Compile(this.query);
     }
     catch (Exception exception3)
     {
         if (Microsoft.Build.Shared.ExceptionHandling.IsCriticalException(exception3))
         {
             throw;
         }
         base.Log.LogErrorWithCodeFromResources("XmlPeekPoke.XPathError", new object[] { this.query, exception3.Message });
         return false;
     }
     XmlNamespaceManager namespaceManager = new XmlNamespaceManager(navigator.NameTable);
     try
     {
         this.LoadNamespaces(ref namespaceManager, this.namespaces);
     }
     catch (Exception exception4)
     {
         if (Microsoft.Build.Shared.ExceptionHandling.IsCriticalException(exception4))
         {
             throw;
         }
         base.Log.LogErrorWithCodeFromResources("XmlPeek.NamespacesError", new object[] { exception4.Message });
         return false;
     }
     try
     {
         expr.SetContext(namespaceManager);
     }
     catch (XPathException exception5)
     {
         base.Log.LogErrorWithCodeFromResources("XmlPeek.XPathContextError", new object[] { exception5.Message });
         return false;
     }
     XPathNodeIterator iterator = navigator.Select(expr);
     List<string> list = new List<string>();
     while (iterator.MoveNext())
     {
         if ((iterator.Current.NodeType == XPathNodeType.Attribute) || (iterator.Current.NodeType == XPathNodeType.Text))
         {
             list.Add(iterator.Current.Value);
         }
         else
         {
             list.Add(iterator.Current.OuterXml);
         }
     }
     this.result = new ITaskItem[list.Count];
     int num = 0;
     foreach (string str in list)
     {
         this.result[num++] = new TaskItem(str);
         base.Log.LogMessageFromResources("XmlPeek.Found", new object[] { str });
     }
     if (this.result.Length == 0)
     {
         base.Log.LogMessageFromResources("XmlPeek.NotFound", new object[0]);
     }
     return true;
 }
예제 #41
0
        public void Load()
        {
            UndoMgr undomgr = new UndoMgr(5);
            ObjectStore<TestObject> objstore = new ObjectStore<TestObject>(undomgr);

            string xmlText =
            @"<?xml version=""1.0"" encoding=""utf-16""?>
            <testobjects>
              <testobject id=""2"" x=""8"" f=""9.4"">goodbye</testobject>
              <testobject id=""3"" x=""9"" f=""9.9"">bat</testobject>
              <testobject id=""4"" x=""11"" f=""1.4"">foo</testobject>
            </testobjects>";

            XmlInput xmlinput = new XmlInput(new StringReader(xmlText), "testfile");

            xmlinput.CheckElement("testobjects");
            xmlinput.Read();

            objstore.Load(xmlinput);
            xmlinput.Dispose();

            TestUtil.TestEnumerableAnyOrder(objstore.AllPairs,
                                        new KeyValuePair<Id<TestObject>, TestObject>[] {
                                        new KeyValuePair<Id<TestObject>, TestObject>(new Id<TestObject>(3), new TestObject(9, "bat", 9.9F)),
                                        new KeyValuePair<Id<TestObject>, TestObject>(new Id<TestObject>(4), new TestObject(11, "foo", 1.4F)),
                                        new KeyValuePair<Id<TestObject>, TestObject>(new Id<TestObject>(2), new TestObject(8, "goodbye", 9.4F)) });
        }
예제 #42
0
        public void TextReader()
        {
            string input =
            @"<?xml version=""1.0"" encoding=""utf-8""?>
            <rootsym>
            <!-- This is a comment -->
            <fiddle x=""foo"" y=""1"" z=""false""></fiddle>
            </rootsym>";

            XmlInput xmlinput = new XmlInput(new StringReader(input), "teststring");

            xmlinput.CheckElement("rootsym");
            xmlinput.Read();
            xmlinput.CheckElement("fiddle");
            Assert.AreEqual(1, xmlinput.GetAttributeInt("y"));
            Assert.AreEqual(false, xmlinput.GetAttributeBool("z"));
            Assert.AreEqual("foo", xmlinput.GetAttributeString("x"));
            xmlinput.Skip();
        }
예제 #43
0
 public override void ReadAttributesAndContent(XmlInput xmlinput)
 {
     x = xmlinput.GetAttributeInt("x");
     f = xmlinput.GetAttributeFloat("f");
     s = xmlinput.GetContentString();
 }
 public void AssertXslTransformResultsCatchesFalsePositive()
 {
     StreamReader xsl = ValidatorTests.GetTestReader("animal.xsl");
     XmlInput xslt = new XmlInput(xsl);
     StreamReader xml = ValidatorTests.GetTestReader("testAnimal.xml");
     XmlInput xmlToTransform = new XmlInput(xml);
     XmlInput expectedXml = new XmlInput("<cat/>");
     bool exceptionExpected = true;
     try {
         XmlAssert.XslTransformResults(xslt, xmlToTransform, expectedXml);
         exceptionExpected = false;
         Assert.Fail("Expected dog not cat!");
     } catch (AssertionException e) {
         AvoidUnusedVariableCompilerWarning(e);
         if (!exceptionExpected) {
             throw e;
         }
     }
 }
예제 #45
0
 public void NotEqualsADifferentClass()
 {
     XmlInput input = new XmlInput(INPUT);
     Assert.AreEqual(false, input.Equals(INPUT));
 }
예제 #46
0
        public void Read1()
        {
            XmlInput xmlinput = new XmlInput(TestUtil.GetTestFile("xmlinput.xml"));
            xmlinput.CheckElement("rootsym");

            try {
                xmlinput.CheckElement("fiddle");
                Assert.Fail("expect exception");
            }
            catch (Exception e) {
                Assert.IsTrue(e is XmlFileFormatException);
            }

            xmlinput.Read();
            xmlinput.CheckElement("fiddle");
            Assert.AreEqual(1, xmlinput.GetAttributeInt("y"));
            Assert.AreEqual(false, xmlinput.GetAttributeBool("z"));
            Assert.AreEqual("foo", xmlinput.GetAttributeString("x"));

            xmlinput.Skip();

            xmlinput.CheckElement("faddle");
            Assert.AreEqual(3.4F, xmlinput.GetAttributeFloat("x"));
            try {
                Assert.AreEqual("", xmlinput.GetAttributeString("q"));
                Assert.Fail("should throw");
            }
            catch (Exception e) {
                Assert.IsTrue(e is XmlFileFormatException);
            }

            int i = 0;
            bool first = true;
            while (xmlinput.FindSubElement(first, "hello", "zung", "zang", "zing")) {
                ++i;
                first = false;

                switch (xmlinput.Name) {
                    case "zing":
                        Assert.AreEqual(5, xmlinput.GetAttributeInt("why", 5));
                        Assert.AreEqual(true, xmlinput.GetAttributeBool("why", true));
                        Assert.AreEqual(5.7F, xmlinput.GetAttributeFloat("why", 5.7F));
                        Assert.AreEqual("Whazzzle", xmlinput.GetAttributeString("why", "Whazzzle"));
                        Assert.AreEqual("This is the zing", xmlinput.GetContentString());
                        break;

                    case "zang":
                        Assert.AreEqual(true, xmlinput.GetAttributeBool("r"));
                        try {
                            Assert.AreEqual(true, xmlinput.GetAttributeBool("z"));
                            Assert.Fail("should throw");
                        }
                        catch (Exception) {
                        }

                        xmlinput.Skip();
                        break;

                    case "zung":
                        xmlinput.Read();
                        xmlinput.CheckElement("diddle");
                        xmlinput.Skip();
                        xmlinput.Skip();
                        break;
                    default:
                        Assert.Fail("shouldn't get here");
                        break;
                }
            }

            Assert.AreEqual(4, i);
        }
예제 #47
0
 public void EqualsCopyOfSelf()
 {
     XmlInput input = new XmlInput(INPUT);
     Assert.AreEqual(new XmlInput(INPUT), input);
 }
예제 #48
0
		/// <summary>
		/// Executes the XMLPeek task.
		/// </summary>
		/// <returns>true if transformation succeeds.</returns>
		public override bool Execute ()
		{
			XmlInput xmlinput;
			if (_query == null)
				throw new ArgumentNullException ("Query");

			try {
				xmlinput = new XmlInput (_xmlInputPath, _xmlContent);
			} catch (Exception e) {
				if (IsCriticalException (e)) {
					throw;
				}

				Log.LogError ("MSB3741: Unable to load arguments for the XmlPeek task. {0}", e.Message);
				return false;
			}

			XPathDocument xpathdoc;
			try {
				// Load the XPath Document
				using (XmlReader xr = xmlinput.CreateReader ()) {
					xpathdoc = new XPathDocument (xr);
					xr.Close ();
				}
			} catch (Exception e) {
				if (IsCriticalException (e)) {
					throw;
				}

				Log.LogError ("MSB3733: Input file \"{0}\" cannot be opened. {1}", _xmlInputPath.ItemSpec, e.Message);
				return false;
			} finally {
				xmlinput.CloseReader ();
			}

			XPathNavigator nav = xpathdoc.CreateNavigator ();
			XPathExpression expr = null;
			try {
				// Create the expression from query
				expr = nav.Compile (_query);
			} catch (Exception e) {
				if (IsCriticalException (e)) {
					throw;
				}

				Log.LogError ("MSB3734: XPath Query \"{0}\" cannot be loaded. {1}", _query, e.Message);
				return false;
			}

			// Create the namespace manager and parse the input.
			XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager (nav.NameTable);

			try {
				LoadNamespaces (ref xmlNamespaceManager, _namespaces);
			} catch (Exception e) {
				if (IsCriticalException (e)) {
					throw;
				}

				Log.LogError ("MSB3742: Unable to process the Namespaces argument for the XmlPeek task. {0}", e.Message);
				return false;
			}

			try {
				expr.SetContext (xmlNamespaceManager);
			} catch (XPathException e) {
				Log.LogError ("MSB3743: Unable to set XPath expression's Context. {0}", e.Message);
				return false;
			}

			XPathNodeIterator iter = nav.Select (expr);

			List<string> peekValues = new List<string> ();
			while (iter.MoveNext ()) {
				if (iter.Current.NodeType == XPathNodeType.Attribute
				                || iter.Current.NodeType == XPathNodeType.Text) {
					peekValues.Add (iter.Current.Value);
				} else {
					peekValues.Add (iter.Current.OuterXml);
				}
			}

			_result = new ITaskItem[peekValues.Count];
			int i = 0;
			foreach (string item in peekValues) {
				_result [i++] = new TaskItem (item);

				// This can be logged a lot, so low importance
				Log.LogMessage (MessageImportance.Low, "Found \"{0}\".", item);
			}

			if (_result.Length == 0) {
				// Logged no more than once per execute of this task
				Log.LogMessage ("The specified XPath query did not capture any nodes.");
			}

			return true;
		}
예제 #49
0
파일: XmlPeek.cs 프로젝트: Profit0004/mono
		/// <summary>
		/// Executes the XMLPeek task.
		/// </summary>
		/// <returns>true if transformation succeeds.</returns>
		public override bool Execute ()
		{
			XmlInput xmlinput;
			if (_query == null)
				throw new ArgumentNullException ("Query");

			try {
				xmlinput = new XmlInput (_xmlInputPath, _xmlContent);
			} catch (Exception e) {
				if (IsCriticalException (e)) {
					throw;
				}

				Log.LogErrorWithCodeFromResources ("XmlPeek.ArgumentError", e.Message);
				return false;
			}

			XPathDocument xpathdoc;
			try {
				// Load the XPath Document
				using (XmlReader xr = xmlinput.CreateReader ()) {
					xpathdoc = new XPathDocument (xr);
					xr.Close ();
				}
			} catch (Exception e) {
				if (IsCriticalException (e)) {
					throw;
				}

				Log.LogErrorWithCodeFromResources ("XmlPeekPoke.InputFileError", _xmlInputPath.ItemSpec, e.Message);
				return false;
			} finally {
				xmlinput.CloseReader ();
			}

			XPathNavigator nav = xpathdoc.CreateNavigator ();
			XPathExpression expr = null;
			try {
				// Create the expression from query
				expr = nav.Compile (_query);
			} catch (Exception e) {
				if (IsCriticalException (e)) {
					throw;
				}

				Log.LogErrorWithCodeFromResources ("XmlPeekPoke.XPathError", _query, e.Message);
				return false;
			}

			// Create the namespace manager and parse the input.
			XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager (nav.NameTable);

			try {
				LoadNamespaces (ref xmlNamespaceManager, _namespaces);
			} catch (Exception e) {
				if (IsCriticalException (e)) {
					throw;
				}

				Log.LogErrorWithCodeFromResources ("XmlPeek.NamespacesError", e.Message);
				return false;
			}

			try {
				expr.SetContext (xmlNamespaceManager);
			} catch (XPathException e) {
				Log.LogErrorWithCodeFromResources ("XmlPeek.XPathContextError", e.Message);
				return false;
			}

			XPathNodeIterator iter = nav.Select (expr);

			List<string> peekValues = new List<string> ();
			while (iter.MoveNext ()) {
				if (iter.Current.NodeType == XPathNodeType.Attribute
				                || iter.Current.NodeType == XPathNodeType.Text) {
					peekValues.Add (iter.Current.Value);
				} else {
					peekValues.Add (iter.Current.OuterXml);
				}
			}

			_result = new ITaskItem[peekValues.Count];
			int i = 0;
			foreach (string item in peekValues) {
				_result [i++] = new TaskItem (item);

				// This can be logged a lot, so low importance
				Log.LogMessageFromResources (MessageImportance.Low, "XmlPeek.Found", item);
			}

			if (_result.Length == 0) {
				// Logged no more than once per execute of this task
				Log.LogMessageFromResources ("XmlPeek.NotFound");
			}

			return true;
		}
예제 #50
0
 public void EqualsSelf()
 {
     XmlInput input = new XmlInput(INPUT);
     Assert.AreEqual(input, input);
 }