Ejemplo n.º 1
0
        public void XmlMatchFormat()
        {
            string originalXML;
            string controlXML;

            var xml = GetType().Module.Assembly.GetManifestResourceStream("Carrousel1.Test.Resources.XML.Images.xml");

            using (StreamReader reader = new StreamReader(xml))
            {
                originalXML = reader.ReadToEnd();
            }

            var xmlControl = GetType().Module.Assembly.GetManifestResourceStream("Carrousel1.Test.Resources.XML.ImageControl.xml");

            using (StreamReader reader = new StreamReader(xmlControl))
            {
                controlXML = reader.ReadToEnd();
            }

            XmlDiff diff = new XmlDiff(controlXML, originalXML);

            XmlDiffOptions options = new XmlDiffOptions();

            var result = diff.CompareDocuments(options);

            Assert.IsTrue(diff.DiffNodeList.Count == 0);
        }
Ejemplo n.º 2
0
        public void TestXmlDiff()
        {
            XmlDiff        diff    = new XmlDiff(TestResources.HAAR01000, TestResources.HAAR01001, "HAAR01000", "HAAR01001");
            XmlDiffOptions options = new XmlDiffOptions();

            options.IgnoreAttributeOrder   = true;
            options.IgnoreAttributes       = false;
            options.MaxAttributesToDisplay = 3;
            diff.CompareDocuments(options);
            Assert.AreEqual(diff.DiffNodeList.Count, 0);
            XmlDocument xdoc = new XmlDocument();

            xdoc.LoadXml(TestResources.HAAR01001);
            XmlNode node = xdoc.SelectSingleNode("//Product");

            node.Attributes["EffDate"].Value = "01/01/3000";
            diff = new XmlDiff(TestResources.HAAR01000, xdoc.InnerXml, "HAAR01000", "HAAR01001");
            diff.CompareDocuments(options);
            Assert.AreEqual(diff.DiffNodeList.Count, 2);
            Assert.IsTrue(diff.DiffNodeList[1].Description.Contains("EffDate"));
            xdoc.LoadXml(TestResources.HAAR01001);
            node = xdoc.SelectSingleNode("//Company");
            node.Attributes["CompanyID"].Value = "1000";
            diff = new XmlDiff(TestResources.HAAR01000, xdoc.InnerXml);
            diff.CompareDocuments(options);
            Assert.AreEqual(diff.DiffNodeList.Count, 2);
            Assert.IsTrue(diff.DiffNodeList[1].Description.Contains("CompanyID"));
        }
Ejemplo n.º 3
0
        public void TryUpdateElementTest()
        {
            XmlDocument actualXmlDoc = new XmlDocument();

            actualXmlDoc.LoadXml(TestResources.updatenodetest);
            XmlDocument expectedXmlDoc = new XmlDocument();

            expectedXmlDoc.LoadXml(TestResources.updatenodeexpected);

            XmlNode insNode = actualXmlDoc.SelectSingleNode("ACORD/InsuranceSvcRq/PersAutoPolicyQuoteInqRq/PersAutoLineBusiness/PersDriver[@id = 'D1']");

            Assert.IsTrue(insNode.TryUpdateElement("DriverInfo/DriversLicense", "StateProvCd", "IT"));

            Assert.IsFalse(insNode.TryUpdateElement("DriverInfo/DriversLicense", "LicenseTypeCd", "Permit"));

            Assert.IsTrue(actualXmlDoc.TryUpdateElement("ACORD/InsuranceSvcRq/PersAutoPolicyQuoteInqRq/PersAutoLineBusiness/PersDriver[@id = 'D1']/DriverInfo/DriversLicense", "CountryCd", "CA", true));

            XmlDiff        diff    = new XmlDiff(actualXmlDoc.InnerXml, expectedXmlDoc.InnerXml);
            XmlDiffOptions options = new XmlDiffOptions();

            options.TwoWayMatch = true;
            Assert.IsTrue(diff.CompareDocuments(options));

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(TestResources.alliedreqxml);
            var node = xmlDoc.SelectSingleNode("//HomeLineBusiness/Dwell/Coverage[CoverageCd=\"DWELL\"]/Limit");

            Assert.IsTrue(node.TryUpdateElement("FormatInteger", "150000"));
            Assert.AreEqual("150000", xmlDoc.XPathSelectSingle("//HomeLineBusiness/Dwell/Coverage[CoverageCd='DWELL']/Limit/FormatInteger").GetValue());
        }
