Example #1
1
        internal static bool CompareXML(XDocument xmlDocument1, XDocument xmlDocument2)
        {
            XmlDiff diff = new XmlDiff();
            diff.IgnoreChildOrder = true;
            diff.IgnoreXmlDecl = true;
            diff.IgnoreWhitespace = true;
            diff.IgnoreComments = true;
            diff.IgnorePI = true;
            diff.IgnoreDtd = true;
            var doc1 = new XmlDocument();
            doc1.LoadXml(xmlDocument1.ToString());
            var doc2 = new XmlDocument();
            doc2.LoadXml(xmlDocument2.ToString());

            bool result = diff.Compare(doc1, doc2);

            return result;
        }
        public void TestSerialization()
        {
            MSBuildCodeMetricsReport report = MSBuildCodeMetricsReport.Create().CreateSummary().Report.CreateDetails().Report;

            report.Summary.AddMetric("VisualStudioMetrics", _cyclomaticComplexity).CreateRanges().
                AddRange("> 10", 5).
                AddRange("<= 10 and > 5", 3).
                AddRange("<= 5", 1);

            report.Summary.AddMetric("VisualStudioMetrics", _linesOfCode).CreateRanges().
                AddRange("> 100", 5).
                AddRange("<= 100 and > 50", 3).
                AddRange("<= 50", 1);

            report.Details.AddMetric("VisualStudioMetrics", _cyclomaticComplexity).CreateMeasures().
                AddMeasure("Method1() : void", 100).
                AddMeasure("Method2() : void", 50);

            report.Details.AddMetric("VisualStudioMetrics", _linesOfCode).CreateMeasures().
                AddMeasure("Method1() : void", 1000).
                AddMeasure("Method2() : void", 500);

            Stream ms = report.SerializeToMemoryStream(true);
            XmlDiff diff = new XmlDiff();
            Assert.IsTrue(diff.Compare(_expectedReportStream, ms));
        }
        internal static void Equal(string file1, string file2)
        {
            var diffFile = @"diff.xml";
            XmlTextWriter tw = new XmlTextWriter(new StreamWriter(diffFile));
            tw.Formatting = Formatting.Indented;
            var diff = new XmlDiff();
            diff.Options = XmlDiffOptions.IgnoreWhitespace | XmlDiffOptions.IgnoreComments | XmlDiffOptions.IgnoreXmlDecl;
            var result = diff.Compare(file1, file2, false, tw);
            tw.Close();
            if (!result)
            {
                //Files were not equal, so construct XmlDiffView.
                XmlDiffView dv = new XmlDiffView();

                //Load the original file again and the diff file.
                XmlTextReader orig = new XmlTextReader(file1);
                XmlTextReader diffGram = new XmlTextReader(diffFile);
                dv.Load(orig, diffGram);
                string tempFile = "test.htm";

                StreamWriter sw1 = new StreamWriter(tempFile);
                //Wrapping
                sw1.Write("<html><body><table>");
                sw1.Write("<tr><td><b>");
                sw1.Write(file1);
                sw1.Write("</b></td><td><b>");
                sw1.Write(file2);
                sw1.Write("</b></td></tr>");

                //This gets the differences but just has the 
                //rows and columns of an HTML table
                dv.GetHtml(sw1);

                //Finish wrapping up the generated HTML and 
                //complete the file by putting legend in the end just like the 
                //online tool.

                sw1.Write("<tr><td><b>Legend:</b> <font style='background-color: yellow'" +
                " color='black'>added</font>&nbsp;&nbsp;<font style='background-color: red'" +
                "color='black'>removed</font>&nbsp;&nbsp;<font style='background-color: " +
                "lightgreen' color='black'>changed</font>&nbsp;&nbsp;" +
                "<font style='background-color: red' color='blue'>moved from</font>" +
                "&nbsp;&nbsp;<font style='background-color: yellow' color='blue'>moved to" +
                "</font>&nbsp;&nbsp;<font style='background-color: white' color='#AAAAAA'>" + "ignored</font></td></tr>");

                sw1.Write("</table></body></html>");

                //HouseKeeping...close everything we dont want to lock.
                sw1.Close();
                orig.Close();
                diffGram.Close();
                Process.Start("test.htm");
            }

            Assert.True(result);
        }
Example #4
0
        public XElement GenerateDiffGram(XElement element1, XElement element2) {
            using (var node1Reader = element1.CreateReader())
            using (var node2Reader = element2.CreateReader()) {
                var result = new XDocument();
                using (var writer = result.CreateWriter()) {
                    var diff = new XmlDiff(XmlDiffOptions.IgnoreChildOrder | XmlDiffOptions.IgnoreWhitespace | XmlDiffOptions.IgnoreComments | XmlDiffOptions.IgnoreXmlDecl);
                    diff.Compare(node1Reader, node2Reader, writer);
                    writer.Flush();
                    writer.Close();
                }

                return result.Root;
            }
        }
Example #5
0
        public static void DiffXmlStrict(string actual, string expected)
        {
            XmlDocument expectedDoc;
            XmlDocument actualDoc;

            try
            {
                expectedDoc = new XmlDocument();
                expectedDoc.LoadXml(expected);
            }
            catch (XmlException e)
            {
                throw new Exception("Expected: " + e.Message + "\r\n" + expected);
            }

            try
            {
                actualDoc = new XmlDocument();
                actualDoc.LoadXml(actual);
            }
            catch (XmlException e)
            {
                throw new Exception("Actual: " + e.Message + "\r\n" + actual);
            }

            using (var stringWriter = new StringWriter())
            using (var writer = new XmlTextWriter(stringWriter))
            {
                writer.Formatting = Formatting.Indented;

                var xmldiff = new XmlDiff(XmlDiffOptions.None
                    //XmlDiffOptions.IgnoreChildOrder |
                    | XmlDiffOptions.IgnoreNamespaces
                    //XmlDiffOptions.IgnorePrefixes
                    );
                var identical = xmldiff.Compare(expectedDoc, actualDoc, writer);

                if (!identical)
                {
                    var error = string.Format("Expected:\r\n{0}\r\n\r\n" + "Actual:\r\n{1}\r\n\r\nDiff:\r\n{2}",
                        expected, actual, stringWriter.GetStringBuilder());

                    throw new Exception(error);
                }
            }
        }
Example #6
0
 public static bool CompareJson(string expected, string actual)
 {
     var expectedDoc = JsonConvert.DeserializeXmlNode(expected, "root");
     var actualDoc = JsonConvert.DeserializeXmlNode(actual, "root");
     var diff = new XmlDiff(XmlDiffOptions.IgnoreWhitespace |
                            XmlDiffOptions.IgnoreChildOrder);
     using (var ms = new MemoryStream())
     {
         var writer = new XmlTextWriter(ms, Encoding.UTF8);
         var result = diff.Compare(expectedDoc, actualDoc, writer);
         if (!result)
         {
             ms.Seek(0, SeekOrigin.Begin);
             Console.WriteLine(new StreamReader(ms).ReadToEnd());
         }
         return result;
     }
 }
