Esempio n. 1
0
        /// <summary>
        /// Applies all tests.
        /// </summary>
        /// <returns>The test instance.</returns>
        public CssSelectorTest Run()
        {
            Console.WriteLine("Running tests ...");
            var totalTime = 0L;

            for (int i = 0; i < _tests.Count; i++)
            {
                var test   = _tests[i];
                var result = _doc.QuerySelectorAll(test).Length;
                var sw     = Stopwatch.StartNew();

                for (int j = 0; j < n; j++)
                {
                    _doc.QuerySelectorAll(test);
                }

                sw.Stop();
                var time = sw.ElapsedMilliseconds / n;
                totalTime += time;
                Console.WriteLine("\t{0}\t{1}\t( {2} ms )", test.PadRight(25), result.ToString().PadLeft(4), time);
            }

            Console.WriteLine("... finished [ {0} ms ] !", totalTime);
            return(this);
        }
        public void CSSSelectorUsageTest()
        {
            // Prepare HTML code
            var code = @"
                <div class='happy'>
                    <div>
                        <span>Hello</span>
                    </div>
                </div>
                <p class='happy'>
                    <span>World!</span>
                </p>
            ";

            // Initialize a document based on the prepared code
            using (var document = new HTMLDocument(code, "."))
            {
                // Here we create a CSS Selector that extract all elements whose 'class' attribute equals to 'happy' and their child SPAN elements
                var elements = document.QuerySelectorAll(".happy span");

                // Iterate over the resulted list of elements
                foreach (HTMLElement element in elements)
                {
                    Output.WriteLine(element.InnerHTML);
                    // output: Hello
                    // output: World!
                }

                Assert.Equal("HTML", document.DocumentElement.TagName);
            }
        }
Esempio n. 3
0
        void ChangeQuery()
        {
            if (document == null)
            {
                return;
            }

            State = Brushes.LightGreen;

            try
            {
                ProfilerViewModel.Data.Start("Query", OxyPlot.OxyColors.SteelBlue);
                var sw       = Stopwatch.StartNew();
                var elements = document.QuerySelectorAll(query);
                sw.Stop();
                ProfilerViewModel.Data.Stop();
                source.Clear();

                foreach (var element in elements)
                {
                    source.Add(element);
                }

                State  = Brushes.White;
                Time   = sw.ElapsedMilliseconds;
                Result = elements.Length;
            }
            catch (DOMException)
            {
                State = Brushes.LightPink;
            }
        }
Esempio n. 4
0
        public void NetworkServiceTest()
        {
            // Prepare HTML code and save it to a file
            var code = "<img src=\"https://docs.aspose.com/svg/net/drawing-basics/filters-and-gradients/park.jpg\" >\r\n" +
                       "<img src=\"https://docs.aspose.com/html/net/missing1.jpg\" >\r\n" +
                       "<img src=\"https://docs.aspose.com/html/net/missing2.jpg\" >\r\n";

            File.WriteAllText(Path.Combine(OutputDir, "network-service.html"), code);

            // Create an instance of Configuration
            using (var configuration = new Configuration())
            {
                // Add the LogMessageHandler to the chain of existing message handlers
                var networkService = configuration.GetService <INetworkService>();

                var logHandler = new LogMessageHandler();
                networkService.MessageHandlers.Add(logHandler);

                // Initialize an HTML document with specified configuration
                using (var document = new HTMLDocument(Path.Combine(OutputDir, "network-service.html"), configuration))
                {
                    //Convert HTML to PNG
                    Converter.ConvertHTML(document, new ImageSaveOptions(), Path.Combine(OutputDir, "network-service_out.png"));

                    // Print the List of ErrorMessages
                    foreach (string errorMessage in logHandler.ErrorMessages)
                    {
                        Output.WriteLine(errorMessage);
                    }

                    Assert.False(document.QuerySelectorAll("img").Length > 3);
                }
            }
        }
        public void XPathQueryUsageTest()
        {
            // Prepare an HTML code
            var code = @"
                <div class='happy'>
                    <div>
                        <span>Hello!</span>
                    </div>
                </div>
                <p class='happy'>
                    <span>World</span>
                </p>
            ";

            // Initialize a document based on the prepared code
            using (var document = new HTMLDocument(code, "."))
            {
                // Here we evaluate the XPath expression where we select all child SPAN elements from elements whose 'class' attribute equals to 'happy':
                var result = document.Evaluate("//*[@class='happy']//span",
                                               document,
                                               null,
                                               XPathResultType.Any,
                                               null);

                // Iterate over the resulted nodes
                for (Node node; (node = result.IterateNext()) != null;)
                {
                    Output.WriteLine(node.TextContent);
                    // output: Hello
                    // output: World!
                }

                Assert.True(document.QuerySelectorAll("div").Length > 0);
            }
        }