Ejemplo n.º 4
0
        public void TestXmlDiffWithCompareFunction()
        {
            XmlDiffOptions options = new XmlDiffOptions()
            {
                CompareFunction = DoubleCompare
            };
            XmlDiff diff = new XmlDiff(TestResources.exampleA_Function, TestResources.exampleB_Function);

            diff.CompareDocuments(options);
            Assert.AreEqual(diff.DiffNodeList.Count, 2);
        }
Ejemplo n.º 5
0
        private static void CompareXmls(string sourceXml, string targetXml, XmlDiffOptions diffOptions, out List <ResultDto> outputSourceToTarget)
        {
            try
            {
                outputSourceToTarget = null;
                var diff1 = new XmlDiff(sourceXml, targetXml);

                diff1.CompareDocuments(diffOptions);

                if (diff1.DiffNodeList.Count > 0)
                {
                    Console.WriteLine(diff1.ToString());
                    var dataList = diff1.DiffNodeList.Select(z => z).OrderBy(z => z.DiffId).ToList();

                    var resultList = new List <ResultDto>();
                    foreach (var record in dataList)
                    {
                        MakeResult(record, resultList);
                    }

                    var resultsTobeDisplayed = resultList.Where(x => x.NodeType != "Node").ToList();

                    foreach (var record in resultsTobeDisplayed)
                    {
                        var initialDescription = "";
                        initialDescription = MakeDescription(record, initialDescription);
                        var completeDescription = new StringBuilder();
                        completeDescription.Append("DiffType:");
                        completeDescription.Append(initialDescription);
                        completeDescription.Append(record.DiffType);
                        completeDescription.Append(" ; Xpath : " + record.XPath + " ; " +
                                                   record.Description);
                        record.ResultantOutput = completeDescription.ToString();
                        //Console.WriteLine(completeDescription);
                    }

                    outputSourceToTarget = resultsTobeDisplayed;
                }
            }
            catch (Exception ex)
            {
                outputSourceToTarget = null;
            }
        }
        private void AppendAndCompare(string configFilePath, string appendedConfigFilePath)
        {
            File.Copy(configFilePath, appendedConfigFilePath, true);

            options.WebConfigFilePath = appendedConfigFilePath;

            using (var appender = new WebConfigFileAppender(options, logger, new RedisConnectionProviderStub(), new CryptoGeneratorStub()))
                appender.ApplyChanges();

            var expectedWebConfig = File.ReadAllText(expectedConfigPath);
            var appendedWebConfig = File.ReadAllText(appendedConfigFilePath);

            var diff = new XmlDiff(expectedWebConfig, appendedWebConfig);

            diff.CompareDocuments(new XmlDiffOptions()
            {
                IgnoreAttributeOrder = true, IgnoreCase = true, TrimWhitespace = true
            });

            Assert.Empty(diff.DiffNodeList);
        }
Ejemplo n.º 7
0
        public void Test_AppliesNecessaryConfigurationToModulesIfModuleIsNotEmpty()
        {
            var originalWebConfigPath = string.Format(originalWebConfigPathNonEmptyTemplate, "Test");

            File.Copy(string.Format(originalWebConfigPathNonEmptyTemplate, string.Empty), originalWebConfigPath, true);

            using (var appender = new WebConfigFileAppender(originalWebConfigPath))
                appender.Execute();

            var expectedWebConfig = File.ReadAllText(expectedWebConfigPathModuleNonEmpty);
            var appendedWebConfig = File.ReadAllText(originalWebConfigPath);

            var diff = new XmlDiff(expectedWebConfig, appendedWebConfig);

            diff.CompareDocuments(new XmlDiffOptions()
            {
                IgnoreAttributeOrder = true, IgnoreCase = true, TrimWhitespace = true
            });

            Assert.Empty(diff.DiffNodeList);
        }
