public void XmlResolverAddWithValidData() { var xmlResolver = new XmlPreloadedResolver(XmlKnownDtds.Xhtml10); byte[] data = "hello world" u8.ToArray(); MemoryStream stream = new MemoryStream(data); xmlResolver.Add(new Uri("-//Sample//URI//For Testing", UriKind.RelativeOrAbsolute), stream); Stream result = xmlResolver.GetEntity(new Uri("-//Sample//URI//For Testing", UriKind.RelativeOrAbsolute), null, typeof(Stream)) as Stream; Assert.NotNull(result); byte[] output = new byte[data.Length]; result.Read(output, 0, output.Length); Assert.Equal(data, output); DummyStream dummyStream = new DummyStream(data); xmlResolver.Add(new Uri("-//W3C//DTD XHTML 1.0 Strict//EN", UriKind.RelativeOrAbsolute), dummyStream); Stream otherResult = xmlResolver.GetEntity(new Uri("-//W3C//DTD XHTML 1.0 Strict//EN", UriKind.RelativeOrAbsolute), null, typeof(Stream)) as Stream; output = new byte[data.Length]; otherResult.Read(output, 0, output.Length); Assert.Equal(data, output); }
public void Add_NoOverride() { var uri = new Uri("http://test.local"); byte[] resourceA = new byte[] { 43, 59 }; byte[] resourceB = new byte[] { 217, 24, 64 }; var xmlResolver = new XmlPreloadedResolver(); xmlResolver.Add(uri, resourceA); xmlResolver.Add(uri, resourceB, @override: false); VerifyResource(resourceA, xmlResolver, uri); }
public static XmlDocument LoadHtml(string path, out XmlPreloadedResolver resolver) { resolver = new XmlPreloadedResolver(XmlKnownDtds.Xhtml10); XmlDocument htmlDocument = new XmlDocument { XmlResolver = resolver }; htmlDocument.AppendChild(htmlDocument.CreateDocumentType("html", "", EntityMapDictionary.DtdURI_Xhtml_Transitional, "")); htmlDocument.AppendChild(htmlDocument.CreateElement("html", NamespaceURI_Xhtml)); if (string.IsNullOrEmpty(path) || !File.Exists(path)) { return(htmlDocument); } string content; using (StreamReader reader = new StreamReader(path, new UTF8Encoding(false, false))) content = reader.ReadToEnd(); Match m = DocTypeRegex.Match(content); Uri uri = new Uri(path, UriKind.Absolute); resolver.Add(uri, "<!DOCTYPE html SYSTEM \"" + EntityMapDictionary.DtdURI_Xhtml_Transitional + "\">" + Environment.NewLine + ((m.Success) ? content.Substring(m.Length) : content)); using (XmlReader reader = XmlReader.Create(uri.AbsoluteUri, new XmlReaderSettings { CheckCharacters = false, DtdProcessing = DtdProcessing.Parse, XmlResolver = resolver })) htmlDocument.Load(reader); ConvertElementContentToEntities(htmlDocument, EntityMapDictionary.Default, htmlDocument.DocumentElement); return(htmlDocument); }
/// <summary> /// Generates C# code from a given <paramref name="xsdFile"/> and then returns the <see cref="CSharpSyntaxTree"/> of /// the generated code. /// </summary> /// <param name="xsdFile"></param> /// <returns></returns> public static CSharpSyntaxTree GenerateSyntaxTree(FileInfo xsdFile) { if (xsdFile == null) { throw new ArgumentNullException(nameof(xsdFile)); } var folderWithAdditionalXsdFiles = xsdFile.DirectoryName; var directoryInfo = new DirectoryInfo(folderWithAdditionalXsdFiles); var additionalXsds = directoryInfo.GetFiles("*.xsd"); var xmlPreloadedResolver = new XmlPreloadedResolver(); foreach (var xsd in additionalXsds) { xmlPreloadedResolver.Add(new Uri($"file://{xsd.FullName}"), File.OpenRead(xsd.FullName)); } var xmlReaderSettings = new XmlReaderSettings() { DtdProcessing = DtdProcessing.Ignore, CloseInput = true }; var atomXsdSchemaSet = XmlReader.Create(xsdFile.FullName, xmlReaderSettings) .ToXmlSchemaSet(xmlPreloadedResolver); var sourceText = GenerateSourceText(atomXsdSchemaSet, xsdFile.FullName); using var writer = new StreamWriter(xsdFile.FullName + ".cs"); sourceText.Write(writer); var tree = CSharpSyntaxTree.ParseText(sourceText, CSharpParseOptions.Default); return(tree as CSharpSyntaxTree); }
/// <summary> /// Validate the OSTC certificate request document /// </summary> /// <param name="order">the OSTC certificate request document</param> public void Validate(byte[] order) { var resolver = new XmlPreloadedResolver(); var ostcUri = "http://localhost/OSTC.xsd"; var asm = typeof(OstcAntragValidator).Assembly; using (var stream = asm.GetManifestResourceStream(typeof(OstcAntragValidator), "Schemas.OSTC.xsd")) { resolver.Add(new Uri(ostcUri, UriKind.RelativeOrAbsolute), stream); } var settings = new XmlReaderSettings { ValidationType = ValidationType.Schema, ValidationFlags = XmlSchemaValidationFlags.ProcessSchemaLocation, XmlResolver = resolver, }; var input = FixDocument(order, ostcUri); var reader = XmlReader.Create(input, settings); while (reader.Read()) { } }
private XmlPreloadedResolver GetResolverWithStringData(XmlKnownDtds dtd, string data, Uri uri) { var xmlResolver = new XmlPreloadedResolver(dtd); xmlResolver.Add(uri, data); return(xmlResolver); }
private static void AddDTD(this XmlPreloadedResolver resolver, string url, string resourceName) { using (var stream = ReadResource(resourceName)) { resolver.Add(new Uri(url), stream); } }
/// <summary> /// Assuming that other XSDs exist in the same directory as the given <paramref name="fileName"/>, this will pre-load those /// additional XSDs into an <see cref="XmlPreloadedResolver"/> and use them if they are referenced by the file. /// </summary> /// <param name="fileName"></param> /// <returns>Returns a compiled <see cref="XmlSchemaSet"/></returns> public static XmlSchemaSet PreLoadXmlSchemas(string fileName) { if (fileName.IsEmpty()) { throw new ArgumentNullException(nameof(fileName)); } var xsdFile = new FileInfo(fileName); var directoryInfo = new DirectoryInfo(Path.GetDirectoryName(fileName)); FileInfo[] additionalXsds = directoryInfo.GetFiles("*.xsd"); var xmlPreloadedResolver = new XmlPreloadedResolver(); foreach (FileInfo xsd in additionalXsds) { xmlPreloadedResolver.Add(new Uri($"file://{xsd.FullName}"), File.OpenRead(xsd.FullName)); } var xmlReaderSettings = new XmlReaderSettings() { DtdProcessing = DtdProcessing.Ignore, CloseInput = true }; XmlSchemaSet xmlSchemaSet = XmlReader.Create(xsdFile.FullName, xmlReaderSettings) .ToXmlSchemaSet(xmlPreloadedResolver); return(xmlSchemaSet); }
public void ExcC14NSpecExample1() { XmlPreloadedResolver resolver = new XmlPreloadedResolver(); resolver.Add(TestHelpers.ToUri("doc.dtd"), ""); string res = ExecuteXmlDSigExcC14NTransform(ExcC14NSpecExample1Input); Assert.Equal(ExcC14NSpecExample1Output, res); }
public static bool Add(this XmlPreloadedResolver resolver, Uri uri, Stream value, bool @override) { if (@override || !resolver.PreloadedUris.Contains(uri)) { resolver.Add(uri, value); return(true); } return(false); }
public void C14NSpecExample5() { XmlPreloadedResolver resolver = new XmlPreloadedResolver(); resolver.Add(TestHelpers.ToUri("doc.txt"), "world"); string result = TestHelpers.ExecuteTransform(C14NSpecExample5Input, new XmlDsigC14NTransform(), Encoding.UTF8, resolver); Assert.Equal(C14NSpecExample5Output, result); }
public void C14NSpecExample1() { XmlPreloadedResolver resolver = new XmlPreloadedResolver(); resolver.Add(TestHelpers.ToUri("world.dtd"), ""); string res = TestHelpers.ExecuteTransform(C14NSpecExample1Input, new XmlDsigC14NWithCommentsTransform(), Encoding.UTF8, resolver); Assert.Equal(C14NSpecExample1Output, res); }
public void C14NSpecExample1() { XmlPreloadedResolver resolver = new XmlPreloadedResolver(); resolver.Add(new Uri("doc.xsl", UriKind.Relative), ""); string result = TestHelpers.ExecuteTransform(C14NSpecExample1Input, new XmlDsigC14NTransform()); Assert.Equal(C14NSpecExample1Output, result); }
public void ExcC14NSpecExample5() { XmlPreloadedResolver resolver = new XmlPreloadedResolver(); resolver.Add(TestHelpers.ToUri("doc.txt"), "world"); string input = ExcC14NSpecExample5Input; string res = ExecuteXmlDSigExcC14NTransform(input, resolver); Assert.Equal(ExcC14NSpecExample5Output, res); }
public void XmlResolverRemoveWithValidData() { var xmlResolver = new XmlPreloadedResolver(XmlKnownDtds.Xhtml10); byte[] data = "hello world" u8.ToArray(); MemoryStream stream = new MemoryStream(data); xmlResolver.Add(new Uri("-//W3C//DTD XHTML 1.0 Transitional//EN", UriKind.RelativeOrAbsolute), stream); xmlResolver.Remove(new Uri("-//W3C//DTD XHTML 1.0 Transitional//EN", UriKind.RelativeOrAbsolute)); }
public void C14NSpecExample5() { XmlPreloadedResolver resolver = new XmlPreloadedResolver(); resolver.Add(TestHelpers.ToUri("doc.txt"), "world"); string input = C14NSpecExample5Input; string result = ExecuteXmlDSigC14NTransform(input, Encoding.UTF8, resolver); string expectedResult = C14NSpecExample5Output; Assert.Equal(expectedResult, result); }
public void Add_CustomComparer() { var uriA = new Uri("http://test.local/abc"); var uriB = new Uri("http://test.local/xyz"); var resourceA = new byte[] { 43, 59 }; var resourceB = new byte[] { 217, 24, 64 }; var uriComparer = KeyEqualityComparer.Create((Uri uri) => uri.Host); var xmlResolver = new XmlPreloadedResolver(null, XmlKnownDtds.None, uriComparer); xmlResolver.Add(uriA, resourceA); xmlResolver.Add(uriB, resourceB, @override: false); VerifyResource(resourceA, xmlResolver, uriA); VerifyResource(resourceA, xmlResolver, uriB); xmlResolver.Add(uriB, resourceB, @override: true); VerifyResource(resourceB, xmlResolver, uriA); VerifyResource(resourceB, xmlResolver, uriB); }
public void XmlResolverGetEntityAsyncWithValidUserSuppliedData() { byte[] inpData = Encoding.ASCII.GetBytes("hello world"); var xmlResolver = new XmlPreloadedResolver(XmlKnownDtds.Xhtml10); xmlResolver.Add(new Uri("-//W3C//DTD FAKE 1.0 Not Real//EN", UriKind.RelativeOrAbsolute), inpData); Task <object> output = xmlResolver.GetEntityAsync(new Uri("-//W3C//DTD FAKE 1.0 Not Real//EN", UriKind.RelativeOrAbsolute), null, typeof(Stream)); var result = new byte[inpData.Length]; (output.Result as Stream).Read(result, 0, result.Length); Assert.Equal(inpData, result); }
/// <summary> /// Adds a byte array to the <see cref="XmlPreloadedResolver"/> store and maps it to a URI. /// If the store already contains a mapping for the same URI, /// the existing mapping is overridden if <paramref name="override"/> is specified as <see langword="true"/>. /// </summary> /// <param name="resolver">The resolver to which to add the data mapped to the URI.</param> /// <param name="uri">The URI of the data that is being added to the <see cref="XmlPreloadedResolver"/> store.</param> /// <param name="value">A byte array with the data that corresponds to the provided URI.</param> /// <param name="override"> /// Whether to add <paramref name="value"/> and override the mapping for <paramref name="uri"/> /// even if it is already defined in the store. /// </param> /// <returns> /// <see langword="true"/> if <paramref name="value"/> was added to the store and mapped to <paramref name="uri"/>; /// <see langword="false"/> if <paramref name="uri"/> was already defined and not overridden. /// </returns> /// <remarks> /// Refer to the remarks on the <see cref="Add(XmlPreloadedResolver, Uri, Stream, bool)"/> overload. /// </remarks> public static bool Add(this XmlPreloadedResolver resolver, Uri uri, byte[] value, bool @override) { ArgumentValidate.NotNull(resolver, nameof(resolver)); ArgumentValidate.NotNull(uri, nameof(uri)); ArgumentValidate.NotNull(value, nameof(value)); if (@override || !resolver.PreloadedUris.Contains(uri)) { resolver.Add(uri, value); return(true); } return(false); }
public void XmlResolverSupportsTypeWithValidData() { var xmlResolver = new XmlPreloadedResolver(); var uri = new Uri("-//W3C//DTD XHTML 1.0 Strict//EN", UriKind.RelativeOrAbsolute); bool result = xmlResolver.SupportsType(uri, typeof(string)); Assert.False(result); xmlResolver = new XmlPreloadedResolver(new XmlPreloadedResolver(), XmlKnownDtds.Xhtml10); Assert.True(xmlResolver.SupportsType(uri, typeof(Stream))); xmlResolver.Add(uri, "String Value"); result = xmlResolver.SupportsType(uri, typeof(TextReader)); Assert.True(result); result = xmlResolver.SupportsType(uri, null); Assert.True(result); }
public XSLTValidator(string languageName, XsltArgumentList xsltArgumentList) { if (null == xsltArgumentList) { throw new ArgumentNullException("xsltArgumentList"); } _xslArg = xsltArgumentList; _xslt = new XslCompiledTransform(); var assembly = this.GetType().Assembly; var resolver = new XmlPreloadedResolver(); string mainXSLT = null; string[] resourceNames = this.GetType().Assembly.GetManifestResourceNames(); foreach (string resourceName in resourceNames) { if (resourceName.EndsWith(".xslt") && resourceName.Contains(languageName)) { string templateName = resourceName.Substring(resourceName.LastIndexOf(languageName) + languageName.Length); if (templateName == ".xslt") { mainXSLT = resourceName; } else { using (var stream = assembly.GetManifestResourceStream(resourceName)) { resolver.Add(resolver.ResolveUri(null, templateName), stream); } } } } using (var stream = assembly.GetManifestResourceStream(mainXSLT)) using (var reader = XmlReader.Create(stream)) { _xslt.Load(reader, null, resolver); } }
protected override void Render(HtmlTextWriter writer) { StringBuilder sbOut = new StringBuilder(); StringWriter swOut = new StringWriter(sbOut); HtmlTextWriter htwOut = new HtmlTextWriter(swOut); base.Render(htwOut); string originalHTML = sbOut.ToString(); if ("true".Equals(Context.Items["EmailRequest"])) { XmlDocument document = new XmlDocument(); string xhtmlStr = sbOut.ToString(); XmlPreloadedResolver resolver = new XmlPreloadedResolver(); resolver.Add(resolver.ResolveUri(null, "Static/xhtml-trans10.dtd"), xhtmlStr); XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.XmlResolver = resolver; readerSettings.DtdProcessing = DtdProcessing.Parse; StringReader sr = new StringReader(xhtmlStr); XmlReader reader = XmlReader.Create(sr, readerSettings); document.Load(reader); XmlElement root = document.DocumentElement; XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable); nsmgr.AddNamespace("h", document.DocumentElement.NamespaceURI); RewriteImageURLs(root.SelectNodes("//h:img", nsmgr)); RewriteCSSPaths(root.SelectNodes("//h:link", nsmgr)); TransformNodes(document, root.SelectNodes("//h:a", nsmgr), "span"); DeleteNodes(root.SelectNodes("//h:div[@id='inventory-graph']", nsmgr)); DeleteNodes(root.SelectNodes("//h:div[@id='chart']", nsmgr)); DeleteNodes(root.SelectNodes("//h:script", nsmgr)); DeleteNodes(root.SelectNodes("//h:input[@type='hidden']", nsmgr)); // this bit of xpath gets all elements that have onclick attributes RemoveOnClickEvents(root.SelectNodes("self::node()/descendant-or-self::node()[@onclick]", nsmgr)); string reportHTML = "<!DOCTYPE html PUBLIC \" -//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"; reportHTML += document.DocumentElement.OuterXml; _message.Body += "<br/>" + reportHTML; if (Context.Items["EmailAttachmentName"].ToString().EndsWith("pdf")) { PdfService service = new PdfService(); byte[] pdf = service.GeneratePdf(reportHTML); _message.Attachments.Add(new Attachment(new MemoryStream(pdf), Context.Items["EmailAttachmentName"].ToString())); } else if (Context.Items["EmailAttachmentName"].ToString().EndsWith("html")) { ASCIIEncoding encoder = new ASCIIEncoding(); _message.Attachments.Add(new Attachment(new MemoryStream(encoder.GetBytes(reportHTML)), Context.Items["EmailAttachmentName"].ToString())); } SmtpClient client = new SmtpClient(); client.Send(_message); } writer.Write(originalHTML); }
public void XmlResolverAddWithInvalidData() { var xmlResolver = new XmlPreloadedResolver(); Assert.Throws <ArgumentNullException>(() => xmlResolver.Add(null, new byte[22])); Assert.Throws <ArgumentNullException>(() => xmlResolver.Add(new Uri("https://html"), null as byte[])); Assert.Throws <ArgumentNullException>(() => xmlResolver.Add(null, null, 0, 0)); Assert.Throws <ArgumentNullException>(() => xmlResolver.Add(new Uri("https://html"), null, 0, 0)); Assert.Throws <ArgumentOutOfRangeException>(() => xmlResolver.Add(new Uri("https://html"), new byte[22], -1, 0)); Assert.Throws <ArgumentOutOfRangeException>(() => xmlResolver.Add(new Uri("https://html"), new byte[22], 0, -1)); Assert.Throws <ArgumentOutOfRangeException>(() => xmlResolver.Add(new Uri("https://html"), new byte[11], 5, 20)); //No Exception should be thrown for the below cases as these are border cases xmlResolver.Add(new Uri("https://html"), new byte[0], 0, 0); xmlResolver.Add(new Uri("https://html"), new byte[5], 0, 5); Assert.Throws <ArgumentNullException>(() => xmlResolver.Add(null, new MemoryStream())); Assert.Throws <ArgumentNullException>(() => xmlResolver.Add(new Uri("https://html"), null as MemoryStream)); Assert.Throws <ArgumentNullException>(() => xmlResolver.Add(null, string.Empty)); Assert.Throws <ArgumentNullException>(() => xmlResolver.Add(new Uri("https://html"), null as string)); }