Esempio n. 6
0
        public void SandboxingTest()
        {
            // Prepare HTML code and save it to a file
            var code = "<span>Hello World!!</span> " +
                       "<script>document.write('Have a nice day!');</script>";

            File.WriteAllText(Path.Combine(OutputDir, "sandboxing.html"), code);

            // Create an instance of Configuration
            using (var configuration = new Configuration())
            {
                // Mark 'scripts' as an untrusted resource
                configuration.Security |= Sandbox.Scripts;

                // Initialize an HTML document with specified configuration
                using (var document = new HTMLDocument(Path.Combine(OutputDir, "sandboxing.html"), configuration))
                {
                    // Convert HTML to PDF
                    Converter.ConvertHTML(document, new PdfSaveOptions(), Path.Combine(OutputDir, "sandboxing_out.pdf"));

                    Assert.True(document.QuerySelectorAll("script").Length > 0);
                }

                Assert.True(File.Exists(Path.Combine(OutputDir, "sandboxing_out.pdf")));
            }
        }
        public void ExternalCSSTest()
        {
            // Create an instance of HTML document with specified content
            var htmlContent = "<link rel=\"stylesheet\" href=\"https://docs.aspose.com/html/net/editing-a-document/external.css\" type=\"text/css\" />\r\n" +
                              "<div class=\"rect1\" ></div>\r\n" +
                              "<div class=\"rect2\" ></div>\r\n" +
                              "<div class=\"frame\">\r\n" +
                              "<p style=\"font-size:2.5em; color:#ae4566;\"> External CSS </p>\r\n" +
                              "<p class=\"rect3\"> An external CSS can be created once and applied to multiple web pages</p></div>\r\n";

            using (var document = new HTMLDocument(htmlContent, "."))
            {
                // Save the HTML document to a file
                document.Save(Path.Combine(OutputDir, "external-css.html"));

                // Create the instance of the PDF output device and render the document into this device
                using (var device = new PdfDevice(Path.Combine(OutputDir, "external-css.pdf")))
                {
                    // Render HTML to PDF
                    document.RenderTo(device);
                }

                Assert.True(document.QuerySelectorAll("link").Length > 0);
            }

            Assert.True(File.Exists(Path.Combine(OutputDir, "external-css.html")));
        }
Esempio n. 8
0
        public void SaveHTMLWithLinkedFileTest()
        {
            // Prepare an output path for an HTML document
            string documentPath = Path.Combine(OutputDir, "save-with-linked-file.html");

            // Prepare a simple HTML file with a linked document
            File.WriteAllText(documentPath, "<p>Hello World!</p>" +
                              "<a href='linked.html'>linked file</a>");

            // Prepare a simple linked HTML file
            File.WriteAllText(Path.Combine(OutputDir, "linked.html"), "<p>Hello linked file!</p>");

            // Load the "save-with-linked-file.html" into memory
            using (var document = new HTMLDocument(documentPath))
            {
                // Create a save options instance
                var options = new HTMLSaveOptions();

                // The following line with value '0' cuts off all other linked HTML-files while saving this instance
                // If you remove this line or change value to the '1', the 'linked.html' file will be saved as well to the output folder
                options.ResourceHandlingOptions.MaxHandlingDepth = 1;

                // Save the document with the save options
                document.Save(Path.Combine(OutputDir, "save-with-linked-file_out.html"), options);

                Assert.True(document.QuerySelectorAll("p").Length > 0);
            }

            Assert.True(File.Exists(documentPath));
        }
        public void EditInternalCSSTest()
        {
            // Create an instance of an HTML document with specified content
            var content = "<div><p>Internal CSS</p><p>An internal CSS is used to define a style for a single HTML page</p></div>";

            using (var document = new HTMLDocument(content, "."))
            {
                var style = document.CreateElement("style");
                style.TextContent = ".frame1 { margin-top:50px; margin-left:50px; padding:20px; width:360px; height:90px; background-color:#a52a2a; font-family:verdana; color:#FFF5EE;} \r\n" +
                                    ".frame2 { margin-top:-90px; margin-left:160px; text-align:center; padding:20px; width:360px; height:100px; background-color:#ADD8E6;}";

                // Find the document header element and append the style element to the header
                var head = document.GetElementsByTagName("head").First();
                head.AppendChild(style);

                // Find the first paragraph element to inspect the styles
                var paragraph = (HTMLElement)document.GetElementsByTagName("p").First();
                paragraph.ClassName = "frame1";

                // Find the last paragraph element to inspect the styles
                var lastParagraph = (HTMLElement)document.GetElementsByTagName("p").Last();
                lastParagraph.ClassName = "frame2";

                // Set a color to the first paragraph
                paragraph.Style.FontSize  = "250%";
                paragraph.Style.TextAlign = "center";

                // Set a font-size to the last paragraph
                lastParagraph.Style.Color      = "#434343";
                lastParagraph.Style.FontSize   = "150%";
                lastParagraph.Style.FontFamily = "verdana";

                // Save the HTML document to a file
                document.Save(Path.Combine(OutputDir, "edit-internal-css.html"));

                // Create the instance of the PDF output device and render the document into this device
                using (var device = new PdfDevice(Path.Combine(OutputDir, "edit-internal-css.pdf")))
                {
                    // Render HTML to PDF
                    document.RenderTo(device);
                }

                Assert.True(document.QuerySelectorAll("style").Length > 0);

                Assert.True(File.Exists(Path.Combine(OutputDir, "edit-internal-css.pdf")));

                Assert.True(File.Exists(Path.Combine(OutputDir, "edit-internal-css.html")));
            }
        }