Ejemplo n.º 8
0
        public void Test_WillNotSaveTheFileIfNotExecutedAsDisposable()
        {
            var originalWebConfigPath = string.Format(originalWebConfigPathTemplate, "Test");

            File.Copy(string.Format(originalWebConfigPathTemplate, string.Empty), originalWebConfigPath, true);

            var appender = new WebConfigFileAppender(originalWebConfigPath);

            appender.Execute();

            var expectedWebConfig = File.ReadAllText(expectedWebConfigPath);
            var appendedWebConfig = File.ReadAllText(originalWebConfigPath);

            var diff = new XmlDiff(expectedWebConfig, appendedWebConfig);

            diff.CompareDocuments(new XmlDiffOptions()
            {
                IgnoreAttributeOrder = true, IgnoreCase = true, TrimWhitespace = true
            });

            Assert.NotEmpty(diff.DiffNodeList);
        }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            XmlDiffOptions xDiffOptions = new XmlDiffOptions();
            string         fromFile     = "C:\\Users\\rmiao\\Desktop\\configSample.xml";
            string         toFile       = fromFile;
            XmlDiff        xdiff;

            try
            {
                xdiff = new XmlDiff(File.ReadAllText(fromFile), File.ReadAllText(toFile));
                xdiff.CompareDocuments(xDiffOptions);
                Console.WriteLine(xdiff.ToString());
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: {0}", ex.Message);
                return;
            }

            /*
             * string fromFile = string.Empty;
             * string toFile = string.Empty;
             * string outFile = string.Empty;
             * bool toCsv = false;
             *
             * var options = new GetOpt("XmlDiff: Tool for finding the difference between two Xml files.",
             * new[]
             * {
             * new CommandLineOption('o', "outfile", "Output file to write to. Files with csv extension open in Excel.",
             *  ParameterType.String, o => outFile = (string)o),
             * new CommandLineOption('\0', "csv", "Creates a diff csv file and opens in Excel. If no outfile is specified writes output to xmldiff.csv. Default=False",
             *  ParameterType.None, none => toCsv = true),
             * new CommandLineOption('m', "nomatch", "Don't match text node value types (i.e. 0.00 != 0). Default=False",
             *  ParameterType.None, none => xDiffOptions.MatchValueTypes = false),
             * new CommandLineOption('\0', "ignoretypes", "If -m or --nomatch is NOT chosen, then this chooses which match types to ignore. " +
             *                      "Possible values are (string, integer, double, datetime). Multiple values may be separated by '|'", ParameterType.String,
             *                      (types) =>
             *                        {
             *                          string[] values = ((string)types).Split('|');
             *                          foreach (string value in values)
             *                          {
             *                            switch (value.ToLower().Trim())
             *                            {
             *                              case "string":
             *                                xDiffOptions.IgnoreTextTypes.Add(XmlDiffOptions.IgnoreTextNodeOptions.XmlString);
             *                                break;
             *                              case "integer":
             *                                xDiffOptions.IgnoreTextTypes.Add(XmlDiffOptions.IgnoreTextNodeOptions.XmlInteger);
             *                                break;
             *                              case "double":
             *                                xDiffOptions.IgnoreTextTypes.Add(XmlDiffOptions.IgnoreTextNodeOptions.XmlDouble);
             *                                break;
             *                              case "datetime":
             *                                xDiffOptions.IgnoreTextTypes.Add(XmlDiffOptions.IgnoreTextNodeOptions.XmlDateTime);
             *                                break;
             *                              default:
             *                                throw new CommandLineException("Error parsing enumerated values.", "ignoretypes");
             *                            }
             *                          }
             *                        }),
             * new CommandLineOption('d', "nodetail", "Will not display details of matching nodes. Default=False", ParameterType.None, none => xDiffOptions.MatchDescendants = false),
             * new CommandLineOption('c', "case", "Case Sensitive. Default=False", ParameterType.None, none => xDiffOptions.IgnoreCase = false),
             * new CommandLineOption('\0', "2way", "Does a comparison in both directions. Default=False", ParameterType.None, none => xDiffOptions.TwoWayMatch = true),
             * new CommandLineOption("Required. FromFile", ParameterType.String, file => fromFile = (string)file),
             * new CommandLineOption("Required. ToFile", ParameterType.String, file => toFile = (string)file)
             * });
             *
             * try
             * {
             * options.ParseOptions(args);
             * }
             * catch (CommandLineException ex)
             * {
             * Console.WriteLine("Error: {0}", ex.Message);
             * return;
             * }
             *
             * StreamWriter sw;
             * XmlDiff xdiff;
             * try
             * {
             * xdiff = new XmlDiff(File.ReadAllText(fromFile), File.ReadAllText(toFile));
             * xdiff.CompareDocuments(xDiffOptions);
             * }
             * catch (Exception ex)
             * {
             * Console.WriteLine("Error: {0}", ex.Message);
             * return;
             * }
             *
             * if (toCsv)
             * {
             * try
             * {
             * string file;
             * if (!string.IsNullOrEmpty(outFile))
             *  file = outFile;
             * else
             *  file = "xmldiff.csv";
             * sw = new StreamWriter(file);
             * sw.Write((toCsv) ? xdiff.ToCSVString() : xdiff.ToJsonString());
             * sw.Close();
             * Process.Start(file);
             * }
             * catch (IOException ex)
             * {
             * Console.WriteLine("Error: {0}", ex.Message);
             * return;
             * }
             * }
             * else
             * {
             * if (string.IsNullOrEmpty(outFile))
             * Console.WriteLine(xdiff.ToJsonString());
             * else
             * {
             * try
             * {
             *  sw = new StreamWriter(outFile);
             *  sw.WriteLine(xdiff.ToJsonString());
             *  sw.Close();
             * }
             * catch (IOException ex)
             * {
             *  Console.WriteLine("Error: {0}", ex.Message);
             *  return;
             * }
             * }
             * }
             */
        }