Example #7
0
        public void Serializable()
        {
            XmlDiff diff = new XmlDiff();
            LayoutBox layoutBox = LayoutBox.LoadFromString(LayoutingResource.LayoutsDefault);
            String result = layoutBox.Serialize();

            diff.IgnoreChildOrder = true;
            diff.IgnoreComments = true;
            diff.IgnoreDtd = true;
            diff.IgnoreNamespaces = true;
            diff.IgnorePI = true;
            diff.IgnorePrefixes = true;
            diff.IgnoreWhitespace = true;
            diff.IgnoreXmlDecl = true;

            StringWriter diffgramString = new StringWriter();
            XmlTextWriter diffgramXml = new XmlTextWriter(diffgramString);
            bool diffBool = diff.Compare(new XmlTextReader(new StringReader(result)), new XmlTextReader(new StringReader(LayoutingResource.LayoutsDefault)), diffgramXml);
            //MessageBox.Show(diffgramString.ToString());
            Assert.True(diffBool);
        }
        /// <summary>
        /// Compares the two XML files and throws an error if they are different.
        /// </summary>
        public static void Compare(XmlDocument expected, XmlDocument actual)
        {
            XmlNamespaceManager ns = new XmlNamespaceManager(expected.NameTable);
            ns.AddNamespace("tst", "http://schemas.asidua.com/testing");

            var diffReport = new StringBuilder();

            //  Remove the ignored nodes from both XML documents
            foreach (XmlAttribute ignored in expected.SelectNodes("//@tst:IGNORE[.='Content']", ns))
            {
                string xpath = generateXPath(ignored.OwnerElement);

                //  Remove the node's content from the expected results
                ignored.OwnerElement.InnerText = "";
                ignored.OwnerElement.RemoveAttribute(ignored.Name);

                //  Remove the node's content from the actual results
                var node = actual.SelectSingleNode(xpath);
                if (node != null) node.InnerText = "";
            }

            XmlDiff comparer = new XmlDiff();
            comparer.Options = XmlDiffOptions.IgnoreComments | XmlDiffOptions.IgnoreNamespaces | XmlDiffOptions.IgnorePrefixes | XmlDiffOptions.IgnoreWhitespace | XmlDiffOptions.IgnoreXmlDecl;

            var settings = new XmlWriterSettings
            {
                OmitXmlDeclaration = true,
                Indent = true,
            };
            using (var writer = XmlWriter.Create(diffReport, settings))
            {
                Assert.IsTrue(
                    comparer.Compare(expected, actual, writer),
                    "Expected Results:\n{0}\n\n" +
                    "Actual Results:\n{1}\n\n" +
                    "Difference Report:\n{2}",
                    formatXml(expected), formatXml(actual), diffReport
                );
            }
        }
        private void DoCompare(string changed)
        {
            CleanupTempFiles();

            XmlDocument original = this.model.Document;
            XmlDocument doc = new XmlDocument();

            XmlReaderSettings settings = model.GetReaderSettings();
            using (XmlReader reader = XmlReader.Create(changed, settings)) {
                doc.Load(reader);
            }

            string startupPath = Application.StartupPath;
            //output diff file.
            string diffFile = Path.Combine(Path.GetTempPath(),
                Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".xml");
            this.tempFiles.AddFile(diffFile, false);

            bool isEqual = false;
            XmlTextWriter diffWriter = new XmlTextWriter(diffFile, Encoding.UTF8);
            diffWriter.Formatting = Formatting.Indented;
            using (diffWriter) {
                XmlDiff diff = new XmlDiff();
                isEqual = diff.Compare(original, doc, diffWriter);
                diff.Options = XmlDiffOptions.None;
            }

            if (isEqual) {
                //This means the files were identical for given options.
                MessageBox.Show(this, SR.FilesAreIdenticalPrompt, SR.FilesAreIdenticalCaption,
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            string tempFile = Path.Combine(Path.GetTempPath(),
                Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".htm");
            tempFiles.AddFile(tempFile, false);

            using (XmlReader diffGram = XmlReader.Create(diffFile, settings)) {
                XmlDiffView diffView = new XmlDiffView();
                diffView.Load(new XmlNodeReader(original), diffGram);
                using (TextWriter htmlWriter = new StreamWriter(tempFile)) {
                    SideBySideXmlNotepadHeader(this.model.FileName, changed, htmlWriter);
                    diffView.GetHtml(htmlWriter);
                }
            }

            /*
            Uri uri = new Uri(tempFile);
            WebBrowserForm browserForm = new WebBrowserForm(uri, "XmlDiff");
            browserForm.Show();
            */
        }
        /// <summary>
        /// Compares table columns from two distinct XML schema files. These files are generated by the SerializeDB method.  
        /// This method is called from the CompareTables method.
        /// </summary>
        /// <param name="tableName">The string value representing the current SQL table object.</param>
        /// <param name="xnlSource">The XmlNodeList, a collection of source XML nodes to compare with the destination XML 
        /// nodes.</param>
        /// <param name="xnlDestination">The XmlNodeList, a collection of destination/target XML nodes to compare with the 
        /// source XML nodes.</param>
        /// <param name="xmlDiffDoc">The XML Diffgram object to update.</param>
        /// <param name="xmlDiff">The XmlDiff Object used from the GotDotNet XmlDiff class. Performs the XML node compare.</param>
        private static void CompareColumns(string tableName, XmlNodeList xnlSource, XmlNodeList xnlDestination,
            XmlDocument xmlDiffDoc, XmlDiff xmlDiff)
        {
            SQLObjects.ColumnCollection tableColumns = new SQLObjects.ColumnCollection(tableName);

            Hashtable htDropAdd = new Hashtable();
            // compare source columns to destination columns, looking for changed or missing destination columns
            if (xnlSource != null)
            {
                // if a matching destination table was found with columns
                if (xnlDestination != null)
                {
                    tableColumns.SchemaAction = SQLObjects.COLUMN.ColumnAction.Alter;
                    // identify the source columns that are different
                    foreach (XmlNode xn in xnlSource)
                    {
                        string column_Name = xn.ChildNodes[1].InnerXml;
                        XmlNode Found = FindNode(xnlDestination, column_Name, "<Column_Name>{0}</Column_Name>");
                        // look for existing columns
                        if (Found != null)
                        {
                            // if the columns don't compare then
                            if (!xmlDiff.Compare(xn, Found))
                            {
                                SQLObjects.COLUMN col = new SQLObjects.COLUMN();
                                col.Action = SQLObjects.COLUMN.ColumnAction.Alter;

                                // add original_rules from the destination column so that if they are not on the source columns we can exec sp_unbindrule on them.
                                // There is XSLT code to handle sp_bindrule for the source columns where they were not bound to the destination(original) column.
                                // IF the source and destination rule names are the same, then we should be able to ignore changing the column bound rule
                                XmlNode xnRule = xn.OwnerDocument.CreateNode(XmlNodeType.Element, "RULE_ORIG_NAME", xn.OwnerDocument.NamespaceURI);
                                if (Found.SelectSingleNode("Rule_Name") != null)
                                {
                                    xnRule.InnerXml = Found.SelectSingleNode("Rule_Name").InnerXml;
                                    xn.AppendChild(xnRule);
                                }

                                xnRule = xn.OwnerDocument.CreateNode(XmlNodeType.Element, "RULE_ORIG_OWNER", xn.OwnerDocument.NamespaceURI);
                                if (Found.SelectSingleNode("Rule_Owner") != null)
                                {
                                    xnRule.InnerXml = Found.SelectSingleNode("Rule_Owner").InnerXml;
                                    xn.AppendChild(xnRule);
                                }

                                XmlNode xnDefault = xn.OwnerDocument.CreateNode(XmlNodeType.Element, "DEFAULT_ORIG_NAME", xn.OwnerDocument.NamespaceURI);
                                if (Found.SelectSingleNode("Default_Name") != null)
                                {
                                    xnDefault.InnerXml = Found.SelectSingleNode("Default_Name").InnerXml;
                                    xn.AppendChild(xnDefault);
                                }

                                xnDefault = xn.OwnerDocument.CreateNode(XmlNodeType.Element, "DEFAULT_ORIG_VALUE", xn.OwnerDocument.NamespaceURI);
                                if (Found.SelectSingleNode("Default_Value") != null)
                                {
                                    xnDefault.InnerXml = Found.SelectSingleNode("Default_Value").InnerXml;
                                    xn.AppendChild(xnDefault);
                                }

                                XmlNode xnRowGuidCol = xn.OwnerDocument.CreateNode(XmlNodeType.Element, "ORIG_RowGuidCol", xn.OwnerDocument.NamespaceURI);
                                if (Found.SelectSingleNode("isRowGuidCol") != null)
                                {
                                    xnRowGuidCol.InnerXml = Found.SelectSingleNode("isRowGuidCol").InnerXml;
                                    xn.AppendChild(xnRowGuidCol);
                                }

                                // lookup any altered columns to see if there are Reference dependencies
                                // may need to use something like this: descendant::*[contains(local-name(),'cKeyCol')]
                                for (int x = 1; x < 17; x++)
                                {
                                    if (Found.SelectSingleNode("../TABLE_REFERENCE/cRefCol" + x.ToString()) != null)
                                    {
                                        CheckColumnDependencies(column_Name, tableName, "DropAdd_References", "TABLE_REFERENCE", "Constraint", "cRefCol" + x.ToString(),
                                            false, ref htDropAdd, Found, xn, xmlDiffDoc);
                                    }
                                }

                                // lookup any altered columns to see if there are Constraint dependencies
                                CheckColumnDependencies(column_Name, tableName, "DropAdd_Constraints", "TABLE_CONSTRAINTS", "CONSTRAINT_NAME", "COLUMN_NAME",
                                    false, ref htDropAdd, Found, xn, xmlDiffDoc);

                                // lookup any altered columns to see if there are index dependencies
                                CheckColumnDependencies(column_Name, tableName, "DropAdd_Indexes", "TABLE_INDEX", "index_name", "index_keys",
                                    false, ref htDropAdd, Found, xn, xmlDiffDoc);

                                // add xml node to the table columns collection
                                SQLObjects.COLUMN c = col.Convert(xn);
                                tableColumns.Add(c);
                            }
                            else
                                continue;
                        }
                        else // the column was not found in the destination table
                        {
                            SQLObjects.COLUMN col = new SQLObjects.COLUMN();
                            col.Action = SQLObjects.COLUMN.ColumnAction.Add;
                            tableColumns.Add(col.Convert(xn));
                        }
                    }
                }
                else // no destination table so add all the columns
                {
                    foreach (XmlNode xn in xnlSource)
                    {
                        string column_Name = xn.ChildNodes[1].InnerXml;
                        SQLObjects.COLUMN col = new SQLObjects.COLUMN();
                        col.Action = SQLObjects.COLUMN.ColumnAction.Add;
                        tableColumns.Add(col.Convert(xn));
                    }
                }
            }
            // look for desination columns not in the source table, so as to mark the desination columns to drop
            if (xnlDestination != null)
            {
                if (xnlSource != null)
                {
                    tableColumns.SchemaAction = SQLObjects.COLUMN.ColumnAction.Alter;
                    // identify the destination columns that are missing 
                    foreach (XmlNode xn in xnlDestination)
                    {
                        string column_Name = xn.ChildNodes[1].InnerXml;
                        XmlNode Found = FindNode(xnlSource, column_Name, "<Column_Name>{0}</Column_Name>");
                        if (Found == null)
                        {
                            SQLObjects.COLUMN col = new SQLObjects.COLUMN();
                            col.Action = SQLObjects.COLUMN.ColumnAction.Drop;

                            XmlNode xnRule = xn.OwnerDocument.CreateNode(XmlNodeType.Element, "RULE_ORIG_NAME", xn.OwnerDocument.NamespaceURI);
                            if (xn.SelectSingleNode("Rule_Name") != null)
                            {
                                xnRule.InnerXml = xn.SelectSingleNode("Rule_Name").InnerXml;
                                xn.AppendChild(xnRule);
                            }

                            xnRule = xn.OwnerDocument.CreateNode(XmlNodeType.Element, "RULE_ORIG_OWNER", xn.OwnerDocument.NamespaceURI);
                            if (xn.SelectSingleNode("Rule_Owner") != null)
                            {
                                xnRule.InnerXml = xn.SelectSingleNode("Rule_Owner").InnerXml;
                                xn.AppendChild(xnRule);
                            }

                            XmlNode xnDefault = xn.OwnerDocument.CreateNode(XmlNodeType.Element, "DEFAULT_ORIG_NAME", xn.OwnerDocument.NamespaceURI);
                            if (xn.SelectSingleNode("Default_Name") != null)
                            {
                                xnDefault.InnerXml = xn.SelectSingleNode("Default_Name").InnerXml;
                                xn.AppendChild(xnDefault);
                            }

                            xnDefault = xn.OwnerDocument.CreateNode(XmlNodeType.Element, "DEFAULT_ORIG_VALUE", xn.OwnerDocument.NamespaceURI);
                            if (xn.SelectSingleNode("Default_Value") != null)
                            {
                                xnDefault.InnerXml = xn.SelectSingleNode("Default_Value").InnerXml;
                                xn.AppendChild(xnDefault);
                            }

                            // lookup any dropped columns to see if there are Reference dependencies,
                            // may need to use something like this: descendant::*[contains(local-name(),'cKeyCol')]
                            for (int x = 1; x < 17; x++)
                            {
                                if (xn.SelectSingleNode("../TABLE_REFERENCE/cRefCol" + x.ToString()) != null)
                                {
                                    CheckColumnDependencies(column_Name, tableName, "DropAdd_References", "TABLE_REFERENCE", "Constraint", "cRefCol" + x.ToString(),
                                        true, ref htDropAdd, null, xn, xmlDiffDoc);
                                }
                            }

                            // lookup any altered columns to see if there are Constraint dependencies
                            CheckColumnDependencies(column_Name, tableName, "DropAdd_Constraints", "TABLE_CONSTRAINTS", "CONSTRAINT_NAME", "COLUMN_NAME",
                                true, ref htDropAdd, null, xn, xmlDiffDoc);

                            // lookup any dropped columns to see if there are index dependencies
                            CheckColumnDependencies(column_Name, tableName, "DropAdd_Indexes", "TABLE_INDEX", "index_name", "index_keys",
                                true, ref htDropAdd, null, xn, xmlDiffDoc);

                            tableColumns.Add(col.Convert(xn));
                        }
                    }
                }
            }
            // persist the tableColumns collection as XML if there are any
            if (tableColumns.Count > 0)
            {
                XmlNode xTableColumns = tableColumns.SerializeAsXmlNode(xmlDiffDoc);
                foreach (object obj in htDropAdd.Values)
                {
                    xTableColumns.AppendChild((XmlNode)obj);
                }
                xmlDiffDoc.SelectSingleNode("/DataBase_Schema").AppendChild(xTableColumns);
            }
        }
        /// <summary>
        /// Compare the xml data files
        /// </summary>
        /// <param name="sourceXmlFile">baseline file</param>
        /// <param name="changedXmlFile">actual file</param>
        /// <param name="fragment">xml data fragment</param>
        /// <param name="options">comparison options</param>
        /// <returns>data is identical</returns>
        private bool GenerateDiffGram(
            string sourceXmlFile,
            string changedXmlFile,
            bool fragment,
            XmlDiffOptions options)
        {
            // set class scope variables
            // MemoryStream diffgram
            bool identicalData;
            this.diffgram = new MemoryStream();
            XmlTextWriter diffgramWriter = new XmlTextWriter(
                new StreamWriter(this.diffgram));

            Trace.WriteLine("Comparing " + sourceXmlFile +
                " & " + changedXmlFile);
            XmlDiffOptions xmlDiffOptions = (XmlDiffOptions)options;
            XmlDiff xmlDiff = new XmlDiff(xmlDiffOptions);

            try
            {
                identicalData = xmlDiff.Compare(
                    sourceXmlFile,
                    changedXmlFile,
                    fragment,
                    diffgramWriter);
            }
            catch (XmlException format)
            {
                Trace.WriteLine(format.Message);
                throw;
            }
            Trace.WriteLine("Files compared " +
                (identicalData ? "identical." : "different."));

            return identicalData;
        }
        /// <summary>
        /// Compares SQL table schemas from two distinct XML schema files.  These files are generated by the SerializeDB method.
        /// </summary>
        /// <param name="_serverDB"></param>
        /// <param name="xmlSourceDoc">The XmlDataDocument, the source XML to compare with the destination XML.</param>
        /// <param name="xmlDestinationDoc">The XmlDataDocument, the destination/target XML to compare with the source XML.</param>
        /// <param name="xmlDiffDoc">The XML Diffgram document to update.</param>
        /// <param name="xmlDiff">The XmlDiff Object used from the GotDotNet XmlDiff class. Performs the XML node compare.</param>
        /// <param name="TableName">specifies a specific SQL table to compare</param>
        public static void CompareTables(string _serverDB, XmlDocument xmlSourceDoc, XmlDocument xmlDestinationDoc,
            XmlDocument xmlDiffDoc, XmlDiff xmlDiff, string TableName)
        {
            // NOTE:  we are ignoring the destination tables that don't exist in the source DB
            XPathNavigator navSource = xmlSourceDoc.CreateNavigator();
            XPathNavigator navDest = xmlDestinationDoc.CreateNavigator();

            // iterate thru the source tables 
            // we are going to ignore destination tables which are not in the source DB
            // as they could be custom tables added by some outside tool or person
            XmlNodeList xNodeList = xmlSourceDoc.SelectNodes("/DataBase_Schema/TABLE");
            foreach (XmlNode xnChild_Source in xNodeList)
            {
                XmlNode xmlTableNode = null;
                string tableName = xnChild_Source.ChildNodes[0].InnerXml;
                if (TableName != null && !tableName.ToLower().Equals(TableName.ToLower()))
                {
                    continue; // if in single table mode then loop until correct table is found
                }
                string xpath = "descendant::TABLE[TABLE_NAME='" + tableName + "']/COLUMN";
                logger.Debug("\n{1}: Comparing columns for {0}.", tableName, _serverDB);

                XPathExpression exprSource = navSource.Compile(xpath);
                XPathExpression exprDest = navDest.Compile(xpath);

                // get xmlnodes for columns in source
                XmlNodeList xnlSource = xmlSourceDoc.SelectNodes(exprSource.Expression);
                // get xmlnode for table in destination
                XmlNode xmlDestTable = xmlDestinationDoc.SelectSingleNode("/DataBase_Schema/TABLE[TABLE_NAME='" + tableName + "']");

                if (xmlDestTable != null)
                {
                    // if table doesn't compare then walk thru each column else
                    if (!xmlDiff.Compare(xnChild_Source, xmlDestTable))
                    {
                        // get xmlnodes for columns in destination
                        XmlNodeList xnlDestination = xmlDestinationDoc.SelectNodes(exprDest.Expression);
                        // Compare table columns and updates the DiffGram XML doc
                        // TODO: use async threads to launch CompareColumns so that multiples can run at the same time
                        CompareColumns(tableName, xnlSource, xnlDestination, xmlDiffDoc, xmlDiff);

                        // add the missing source table related child nodes
                        xmlTableNode = xmlDiffDoc.SelectSingleNode("/DataBase_Schema/TABLE[TABLE_NAME='" + tableName + "']");
                        if (xmlTableNode != null)
                        {
                            // assume same owner as source table, may need to change this in the future
                            xmlTableNode.SelectSingleNode("TABLE_OWNER").InnerXml = xnChild_Source.SelectSingleNode("TABLE_OWNER").InnerXml;
                            // assume same FileGroup as source table, may need to change this in the future
                            xmlTableNode.SelectSingleNode("TABLE_FILEGROUP").InnerXml = xnChild_Source.SelectSingleNode("TABLE_FILEGROUP").InnerXml;
                            // walk all source and dest references nodes and add them to the xml diff doc
                            CompareTableObjs("References", xnChild_Source, xmlDestTable, xmlTableNode, xmlDiffDoc, xmlDiff);
                            // walk all source and dest index nodes and add them to the xml diff doc
                            CompareTableObjs("Indexes", xnChild_Source, xmlDestTable, xmlTableNode, xmlDiffDoc, xmlDiff);
                            // walk all source and dest constraints nodes and add them to the xml diff doc
                            CompareTableObjs("Constraints", xnChild_Source, xmlDestTable, xmlTableNode, xmlDiffDoc, xmlDiff);
                        }
                        else
                        {
                            xmlTableNode = xmlDiffDoc.CreateNode(XmlNodeType.Element, "TABLE", xmlDiffDoc.NamespaceURI);
                            xmlTableNode.AppendChild(xmlDiffDoc.CreateNode(XmlNodeType.Element, "TABLE_NAME", xmlDiffDoc.NamespaceURI));
                            xmlTableNode.AppendChild(xmlDiffDoc.CreateNode(XmlNodeType.Element, "TABLE_OWNER", xmlDiffDoc.NamespaceURI));
                            xmlTableNode.AppendChild(xmlDiffDoc.CreateNode(XmlNodeType.Element, "TABLE_FILEGROUP", xmlDiffDoc.NamespaceURI));
                            xmlTableNode.AppendChild(xmlDiffDoc.CreateNode(XmlNodeType.Element, "TABLE_REFERENCE", xmlDiffDoc.NamespaceURI));
                            xmlTableNode.AppendChild(xmlDiffDoc.CreateNode(XmlNodeType.Element, "TABLE_CONSTRAINTS", xmlDiffDoc.NamespaceURI));
                            xmlTableNode.AppendChild(xmlDiffDoc.CreateNode(XmlNodeType.Element, "TABLE_ORIG_CONSTRAINTS", xmlDiffDoc.NamespaceURI));
                            xmlTableNode.AppendChild(xmlDiffDoc.CreateNode(XmlNodeType.Element, "TABLE_ORIG_REFERENCE", xmlDiffDoc.NamespaceURI));
                            xmlTableNode.Attributes.Append((XmlAttribute)xmlDiffDoc.CreateNode(XmlNodeType.Attribute, "Action", xmlDiffDoc.NamespaceURI));
                            xmlTableNode.SelectSingleNode("TABLE_NAME").InnerXml = tableName;
                            xmlTableNode.Attributes["Action"].Value = "Alter";

                            xmlDiffDoc.SelectSingleNode("/DataBase_Schema").AppendChild(xmlTableNode);
                            // assume same owner as source table, may need to change this in the future
                            xmlTableNode.SelectSingleNode("TABLE_OWNER").InnerXml = xnChild_Source.SelectSingleNode("TABLE_OWNER").InnerXml;
                            // assume same FileGroup as source table, may need to change this in the future
                            xmlTableNode.SelectSingleNode("TABLE_FILEGROUP").InnerXml = xnChild_Source.SelectSingleNode("TABLE_FILEGROUP").InnerXml;
                            // walk all source and dest references nodes and add them to the xml diff doc
                            CompareTableObjs("References", xnChild_Source, xmlDestTable, xmlTableNode, xmlDiffDoc, xmlDiff);
                            // walk all source and dest index nodes and add them to the xml diff doc
                            CompareTableObjs("Indexes", xnChild_Source, xmlDestTable, xmlTableNode, xmlDiffDoc, xmlDiff);
                            // walk all source and dest constraints nodes and add them to the xml diff doc
                            CompareTableObjs("Constraints", xnChild_Source, xmlDestTable, xmlTableNode, xmlDiffDoc, xmlDiff);
                        }
                    }
                    else
                        continue;
                }
                else // a new table which doesn't have the add element or attribute for the columns, just the table itself
                {
                    // add copy of source table node (and child nodes) to xmldiffdoc, since it doesn't exist in the destination 
                    // table
                    xmlTableNode = xmlDiffDoc.CreateNode(XmlNodeType.Element, "TABLE", xmlDiffDoc.NamespaceURI);
                    xmlTableNode.InnerXml = xnChild_Source.InnerXml;
                    xmlTableNode.Attributes.Append((XmlAttribute)xmlDiffDoc.CreateNode(XmlNodeType.Attribute, "Action", xmlDiffDoc.NamespaceURI));
                    xmlTableNode.Attributes["Action"].Value = "Add";
                    xmlDiffDoc.SelectSingleNode("/DataBase_Schema").AppendChild(xmlTableNode);
                }
            }
            navSource = null;
            navDest = null;
        }
        /// <summary>
        /// compares two xml data sources as xml strings
        /// </summary>
        /// <param name="querySource">the SQL query text for the source</param>
        /// <param name="queryTarget">the SQL query text for the target</param>
        /// <param name="connectionSource">The sql connection object for the source</param>
        /// <param name="connectionTarget">The sql connection object for the target</param>
        /// <param name="asTextFile"></param>
        /// <returns></returns>
        public static string CompareData(string querySource, string queryTarget, SqlConnection connectionSource, SqlConnection connectionTarget, bool asTextFile)
        {
            bool isEqual = false;
            string tempFile = "TableDiffReport.html";
            string sourceName = querySource.Replace("select * from ", "").Split(' ')[0].Replace("\\", "_").Replace(":", "-") + ".xml";
            string targetName = queryTarget.Replace("select * from ", "").Split(' ')[0].Replace("\\", "_").Replace(":", "-") + ".xml";
            //output diff file.
            string diffFile = sourceName.Replace(".xml", "") + "_DIFF_" + targetName;
            XmlDiffOptions xdo = XmlDiffOptions.IgnoreWhitespace | XmlDiffOptions.IgnoreComments | XmlDiffOptions.IgnoreChildOrder | XmlDiffOptions.IgnoreNamespaces | XmlDiffOptions.IgnorePI;

            XmlDocument original = new XmlDocument();
            original.LoadXml(GetXMLData(querySource, connectionSource));
            original.Save(sourceName);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(GetXMLData(queryTarget, connectionTarget));
            doc.Save(targetName);

            if (asTextFile)
            {
                XmlDiffView diffView = new XmlDiffView();
                diffView.DifferencesAsFormattedText(sourceName, targetName, diffFile.Replace(".xml", "") + ".txt", false, xdo);
                diffView = null;
                return diffFile.Replace(".xml", "") + ".txt";
            }
            else
            {

                XmlTextWriter diffWriter = new XmlTextWriter(diffFile, Encoding.UTF8);
                diffWriter.Formatting = Formatting.Indented;
                using (diffWriter)
                {
                    XmlDiff diff = new XmlDiff();
                    isEqual = diff.Compare(original, doc, diffWriter);
                    diff.Options = xdo;
                }

                if (isEqual)
                {
                    //This means the files were identical for given options.
                    MessageBox.Show("Tables are identical", "Identical",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return string.Empty;
                }

                using (XmlReader diffGram = XmlReader.Create(diffFile))
                {
                    XmlDiffView diffView = new XmlDiffView();
                    diffView.Load(new XmlNodeReader(original), diffGram);
                    using (TextWriter htmlWriter = new StreamWriter(tempFile))
                    {
                        SideBySideXmlNotepadHeader(sourceName, targetName, htmlWriter);
                        diffView.GetHtml(htmlWriter);
                    }
                    diffView = null;
                }
            }
            return tempFile;
        }
        private static void CompareXml(string actualFileLocation, string expectedFileName)
        {
            Contract.Requires(!String.IsNullOrEmpty(actualFileLocation));
            Contract.Requires(!String.IsNullOrEmpty(expectedFileName));
            Contract.Requires(File.Exists(actualFileLocation));

            var actualFile = new XmlDocument();
            actualFile.Load(actualFileLocation);

            var expectedFile = new XmlDocument();
            expectedFile.Load(Assembly.GetExecutingAssembly().GetManifestResourceStream("Oddleif.RunKeeper.Client.Test.ExpectedOutput." + expectedFileName));

            var diff = new XmlDiff();

            Assert.IsTrue(diff.Compare(expectedFile.DocumentElement, actualFile.DocumentElement));
        }
Example #15
0
        private static void Main(string[] args)
        {
            var bFragments       = false;
            var flag1            = false;
            var xmlDiffAlgorithm = XmlDiffAlgorithm.Auto;

            try
            {
                if (args.Length < 3)
                {
                    TestXmlDiff.WriteUsage();
                    return;
                }
                var options = XmlDiffOptions.None;
                var index   = 0;
                var empty   = string.Empty;
                while (args[index][0] == '/')
                {
                    if (args[index].Length != 2)
                    {
                        Console.Write("Invalid option: " + args[index] + "\n");
                        return;
                    }
                    switch (args[index][1])
                    {
                    case 'c':
                        options |= XmlDiffOptions.IgnoreComments;
                        break;

                    case 'd':
                        options |= XmlDiffOptions.IgnoreDtd;
                        break;

                    case 'e':
                        flag1 = true;
                        break;

                    case 'f':
                        bFragments = true;
                        break;

                    case 'n':
                        options |= XmlDiffOptions.IgnoreNamespaces;
                        break;

                    case 'o':
                        options |= XmlDiffOptions.IgnoreChildOrder;
                        break;

                    case 'p':
                        options |= XmlDiffOptions.IgnorePI;
                        break;

                    case 'r':
                        options |= XmlDiffOptions.IgnorePrefixes;
                        break;

                    case 't':
                        xmlDiffAlgorithm = XmlDiffAlgorithm.Fast;
                        break;

                    case 'w':
                        options |= XmlDiffOptions.IgnoreWhitespace;
                        break;

                    case 'x':
                        options |= XmlDiffOptions.IgnoreXmlDecl;
                        break;

                    case 'z':
                        xmlDiffAlgorithm = XmlDiffAlgorithm.Precise;
                        break;

                    default:
                        Console.Write("Invalid option: " + args[index] + "\n");
                        return;
                    }
                    empty += (string)(object)args[index][1];
                    ++index;
                    if (args.Length - index < 3)
                    {
                        TestXmlDiff.WriteUsage();
                        return;
                    }
                }
                var str1  = args[index];
                var str2  = args[index + 1];
                var str3  = args[index + 2];
                var flag2 = args.Length - index == 4 && args[index + 3] == "verify";
                var str4  = str1.Substring(str1.LastIndexOf("\\") + 1) + " & " + str2.Substring(str2.LastIndexOf("\\") + 1) + " -> " + str3.Substring(str3.LastIndexOf("\\") + 1);
                if (empty != string.Empty)
                {
                    str4 = str4 + " (" + empty + ")";
                }
                Console.Write(str4.Length >= 60 ? str4 + "\n" + new string(' ', 60) : str4 + new string(' ', 60 - str4.Length));
                var diffgramWriter1 = (XmlWriter) new XmlTextWriter(str3, (Encoding) new UnicodeEncoding());
                var xmlDiff         = new XmlDiff(options);
                xmlDiff.Algorithm = xmlDiffAlgorithm;
                bool flag3;
                if (flag1)
                {
                    if (bFragments)
                    {
                        Console.Write("Cannot have option 'd' and 'f' together.");
                        return;
                    }
                    var xmlDocument1 = new XmlDocument();
                    xmlDocument1.Load(str1);
                    var xmlDocument2 = new XmlDocument();
                    xmlDocument2.Load(str2);
                    flag3 = xmlDiff.Compare((XmlNode)xmlDocument1, (XmlNode)xmlDocument2, diffgramWriter1);
                }
                else
                {
                    flag3 = xmlDiff.Compare(str1, str2, bFragments, diffgramWriter1);
                }
                if (flag3)
                {
                    Console.Write("identical");
                }
                else
                {
                    Console.Write("different");
                }
                diffgramWriter1.Close();
                if (!flag3 && flag2)
                {
                    XmlNode sourceNode;
                    if (bFragments)
                    {
                        var     nameTable        = new NameTable();
                        var     xmlTextReader    = new XmlTextReader((Stream) new FileStream(str1, FileMode.Open, FileAccess.Read), XmlNodeType.Element, new XmlParserContext((XmlNameTable)nameTable, new XmlNamespaceManager((XmlNameTable)nameTable), string.Empty, XmlSpace.Default));
                        var     xmlDocument      = new XmlDocument();
                        var     documentFragment = xmlDocument.CreateDocumentFragment();
                        XmlNode newChild;
                        while ((newChild = xmlDocument.ReadNode((XmlReader)xmlTextReader)) != null)
                        {
                            if (newChild.NodeType != XmlNodeType.Whitespace)
                            {
                                documentFragment.AppendChild(newChild);
                            }
                        }
                        sourceNode = (XmlNode)documentFragment;
                    }
                    else
                    {
                        var xmlDocument = new XmlDocument();
                        xmlDocument.XmlResolver = (XmlResolver)null;
                        xmlDocument.Load(str1);
                        sourceNode = (XmlNode)xmlDocument;
                    }
                    new XmlPatch().Patch(ref sourceNode, (XmlReader) new XmlTextReader(str3));
                    if (sourceNode.NodeType == XmlNodeType.Document)
                    {
                        ((XmlDocument)sourceNode).Save("_patched.xml");
                    }
                    else
                    {
                        var xmlTextWriter = new XmlTextWriter("_patched.xml", Encoding.Unicode);
                        sourceNode.WriteTo((XmlWriter)xmlTextWriter);
                        xmlTextWriter.Close();
                    }
                    var diffgramWriter2 = (XmlWriter) new XmlTextWriter("_2ndDiff.xml", (Encoding) new UnicodeEncoding());
                    if (xmlDiff.Compare("_patched.xml", str2, bFragments, diffgramWriter2))
                    {
                        Console.Write(" - ok");
                    }
                    else
                    {
                        Console.Write(" - FAILED");
                    }
                    diffgramWriter2.Close();
                }
                Console.Write("\n");
            }
            catch (Exception ex)
            {
                Console.Write("\n*** Error: " + ex.Message + " (source: " + ex.Source + ")\n");
            }
            if (!Debugger.IsAttached)
            {
                return;
            }
            Console.Write("\nPress enter...\n");
            Console.Read();
        }
Example #16
0
        public bool XmlDiffHtm(string source, string target, string intervalo, string server, string classe)
        {
            // Randomiza para criar arquivos unicos de comparação
            r = new Random();
            bool isEqual = false;

            //Pega o usuário logado...
            MembershipUser currentUser = Membership.GetUser();

            //output diff file.
            startupPath = ConfigurationManager.AppSettings["XMLData"] + "\\RPTs";
            diffFile = startupPath + Path.DirectorySeparatorChar + "vxd" + r.Next() + ".out";
            //
            XmlTextWriter tw = new XmlTextWriter(new StreamWriter(diffFile));
            tw.Formatting = Formatting.Indented;

            try
            {
                XmlReader expected = XmlReader.Create(new StringReader(target));
                XmlReader actual = XmlReader.Create(new StringReader(source));

                XmlDiff diff = new XmlDiff( XmlDiffOptions.IgnoreChildOrder |
                                            XmlDiffOptions.IgnoreComments   |
                                            XmlDiffOptions.IgnoreXmlDecl    |
                                            XmlDiffOptions.IgnoreWhitespace);

                isEqual = diff.Compare(actual, expected, tw);
                tw.Close();

                //-----------------------------------------------------------------
                // Cria a comparação dos XMLs...
                XmlDiffView dv = new XmlDiffView();

                // Carrega o arquivo orig = source + o arquivo XML das Diff...
                XmlTextReader orig = new XmlTextReader(new StringReader(source)); //source
                XmlTextReader diffGram = new XmlTextReader(diffFile);
                dv.Load(orig,
                    diffGram);

                orig.Close();
                diffGram.Close();

                // Chama a função para gravar e formatar o conteudo + diff em HTM...
                if (!isEqual)
                { GrHtm(dv, intervalo, server, classe); }
                //
                return isEqual;
            }
            catch (XmlException xe)
            {
                divMessage.InnerHtml = "<span id='msg' style='color:#FF3300;font-size:Smaller;font-weight:bold;'>Ocorreu um erro de Comparação - " + xe.StackTrace + "</span>";
                return isEqual;
            }
        }
        private bool CompareXmlFiles(string expectationFile, string transformedResultFile, out string diffFile)
        {
            diffFile = Path.GetTempFileName();

            // ReSharper disable BitwiseOperatorOnEnumWithoutFlags
            var xmldiff = new XmlDiff(XmlDiffOptions.IgnoreDtd |
                                      XmlDiffOptions.IgnoreNamespaces |
                                      XmlDiffOptions.IgnorePrefixes |
                                      XmlDiffOptions.IgnoreWhitespace |
                                      XmlDiffOptions.IgnoreXmlDecl);
            // ReSharper restore BitwiseOperatorOnEnumWithoutFlags
            using (var writer = new XmlTextWriter(diffFile, Encoding.UTF8))
            {
                return xmldiff.Compare(expectationFile, transformedResultFile, false, writer);
            }
        }
Example #18
0
        public void Run()
        {
            Stream strmDiff = null;
              DateTime dtStart = DateTime.Now;
              int iFileCount = 0;

              try
              {

            string strXmlInputRoot = ConfigurationManager.AppSettings.Get("XmlInputDirectory");
            inputDirectory = new DirectoryInfo(string.Format("{0}\\today", strXmlInputRoot));
            updateDirectory = new DirectoryInfo(string.Format("{0}\\update", strXmlInputRoot));
            currentDirectory = new DirectoryInfo(string.Format("{0}\\current", strXmlInputRoot));
            rejectDirectory = new DirectoryInfo(string.Format("{0}\\reject", strXmlInputRoot));

            // delete all files in update directory
            updateDirectory.Empty();

            // get list of files in input & current directories
            FileInfo[] arrFiles = inputDirectory.GetFiles();

            arrFiles = (from oFile in arrFiles
                   orderby oFile.Length ascending
                   select oFile).ToArray<FileInfo>();
            string[] arrCurrentFiles = Directory.GetFiles(currentDirectory.FullName);
            writeLogInfo(string.Format("{0} files in today's folder", arrFiles.Length.ToString()));
            int iMaxFiles = arrFiles.Length;
            /*
            if (iMaxFiles > 100)
              iMaxFiles = 100;
            */
            for (int i = 0; i < iMaxFiles; i++)
            {
              FileInfo fiFile = arrFiles[i];
              iFileCount++;
              writeLogInfo(fiFile.Name + " : " + iFileCount.ToString());
              if (validateXml(fiFile))
              {
            xmlDocToday = oDoc;
            if (!arrCurrentFiles.Contains<string>(string.Format("{0}\\{1}", currentDirectory.FullName, fiFile.Name)))
            {
              if (processWholeFile(fiFile, xmlDocToday))
              {
                // Move file to "Current" and "Update" folders
                fiFile.CopyTo(string.Format("{0}\\{1}", updateDirectory.FullName, fiFile.Name));
                fiFile.MoveTo(string.Format("{0}\\{1}", currentDirectory.FullName, fiFile.Name));
              }
            }
            else
            {
              xmlCurrent.Load(string.Format("{0}\\{1}", currentDirectory.FullName, fiFile.Name));
              strmDiff = new MemoryStream();
              XmlTextWriter diffGram = new XmlTextWriter(new StreamWriter(strmDiff));
              diffGram.Formatting = Formatting.Indented;
              XmlDiff diff = new XmlDiff(XmlDiffOptions.IgnoreChildOrder);
              diff.Compare(xmlCurrent, xmlDocToday, diffGram);
              strmDiff.Position = 0;
              strRead = new StreamReader(strmDiff);
              string strDiffGraph = strRead.ReadToEnd();
              xmlDiffGraph.LoadXml(strDiffGraph);
              if (xmlDiffGraph.ChildNodes[1].HasChildNodes)
              {
                if (processWholeFile(fiFile, xmlDocToday))
                {
                  // Move file to "Current" and "Update" folders
                  fiFile.CopyTo(string.Format("{0}\\{1}", updateDirectory.FullName, fiFile.Name));
                  fiFile.MoveTo(string.Format("{0}\\{1}", currentDirectory.FullName, fiFile.Name));
                }
              }
            }
              }
              else
              {
            fiFile.MoveTo(string.Format("{0}\\{1}", rejectDirectory.FullName, fiFile.Name));
              }

            }
            //PublishTours(itmTourFolder);
              }
              catch (Exception ex)
              {
            logError(ex.ToString());
              }
              finally
              {
            // clean up resources
            if (strmDiff != null)
            {
              strmDiff.Close();
              strmDiff.Dispose();
            }
            if (strRead != null)
            {
              strRead.Close();
              strRead.Dispose();
            }
            writeLogInfo((DateTime.Now - dtStart).TotalSeconds.ToString());
              }
        }
        /// <summary>
        /// Compares table indexes, table constraints, and table FK/PK references from two distinct XML schema files. These 
        /// files are generated by the SerializeDB method.  This method is called by the CompareTables method.
        /// </summary>
        /// <param name="objType">The type of database table related object collection to compare, i.e. indexes, constraints 
        /// (check and default), and references.</param>
        /// <param name="SourceTable">The SourceTable XML Node containing all table object related child nodes to compare with 
        /// the destination child nodes.</param>
        /// <param name="DestTable">The DestTable XML Node containing all table object related child nodes to compare with 
        /// the source child nodes.</param>
        /// <param name="DiffTable">The XML Diffgram table node to update.</param>
        /// <param name="xmlDiffDoc">The XML Diffgram document to update.</param>
        /// <param name="xmlDiff">The XmlDiff Object used from the GotDotNet XmlDiff class. Performs the XML node compare.</param>
        private static void CompareTableObjs(string objType, XmlNode SourceTable, XmlNode DestTable, XmlNode DiffTable,
            XmlDocument xmlDiffDoc, XmlDiff xmlDiff)
        {
            string MainNode = string.Empty;
            string OrigNode = string.Empty;
            string xpathpart = string.Empty;
            string objName = string.Empty;
            switch (objType.ToLower())
            {
                case "indexes":
                    {
                        MainNode = "TABLE_INDEX";
                        OrigNode = "TABLE_ORIG_INDEX";
                        xpathpart = "TABLE_INDEX[index_name='";
                        objName = "index_name";
                        break;
                    }
                case "constraints":
                    {
                        MainNode = "TABLE_CONSTRAINTS";
                        OrigNode = "TABLE_ORIG_CONSTRAINTS";
                        xpathpart = "TABLE_CONSTRAINTS[CONSTRAINT_NAME='";
                        objName = "CONSTRAINT_NAME";
                        break;
                    }
                case "references":
                    {
                        MainNode = "TABLE_REFERENCE";
                        OrigNode = "TABLE_ORIG_REFERENCE";
                        xpathpart = "TABLE_REFERENCE[Constraint='";
                        objName = "Constraint";
                        break;
                    }
            }

            XmlNodeList xmlSourceObjs = SourceTable.SelectNodes(MainNode);
            XmlNodeList xmlDestObjs = DestTable.SelectNodes(MainNode);
            // compare source and dest nodes, also looking for missing dest nodes
            foreach (XmlNode xnsourceobj in xmlSourceObjs)
            {
                XmlNode xn = xnsourceobj.SelectSingleNode(objName);
                if (xn != null)
                {
                    string source_obj_name = xn.InnerXml;
                    XmlNode dest_obj_node = DestTable.SelectSingleNode(xpathpart + source_obj_name + "']");
                    // if dest index node is found then compare
                    if (dest_obj_node != null)
                    {
                        // if the source and dest index nodes don't match then add both the the xml diff file
                        if (!xmlDiff.Compare(xnsourceobj, dest_obj_node))
                        {
                            // check node for children, otherwise its a waste of time
                            if (xnsourceobj.HasChildNodes)
                            {
                                XmlNode xnChild1 = xmlDiffDoc.CreateNode(XmlNodeType.Element, MainNode, xmlDiffDoc.NamespaceURI);
                                xnChild1.InnerXml = xnsourceobj.InnerXml;
                                DiffTable.AppendChild(xnChild1);
                            }
                            // check node for children, otherwise its a waste of time
                            if (dest_obj_node.HasChildNodes)
                            {
                                XmlNode xnChild2 = xmlDiffDoc.CreateNode(XmlNodeType.Element, OrigNode, xmlDiffDoc.NamespaceURI);
                                xnChild2.InnerXml = dest_obj_node.InnerXml;
                                DiffTable.AppendChild(xnChild2);
                            }
                        }
                    }
                    else // missing dest node, so add source node
                    {
                        // check node for children, otherwise its a waste of time
                        if (xnsourceobj.HasChildNodes)
                        {
                            XmlNode xnChild1 = xmlDiffDoc.CreateNode(XmlNodeType.Element, MainNode, xmlDiffDoc.NamespaceURI);
                            xnChild1.InnerXml = xnsourceobj.InnerXml;
                            DiffTable.AppendChild(xnChild1);
                        }
                    }
                }
            }
            // look for dest nodes that don't exist in source
            foreach (XmlNode xndestobj in xmlDestObjs)
            {
                XmlNode xn = xndestobj.SelectSingleNode(objName);
                if (xn != null)
                {
                    string dest_obj_name = xn.InnerXml;
                    XmlNode source_index_node = SourceTable.SelectSingleNode(xpathpart + dest_obj_name + "']");
                    // if dest node doesn't exist in source table then add dest node to the xml diff doc so thaqt it can be removed
                    if (source_index_node == null || !source_index_node.HasChildNodes)
                    {
                        // check node for children, otherwise its a waste of time
                        if (xndestobj.HasChildNodes)
                        {
                            XmlNode xnChild2 = xmlDiffDoc.CreateNode(XmlNodeType.Element, OrigNode, xmlDiffDoc.NamespaceURI);
                            xnChild2.InnerXml = xndestobj.InnerXml;
                            DiffTable.AppendChild(xnChild2);
                        }
                    }
                }
            }
        }
Example #20
0
        static void Main(string[] args)
        {
            bool fragments = false;
            XmlDiffAlgorithm algorithm = XmlDiffAlgorithm.Auto;
            XmlDiffOptions options = XmlDiffOptions.None;

            // process options
            int curArgsIndex = 0;
            while ( curArgsIndex < args.Length &&
                ( args[curArgsIndex][0] == '/' || args[curArgsIndex][0] == '-' ) ) {

                if ( args[curArgsIndex].Length != 2 ) {
                    Console.WriteLine( "Invalid option: " + args[curArgsIndex] );
                    WriteUsage();
                    return;
                }

                switch ( args[curArgsIndex][1] ) {
                    case 'o':
                        options |= XmlDiffOptions.IgnoreChildOrder;
                        break;
                    case 'c':
                        options |= XmlDiffOptions.IgnoreComments;
                        break;
                    case 'p':
                        options |= XmlDiffOptions.IgnorePI;
                        break;
                    case 'w':
                        options |= XmlDiffOptions.IgnoreWhitespace;
                        break;
                    case 'n':
                        options |= XmlDiffOptions.IgnoreNamespaces;
                        break;
                    case 'r':
                        options |= XmlDiffOptions.IgnorePrefixes;
                        break;
                    case 'x':
                        options |= XmlDiffOptions.IgnoreXmlDecl;
                        break;
                    case 'd':
                        options |= XmlDiffOptions.IgnoreDtd;
                        break;
                    case 'f':
                        fragments = true;
                        break;
                    case 't':
                        algorithm = XmlDiffAlgorithm.Fast;
                        break;
                    case 'z':
                        algorithm = XmlDiffAlgorithm.Precise;
                        break;
                    case '?':
                        WriteUsage();
                        return;
                    default:
                        Console.Write( "Invalid option: " + args[curArgsIndex] + "\n" );
                        return;
                }
                curArgsIndex++;
            }

            if ( args.Length < 2 ) {
                Console.WriteLine( "Invalid arguments." );
                WriteUsage();
                return;
            }

            // extract names from command line
            string sourceXmlFileName = args[ curArgsIndex ];
            string changedXmlFileName = args[ curArgsIndex + 1 ];
            string ignoreFileName = args[curArgsIndex + 2];
            string diffgramFileName = (curArgsIndex + 3 < args.Length) ? args[curArgsIndex + 3] : null;

            Console.WriteLine( "Comparing " + sourceXmlFileName + " to " + changedXmlFileName + " using ignore config " + ignoreFileName );

            // create XmlTextWriter where the diffgram will be saved
            XmlWriter diffgramWriter = null;
            if ( diffgramFileName != null ) {
                diffgramWriter = new XmlTextWriter( diffgramFileName, Encoding.Unicode );
            }

            // create XmlDiff object & set the desired options and algorithm
            XmlDiff xmlDiff = new XmlDiff( options );
            xmlDiff.Algorithm = algorithm;

            // Compare the XML files
            bool bEqual = false;
            try {
                bEqual = xmlDiff.Compare(sourceXmlFileName, changedXmlFileName, fragments, diffgramWriter, ignoreFileName);
            }
            catch (Exception e) {
                WriteError(e.Message);
                Console.ReadKey();
                return;
            }
            if (bEqual) {
                Console.WriteLine( "Files are identical." );
            }
            else {
                Console.WriteLine( "Files are different." );
            }
            if ( diffgramWriter != null ) {
                diffgramWriter.Close();
                Console.WriteLine( "XDL diffgram has been saved to " + diffgramFileName + "." );
            }

            Console.ReadKey();
            return;
        }
Example #21
0
		public bool DoTest(string sfmFileName, string mapFileName, string phase4KeyFileName, string locationOfFinalFile)
		{
			m_sfmName = sfmFileName;
			m_mapName = mapFileName;
			m_keyName = phase4KeyFileName;
			m_Phase5Output = locationOfFinalFile;

			Converter conv = new Converter();

			// read in the Lex Import Fields
			LexImportFields autoFields = new LexImportFields();
			autoFields.ReadLexImportFields(@"C:\fw\DistFiles\Language Explorer\Import\ImportFields.xml");
			// if there are auto fields in the xml file, pass them on to the converter
			Hashtable htAutoFields = autoFields.GetAutoFields();
			foreach (DictionaryEntry laf in htAutoFields)
			{
				string entryClass = laf.Key as String;
				LexImportField lexField = laf.Value as LexImportField;
				string fwDest = lexField.ID;
				conv.AddPossibleAutoField(entryClass, fwDest);
			}

			//// here the Auto import fields needs to be added to the converter as it is in the actual import process
			//conv.AddPossibleAutoField("Entry", "eires");
			//conv.AddPossibleAutoField("Sense", "sires");
			//conv.AddPossibleAutoField("Subentry", "seires");
			//conv.AddPossibleAutoField("Variant", "veires");

			conv.Convert(m_sfmName, m_mapName, m_phase1output);
			ProcessPhase1Errors();

			DoTransform(m_BuildPhase2XSLT, m_phase1output, m_Phase2XSLT);
			DoTransform(m_Phase2XSLT, m_phase1output, m_Phase2Output);
			DoTransform(m_Phase3XSLT, m_Phase2Output, m_Phase3Output);
#if true
			// put the phase4output in to the 'phase 5' file for comparing as there is no phase 5 now.
			DoTransform(m_Phase4XSLT, m_Phase3Output, m_Phase5Output);
			Microsoft.XmlDiffPatch.XmlDiff diff = new Microsoft.XmlDiffPatch.XmlDiff(
				Microsoft.XmlDiffPatch.XmlDiffOptions.IgnoreChildOrder |
				Microsoft.XmlDiffPatch.XmlDiffOptions.IgnoreComments |
				Microsoft.XmlDiffPatch.XmlDiffOptions.IgnoreWhitespace);
			bool same = diff.Compare(m_keyName, m_Phase5Output, false);

#else
			DoTransform(m_Phase4XSLT, m_Phase3Output, m_Phase4Output);

			// strip out the id and target attributes as the guids WILL be different
			DoTransform(m_Phase5XSLT, m_Phase4Output, m_Phase5Output);
			DoTransform(m_Phase5XSLT, m_keyName, m_KeyOutput);
			Microsoft.XmlDiffPatch.XmlDiff diff = new Microsoft.XmlDiffPatch.XmlDiff(
				Microsoft.XmlDiffPatch.XmlDiffOptions.IgnoreChildOrder |
				Microsoft.XmlDiffPatch.XmlDiffOptions.IgnoreComments |
				Microsoft.XmlDiffPatch.XmlDiffOptions.IgnoreWhitespace );
			bool same = diff.Compare(m_KeyOutput, m_Phase5Output, false);
#endif

			return same;
		}
Example #22
0
        static void Main( string[] args )
        {
            bool bFragment = false;
            bool bNodes = false;
            XmlDiffAlgorithm algorithm = XmlDiffAlgorithm.Auto;

            try
            {
            if ( args.Length < 3 )
            {
                WriteUsage();
                return;
            }

            XmlDiffOptions options = XmlDiffOptions.None;

            // process options
            int curArgsIndex = 0;
            string optionsString = string.Empty;
            while ( args[curArgsIndex][0] == '/' )
            {
                if ( args[curArgsIndex].Length != 2 )
                {
                    System.Console.Write( "Invalid option: " + args[curArgsIndex] + "\n" );
                    return;
                }

                switch ( args[curArgsIndex][1] )
                {
                    case 'o':
                        options |= XmlDiffOptions.IgnoreChildOrder;
                        break;
                    case 'c':
                        options |= XmlDiffOptions.IgnoreComments;
                        break;
                    case 'p':
                        options |= XmlDiffOptions.IgnorePI;
                        break;
                    case 'w':
                        options |= XmlDiffOptions.IgnoreWhitespace;
                        break;
                    case 'n':
                        options |= XmlDiffOptions.IgnoreNamespaces;
                        break;
                    case 'r':
                        options |= XmlDiffOptions.IgnorePrefixes;
                        break;
                    case 'x':
                        options |= XmlDiffOptions.IgnoreXmlDecl;
                        break;
                    case 'd':
                        options |= XmlDiffOptions.IgnoreDtd;
                        break;
                    case 'e':
                        bNodes = true;
                        break;
                    case 'f':
                        bFragment = true;
                        break;
                    case 't':
                        algorithm = XmlDiffAlgorithm.Fast;
                        break;
                    case 'z':
                        algorithm = XmlDiffAlgorithm.Precise;
                        break;
                    default:
                        System.Console.Write( "Invalid option: " + args[curArgsIndex] + "\n" );
                        return;
                }
                optionsString += args[curArgsIndex][1];
                curArgsIndex++;

                if ( args.Length - curArgsIndex < 3 )
                {
                    WriteUsage();
                    return;
                }
            }

            // extract names from command line
            string sourceXml = args[ curArgsIndex ];
            string targetXml = args[ curArgsIndex + 1 ];
            string diffgram  = args[ curArgsIndex + 2 ];
            bool bVerify = ( args.Length - curArgsIndex == 4 ) && ( args[ curArgsIndex + 3 ] == "verify" );

            // write legend
            string legend = sourceXml.Substring( sourceXml.LastIndexOf("\\") + 1 ) + " & " +
                            targetXml.Substring( targetXml.LastIndexOf("\\") + 1 ) + " -> " +
                            diffgram.Substring( diffgram.LastIndexOf("\\") + 1 );
            if ( optionsString != string.Empty )
                legend += " (" + optionsString + ")";

            if ( legend.Length < 60 )
                legend += new String( ' ', 60 - legend.Length );
            else
                legend += "\n" + new String( ' ', 60 );

            System.Console.Write( legend );

            // create diffgram writer
            XmlWriter DiffgramWriter = new XmlTextWriter( diffgram, new System.Text.UnicodeEncoding() );

            // create XmlDiff object & set the options
            XmlDiff xmlDiff = new XmlDiff( options );
            xmlDiff.Algorithm = algorithm;

            // compare xml files
            bool bIdentical;
            if ( bNodes ) {
                if ( bFragment ) {
                    Console.Write( "Cannot have option 'd' and 'f' together." );
                    return;
                }

                XmlDocument sourceDoc = new XmlDocument();
                sourceDoc.Load( sourceXml );
                XmlDocument targetDoc = new XmlDocument();
                targetDoc.Load( targetXml );

                bIdentical = xmlDiff.Compare( sourceDoc, targetDoc, DiffgramWriter );
            }
            else {
                bIdentical = xmlDiff.Compare( sourceXml, targetXml, bFragment, DiffgramWriter );
            }

            /*
             *             if ( bMeasurePerf ) {
                Type type = xmlDiff.GetType();
                MemberInfo[] mi = type.GetMember( "_xmlDiffPerf" );
                if ( mi != null && mi.Length > 0 ) {
                    XmlDiffPerf xmldiffPerf = (XmlDiffPerf)type.InvokeMember( "_xmlDiffPerf", BindingFlags.GetField, null, xmlDiff, new object[0]);
                }
            }
            */

            // write result
            if ( bIdentical )
                System.Console.Write( "identical" );
            else
                System.Console.Write( "different" );

            DiffgramWriter.Close();

            // verify
            if ( !bIdentical && bVerify )
            {
                XmlNode sourceNode;
                if ( bFragment )
                {
                    NameTable nt = new NameTable();
                    XmlTextReader tr = new XmlTextReader( new FileStream( sourceXml, FileMode.Open, FileAccess.Read ),
                                                          XmlNodeType.Element,
                                                          new XmlParserContext( nt, new XmlNamespaceManager( nt ),
                                                                                string.Empty, XmlSpace.Default ) );
                    XmlDocument doc = new XmlDocument();
                    XmlDocumentFragment frag = doc.CreateDocumentFragment();

                    XmlNode node;
                    while ( ( node = doc.ReadNode( tr ) ) != null ) {
                        if ( node.NodeType != XmlNodeType.Whitespace )
                            frag.AppendChild( node );
                    }

                    sourceNode = frag;
                }
                else
                {
                    // load source document
                    XmlDocument sourceDoc = new XmlDocument();
                    sourceDoc.XmlResolver = null;
                    sourceDoc.Load( sourceXml );
                    sourceNode = sourceDoc;
                }

                // patch it & save
                new XmlPatch().Patch( ref sourceNode, new XmlTextReader( diffgram ) );
                if ( sourceNode.NodeType == XmlNodeType.Document )
                    ((XmlDocument)sourceNode).Save( "_patched.xml" );
                else {
                    XmlTextWriter tw = new XmlTextWriter( "_patched.xml", Encoding.Unicode );
                    sourceNode.WriteTo( tw );
                    tw.Close();
                }

                XmlWriter diffgramWriter2 = new XmlTextWriter( "_2ndDiff.xml", new System.Text.UnicodeEncoding() );

                // compare patched source document and target document
                if ( xmlDiff.Compare( "_patched.xml", targetXml, bFragment, diffgramWriter2 ) )
                    System.Console.Write( " - ok" );
                else
                    System.Console.Write( " - FAILED" );

                diffgramWriter2.Close();
            }
            System.Console.Write( "\n" );
            }
            catch ( Exception e )
            {
            Console.Write("\n*** Error: " + e.Message + " (source: " + e.Source + ")\n");
            }

            if ( System.Diagnostics.Debugger.IsAttached )
            {
            Console.Write( "\nPress enter...\n" );
            Console.Read();
            }
        }
Example #23
0
        private static bool Compare(out StringBuilder diff, string goalFilePath, string foundFilePath, IEnumerable<Replacement> replacements, IEnumerable<string> elementsToExclude, IEnumerable<Attribute> attributesToExclude, bool ignoreChildOrder, bool ignoreComments)
        {
            bool retVal;
            diff = new StringBuilder();

            var foundFileDocument = new XmlDocument();
            var goalFileDocument = new XmlDocument();

            TextReader goalFileReader = null;
            TextReader foundFileReader = null;

            XmlReader foundFileXmlReader = null;
            XmlReader goalXmlReader = null;

            try
            {
                goalFileReader = new StringReader(XmlDocumentCleaner.ReplaceInDocument(goalFilePath, replacements));
                foundFileReader = new StringReader(XmlDocumentCleaner.ReplaceInDocument(foundFilePath, replacements));

                foundFileDocument.Load(foundFileReader);
                goalFileDocument.Load(goalFileReader);

                foreach (string element in elementsToExclude)
                {
                    XmlDocumentCleaner.RemoveElements(ref foundFileDocument, element);
                    XmlDocumentCleaner.RemoveElements(ref goalFileDocument, element);
                }

                foreach (Attribute attribute in attributesToExclude)
                {
                    XmlDocumentCleaner.RemoveAttribute(ref foundFileDocument, attribute);
                    XmlDocumentCleaner.RemoveAttribute(ref goalFileDocument, attribute);
                }

                foundFileXmlReader = new XmlNodeReader(foundFileDocument);
                goalXmlReader = new XmlNodeReader(goalFileDocument);

                var comparer = new XmlDiff();
                comparer.IgnoreChildOrder = ignoreChildOrder;
                comparer.IgnoreComments = ignoreComments;

                XmlWriter diffWriter = XmlWriter.Create(diff);
                retVal = comparer.Compare(goalXmlReader, foundFileXmlReader, diffWriter);
                diffWriter.Flush();
            }
            finally
            {
                if (goalXmlReader != null) goalXmlReader.Close();
                if (foundFileXmlReader != null) foundFileXmlReader.Close();

                if (goalFileReader != null) goalFileReader.Dispose();
                if (foundFileReader != null) foundFileReader.Dispose();
            }

            return retVal;
        }
Example #24
0
        static void Main(string[] args)
        {
            bool             bFragment = false;
            bool             bNodes    = false;
            XmlDiffAlgorithm algorithm = XmlDiffAlgorithm.Auto;

            try
            {
                if (args.Length < 3)
                {
                    WriteUsage();
                    return;
                }

                XmlDiffOptions options = XmlDiffOptions.None;

                // process options
                int    curArgsIndex  = 0;
                string optionsString = string.Empty;
                while (args[curArgsIndex][0] == '/')
                {
                    if (args[curArgsIndex].Length != 2)
                    {
                        System.Console.Write("Invalid option: " + args[curArgsIndex] + "\n");
                        return;
                    }

                    switch (args[curArgsIndex][1])
                    {
                    case 'o':
                        options |= XmlDiffOptions.IgnoreChildOrder;
                        break;

                    case 'c':
                        options |= XmlDiffOptions.IgnoreComments;
                        break;

                    case 'p':
                        options |= XmlDiffOptions.IgnorePI;
                        break;

                    case 'w':
                        options |= XmlDiffOptions.IgnoreWhitespace;
                        break;

                    case 'n':
                        options |= XmlDiffOptions.IgnoreNamespaces;
                        break;

                    case 'r':
                        options |= XmlDiffOptions.IgnorePrefixes;
                        break;

                    case 'x':
                        options |= XmlDiffOptions.IgnoreXmlDecl;
                        break;

                    case 'd':
                        options |= XmlDiffOptions.IgnoreDtd;
                        break;

                    case 'e':
                        bNodes = true;
                        break;

                    case 'f':
                        bFragment = true;
                        break;

                    case 't':
                        algorithm = XmlDiffAlgorithm.Fast;
                        break;

                    case 'z':
                        algorithm = XmlDiffAlgorithm.Precise;
                        break;

                    default:
                        System.Console.Write("Invalid option: " + args[curArgsIndex] + "\n");
                        return;
                    }
                    optionsString += args[curArgsIndex][1];
                    curArgsIndex++;

                    if (args.Length - curArgsIndex < 3)
                    {
                        WriteUsage();
                        return;
                    }
                }

                // extract names from command line
                string sourceXml = args[curArgsIndex];
                string targetXml = args[curArgsIndex + 1];
                string diffgram  = args[curArgsIndex + 2];
                bool   bVerify   = (args.Length - curArgsIndex == 4) && (args[curArgsIndex + 3] == "verify");

                // write legend
                string legend = sourceXml.Substring(sourceXml.LastIndexOf("\\") + 1) + " & " +
                                targetXml.Substring(targetXml.LastIndexOf("\\") + 1) + " -> " +
                                diffgram.Substring(diffgram.LastIndexOf("\\") + 1);
                if (optionsString != string.Empty)
                {
                    legend += " (" + optionsString + ")";
                }

                if (legend.Length < 60)
                {
                    legend += new String(' ', 60 - legend.Length);
                }
                else
                {
                    legend += "\n" + new String(' ', 60);
                }

                System.Console.Write(legend);

                // create diffgram writer
                XmlWriter DiffgramWriter = new XmlTextWriter(diffgram, new System.Text.UnicodeEncoding());

                // create XmlDiff object & set the options
                XmlDiff xmlDiff = new XmlDiff(options);
                xmlDiff.Algorithm = algorithm;

                // compare xml files
                bool bIdentical;
                if (bNodes)
                {
                    if (bFragment)
                    {
                        Console.Write("Cannot have option 'd' and 'f' together.");
                        return;
                    }

                    XmlDocument sourceDoc = new XmlDocument();
                    sourceDoc.Load(sourceXml);
                    XmlDocument targetDoc = new XmlDocument();
                    targetDoc.Load(targetXml);

                    bIdentical = xmlDiff.Compare(sourceDoc, targetDoc, DiffgramWriter);
                }
                else
                {
                    bIdentical = xmlDiff.Compare(sourceXml, targetXml, bFragment, DiffgramWriter);
                }

/*
 *             if ( bMeasurePerf ) {
 *              Type type = xmlDiff.GetType();
 *              MemberInfo[] mi = type.GetMember( "_xmlDiffPerf" );
 *              if ( mi != null && mi.Length > 0 ) {
 *                  XmlDiffPerf xmldiffPerf = (XmlDiffPerf)type.InvokeMember( "_xmlDiffPerf", BindingFlags.GetField, null, xmlDiff, new object[0]);
 *              }
 *          }
 */

                // write result
                if (bIdentical)
                {
                    System.Console.Write("identical");
                }
                else
                {
                    System.Console.Write("different");
                }

                DiffgramWriter.Close();

                // verify
                if (!bIdentical && bVerify)
                {
                    XmlNode sourceNode;
                    if (bFragment)
                    {
                        NameTable     nt = new NameTable();
                        XmlTextReader tr = new XmlTextReader(new FileStream(sourceXml, FileMode.Open, FileAccess.Read),
                                                             XmlNodeType.Element,
                                                             new XmlParserContext(nt, new XmlNamespaceManager(nt),
                                                                                  string.Empty, XmlSpace.Default));
                        XmlDocument         doc  = new XmlDocument();
                        XmlDocumentFragment frag = doc.CreateDocumentFragment();

                        XmlNode node;
                        while ((node = doc.ReadNode(tr)) != null)
                        {
                            if (node.NodeType != XmlNodeType.Whitespace)
                            {
                                frag.AppendChild(node);
                            }
                        }

                        sourceNode = frag;
                    }
                    else
                    {
                        // load source document
                        XmlDocument sourceDoc = new XmlDocument();
                        sourceDoc.XmlResolver = null;
                        sourceDoc.Load(sourceXml);
                        sourceNode = sourceDoc;
                    }

                    // patch it & save
                    new XmlPatch().Patch(ref sourceNode, new XmlTextReader(diffgram));
                    if (sourceNode.NodeType == XmlNodeType.Document)
                    {
                        ((XmlDocument)sourceNode).Save("_patched.xml");
                    }
                    else
                    {
                        XmlTextWriter tw = new XmlTextWriter("_patched.xml", Encoding.Unicode);
                        sourceNode.WriteTo(tw);
                        tw.Close();
                    }

                    XmlWriter diffgramWriter2 = new XmlTextWriter("_2ndDiff.xml", new System.Text.UnicodeEncoding());

                    // compare patched source document and target document
                    if (xmlDiff.Compare("_patched.xml", targetXml, bFragment, diffgramWriter2))
                    {
                        System.Console.Write(" - ok");
                    }
                    else
                    {
                        System.Console.Write(" - FAILED");
                    }

                    diffgramWriter2.Close();
                }
                System.Console.Write("\n");
            }
            catch (Exception e)
            {
                Console.Write("\n*** Error: " + e.Message + " (source: " + e.Source + ")\n");
            }

            if (System.Diagnostics.Debugger.IsAttached)
            {
                Console.Write("\nPress enter...\n");
                Console.Read();
            }
        }
        /// <summary>
        /// Compares database objects (except tables and columns) from two distinct XML schema files. These files are generated 
        /// by the SerializeDB method.  This method is called from the CompareSchema method.
        /// </summary>
        /// <param name="_serverDB">Used to identify which server the compare objects came from</param>
        /// <param name="xmlSourceDoc">The XmlDataDocument, the source XML to compare with the destination XML.</param>
        /// <param name="xmlDestinationDoc">The XmlDataDocument, the destination/target XML to compare with the source XML.</param>
        /// <param name="xmlDiffDoc">The XML Diffgram document to update.</param>
        /// <param name="type">The type of database object collection to compare, i.e. defaults, UDDTs, rules, views, functions, 
        /// stored procedures, and triggers.</param>
        /// <param name="xmlDiff">The XmlDiff Object used from the GotDotNet XmlDiff class. Performs the XML node compare.</param>
        /// <param name="CompareTextFlag">Flag that performs full text compare between objects</param>
        /// <param name="sqlObjectName">specifies a specific SQL object to compare</param>
        public static void CompareObjects(string _serverDB, XmlDocument xmlSourceDoc, XmlDocument xmlDestinationDoc,
            XmlDocument xmlDiffDoc, _NodeType type, XmlDiff xmlDiff, bool CompareTextFlag, string sqlObjectName)
        {
            SortedList sl = new SortedList();
            SortedList slDep = new SortedList();

            bool addFlag = false;
            bool alterFlag = false;
            bool sortFlag = false;

            string selectNodes = string.Empty;
            string selectText = string.Empty;
            string typeName = string.Empty;
            string depText = string.Empty;

            // iterate thru the source tables 
            // we are going to ignore destination tables which are not in the source DB
            // as they could be custom tables added by some outside tool or person
            switch (type)
            {
                case _NodeType.SPROC:
                    {
                        selectNodes = SPROCPATH;
                        selectText = SPROCTEXT;
                        depText = SPROCDEP;
                        typeName = type.ToString();
                        sortFlag = true;
                        break;
                    }
                case _NodeType.FUNCTION:
                    {
                        selectNodes = FUNCPATH;
                        selectText = FUNCTEXT;
                        depText = FUNCDEP;
                        typeName = type.ToString().Substring(0, 4);
                        sortFlag = true;
                        break;
                    }
                case _NodeType.VIEW:
                    {
                        selectNodes = VIEWPATH;
                        selectText = VIEWTEXT;
                        depText = VIEWDEP;
                        typeName = type.ToString();
                        sortFlag = true;
                        break;
                    }
                case _NodeType.TRIGGER:
                    {
                        selectNodes = TRIGGERPATH;
                        selectText = TRIGGERTEXT;
                        typeName = type.ToString();
                        break;
                    }
                case _NodeType.DEFAULT:
                    {
                        selectNodes = DEFAULTPATH;
                        selectText = DEFAULTTEXT;
                        typeName = type.ToString();
                        break;
                    }
                case _NodeType.RULE:
                    {
                        selectNodes = RULEPATH;
                        selectText = RULETEXT;
                        typeName = type.ToString();
                        break;
                    }
                case _NodeType.UDDT:
                    {
                        selectNodes = UDDTPATH;
                        selectText = UDDTTEXT;
                        typeName = type.ToString();
                        break;
                    }
            }

            SortedList slMatch = new SortedList();
            XmlNodeList xNodeList = xmlSourceDoc.SelectNodes(selectNodes, nsmgr_Source);
            XmlNode xnDestParent = xmlDestinationDoc.SelectSingleNode(selectNodes, nsmgr_Dest);

            // use stringbuilder class as it should be faster
            StringBuilder sourceTxt = new StringBuilder();
            StringBuilder destTxt = new StringBuilder();
            StringBuilder sortedname = new StringBuilder();

            foreach (XmlNode xnChild_Source in xNodeList)
            {
                XmlNode xnDest = null;
                XmlNodeList XmlDestTextList = null;
                sourceTxt.Length = 0;
                destTxt.Length = 0;
                int destNodeCount = 0;
                int sourceNodeCount = 0;

                string SqlObjectName = xnChild_Source.ChildNodes[0].InnerXml;
                if (sqlObjectName != null && !SqlObjectName.ToLower().Equals(sqlObjectName.ToLower()))
                {
                    continue; // loop until passed in object name is found
                }
                string xpath = selectText + SqlObjectName + "']";
                XmlNode xnChk = xnChild_Source.SelectSingleNode("Check_Sum");
                string src_checksum = string.Empty;
                string dst_checksum = string.Empty;
                if (xnChk != null)
                {
                    src_checksum = xnChk.InnerXml;
                }

                logger.Debug("\n{2}: Comparing {1}: {0}.", SqlObjectName, type.ToString().ToLower(), _serverDB);

                // walk thru destination xml doc nodes to find matching sproc node
                if (xnDestParent != null)
                {
                    xnDest = xnDestParent.SelectSingleNode(selectNodes + "[" + xpath.Split('[')[1]);
                }
                // get xmlnodes for text rows in destination doc
                if (xnDest != null)
                {
                    xnChk = xnDest.SelectSingleNode("Check_Sum");
                    if (xnChk != null)
                    {
                        dst_checksum = xnChk.InnerXml;
                    }
                    // if objects don't compare then walk each line of text
                    if (!xmlDiff.Compare(xnChild_Source, xnDest))
                    {
                        XmlDestTextList = xnDest.SelectNodes(selectText.Split('[')[0]);
                        // only comapre the text length (not a checksum) if there is not a match on the nodes
                        if (xnChk != null && dst_checksum == src_checksum)
                        {
                            continue;
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
                if (xnDest != null && XmlDestTextList != null && XmlDestTextList.Count > 0)
                {
                    // don't care about existing UDDTs and Defaults, only new ones
                    // so resume at next node
                    if (type == _NodeType.UDDT || type == _NodeType.DEFAULT || type == _NodeType.RULE)
                    {
                        continue;
                    }

                    if (CompareTextFlag)
                    {
                        // get xmlnodes for text rows in source
                        XmlNodeList xnlSource = xnChild_Source.SelectNodes(xpath, nsmgr_Source);
                        // build text for source
                        foreach (XmlNode xnSource in xnlSource)
                        {
                            // ignore blank text nodes, tabs, newline and carriage returns
                            if (xnSource.SelectSingleNode("Text") == null || xnSource.SelectSingleNode("Text").InnerText.Length == 0)
                            {
                                continue;
                            }
                            sourceNodeCount += 1;
                            sourceTxt.Append(xnSource.SelectSingleNode("Text").InnerText.ToLower().Trim());
                            sourceTxt.Replace(" ", "");
                            sourceTxt.Replace("\n", "");
                            sourceTxt.Replace("\r", "");
                            sourceTxt.Replace("\t", "");
                        }
                        if (sourceTxt.ToString().Length > 0)
                        {
                            // build text for destination
                            foreach (XmlNode xnChild in XmlDestTextList)
                            {
                                // ignore blank text nodes, tabs, newline and carriage returns
                                if (xnChild.SelectSingleNode("Text") == null || xnChild.SelectSingleNode("Text").InnerText.Length == 0)
                                {
                                    continue;
                                }
                                destNodeCount += 1;
                                destTxt.Append(xnChild.SelectSingleNode("Text").InnerText.ToLower().Trim());
                                destTxt.Replace(" ", "");
                                destTxt.Replace("\n", "");
                                destTxt.Replace("\r", "");
                                destTxt.Replace("\t", "");
                                // look for this text string in the source text string
                                // if theres no match then we do not need to look thru
                                // all the dest text nodes, so exit out of loop, instead of continuing on
                                // Contains = true if the value parameter occurs within this string, or if value is the empty string (""); otherwise, false. 
                                if (!sourceTxt.ToString().Contains(destTxt.ToString()) && destTxt.ToString().Length > 0)
                                {
                                    break;
                                }
                            }
                        }
                        //CompareInfo compare = CultureInfo.InvariantCulture.CompareInfo;
                        //int compareResult = compare.Compare(sourceTxt.ToString(), destTxt.ToString(), CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace);
                    }
                    else
                    {
                        alterFlag = true;
                    }
                    // compare source and dest text
                    if (sourceTxt.ToString().ToLower() != destTxt.ToString().ToLower())
                    {
                        alterFlag = true;
                    }
                    // if no differences then resume at next source node
                    if (!alterFlag)
                    {
                        continue;
                    }
                }
                else  // we have a source node, but no matching destination node so set the add flag to true
                {
                    addFlag = true;
                }
                // if no destination text, we need to add it from the source
                if (sourceNodeCount > 0 && (destNodeCount == 0 || xnDest == null))
                {
                    // the object_text node was not found in the destination so add parent node for object to DiffDoc as an add
                    addFlag = true;
                }
                XmlNode xNode = null;
                if (addFlag)
                {
                    xNode = xmlDiffDoc.CreateNode(XmlNodeType.Element, typeName, xmlDiffDoc.NamespaceURI);
                    XmlAttribute xNodeAttrib = xmlDiffDoc.CreateAttribute("Action");
                    xNodeAttrib.Value = "Add";
                    xNode.InnerXml = xnChild_Source.InnerXml;
                    xNode.Attributes.Append(xNodeAttrib);
                    if (!sortFlag) xmlDiffDoc.SelectSingleNode("/DataBase_Schema").AppendChild(xNode);
                    addFlag = false;
                }
                if (alterFlag)
                {
                    xNode = xmlDiffDoc.CreateNode(XmlNodeType.Element, typeName, xmlDiffDoc.NamespaceURI);
                    XmlAttribute xNodeAttrib = xmlDiffDoc.CreateAttribute("Action");
                    xNodeAttrib.Value = "Alter";
                    xNode.InnerXml = xnChild_Source.InnerXml;
                    xNode.Attributes.Append(xNodeAttrib);
                    if (!sortFlag) xmlDiffDoc.SelectSingleNode("/DataBase_Schema").AppendChild(xNode);
                    alterFlag = false;
                }
                if (sortFlag)
                {
                    if (xNode != null)
                    {
                        XmlNodeList xnlSource = xnChild_Source.SelectNodes(depText + SqlObjectName + "']", nsmgr_Source);
                        // get dependencies names and add to sorted list
                        int ii = 0;
                        foreach (XmlNode xnSource in xnlSource)
                        {
                            if (xnSource.ChildNodes[1] != null)
                            {
                                slDep.Add(string.Format("{1:0000}!{0}", SqlObjectName.ToLower(), ii), xnSource.ChildNodes[1].InnerXml.ToLower());
                                ii += 1;
                            }
                        }
                        if (ii > 0)
                        {
                            sl.Add(string.Format("{1:0000}!{0}", SqlObjectName.ToLower(), ii), xNode);
                        }
                        else
                        {
                            sl.Add(string.Format("0000!{0}", SqlObjectName.ToLower()), xNode);
                        }
                    }
                }
            } // end of main for loop
            if (sortFlag)
            {
                // if sldep has count > 0 then we need to do some additional sorting
                SortedList sl2 = new SortedList();
                int zz = 0;
                for (int ii = 0; ii < sl.Count; ii++)
                {
                    sl2.Add(string.Format("{1:00000},{0}", sl.GetKey(ii).ToString(), zz), sl.GetByIndex(ii));
                    zz += 10;
                }
                if (slDep.Count > 0)
                {
                    int start = 0;
                    RecurseDependencies(_serverDB, ref sl2, ref slDep, 0, ref start);
                }
                for (int ii = 0; ii < sl2.Count; ii++)
                {
                    XmlNode xn = (XmlNode)sl2.GetByIndex(ii);
                    xmlDiffDoc.SelectSingleNode("/DataBase_Schema").AppendChild(xn);
                }
            }
        }
Example #26
0
 private void CompareResults(String name) {
     PdfReader reader = new PdfReader(OUT + name + ".pdf");
     string orig = RESOURCES + "xml\\test" + name + ".xml";
     string curr = TARGET + "xml\\test" + name + ".xml";
     FileStream xmlOut = new FileStream(curr, FileMode.Create);
     new MyTaggedPdfReaderTool().ConvertToXml(reader, xmlOut);
     xmlOut.Close();
     XmlDiff xmldiff = new XmlDiff(XmlDiffOptions.None);
     Assert.True(xmldiff.Compare(orig, curr, false));
 }
Example #27
0
	public void GenerateOutput(BuildItem buildItem, Stream outputStream, IDictionary<string, Stream> inputFormatStreams, string defaultNamespace)
	{
		outputStream = new UncloseableStream(outputStream);
		Stream undeadOial = inputFormatStreams["UndeadOIAL"];
		Stream liveOial = inputFormatStreams["LiveOIAL"];

		XmlDiff xmlDiff = new XmlDiff(XmlDiffOptions.IgnoreComments | XmlDiffOptions.IgnoreXmlDecl | XmlDiffOptions.IgnorePrefixes);

		xmlDiff.Algorithm = XmlDiffAlgorithm.Precise;

		bool identical = false;

		MemoryStream diffgram = new MemoryStream(8192);

		using (XmlWriter diffgramWriter = XmlWriter.Create(diffgram))
		{
			try
			{
				using (XmlReader undeadReader = XmlReader.Create(undeadOial, XmlReaderSettings), liveReader = XmlReader.Create(liveOial, XmlReaderSettings))
				{
					identical = xmlDiff.Compare(undeadReader, liveReader, diffgramWriter);
				}
			}
			finally
			{
				undeadOial.Seek(0, SeekOrigin.Begin);
				liveOial.Seek(0, SeekOrigin.Begin);
			}
		}

		// Files have been compared, and the diff has been written to the diffgramwriter.

		TextWriter resultHtml = new StreamWriter(outputStream);
		resultHtml.WriteLine("<html><head>");
		resultHtml.WriteLine("<style TYPE='text/css' MEDIA='screen'>");
		resultHtml.Write("<!-- td { font-family: Courier New; font-size:14; } " +
							"th { font-family: Arial; } " +
							"p { font-family: Arial; } -->");
		resultHtml.WriteLine("</style></head>");
		resultHtml.WriteLine("<body><h3 style='font-family:Arial'>XmlDiff view</h3><table border='0'><tr><td><table border='0'>");
		resultHtml.WriteLine("<tr><th>Undead OIAL</th><th>Live OIAL</th></tr>" +
							"<tr><td colspan=2><hr size=1></td></tr>");

		if (identical)
		{
			resultHtml.WriteLine("<tr><td colspan='2' align='middle'>Files are identical.</td></tr>");
		}
		else
		{
			resultHtml.WriteLine("<tr><td colspan='2' align='middle'>Files are different.</td></tr>");
		}

		diffgram.Seek(0, SeekOrigin.Begin);
		XmlDiffView xmlDiffView = new XmlDiffView();

		XmlTextReader sourceReader = new XmlTextReader(undeadOial);

		sourceReader.XmlResolver = null;

		xmlDiffView.Load(sourceReader, new XmlTextReader(diffgram));

		xmlDiffView.GetHtml(resultHtml);

		resultHtml.WriteLine("</table></table></body></html>");

		resultHtml.Flush();
		resultHtml.Close();
	}
Example #28
0
        private void CompareResults(String orig, String curr) {
            PdfReader cmpReader = new PdfReader(CMP_FOLDER + orig);
            PdfReader outReader = new PdfReader(OUT_FOLDER + curr);
            byte[] cmpBytes = cmpReader.Metadata, outBytes = outReader.Metadata;
            IXmpMeta xmpMeta = XmpMetaFactory.ParseFromBuffer(cmpBytes);

            XmpUtils.RemoveProperties(xmpMeta, XmpConst.NS_XMP, XmpBasicProperties.CREATEDATE, true, true);
            XmpUtils.RemoveProperties(xmpMeta, XmpConst.NS_XMP, XmpBasicProperties.MODIFYDATE, true, true);
            XmpUtils.RemoveProperties(xmpMeta, XmpConst.NS_XMP, XmpBasicProperties.METADATADATE, true, true);
            XmpUtils.RemoveProperties(xmpMeta, XmpConst.NS_PDF, PdfProperties.PRODUCER, true, true);

            cmpBytes = XmpMetaFactory.SerializeToBuffer(xmpMeta, new SerializeOptions(SerializeOptions.SORT));

            xmpMeta = XmpMetaFactory.ParseFromBuffer(outBytes);
            XmpUtils.RemoveProperties(xmpMeta, XmpConst.NS_XMP, XmpBasicProperties.CREATEDATE, true, true);
            XmpUtils.RemoveProperties(xmpMeta, XmpConst.NS_XMP, XmpBasicProperties.MODIFYDATE, true, true);
            XmpUtils.RemoveProperties(xmpMeta, XmpConst.NS_XMP, XmpBasicProperties.METADATADATE, true, true);
            XmpUtils.RemoveProperties(xmpMeta, XmpConst.NS_PDF, PdfProperties.PRODUCER, true, true);

            outBytes = XmpMetaFactory.SerializeToBuffer(xmpMeta, new SerializeOptions(SerializeOptions.SORT));

            XmlDiff xmldiff = new XmlDiff(XmlDiffOptions.None);
            if (!xmldiff.Compare(new XmlTextReader(new MemoryStream(cmpBytes)),
                                 new XmlTextReader(new MemoryStream(outBytes)))) {
                String currXmlName = curr.Replace(".pdf", ".xml");
                FileStream outStream = new FileStream(OUT_FOLDER + "cmp_" + currXmlName, FileMode.Create);
                outStream.Write(cmpBytes, 0, cmpBytes.Length);

                outStream = new FileStream(OUT_FOLDER + currXmlName, FileMode.Create);
                outStream.Write(outBytes, 0, outBytes.Length);
                Assert.Fail("The XMP packages are different!!!");
            }
        }
Example #29
0
		/// <summary>
		/// Invokes the XmlDiff Compare method. The strings attribute order and whitespace are ignored.
		/// </summary>
		/// <param name="diffs">The raw byte array of "diffgram" XML returned.</param>
		/// <param name="same">True if the two xml strings are identical.</param>
		/// <returns>Number of bytes read.</returns>
		private int Compare(out byte [] diffs, out bool same)
		{
			Encoding enc = Encoding.UTF8; //.Unicode;
			System.IO.Stream stream = new System.IO.MemoryStream();
			XmlDiff xDiff = new XmlDiff(XmlDiffOptions.IgnoreWhitespace);
			XmlWriter writer = new XmlTextWriter(stream, enc);
			same = xDiff.Compare(m_baseReader, m_targetReader, writer);
			stream.Position = 0;
			diffs = new Byte[stream.Length];
			int bytesRead = stream.Read(diffs,0,(int)stream.Length);
			writer.Close(); // closes stream too.
			m_Compared = true;
			return bytesRead;
		}
Example #30
0
 virtual protected bool CompareXmls(String xml1, String xml2) {
     XmlDiff xmldiff = new XmlDiff(XmlDiffOptions.None);
     return xmldiff.Compare(xml1, xml2, false);
 }
Example #31
-1
        public void Serialization()
        {
            try {
                XmlDiff diff = new XmlDiff();
                TemplateBox templateBox = new TemplateBox(TemplatingResources.TemplatesDefault);
                String result = templateBox.Serialize();
                //Utils.WriteToFile(@"C:\temp\templates.xml", result);

                diff.IgnoreChildOrder = true;
                diff.IgnoreComments = true;
                diff.IgnoreDtd = true;
                diff.IgnoreNamespaces = true;
                diff.IgnorePI = true;
                diff.IgnorePrefixes = true;
                diff.IgnoreWhitespace = true;
                diff.IgnoreXmlDecl = true;

                StringWriter diffgramString = new StringWriter();
                XmlTextWriter diffgramXml = new XmlTextWriter(diffgramString);
                bool diffBool = diff.Compare(new XmlTextReader(new StringReader(result)), new XmlTextReader(new StringReader(TemplatingResources.TemplatesDefault)), diffgramXml);
                //MessageBox.Show(diffgramString.ToString());
                Assert.True(diffBool, diffgramXml.ToString());

            } catch (Exception e) {
                Assert.Fail("Exception: " + e.GetType().Name + "\n" + e.Message + "\n" + e.StackTrace);
            }
        }
        private void Compare(String outPdf, String cmpPdf) {
            CompareTool ct = new CompareTool(outPdf, cmpPdf);
            Assert.IsNull(ct.Compare(OUT_FOLDER, "difference"));

            String outXml = Path.GetFileNameWithoutExtension(outPdf);
            String cmpXml = Path.GetFileNameWithoutExtension(cmpPdf);

            outXml = OUT_FOLDER + outXml.Replace(".pdf", "") + ".xml";
            cmpXml = OUT_FOLDER + "cmp_" + cmpXml.Replace("cmp_", "").Replace(".pdf", "") + ".xml";
            
            PdfReader reader = new PdfReader(outPdf);
            new MyTaggedPdfReaderTool().ConvertToXml(reader, new FileStream(outXml, FileMode.Create));
            reader.Close();

            reader = new PdfReader(outPdf);
            new MyTaggedPdfReaderTool().ConvertToXml(reader, new FileStream(cmpXml, FileMode.Create));
            reader.Close();

            XmlDiff xmldiff = new XmlDiff(XmlDiffOptions.None);
            Assert.True(xmldiff.Compare(cmpXml, outXml, false));
        }