Esempio n. 10
0
        public void SaveHTMLToMDTest()
        {
            // Prepare an output path for a document saving
            string documentPath = Path.Combine(OutputDir, "save-to-MD.md");

            // Prepare HTML code
            var html_code = "<H2>Hello World!</H2>";

            // Initialize a document from a string variable
            using (var document = new HTMLDocument(html_code, "."))
            {
                // Save the document as a Markdown file
                document.Save(documentPath, HTMLSaveFormat.Markdown);

                Assert.True(document.QuerySelectorAll("H2").Length > 0);
            }

            Assert.True(File.Exists(documentPath));
        }
Esempio n. 11
0
        public void SaveHTMLToFileTest()
        {
            // Prepare an output path for a document saving
            string documentPath = Path.Combine(OutputDir, "save-to-file.html");

            // Initialize an empty HTML document
            using (var document = new HTMLDocument())
            {
                // Create a text element and add it to the document
                var text = document.CreateTextNode("Hello World!");
                document.Body.AppendChild(text);

                // Save the HTML document to the file on a disk
                document.Save(documentPath);

                Assert.True(document.QuerySelectorAll("body").Length > 0);
            }

            Assert.True(File.Exists(documentPath));
        }
Esempio n. 12
0
        public void LoadDocumentFromStreamTest()
        {
            // Create a memory stream object
            using (var mem = new MemoryStream())
                using (var sw = new StreamWriter(mem))
                {
                    // Write the HTML Code into memory object
                    sw.Write("<p>Hello World! I love HTML!</p>");

                    // It is important to set the position to the beginning, since HTMLDocument starts the reading exactly from the current position within the stream
                    sw.Flush();
                    mem.Seek(0, SeekOrigin.Begin);

                    // Initialize a document from the string variable
                    using (var document = new HTMLDocument(mem, "."))
                    {
                        // Save the document to disk
                        document.Save(Path.Combine(OutputDir, "load-from-stream.html"));

                        Assert.True(document.QuerySelectorAll("p").Length > 0);
                    }
                }
        }
Esempio n. 13
0
        public void SaveHTMLToMHTMLTest()
        {
            // Prepare an output path for a document saving
            string savePath = Path.Combine(OutputDir, "save-to-MHTML.mht");

            // Prepare a simple HTML file with a linked document
            File.WriteAllText("save-to-MHTML.html", "<p>Hello World!</p>" +
                              "<a href='linked-file.html'>linked file</a>");

            // Prepare a simple linked HTML file
            File.WriteAllText("linked-file.html", "<p>Hello linked file!</p>");

            // Load the "save-to-MTHML.html" into memory
            using (var document = new HTMLDocument("save-to-MHTML.html"))
            {
                // Save the document to MHTML format
                document.Save(savePath, HTMLSaveFormat.MHTML);

                Assert.True(document.QuerySelectorAll("a").Length > 0);
            }

            Assert.True(File.Exists(savePath));
        }
Esempio n. 14
0
        public void QuerySelectorAllClass()
        {
            var qsa = document.QuerySelectorAll(".testClass");

            Assert.AreEqual(2, qsa.Length);
        }
Esempio n. 15
0
 HTMLCollection RunQuery(string query)
 {
     return(document.QuerySelectorAll(query));
 }