public void CreateDiffResult() { _result = new DiffResult(); _diff = new XmlDiff("<a/>", "<b/>"); _majorDifference = new Difference(DifferenceType.ElementTagName, XmlNodeType.Element, XmlNodeType.Element); _minorDifference = new Difference(DifferenceType.AttributeSequence, XmlNodeType.Comment, XmlNodeType.Comment); }
public void AssertDifferentStringsNotEqualNorIdentical() { string control = "<assert>true</assert>"; string test = "<assert>false</assert>"; XmlDiff xmlDiff = new XmlDiff(control, test); XmlAssert.XmlNotIdentical(xmlDiff); XmlAssert.XmlNotEquals(xmlDiff); }
public void AssertXmlIdenticalUsesOptionalDescription() { string description = "An Optional Description"; try { XmlDiff diff = new XmlDiff(new XmlInput("<a/>"), new XmlInput("<b/>"), new DiffConfiguration(description)); XmlAssert.XmlIdentical(diff); } catch (AssertionException e) { Assert.AreEqual(true, e.Message.StartsWith(description)); } }
public void CanConfigureNotToUseValidatingParser() { DiffConfiguration diffConfiguration = new DiffConfiguration(false); Assert.AreEqual(false, diffConfiguration.UseValidatingParser); Stream controlFileStream = ValidatorTests.ValidFile; Stream testFileStream = ValidatorTests.InvalidFile; try { XmlDiff diff = new XmlDiff(new XmlInput(controlFileStream), new XmlInput(testFileStream), diffConfiguration); diff.Compare(); } catch (XmlSchemaException e) { Assert.Fail("Unexpected validation failure: " + e.Message); } finally { controlFileStream.Close(); testFileStream.Close(); } }
private void PerformAssertion(XmlDiff diff, bool assertion) { Assertion.AssertEquals(assertion, diff.Compare().Equal); Assertion.AssertEquals(assertion, diff.Compare().Identical); }
internal MinimalTreeDistanceAlgo(XmlDiff xmlDiff) { this._xmlDiff = xmlDiff; }
private void CompareFiles() { Console.WriteLine("Comparison began"); #region variables XmlDiff diff = new XmlDiff(DiffOptions.Set()); XmlWriter diffWriter; bool isIdentical; string referenceFile, newFile, diffFile; #endregion #region Comparing foreach (string file in DataStorage.NewFiles) { //excludingNodesLamps[0] = referenceFile //excludingNodesLamps[1] = newFile bool[] excludingNodesLamps = { false, false }; #region preparing reference, new, and diff directories referenceFile = Path.Combine(Configuration.ReferenceDirectory, file + Configuration.ReferenceToken + Configuration.DiffFileExtension); newFile = Path.Combine(Configuration.NewDirectory, file + Configuration.NewToken + Configuration.DiffFileExtension); diffFile = Path.Combine(Configuration.DiffDirectory, file + Configuration.DiffToken + Configuration.DiffFileExtension); #endregion if (DataStorage.MissedReferenceFiles != null && DataStorage.MissedReferenceFiles.Contains(file)) { continue; } else { if (this.xPaths != null) { excludingNodesLamps = ExcludeNodes(ref referenceFile, ref newFile); } try { isIdentical = diff.Compare(referenceFile, newFile, false); #region writing diff file if not identical if (!isIdentical) { if (DataStorage.ChangedFiles == null) { DataStorage.ChangedFiles = new List <string>(); } DataStorage.ChangedFiles.Add(file); diffWriter = XmlWriter.Create(diffFile); diff.Compare(referenceFile, newFile, false, diffWriter); diffWriter.Close(); } #endregion #region deleting the temp files created during excluding the nodes if (excludingNodesLamps[0]) { File.Delete(referenceFile); } if (excludingNodesLamps[1]) { File.Delete(newFile); } #endregion } catch (IOException ex) { MessageBox.Show("Error occurred while comparing:" + referenceFile + " and " + newFile); throw ex; } } } #endregion }
public async Task ShouldCreatePEXAWorkspaceRequestFromActionstep() { var testUser = await _containerFixture.GetTestUser(); await _containerFixture.ExecuteScopeAsync(async serviceProvider => { using (var authDelegatingHandler = new AuthDelegatingHandler() { InnerHandler = _handler }) using (var httpClient = new HttpClient(authDelegatingHandler)) { var fakeClock = new FakeClock(new Instant()); var testTokenSetRepository = new TestTokenSetRepository(); await testTokenSetRepository.AddOrUpdateTokenSet(new TokenSet("accessToken", "bearer", 3600, new Uri("https://uri/api"), "testOrg", "refreshToken", fakeClock.GetCurrentInstant(), testUser.Id)); var options = new ActionstepServiceConfigurationOptions("clientId", "clientSecret"); var actionstepService = new ActionstepService(new NullLogger <ActionstepService>(), httpClient, options, testTokenSetRepository, fakeClock, new MemoryCache(new MemoryCacheOptions())); var mapper = serviceProvider.GetService <IMapper>(); var actionstepToWcaMapper = serviceProvider.GetService <IActionstepToWCAMapper>(); PrepareTestData(serviceProvider); var handler = new PEXAWorkspaceCreationRequestFromActionstepQueryHandler(actionstepService, mapper, actionstepToWcaMapper); var token = new CancellationToken(); var query = new PEXAWorkspaceCreationRequestFromActionstepQuery { AuthenticatedUser = testUser, MatterId = 1, ActionstepOrg = "testOrg" }; var pexaWorkspaceCreationResponse = await handler.Handle(query, token); Assert.Equal("1", pexaWorkspaceCreationResponse.CreatePexaWorkspaceCommand.PexaWorkspaceCreationRequest.SubscriberReference); Assert.Equal("Yes", pexaWorkspaceCreationResponse.CreatePexaWorkspaceCommand.PexaWorkspaceCreationRequest.FinancialSettlement); var config = new ConfigurationBuilder(); config.AddInMemoryCollection(new Dictionary <string, string>() { { "WCACoreSettings:PEXASettings:Environment", "Test" } }); var pexaService = new PEXAService(httpClient, config.Build()); var request = new WorkspaceCreationRequestCommand(pexaWorkspaceCreationResponse.CreatePexaWorkspaceCommand.PexaWorkspaceCreationRequest, "dummyToken"); var response = await pexaService.Handle <WorkspaceCreationResponse>(request, CancellationToken.None); Assert.Equal("PEXA190167645", response.WorkspaceId); Assert.Equal("In Preparation", response.WorkspaceStatus); var xmldiff = new XmlDiff(XmlDiffOptions.IgnoreChildOrder | XmlDiffOptions.IgnoreNamespaces | XmlDiffOptions.IgnorePrefixes); var expectedXml = EmbeddedResource.Read("ResponseData.create-workspace-result.xml"); var actualXml = _handler.RequestContent; var expectedReader = XElement.Parse(expectedXml).CreateReader(); var actualReader = XElement.Parse(actualXml).CreateReader(); using (var diffStringWriter = new StringWriter()) using (var diffWriter = XmlWriter.Create(diffStringWriter)) { var areXmlIdentical = xmldiff.Compare(expectedReader, actualReader, diffWriter); diffWriter.Flush(); foreach (var diffLine in diffStringWriter.ToString().Split(diffStringWriter.NewLine)) { _output.WriteLine(diffLine); } Assert.True(areXmlIdentical); } } }); }
private void PerformAssertion(XmlDiff diff, bool assertion) { OldAssert.AreEqual(assertion, diff.Compare().Equal); OldAssert.AreEqual(assertion, diff.Compare().Identical); }
private void Comparer(XElement fromDS, XElement toDS, bool equal = false) { string from = fromDS.ToString(); string to = toDS.ToString(); XmlDiff diff = new XmlDiff(); 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(from)), new XmlTextReader(new StringReader(to)), diffgramXml); IList <string> linesFrom = GetLines(from);; IList <string> linesTo = GetLines(to); TextDiff Diff = new TextDiff(HashType.Crc32, true, true); var es = Diff.Execute(linesFrom, linesTo); dc.SetData(linesFrom, linesTo, es, $"{(equal ? "Data Sent To:":"Returned From:")} {(cmbFrom.SelectedItem as Methods).Method}", $"{(equal ?"Data Returned From:":"Data Sent To:")}{(cmdTo.SelectedItem as Methods).Method}"); var dic = GenerateDiffCode(fromDS.Parent, XElement.Load(new StringReader(diffgramString.ToString()))); bool first = true; StringBuilder sbOrig = new StringBuilder(); sbOrig.AppendLine($"//Data Returned from Prior Method{Environment.NewLine}"); sbOrig.AppendLine("//Note data type of each field not known maye not be a string allow the compiler to assist"); StringBuilder sbChanged = new StringBuilder(); sbChanged.AppendLine($"//Data Changed and Sent to the Selected Method {Environment.NewLine}"); sbChanged.AppendLine("//Note data type of each field not known maye not be a string allow the compiler to assist"); if (!equal) { foreach (var x in dic) { string[] ds = x.Key.GetXPath().Split('/'); bool found = false; string dataSet = ""; string dataTable = ""; string field = ""; int dsIdx = -1; foreach (string s in ds) { dsIdx++; if (s.Contains("DataSet")) { found = true; break; } } if (found) { if (first) { dataSet = ds[dsIdx].Substring(0, ds[dsIdx].IndexOf("[")); sbOrig.AppendLine($"{dataSet} ds = new {dataSet}();"); sbChanged.AppendLine($"{dataSet} ds = new {dataSet}();"); first = false; } dataTable = ds[++dsIdx].Substring(0, ds[dsIdx].Length); //TODO: Josh fix this line to subtract 1 from index; sbOrig.Append($"ds.{dataTable}"); sbChanged.Append($"ds.{dataTable}"); field = ds[++dsIdx].Substring(0, ds[dsIdx].IndexOf("[")); sbOrig.Append($".{field} = "); sbChanged.Append($".{field} = "); sbOrig.AppendLine($"\"{x.Key.Value};\""); sbChanged.AppendLine($"\"{x.Value}\";"); } } } TextArea1.Text = sbOrig.ToString(); TextArea2.Text = sbChanged.ToString(); }
/// <summary> /// Compares the two files stored in members _file1 and _file2 /// </summary> /// <param name="filePrefix">Used for making the file with the comparison Results</param> /// <returns>the filename of the file with the comparison results</returns> public string compare(string filePrefix) { // Console.WriteLine(_file1); // Console.WriteLine(_file2); // Console.WriteLine(_containerTag); // Console.WriteLine(_identifyingTag); //Process the XML files and make XML recordlists of them DateTime start = DateTime.Now; DateTime startCompare = start; XMLRecordFileProcessor firstXMLFile = new XMLRecordFileProcessor(_file1, _containerTag, _identifyingTags); firstXMLFile.Process(XMLRecordFileProcessor.ProcessType.ToMemory); DateTime stop = DateTime.Now; TimeSpan duration = stop.Subtract(start); if (_perf) { Console.WriteLine("Duration of processing file {0}: {1:g}", _file1, duration); } start = DateTime.Now; XMLRecordFileProcessor secondXMLFile = new XMLRecordFileProcessor(_file2, _containerTag, _identifyingTags); secondXMLFile.Process(XMLRecordFileProcessor.ProcessType.ToMemory); stop = DateTime.Now; duration = stop.Subtract(start); if (_perf) { Console.WriteLine("Duration of processing file {0}: {1:g}", _file2, duration); } //Make a unique list of IDs from both files start = DateTime.Now; List <string> allIDs = new List <string>(); foreach (string ID in firstXMLFile.getIDList()) { allIDs.Add(ID); } foreach (string ID in secondXMLFile.getIDList()) { if (allIDs.IndexOf(ID) < 0) { allIDs.Add(ID); } } stop = DateTime.Now; duration = stop.Subtract(start); if (_perf) { Console.WriteLine("Duration of making a unique list of IDs: {0:g}", duration); } start = DateTime.Now; allIDs.Sort(); stop = DateTime.Now; duration = stop.Subtract(start); if (_perf) { Console.WriteLine("Duration of sorting the unique list of IDs: {0:g}", duration); } StringBuilder filename = new StringBuilder(""); bool found1 = false; bool found2 = false; if (filePrefix.Length > 0) { filename.AppendFormat("{0}_", filePrefix); } filename.Append("Compare summary.txt"); start = DateTime.Now; TimeSpan[] durations = new TimeSpan[5]; //Initialiseer timespans for (int i = 0; i < durations.Length; i++) { durations[i] = new TimeSpan(0); } using (System.IO.StreamWriter file = new System.IO.StreamWriter(filename.ToString())) { foreach (string ID in allIDs) { start = DateTime.Now; found1 = (firstXMLFile.getIDList().IndexOf(ID) >= 0); found2 = (secondXMLFile.getIDList().IndexOf(ID) >= 0); stop = DateTime.Now; durations[0] += stop.Subtract(start); start = DateTime.Now; StringBuilder msg = new StringBuilder(""); msg.AppendFormat("{0} => ", _containerTag); string[] idTagnames = getIDTags().Split(','); string[] idvalues = ID.Split(','); for (int i = 0; i < idTagnames.Length; i++) { string tag = ""; string value = ""; if (i < idTagnames.Length) { tag = idTagnames[i]; } if (i < idvalues.Length) { value = idvalues[i]; } //clean values if (tag == null) { tag = ""; } if (value == null) { value = ""; } //Neem waarde op als gevuld if (value.Length > 0) { msg.AppendFormat("{0}:{1}\t", tag, value); } } if (found1 && !found2) { msg.AppendFormat("Only present in file 1:'{0}'", firstXMLFile.getFilename()); } if (!found1 && found2) { msg.AppendFormat("Only present in file 2:'{0}'", secondXMLFile.getFilename()); } stop = DateTime.Now; durations[1] += stop.Subtract(start); start = DateTime.Now; if (found1 && found2) { msg.AppendFormat("Present in file '{0}' and file '{1}' => ", firstXMLFile.getFilename(), secondXMLFile.getFilename()); //Haal XMLRecords op XMLRecord XMLRecord1 = firstXMLFile.getXMLRecord(ID); XMLRecord1.MustBeValidatable = true; XmlDocument doc1 = new XmlDocument(); doc1.LoadXml(XMLRecord1.getXMLRecord()); XMLRecord XMLRecord2 = secondXMLFile.getXMLRecord(ID); XMLRecord2.MustBeValidatable = true; XmlDocument doc2 = new XmlDocument(); doc2.LoadXml(XMLRecord2.getXMLRecord()); bool equal = false; // if (XMLRecord1 != null && XMLRecord2 != null) equal = XMLRecord1.getXMLRecord().Equals(XMLRecord2.getXMLRecord()); // if (equal) msg.AppendFormat("Contents are identical (binary compare)"); // else msg.AppendFormat("Contents are different (binary compare)"); XmlDiff myDiff = new XmlDiff(XmlDiffOptions.IgnoreComments | XmlDiffOptions.IgnorePI | XmlDiffOptions.IgnoreXmlDecl | XmlDiffOptions.IgnorePrefixes | XmlDiffOptions.IgnoreNamespaces | XmlDiffOptions.IgnoreChildOrder | XmlDiffOptions.IgnoreWhitespace | XmlDiffOptions.IgnoreDtd); myDiff.Algorithm = XmlDiffAlgorithm.Precise; //XMLRecord1.Write("XML1.xml",firstXMLFile.getNamespaceTag(), firstXMLFile.getEndNamespaceTag()); //// XMLRecord1.Write("XML2.xml",firstXMLFile.getNamespaceTag(), firstXMLFile.getEndNamespaceTag()); //XMLRecord2.Write("XML2.xml",secondXMLFile.getNamespaceTag(), secondXMLFile.getEndNamespaceTag()); try { if (XMLRecord1 != null && XMLRecord2 != null) { equal = myDiff.Compare(doc1, doc2); } if (equal) { msg.AppendFormat(" Contents are identical (XML compare)"); } else { msg.AppendFormat(" Contents are different (XML compare)"); } } catch (Exception e) { msg.Append(" XML compare failed."); StringBuilder sb = new StringBuilder(getIDTags()); sb.AppendFormat("{0}_file1_exception.xml", XMLRecord1.getID()); string filename_tmp = XMLRecordFileProcessor.cleanFilename(sb.ToString()); XMLRecord1.MustBeValidatable = true; XMLRecord1.Write(filename_tmp); msg.AppendFormat("\r\n{0} {1} opgeslagen in bestand {2}", _identifyingTags, XMLRecord1.getID(), filename_tmp); // Console.WriteLine(XMLRecordFile.cleanFilename(sb.ToString())); sb.Clear(); sb.Append(getIDTags()); sb.AppendFormat("{0}_file2_exception.xml", XMLRecord2.getID()); // Console.WriteLine(XMLRecordFile.cleanFilename(sb.ToString())); filename_tmp = XMLRecordFileProcessor.cleanFilename(sb.ToString()); XMLRecord2.MustBeValidatable = true; XMLRecord2.Write(filename_tmp); msg.AppendFormat("\r\n{0} {1} opgeslagen in bestand {2}", _identifyingTags, XMLRecord2.getID(), filename_tmp); msg.AppendFormat("\r\nError message:\r\n{0}", e.ToString()); file.WriteLine(msg.ToString()); } } file.WriteLine(msg.ToString()); stop = DateTime.Now; durations[2] += stop.Subtract(start); } } //performance output if (_perf) { Console.WriteLine("Duration of searching both lists of XMLRecords: {0:g}", durations[0]); } if (_perf) { Console.WriteLine("Message preparation and checking if IDS are in both lists: {0:g}", durations[1]); } if (_perf) { Console.WriteLine("Comparing of two files XML1.xml and XML2.xml: {0:g}", durations[2]); } stop = DateTime.Now; duration = stop.Subtract(startCompare); Console.WriteLine("Duration of compare: {0:g}", duration); return(filename.ToString()); }
/// <summary> /// Asserts that two pieces of XML are identical (or not) given their diff and a boolean value /// </summary> /// <param name="xmlDiff">The XML diff.</param> /// <param name="identical">if set to <c>true</c> the assert passes if the XML is identical. /// if <c>false</c>, the assert passes if the XML is not identical</param> private static void XmlIdentical(XmlDiff xmlDiff, bool identical) { DiffResult diffResult = xmlDiff.Compare(); Assert.AreEqual(identical, diffResult.Identical, xmlDiff.OptionalDescription); }
/// <summary> /// Asserts that two pieces of XML are not identical given their diff /// </summary> /// <param name="xmlDiff">The XML diff.</param> public static void XmlNotIdentical(XmlDiff xmlDiff) { XmlIdentical(xmlDiff, false); }
/// <summary> /// Asserts that two pieces of XML are identical given their diff /// </summary> /// <param name="xmlDiff">The XML diff.</param> public static void XmlIdentical(XmlDiff xmlDiff) { XmlIdentical(xmlDiff, true); }
/// <summary> /// Asserts that two pieces of XML are similar (or not) given their diff and a boolean value /// </summary> /// <param name="xmlDiff">The XML diff.</param> /// <param name="equal">if set to <c>true</c> the assert passes if the XML is similar. /// if <c>false</c>, the assert passes if the XML is not similar</param> private static void XmlEquals(XmlDiff xmlDiff, bool equal) { DiffResult diffResult = xmlDiff.Compare(); Assert.AreEqual(equal, diffResult.Equal, FailMessage(equal, xmlDiff.OptionalDescription)); }
/// <summary> /// Asserts that two pieces of XMl are not similar given their diff /// </summary> /// <param name="xmlDiff">The XML diff.</param> public static void XmlNotEquals(XmlDiff xmlDiff) { XmlEquals(xmlDiff, false); }
/// <summary> /// Asserts that two pieces of XMl are similar given their diff /// </summary> /// <param name="xmlDiff">The XML diff.</param> public static void XmlEquals(XmlDiff xmlDiff) { XmlEquals(xmlDiff, true); }
static void Process(XDocument d, string path) { var elements = d.XPathSelectElements(path); foreach (var element in elements) { var str = element.ToString(); //Console.WriteLine (str); var html = DocConverter.ToHtml(element, currentFile, Path.GetDirectoryName(path)); var ret = DocConverter.ToXml(html); var sb = new StringBuilder(); foreach (var c in element.Nodes()) { sb.Append(c.ToString()); } var expected = sb.ToString(); //estr = estr.Replace (" />", "/>"); sb.Clear(); foreach (var c in ret) { try { if (c is XComment) { sb.Append((c as XComment).Value); } else { sb.Append(c.ToString()); } } catch (ArgumentException e) { // An XML comment cannot end with "-" looks like a bug } } var result = sb.ToString(); if (expected != result) { var diff = new XmlDiff(XmlDiffOptions.IgnoreWhitespace); var xexpected = new XmlTextReader(new StringReader("<group>" + expected + "</group>")); var xresult = new XmlTextReader(new StringReader("<group>" + result + "</group>")); var equal = diff.Compare(xexpected, xresult); //, new XmlTextWriter (Console.Out)); if (!equal && expected != result) { bool found = false; for (int i = 0; i < expected.Length && i < result.Length; i++) { if (expected [i] != result [i]) { Report(expected, result, i); // We redo the steps above, purely as it is easier to debug what happened right after // the error is reported. html = DocConverter.ToHtml(element, currentFile, Path.GetDirectoryName(path)); ret = DocConverter.ToXml(html); found = true; break; } } if (!found) { Report(expected, result, Math.Min(expected.Length, result.Length)); } } } } }
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(); }
public string GetXmlDiffHtml() { var htmlString = ""; var result = new XDocument(); var writer = result.CreateWriter(); //Make an instance of XmlDiff and ignore options var diff = new XmlDiff(XmlDiffOptions.IgnoreChildOrder | XmlDiffOptions.IgnoreNamespaces | XmlDiffOptions.IgnorePrefixes | XmlDiffOptions.IgnoreWhitespace | XmlDiffOptions.IgnoreXmlDecl); //Get project directory path var path = System.AppDomain.CurrentDomain.BaseDirectory.Replace("bin", ""); var oldFile = $"{path}/sdn_xml/SDN.xml"; var newFile = "https://www.treasury.gov/ofac/downloads/sdn.xml"; var newPath = $"{path}/sdn_xml/newSDN.xml"; //Check if source SDN file and local SDN file are equal bool isEqual = diff.Compare(oldFile, newFile, false, writer); writer.Flush(); writer.Close(); if (isEqual) { htmlString = "up to date"; //If SDN files are equal - return return(htmlString); } //Save Diff in new file newSDN.xml result.Save(newPath); XmlDocument diffDoc = new XmlDocument(); //Load the Diff flie diffDoc.Load(newPath); StringBuilder sb = new StringBuilder(); //Get arrays of xml elements XmlNodeList added = diffDoc.GetElementsByTagName("xd:add"); XmlNodeList changed = diffDoc.GetElementsByTagName("xd:change"); XmlNodeList removed = diffDoc.GetElementsByTagName("xd:remove"); //Build the return string sb.Append($"<p>LIST UPDATED - US - OFAC Specially Designated Nationals (SDN) List {DateTime.Now}</p>"); sb.Append("<p>Added: "); sb.Append(added.Count); sb.Append(", Changed: "); sb.Append(changed.Count); sb.Append(", Removed: "); sb.Append(changed.Count); sb.Append("</p>"); htmlString = sb.ToString(); return(htmlString); }
private bool CompareFiles(string pathSource, string pathDestination, string diffFilePath) { string indexfiletocompare1 = "", diffFile; string[] excludeAttributesAddarr; string[] excludeAttributesChangearr; bool compareFragments = false; bool deletediffFile = false; bool isEqual = false; int i; try { var Indexfiles = Directory.GetFiles(pathSource, "*.xml").Select(f => Path.GetFileName(f)); excludeAttributesAddarr = excludeAttributesAdd.Split(','); excludeAttributesChangearr = excludeAttributesChange.Split(','); foreach (string filename in Indexfiles) { string[] indexfiletocompare = Directory.GetFiles(pathDestination, filename); if (indexfiletocompare.Length > 0) { deletediffFile = false; indexfiletocompare1 = Path.Combine(pathSource, filename); XmlDiff diff = new XmlDiff(); diffFile = diffFilePath + filename; XmlTextWriter tw = new XmlTextWriter(new StreamWriter(diffFile)); tw.Formatting = Formatting.Indented; isEqual = diff.Compare(indexfiletocompare1, indexfiletocompare[0], compareFragments, tw); tw.Close(); if (isEqual == false) { XmlDocument doc = new XmlDocument(); doc.Load(diffFile); XmlNodeList elemList = doc.GetElementsByTagName("xd:change"); for (i = 0; i <= (elemList.Count - 1); i++) { if (excludeAttributesChangearr.Contains(elemList[i].Attributes[0].InnerText) == false) { deletediffFile = true; break; } } XmlNodeList elemListadd = doc.GetElementsByTagName("xd:add"); for (i = 0; i <= (elemListadd.Count - 1); i++) { if (excludeAttributesAddarr.Contains(elemListadd[i].Attributes[0].Name) == false) { deletediffFile = true; break; } } if (!deletediffFile) { File.Delete(diffFile); } } else { File.Delete(diffFile); } } } return(true); } catch (Exception ex) { Log("Exception while comparing" + indexfiletocompare1 + ex.Message); this.Cursor = Cursors.Default; return(false); } }
public void TestDescendants() { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(TestResources.desc1actual); // Let's have some fun by making all the number based attributes (i.e. Veh1, Drv1, etc...) 0-based foreach (var node in xmlDoc.Descendants(XmlNodeType.Attribute)) { if (char.IsNumber(node.InnerText[node.InnerText.Length - 1])) // check to see if the last character is numeric { node.InnerText = node.InnerText.Substring(0, node.InnerText.Length - 1) + (node.InnerText[node.InnerText.Length - 1] - '1').ToString(); } } XmlDiff diff = new XmlDiff(xmlDoc.InnerXml, TestResources.desc1expected); diff.CompareDocuments(new XmlDiffOptions()); Assert.AreEqual(0, diff.DiffNodeList.Count); xmlDoc.LoadXml(TestResources.desc2actual); // This time let's remove all empty nodes, and certain partial nodes, while ignoring required nodes // linquified! (from node in xmlDoc.Descendants(XmlNodeType.Element) let ignore = (node.LocalName == "ItemIdInfo" || node.LocalName == "InsuredOrPrincipal") let partialNodes = (node.LocalName == "TaxIdentity" && node.ChildNodes.Count < 2) || (node.LocalName == "QuestionAnswer" && node.ChildNodes.Count < 2) where ((!node.HasChildNodes && node.InnerText == string.Empty) || partialNodes) && !ignore select node).Remove(); diff = new XmlDiff(xmlDoc.InnerXml, TestResources.desc2expected); diff.CompareDocuments(new XmlDiffOptions() { TwoWayMatch = true }); Assert.AreEqual(0, diff.DiffNodeList.Count); // How about aggregating the options nodes - there is already a method for this // see AggregateChildElements. This is just an example of the power of linq xmlDoc.LoadXml(TestResources.aggregatetest); var groups = (from node in xmlDoc.Descendants(XmlNodeType.Element) where node.LocalName == "Option" group node.ChildNodes by node.ParentNode); foreach (var group in groups) { // Remove the old parent "Option" var opts = group.SelectMany(nodes => nodes.Cast <XmlNode>()); opts.Select(n => n.ParentNode).Remove(); // Add the child nodes to the aggregate "Option" group.Key.Add("Option", opts.ToArray()); } diff = new XmlDiff(xmlDoc.InnerXml, TestResources.aggregateexpected); XmlDiffOptions options = new XmlDiffOptions(); options.TwoWayMatch = true; Assert.IsTrue(diff.CompareDocuments(options)); // Now, let's try removing all CurrentTermAmt nodes under PersVeh xmlDoc.LoadXml(TestResources.desc3actual); (from coverage in xmlDoc.XPathSelectMany("//PersVeh[@id = $id and @RatedDriverRef = $driver]/Coverage", "1", "1") where coverage["CurrentTermAmt"].HasValue() select coverage["CurrentTermAmt"]).Remove(); diff = new XmlDiff(xmlDoc.InnerXml, TestResources.desc3expected); Assert.IsTrue(diff.CompareDocuments(new XmlDiffOptions() { TwoWayMatch = true })); // Lastly, let's convert all "PerAccident" text to "PerAcc" xmlDoc.LoadXml(TestResources.desc4actual); (from coverage in xmlDoc.XPathSelectMany("//Coverage") from node in coverage.Descendants(XmlNodeType.Text) where node.InnerText == "PerAccident" select node) .ToList() .ForEach(n => n.InnerText = "PerAcc"); diff = new XmlDiff(xmlDoc.InnerXml, TestResources.desc4expected); Assert.IsTrue(diff.CompareDocuments(new XmlDiffOptions() { TwoWayMatch = true })); }
static void Main(string[] args) { XmlDiffOptions xDiffOptions = new XmlDiffOptions(); string fromFile = string.Empty; string toFile = string.Empty; string outFile = string.Empty; bool toCsv = false; var options = new GetOpt("XmlDiff: Tool for finding the difference between two Xml files.", new[] { new CommandLineOption('o', "outfile", "Output file to write to. Files with csv extension open in Excel.", ParameterType.String, o => outFile = (string)o), new CommandLineOption('\0', "csv", "Creates a diff csv file and opens in Excel. If no outfile is specified writes output to xmldiff.csv. Default=False", ParameterType.None, none => toCsv = true), new CommandLineOption('m', "nomatch", "Don't match text node value types (i.e. 0.00 != 0). Default=False", ParameterType.None, none => xDiffOptions.MatchValueTypes = false), new CommandLineOption('\0', "ignoretypes", "If -m or --nomatch is NOT chosen, then this chooses which match types to ignore. " + "Possible values are (string, integer, double, datetime). Multiple values may be separated by '|'", ParameterType.String, (types) => { string[] values = ((string)types).Split('|'); foreach (string value in values) { switch (value.ToLower().Trim()) { case "string": xDiffOptions.IgnoreTextTypes.Add(XmlDiffOptions.IgnoreTextNodeOptions.XmlString); break; case "integer": xDiffOptions.IgnoreTextTypes.Add(XmlDiffOptions.IgnoreTextNodeOptions.XmlInteger); break; case "double": xDiffOptions.IgnoreTextTypes.Add(XmlDiffOptions.IgnoreTextNodeOptions.XmlDouble); break; case "datetime": xDiffOptions.IgnoreTextTypes.Add(XmlDiffOptions.IgnoreTextNodeOptions.XmlDateTime); break; default: throw new CommandLineException("Error parsing enumerated values.", "ignoretypes"); } } }), new CommandLineOption('d', "nodetail", "Will not display details of matching nodes. Default=False", ParameterType.None, none => xDiffOptions.MatchDescendants = false), new CommandLineOption('c', "case", "Case Sensitive. Default=False", ParameterType.None, none => xDiffOptions.IgnoreCase = false), new CommandLineOption('\0', "2way", "Does a comparison in both directions. Default=False", ParameterType.None, none => xDiffOptions.TwoWayMatch = true), new CommandLineOption("Required. FromFile", ParameterType.String, file => fromFile = (string)file), new CommandLineOption("Required. ToFile", ParameterType.String, file => toFile = (string)file) }); try { options.ParseOptions(args); } catch (CommandLineException ex) { Console.WriteLine("Error: {0}", ex.Message); return; } StreamWriter sw; XmlDiff xdiff; try { xdiff = new XmlDiff(File.ReadAllText(fromFile), File.ReadAllText(toFile)); xdiff.CompareDocuments(xDiffOptions); } catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); return; } if (toCsv) { try { string file; if (!string.IsNullOrEmpty(outFile)) { file = outFile; } else { file = "xmldiff.csv"; } sw = new StreamWriter(file); sw.Write((toCsv) ? xdiff.ToCSVString() : xdiff.ToJsonString()); sw.Close(); Process.Start(file); } catch (IOException ex) { Console.WriteLine("Error: {0}", ex.Message); return; } } else { if (string.IsNullOrEmpty(outFile)) { Console.WriteLine(xdiff.ToJsonString()); } else { try { sw = new StreamWriter(outFile); sw.WriteLine(xdiff.ToJsonString()); sw.Close(); } catch (IOException ex) { Console.WriteLine("Error: {0}", ex.Message); return; } } } }
virtual protected bool CompareXmls(String xml1, String xml2) { XmlDiff xmldiff = new XmlDiff(XmlDiffOptions.None); return(xmldiff.Compare(xml1, xml2, false)); }
/// <summary> /// Run all tests for the given type that match the /// category filters specified for this suite /// </summary> /// <param name="testType">A type with a Test attribute</param> /// <param name="services">Services used to run the test. IORMToolTestServices can /// be retrieved from services.ServiceProvider.</param> /// <param name="suiteReport">The suite report callback</param> private void RunTests(Type testType, IORMToolServices services, IORMToolTestSuiteReport suiteReport) { IORMToolTestServices testServices = (IORMToolTestServices)services.ServiceProvider.GetService(typeof(IORMToolTestServices)); object testTypeInstance = null; object[] methodParams = null; MethodInfo[] methods = testType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); int methodCount = methods.Length; for (int i = 0; i < methodCount; ++i) { MethodInfo method = methods[i]; object[] testAttributes = method.GetCustomAttributes(typeof(ORMTestAttribute), false); Debug.Assert(testAttributes.Length < 2, "Single use attribute with inherit=false, should only pick up zero or one attributes"); // Make sure that the method is flagged as a Test method that can be run per the current category settings if (testAttributes.Length == 0 || !CheckCategoryFilters((ORMTestAttribute)testAttributes[0])) { continue; } // Make sure we've instantiated the test class if (testTypeInstance == null) { ConstructorInfo constructor; if (null != (constructor = testType.GetConstructor(new Type[] { typeof(IORMToolServices) }))) { testTypeInstance = constructor.Invoke(new object[] { services }); methodParams = new object[1]; } bool loadFailure = null == testTypeInstance; suiteReport.BeginTestClass(testType.Namespace, testType.Name, loadFailure); if (loadFailure) { return; } } ParameterInfo[] methodParamInfos = method.GetParameters(); if (!(methodParamInfos.Length == 1 && typeof(Store).IsAssignableFrom(methodParamInfos[0].ParameterType))) { // The test method does not match the signature we need, it should // not have been marked with the Test attribute suiteReport.ReportTestResults(method.Name, ORMTestResult.FailBind, null); } else { Store store = null; try { // Prepare the test services for a new test testServices.OpenReport(); // Populate a store. Automatically loads the starting // file from the test assembly if one is provided store = testServices.Load(method, null, null); // Run the method methodParams[0] = store; method.Invoke(testTypeInstance, methodParams); // Compare the current contents of the store with the // expected state testServices.Compare(store, method, null); testServices.LogValidationErrors(null); } finally { if (store != null) { ((IDisposable)store).Dispose(); } // Close the report and see if the report matches the expected results using (XmlReader reportReader = testServices.CloseReport(method)) { string methodName = method.Name; string resourceName = string.Concat(testType.FullName, ".", methodName, ".Report.xml"); Stream baselineStream = null; try { Assembly testAssembly = testType.Assembly; // Get the baseline that we're comparing to if (null != testAssembly.GetManifestResourceInfo(resourceName)) { baselineStream = testAssembly.GetManifestResourceStream(resourceName); } if (baselineStream != null) { bool hasDiff = false; // See if the data is different. XmlDiff diff = DiffEngine; XmlReaderSettings readerSettings = DetachableReaderSettings; XmlWriterSettings writerSettings = DetachableWriterSettings; using (MemoryStream diffStream = new MemoryStream()) { using (XmlReader baselineReader = XmlReader.Create(baselineStream, readerSettings)) { using (XmlWriter diffWriter = XmlWriter.Create(diffStream, writerSettings)) { hasDiff = !diff.Compare(baselineReader, reportReader, diffWriter); } } if (hasDiff) { // Record the diffgram in the suite report diffStream.Seek(0, SeekOrigin.Begin); using (XmlReader diffReader = XmlTextReader.Create(diffStream, readerSettings)) { suiteReport.ReportTestResults(methodName, ORMTestResult.FailReportDiffgram, diffReader); } } else { // Record a passing result suiteReport.ReportTestResults(methodName, ORMTestResult.Pass, null); } } } else { // Record the full report, we have no baseline to compare against suiteReport.ReportTestResults(methodName, ORMTestResult.FailReportBaseline, reportReader); } } finally { if (baselineStream != null) { ((IDisposable)baselineStream).Dispose(); } } } } } } }
//[Test] public void DefaultConfiguredToUseValidatingParser() { // DiffConfiguration diffConfiguration = new DiffConfiguration(); // OldAssert.AreEqual(DiffConfiguration.DEFAULT_USE_VALIDATING_PARSER, // diffConfiguration.UseValidatingParser); // Stream controlFileStream = ValidatorTests.ValidFile; // Stream testFileStream = ValidatorTests.InvalidFile; // try { // XmlDiff diff = new XmlDiff(new StreamReader(controlFileStream), // new StreamReader(testFileStream)); // diff.Compare(); // OldAssert.Fail("Expected validation failure"); // } catch (XmlSchemaException e) { // string message = e.Message; // to prevent 'unused variable' compiler warning // } finally { // controlFileStream.Close(); // testFileStream.Close(); // } //} //[Test] public void CanConfigureNotToUseValidatingParser() { // DiffConfiguration diffConfiguration = new DiffConfiguration(false); // OldAssert.AreEqual(false, diffConfiguration.UseValidatingParser); // Stream controlFileStream = ValidatorTests.ValidFile; // Stream testFileStream = ValidatorTests.InvalidFile; // try { // XmlDiff diff = new XmlDiff(new XmlInput(controlFileStream), // new XmlInput(testFileStream), // diffConfiguration); // diff.Compare(); // } catch (XmlSchemaException e) { // OldAssert.Fail("Unexpected validation failure: " + e.Message); // } finally { // controlFileStream.Close(); // testFileStream.Close(); // } //} //[Test] public void DefaultConfiguredWithWhitespaceHandlingAll() { // DiffConfiguration diffConfiguration = new DiffConfiguration(); // OldAssert.AreEqual(WhitespaceHandling.All, diffConfiguration.WhitespaceHandling); // PerformAssertion(xmlWithoutWhitespace, xmlWithWhitespaceElement, false); // PerformAssertion(xmlWithoutWhitespace, xmlWithoutWhitespaceElement, false); // PerformAssertion(xmlWithoutWhitespace, xmlWithWhitespace, false); // PerformAssertion(xmlWithoutWhitespaceElement, xmlWithWhitespaceElement, false); //} private void PerformAssertion(string control, string test, bool assertion) { XmlDiff diff = new XmlDiff(control, test); PerformAssertion(diff, assertion); }
public static string CompareXML(string SourceXMLContent, string TargetXMLContent, out bool isEqual) { var diffdir = AppDomain.CurrentDomain.BaseDirectory; Random r = new Random(); var difffile = Path.Combine(diffdir, r.Next() + ".txt"); XmlDiffView dv = new XmlDiffView(); StringReader sourceRdr = new StringReader(SourceXMLContent); XmlReader sourcexmlreader = XmlReader.Create(sourceRdr); StringReader targetRdr = new StringReader(TargetXMLContent); XmlReader targetxmlreader = XmlReader.Create(targetRdr); try { using (XmlTextWriter tw = new XmlTextWriter(new StreamWriter(difffile)) { Formatting = Formatting.Indented }) { XmlDiff diffnew = new XmlDiff() { Options = new XmlDiffOptions(), Algorithm = XmlDiffAlgorithm.Auto }; isEqual = diffnew.Compare(sourcexmlreader, targetxmlreader, tw); } using (StringReader sourceRdr1 = new StringReader(SourceXMLContent)) { using (XmlTextReader orig = new XmlTextReader(sourceRdr1)) { using (XmlTextReader diffGram = new XmlTextReader(difffile)) { dv.Load(orig, diffGram); } File.Delete(difffile); } } } catch (Exception ex) { isEqual = false; string msg = ex.Message; } finally { sourcexmlreader.Close(); targetxmlreader.Close(); sourceRdr.Close(); targetRdr.Close(); } StringBuilder sb = new StringBuilder(""); sb.Append("<html><body><table width='100%'>"); //Write Legend. sb.Append("<tr><td colspan='2' align='center'><b>Legend:</b>"); sb.Append("<font style='background-color: yellow' color='black'>added</font> "); sb.Append("<font style='background-color: red' color='black'>removed</font> "); sb.Append("<font style='background-color: lightgreen' color='black'>changed</font> "); sb.Append("<font style='background-color: red' color='blue'>moved from</font> "); sb.Append("<font style='background-color: yellow' color='blue'>moved to</font> "); sb.Append("<font style='background-color: white' color='#AAAAAA'>ignored</font></td></tr>"); sb.Append("<tr><td><b> Source XML Content : "); sb.Append("</b></td><td><b> Target XML Content : "); sb.Append("</b></td></tr>"); string tempFile = Path.Combine(diffdir, r.Next() + ".htm"); using (StreamWriter sw1 = new StreamWriter(tempFile)) { sw1.Write(sb.ToString()); dv.GetHtml(sw1); sw1.Write("</table></body></html>"); sw1.Close(); } string result = ""; using (var sr = new System.IO.StreamReader(tempFile)) { result = sr.ReadToEnd(); } File.Delete(tempFile); return(result); }
static void Main(string[] args) { try { int curArgIndex = 0; bool bFragment = false; // decode options XmlDiffOptions options = XmlDiffOptions.None; string optionsString = string.Empty; while (curArgIndex < args.Length && (args[curArgIndex][0] == '/' || args[curArgIndex][0] == '-')) { if (args[curArgIndex].Length != 2) { System.Console.Write("Invalid option: " + args[curArgIndex] + "\n"); return; } switch (args[curArgIndex][1]) { case '?': WriteUsage(); return; 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': bFragment = true; break; default: System.Console.Write("Invalid option: " + args[curArgIndex] + "\n"); return; } optionsString += args[curArgIndex][1]; curArgIndex++; } if (args.Length - curArgIndex < 3) { WriteUsage(); return; } bool includeIngnore = (args.Length - curArgIndex > 3); string sourceXmlFile = args[curArgIndex]; string changedXmlFile = args[curArgIndex + 1]; string resultHtmlViewFile = args[curArgIndex + 2]; string diffgramFile = args[curArgIndex + 3]; string ignoreFile = includeIngnore ? args[curArgIndex + 4] : null; MemoryStream diffgram = new MemoryStream(); XmlTextWriter diffgramWriter = new XmlTextWriter(new StreamWriter(diffgram)); var msg = "Comparing " + sourceXmlFile + " to " + changedXmlFile + " using ignore config " + ignoreFile; log.Info(msg); Console.WriteLine(msg); XmlDiff xmlDiff = new XmlDiff(options); bool bIdentical = true; try { bIdentical = xmlDiff.Compare(sourceXmlFile, changedXmlFile, bFragment, diffgramWriter, ignoreFile); } catch (Exception e) { log.Error(e.Message, e); Console.WriteLine(e.Message); return; } msg = "Files compared " + (bIdentical ? "identical." : "different."); log.Info(msg); Console.WriteLine(msg); msg = "Generating " + resultHtmlViewFile + " view file"; log.Info(msg); Console.WriteLine(msg); TextWriter resultHtml = new StreamWriter(new FileStream(resultHtmlViewFile, FileMode.Create, FileAccess.Write)); 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>" + sourceXmlFile + "</th><th>" + changedXmlFile + "</th></tr>" + "<tr><td colspan=2><hr size=1></td></tr>"); if (bIdentical) { 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); Microsoft.XmlDiffPatch.XmlDiffView xmlDiffView = new Microsoft.XmlDiffPatch.XmlDiffView(); XmlTextReader sourceReader; if (bFragment) { NameTable nt = new NameTable(); sourceReader = new XmlTextReader(new FileStream(sourceXmlFile, FileMode.Open, FileAccess.Read), XmlNodeType.Element, new XmlParserContext(nt, new XmlNamespaceManager(nt), string.Empty, XmlSpace.Default)); } else { sourceReader = new XmlTextReader(sourceXmlFile); } sourceReader.XmlResolver = null; xmlDiffView.Load(sourceReader, new XmlTextReader(diffgram)); xmlDiffView.GetHtml(resultHtml); resultHtml.WriteLine("</table></table></body></html>"); resultHtml.Close(); msg = resultHtmlViewFile + " saved successfully."; log.Info(msg); Console.WriteLine(msg); msg = "saving diffgram file"; log.Info(msg); Console.WriteLine(msg); using (FileStream file = new FileStream(diffgramFile, FileMode.Create, FileAccess.Write)) { diffgram.WriteTo(file); } msg = "diffgram file saved to " + diffgramFile; log.Info(msg); Console.WriteLine(msg); } catch (Exception e) { log.Error(e.Message, e); Console.WriteLine("Error: " + e.Message); } if (System.Diagnostics.Debugger.IsAttached) { Console.Write("\nPress enter...\n"); Console.Read(); } }
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(); }
public TCEOFHandling() { _diff = new XmlDiff(); }
private void PerformAssertion(string control, string test, bool assertion, DiffConfiguration xmlUnitConfiguration) { XmlDiff diff = new XmlDiff(new XmlInput(control), new XmlInput(test), xmlUnitConfiguration); PerformAssertion(diff, assertion); }
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; }
public XStreamingElementAPI() { _diff = new XmlDiff(); }
private void PerformAssertion(string control, string test, bool assertion) { XmlDiff diff = new XmlDiff(control, test); PerformAssertion(diff, assertion); }
public SaveWithWriter() { _diff = new XmlDiff(); }
private void PerformAssertion(XmlDiff diff, bool assertion) { Assert.AreEqual(assertion, diff.Compare().Equal); Assert.AreEqual(assertion, diff.Compare().Identical); }
internal XElementEquivalentToConstraint(XElement expectedElement) { _expectedElement = expectedElement; _diff = new XmlDiff(XmlDiffOptions.None); }
public void DefaultConfiguredToUseValidatingParser() { DiffConfiguration diffConfiguration = new DiffConfiguration(); Assert.AreEqual(DiffConfiguration.DEFAULT_USE_VALIDATING_PARSER, diffConfiguration.UseValidatingParser); Stream controlFileStream = ValidatorTests.ValidFile; Stream testFileStream = ValidatorTests.InvalidFile; try { XmlDiff diff = new XmlDiff(new StreamReader(controlFileStream), new StreamReader(testFileStream)); diff.Compare(); Assert.Fail("Expected validation failure"); } catch (XmlSchemaException e) { string message = e.Message; // to prevent 'unused variable' compiler warning } finally { controlFileStream.Close(); testFileStream.Close(); } }
private void ComputeDiff(TextReader original, TextReader modified, IProgress progress) { //enchance: just get a checksum for each entry in both files, use that to determine everything else _idsOfDeletedEntries = new List <string>(); _idsOfAddedEntries = new List <string>(); _idsOfEditedEntries = new List <string>(); _idsInOriginal = new List <string>(); XPathDocument modifiedDoc = new XPathDocument(modified); XPathNavigator modifiedNav = modifiedDoc.CreateNavigator(); XPathDocument originalDoc = new XPathDocument(original); XPathNavigator originalNav = originalDoc.CreateNavigator(); XPathNodeIterator liftElement = originalNav.SelectChildren(XPathNodeType.Element); liftElement.MoveNext(); //move to the one and only <lift> element if (liftElement.Current == null) { return; } XPathNodeIterator originalChildren = liftElement.Current.SelectChildren(XPathNodeType.Element); StringDictionary idToContentsOfModifiedEntries = new StringDictionary(); XPathNodeIterator liftOfModifiedFile = modifiedNav.SelectChildren(XPathNodeType.Element); liftOfModifiedFile.MoveNext(); if (liftOfModifiedFile.Current != null) { XPathNodeIterator modifiedChildren = liftOfModifiedFile.Current.SelectChildren(XPathNodeType.Element); while (modifiedChildren.MoveNext()) { //TODO: consider if there are benefits to using guid as the first key, then try id if (modifiedChildren.Current != null) { string id = modifiedChildren.Current.GetAttribute("id", string.Empty); idToContentsOfModifiedEntries.Add(id, modifiedChildren.Current.OuterXml); } } } while (originalChildren.MoveNext()) { if (originalChildren.Current != null) { string id = originalChildren.Current.GetAttribute("id", string.Empty); _idsInOriginal.Add(id); if (!idToContentsOfModifiedEntries.ContainsKey(id)) { _idsOfDeletedEntries.Add(id); } else { var diff = new XmlDiff(originalChildren.Current.OuterXml, idToContentsOfModifiedEntries[id]); DiffResult result = diff.Compare(); if (!result.AreEqual) { _idsOfEditedEntries.Add(id); } } } } foreach (string id in idToContentsOfModifiedEntries.Keys) { if (!_idsInOriginal.Contains(id)) { _idsOfAddedEntries.Add(id); } } }