Ejemplo n.º 10
0
        public void TestDescendants()
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(TestResources.desc1actual);

            // Let's have some fun by making all the number based attributes (i.e. Veh1, Drv1, etc...) 0-based
            foreach (var node in xmlDoc.Descendants(XmlNodeType.Attribute))
            {
                if (char.IsNumber(node.InnerText[node.InnerText.Length - 1])) // check to see if the last character is numeric
                {
                    node.InnerText = node.InnerText.Substring(0, node.InnerText.Length - 1) + (node.InnerText[node.InnerText.Length - 1] - '1').ToString();
                }
            }
            XmlDiff diff = new XmlDiff(xmlDoc.InnerXml, TestResources.desc1expected);

            diff.CompareDocuments(new XmlDiffOptions());
            Assert.AreEqual(0, diff.DiffNodeList.Count);

            xmlDoc.LoadXml(TestResources.desc2actual);

            // This time let's remove all empty nodes, and certain partial nodes, while ignoring required nodes
            // linquified!
            (from node in xmlDoc.Descendants(XmlNodeType.Element)
             let ignore = (node.LocalName == "ItemIdInfo" || node.LocalName == "InsuredOrPrincipal")
                          let partialNodes = (node.LocalName == "TaxIdentity" && node.ChildNodes.Count < 2) ||
                                             (node.LocalName == "QuestionAnswer" && node.ChildNodes.Count < 2)
                                             where ((!node.HasChildNodes && node.InnerText == string.Empty) || partialNodes) && !ignore
                                             select node).Remove();

            diff = new XmlDiff(xmlDoc.InnerXml, TestResources.desc2expected);
            diff.CompareDocuments(new XmlDiffOptions()
            {
                TwoWayMatch = true
            });
            Assert.AreEqual(0, diff.DiffNodeList.Count);

            // How about aggregating the options nodes - there is already a method for this
            // see AggregateChildElements. This is just an example of the power of linq
            xmlDoc.LoadXml(TestResources.aggregatetest);
            var groups = (from node in xmlDoc.Descendants(XmlNodeType.Element)
                          where node.LocalName == "Option"
                          group node.ChildNodes by node.ParentNode);

            foreach (var group in groups)
            {
                // Remove the old parent "Option"
                var opts = group.SelectMany(nodes => nodes.Cast <XmlNode>());
                opts.Select(n => n.ParentNode).Remove();

                // Add the child nodes to the aggregate "Option"
                group.Key.Add("Option", opts.ToArray());
            }

            diff = new XmlDiff(xmlDoc.InnerXml, TestResources.aggregateexpected);
            XmlDiffOptions options = new XmlDiffOptions();

            options.TwoWayMatch = true;
            Assert.IsTrue(diff.CompareDocuments(options));

            // Now, let's try removing all CurrentTermAmt nodes under PersVeh
            xmlDoc.LoadXml(TestResources.desc3actual);
            (from coverage in xmlDoc.XPathSelectMany("//PersVeh[@id = $id and @RatedDriverRef = $driver]/Coverage", "1", "1")
             where coverage["CurrentTermAmt"].HasValue()
             select coverage["CurrentTermAmt"]).Remove();
            diff = new XmlDiff(xmlDoc.InnerXml, TestResources.desc3expected);
            Assert.IsTrue(diff.CompareDocuments(new XmlDiffOptions()
            {
                TwoWayMatch = true
            }));

            // Lastly, let's convert all "PerAccident" text to "PerAcc"
            xmlDoc.LoadXml(TestResources.desc4actual);
            (from coverage in xmlDoc.XPathSelectMany("//Coverage")
             from node in coverage.Descendants(XmlNodeType.Text)
             where node.InnerText == "PerAccident"
             select node)
            .ToList()
            .ForEach(n => n.InnerText = "PerAcc");
            diff = new XmlDiff(xmlDoc.InnerXml, TestResources.desc4expected);
            Assert.IsTrue(diff.CompareDocuments(new XmlDiffOptions()
            {
                TwoWayMatch = true
            }));
        }