public void IsEmptyOrWhiteSpace_FalseAfterLaterAppend()
    {
        // Arrange
        var tagHelperContent = new DefaultTagHelperContent();

        // Act
        tagHelperContent.SetContent("  ");
        tagHelperContent.Append("Hello");

        // Assert
        Assert.True(tagHelperContent.GetContent().Length > 0);
        Assert.False(tagHelperContent.IsEmptyOrWhiteSpace);
    }
    public void IsEmptyOrWhiteSpace_TrueAfterAppendTagHelperContent_WithDataToEncode(string data)
    {
        // Arrange
        var tagHelperContent       = new DefaultTagHelperContent();
        var copiedTagHelperContent = new DefaultTagHelperContent();

        copiedTagHelperContent.Append(data);

        // Act
        tagHelperContent.AppendHtml(copiedTagHelperContent);

        // Assert
        Assert.True(tagHelperContent.IsEmptyOrWhiteSpace);
    }
    public void Append_WrittenAsEncoded()
    {
        // Arrange
        var tagHelperContent = new DefaultTagHelperContent();

        tagHelperContent.Append("Hi");

        var writer = new StringWriter();

        // Act
        tagHelperContent.WriteTo(writer, new HtmlTestEncoder());

        // Assert
        Assert.Equal("HtmlEncode[[Hi]]", writer.ToString());
    }
    public void WriteTo_WritesToATextWriter()
    {
        // Arrange
        var tagHelperContent = new DefaultTagHelperContent();
        var writer           = new StringWriter();

        tagHelperContent.SetContent("Hello ");
        tagHelperContent.Append("World");

        // Act
        tagHelperContent.WriteTo(writer, new HtmlTestEncoder());

        // Assert
        Assert.Equal("HtmlEncode[[Hello ]]HtmlEncode[[World]]", writer.ToString());
    }
Ejemplo n.º 5
0
        private static TagHelperContext MakeTagHelperContext(
            TagHelperAttributeList attributes = null,
            string content = null)
        {
            attributes = attributes ?? new TagHelperAttributeList();

            return(new TagHelperContext(
                       attributes,
                       items: new Dictionary <object, object>(),
                       uniqueId: Guid.NewGuid().ToString("N"),
                       getChildContentAsync: () =>
            {
                var tagHelperContent = new DefaultTagHelperContent();
                tagHelperContent.Append(content);
                return Task.FromResult((TagHelperContent)tagHelperContent);
            }));
        }
Ejemplo n.º 6
0
 public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
 {
     if (ShowDismiss)
     {
         output.PreContent.AppendFormat(@"<button type='button' class='btn btn-default' data-dismiss='modal'>{0}</button>", DismissText);
     }
     var childContent = await output.GetChildContentAsync();
     var footerContent = new DefaultTagHelperContent();
     if (ShowDismiss)
     {
         footerContent.AppendFormat(@"<button type='button' class='btn btn-default' data-dismiss='modal'>{0}</button>", DismissText);
     }
     footerContent.Append(childContent);
     var modalContext = (ModalContext)context.Items[typeof(BootstrapModalTagHelper)];
     modalContext.Footer = footerContent;
     output.SuppressOutput();
 }
        /// <summary>
        ///     Generate the HTML content for a <see cref="OperationMessage" />.
        /// </summary>
        /// <param name="message">The <see cref="OperationMessage" /> instance.</param>
        /// <param name="useTwoLineMode">If the two line mode should be used.</param>
        /// <returns>The generated HTML content.</returns>
        private static IHtmlContent GenerateMessageContent(OperationMessage message, bool useTwoLineMode)
        {
            var result = new DefaultTagHelperContent();

            // Title
            result.AppendHtml(GenerateTitle(message.Title));

            // If description exists, add it
            if (!string.IsNullOrEmpty(message.Description))
            {
                // Add a newline for two line mode.
                if (useTwoLineMode)
                {
                    result.Append("<br />");
                }

                result.AppendHtml(GenerateDescrption(message.Description));
            }

            return(result);
        }
    public void CopyTo_CopiesAllItems()
    {
        // Arrange
        var source = new DefaultTagHelperContent();

        source.AppendHtml(new HtmlString("hello"));
        source.Append("Test");

        var items       = new List <object>();
        var destination = new HtmlContentBuilder(items);

        destination.Append("some-content");

        // Act
        source.CopyTo(destination);

        // Assert
        Assert.Equal(3, items.Count);

        Assert.Equal("some-content", Assert.IsType <string>(items[0]));
        Assert.Equal("hello", Assert.IsType <HtmlString>(items[1]).Value);
        Assert.Equal("Test", Assert.IsType <string>(items[2]));
    }
Ejemplo n.º 9
0
    public void RenderLinkTags_FallbackHref_WithFileVersion_EncodesAsExpected()
    {
        // Arrange
        var expectedContent = "<link encoded=\"contains \"quotes\"\" " +
                              "href=\"HtmlEncode[[/css/site.css?v=f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk]]\" " +
                              "literal=\"HtmlEncode[[all HTML encoded]]\" " +
                              "mixed=\"HtmlEncode[[HTML encoded]] and contains \"quotes\"\" rel=\"stylesheet\" />" +
                              Environment.NewLine +
                              "<meta name=\"x-stylesheet-fallback-test\" content=\"\" class=\"HtmlEncode[[hidden]]\" /><script>" +
                              "!function(a,b,c,d){var e,f=document,g=f.getElementsByTagName(\"SCRIPT\"),h=g[g.length-1]." +
                              "previousElementSibling,i=f.defaultView&&f.defaultView.getComputedStyle?f.defaultView." +
                              "getComputedStyle(h):h.currentStyle;if(i&&i[a]!==b)for(e=0;e<c.length;e++)f.write('<link " +
                              "href=\"'+c[e]+'\" '+d+\"/>\")}(\"JavaScriptEncode[[visibility]]\",\"JavaScriptEncode[[hidden]]\"," +
                              "[\"JavaScriptEncode[[HtmlEncode[[/fallback.css?v=f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk]]]]\"], " +
                              "\"JavaScriptEncode[[encoded=\"contains \"quotes\"\" literal=\"HtmlEncode[[all HTML encoded]]\" " +
                              "mixed=\"HtmlEncode[[HTML encoded]] and contains \"quotes\"\" rel=\"stylesheet\" ]]\");" +
                              "</script>";
        var mixed = new DefaultTagHelperContent();

        mixed.Append("HTML encoded");
        mixed.AppendHtml(" and contains \"quotes\"");
        var context = MakeTagHelperContext(
            attributes: new TagHelperAttributeList
        {
            { "asp-append-version", "true" },
            { "asp-fallback-href-include", "**/fallback.css" },
            { "asp-fallback-test-class", "hidden" },
            { "asp-fallback-test-property", "visibility" },
            { "asp-fallback-test-value", "hidden" },
            { "encoded", new HtmlString("contains \"quotes\"") },
            { "href", "/css/site.css" },
            { "literal", "all HTML encoded" },
            { "mixed", mixed },
            { "rel", new HtmlString("stylesheet") },
        });
        var output = MakeTagHelperOutput(
            "link",
            attributes: new TagHelperAttributeList
        {
            { "encoded", new HtmlString("contains \"quotes\"") },
            { "literal", "all HTML encoded" },
            { "mixed", mixed },
            { "rel", new HtmlString("stylesheet") },
        });
        var globbingUrlBuilder = new Mock <GlobbingUrlBuilder>(
            new TestFileProvider(),
            Mock.Of <IMemoryCache>(),
            PathString.Empty);

        globbingUrlBuilder.Setup(g => g.BuildUrlList(null, "**/fallback.css", null))
        .Returns(new[] { "/fallback.css" });

        var helper = GetHelper();

        helper.AppendVersion        = true;
        helper.FallbackHrefInclude  = "**/fallback.css";
        helper.FallbackTestClass    = "hidden";
        helper.FallbackTestProperty = "visibility";
        helper.FallbackTestValue    = "hidden";
        helper.GlobbingUrlBuilder   = globbingUrlBuilder.Object;
        helper.Href = "/css/site.css";

        // Act
        helper.Process(context, output);

        // Assert
        Assert.Equal("link", output.TagName);
        Assert.Equal("/css/site.css?v=f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk", output.Attributes["href"].Value);
        var content = HtmlContentUtilities.HtmlContentToString(output, new HtmlTestEncoder());

        Assert.Equal(expectedContent, content);
    }
Ejemplo n.º 10
0
        public void RendersLinkTagsForGlobbedHrefResults_EncodesAsExpected()
        {
            // Arrange
            var expectedContent =
                "<link encoded='contains \"quotes\"' href=\"HtmlEncode[[/css/site.css]]\" " +
                "literal=\"HtmlEncode[[all HTML encoded]]\" " +
                "mixed='HtmlEncode[[HTML encoded]] and contains \"quotes\"' />" +
                "<link encoded='contains \"quotes\"' href=\"HtmlEncode[[/base.css]]\" " +
                "literal=\"HtmlEncode[[all HTML encoded]]\" " +
                "mixed='HtmlEncode[[HTML encoded]] and contains \"quotes\"' />";
            var mixed = new DefaultTagHelperContent();

            mixed.Append("HTML encoded");
            mixed.AppendHtml(" and contains \"quotes\"");
            var context = MakeTagHelperContext(
                attributes: new TagHelperAttributeList
            {
                { "asp-href-include", "**/*.css" },
                { new TagHelperAttribute("encoded", new HtmlString("contains \"quotes\""), HtmlAttributeValueStyle.SingleQuotes) },
                { "href", "/css/site.css" },
                { "literal", "all HTML encoded" },
                { new TagHelperAttribute("mixed", mixed, HtmlAttributeValueStyle.SingleQuotes) },
            });
            var output = MakeTagHelperOutput(
                "link",
                attributes: new TagHelperAttributeList
            {
                { new TagHelperAttribute("encoded", new HtmlString("contains \"quotes\""), HtmlAttributeValueStyle.SingleQuotes) },
                { "literal", "all HTML encoded" },
                { new TagHelperAttribute("mixed", mixed, HtmlAttributeValueStyle.SingleQuotes) },
            });
            var hostingEnvironment = MakeHostingEnvironment();
            var viewContext        = MakeViewContext();
            var globbingUrlBuilder = new Mock <GlobbingUrlBuilder>(
                new TestFileProvider(),
                Mock.Of <IMemoryCache>(),
                PathString.Empty);

            globbingUrlBuilder.Setup(g => g.BuildUrlList(null, "**/*.css", null))
            .Returns(new[] { "/base.css" });

            var helper = new LinkTagHelper(
                hostingEnvironment,
                MakeCache(),
                new HtmlTestEncoder(),
                new JavaScriptTestEncoder(),
                MakeUrlHelperFactory())
            {
                GlobbingUrlBuilder = globbingUrlBuilder.Object,
                Href        = "/css/site.css",
                HrefInclude = "**/*.css",
                ViewContext = viewContext,
            };

            // Act
            helper.Process(context, output);

            // Assert
            Assert.Equal("link", output.TagName);
            Assert.Equal("/css/site.css", output.Attributes["href"].Value);
            var content = HtmlContentUtilities.HtmlContentToString(output, new HtmlTestEncoder());

            Assert.Equal(expectedContent, content);
        }
Ejemplo n.º 11
0
        public void RenderScriptTags_FallbackSrc_WithFileVersion_EncodesAsExpected()
        {
            // Arrange
            var expectedContent =
                "<script encoded=\"contains &quot;quotes&quot;\" literal=\"HtmlEncode[[all HTML encoded]]\" " +
                "mixed=\"HtmlEncode[[HTML encoded]] and contains &quot;quotes&quot;\" " +
                "src=\"HtmlEncode[[/js/site.js?v=f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk]]\"></script>" +
                Environment.NewLine +
                "<script>(isavailable()||document.write(\"<script " +
                "JavaScriptEncode[[encoded]]=\\\"JavaScriptEncode[[contains &quot;quotes&quot;]]\\\" " +
                "JavaScriptEncode[[literal]]=\\\"JavaScriptEncode[[HtmlEncode[[all HTML encoded]]]]\\\" " +
                "JavaScriptEncode[[mixed]]=\\\"JavaScriptEncode[[HtmlEncode[[HTML encoded]] and contains &quot;quotes&quot;]]\\\" " +
                "src=\\\"JavaScriptEncode[[HtmlEncode[[fallback.js?v=f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk]]]]\\\">" +
                "<\\/script>\"));</script>";
            var mixed = new DefaultTagHelperContent();

            mixed.Append("HTML encoded");
            mixed.AppendHtml(" and contains \"quotes\"");
            var context = MakeTagHelperContext(
                attributes: new TagHelperAttributeList
            {
                { "asp-append-version", "true" },
                { "asp-fallback-src-include", "fallback.js" },
                { "asp-fallback-test", "isavailable()" },
                { "encoded", new HtmlString("contains \"quotes\"") },
                { "literal", "all HTML encoded" },
                { "mixed", mixed },
                { "src", "/js/site.js" },
            });
            var output = MakeTagHelperOutput(
                "script",
                attributes: new TagHelperAttributeList
            {
                { "encoded", new HtmlString("contains \"quotes\"") },
                { "literal", "all HTML encoded" },
                { "mixed", mixed },
            });
            var hostingEnvironment = MakeHostingEnvironment();
            var viewContext        = MakeViewContext();

            var helper = new ScriptTagHelper(
                MakeHostingEnvironment(),
                MakeCache(),
                new HtmlTestEncoder(),
                new JavaScriptTestEncoder(),
                MakeUrlHelperFactory())
            {
                AppendVersion          = true,
                FallbackSrc            = "fallback.js",
                FallbackTestExpression = "isavailable()",
                Src         = "/js/site.js",
                ViewContext = viewContext,
            };

            // Act
            helper.Process(context, output);

            // Assert
            Assert.Equal("script", output.TagName);
            Assert.Equal("/js/site.js?v=f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk", output.Attributes["src"].Value);
            var content = HtmlContentUtilities.HtmlContentToString(output, new HtmlTestEncoder());

            Assert.Equal(expectedContent, content);
        }
Ejemplo n.º 12
0
        public void RendersScriptTagsForGlobbedSrcResults_EncodesAsExpected()
        {
            // Arrange
            var expectedContent =
                "<script encoded=\"contains &quot;quotes&quot;\" literal=\"HtmlEncode[[all HTML encoded]]\" " +
                "mixed=\"HtmlEncode[[HTML encoded]] and contains &quot;quotes&quot;\" " +
                "src=\"HtmlEncode[[/js/site.js]]\"></script>" +
                "<script encoded=\"contains &quot;quotes&quot;\" literal=\"HtmlEncode[[all HTML encoded]]\" " +
                "mixed=\"HtmlEncode[[HTML encoded]] and contains &quot;quotes&quot;\" " +
                "src=\"HtmlEncode[[/common.js]]\"></script>";
            var mixed = new DefaultTagHelperContent();

            mixed.Append("HTML encoded");
            mixed.AppendHtml(" and contains \"quotes\"");
            var context = MakeTagHelperContext(
                attributes: new TagHelperAttributeList
            {
                { "asp-src-include", "**/*.js" },
                { "encoded", new HtmlString("contains \"quotes\"") },
                { "literal", "all HTML encoded" },
                { "mixed", mixed },
                { "src", "/js/site.js" },
            });
            var output = MakeTagHelperOutput(
                "script",
                attributes: new TagHelperAttributeList
            {
                { "encoded", new HtmlString("contains \"quotes\"") },
                { "literal", "all HTML encoded" },
                { "mixed", mixed },
            });
            var hostingEnvironment = MakeHostingEnvironment();
            var viewContext        = MakeViewContext();
            var globbingUrlBuilder = new Mock <GlobbingUrlBuilder>(
                new TestFileProvider(),
                Mock.Of <IMemoryCache>(),
                PathString.Empty);

            globbingUrlBuilder.Setup(g => g.BuildUrlList(null, "**/*.js", null))
            .Returns(new[] { "/common.js" });

            var helper = new ScriptTagHelper(
                hostingEnvironment,
                MakeCache(),
                new HtmlTestEncoder(),
                new JavaScriptTestEncoder(),
                MakeUrlHelperFactory())
            {
                GlobbingUrlBuilder = globbingUrlBuilder.Object,
                Src         = "/js/site.js",
                SrcInclude  = "**/*.js",
                ViewContext = viewContext,
            };

            // Act
            helper.Process(context, output);

            // Assert
            Assert.Equal("script", output.TagName);
            Assert.Equal("/js/site.js", output.Attributes["src"].Value);
            var content = HtmlContentUtilities.HtmlContentToString(output, new HtmlTestEncoder());

            Assert.Equal(expectedContent, content);
        }
Ejemplo n.º 13
0
        private void BuildFallbackBlock(TagHelperAttributeList attributes, DefaultTagHelperContent builder)
        {
            EnsureGlobbingUrlBuilder();
            EnsureFileVersionProvider();

            var fallbackSrcs = GlobbingUrlBuilder.BuildUrlList(FallbackSrc, FallbackSrcInclude, FallbackSrcExclude);

            if (fallbackSrcs.Any())
            {
                // Build the <script> tag that checks the test method and if it fails, renders the extra script.
                builder.Append(Environment.NewLine)
                .Append("<script>(")
                .Append(FallbackTestExpression)
                .Append("||document.write(\"");

                // May have no "src" attribute in the dictionary e.g. if Src and SrcInclude were not bound.
                if (!attributes.ContainsName(SrcAttributeName))
                {
                    // Need this entry to place each fallback source.
                    attributes.Add(new TagHelperAttribute(SrcAttributeName, value: null));
                }

                foreach (var src in fallbackSrcs)
                {
                    // Fallback "src" values come from bound attributes and globbing. Must always be non-null.
                    Debug.Assert(src != null);

                    builder.Append("<script");

                    foreach (var attribute in attributes)
                    {
                        if (!attribute.Name.Equals(SrcAttributeName, StringComparison.OrdinalIgnoreCase))
                        {
                            var encodedKey     = JavaScriptEncoder.JavaScriptStringEncode(attribute.Name);
                            var attributeValue = attribute.Value.ToString();
                            var encodedValue   = JavaScriptEncoder.JavaScriptStringEncode(attributeValue);

                            AppendAttribute(builder, encodedKey, encodedValue, escapeQuotes: true);
                        }
                        else
                        {
                            // Ignore attribute.Value; use src instead.
                            var attributeValue = src;
                            if (AppendVersion == true)
                            {
                                attributeValue = _fileVersionProvider.AddFileVersionToPath(attributeValue);
                            }

                            // attribute.Key ("src") does not need to be JavaScript-encoded.
                            var encodedValue = JavaScriptEncoder.JavaScriptStringEncode(attributeValue);

                            AppendAttribute(builder, attribute.Name, encodedValue, escapeQuotes: true);
                        }
                    }

                    builder.Append("><\\/script>");
                }

                builder.Append("\"));</script>");
            }
        }
Ejemplo n.º 14
0
        public void RenderLinkTags_FallbackHref_WithFileVersion_EncodesAsExpected()
        {
            // Arrange
            var expectedContent = "<link encoded=\"contains &quot;quotes&quot;\" " +
                                  "href=\"HtmlEncode[[/css/site.css?v=f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk]]\" " +
                                  "literal=\"HtmlEncode[[all HTML encoded]]\" " +
                                  "mixed=\"HtmlEncode[[HTML encoded]] and contains &quot;quotes&quot;\" />" +
                                  Environment.NewLine +
                                  "<meta name=\"x-stylesheet-fallback-test\" content=\"\" class=\"HtmlEncode[[hidden]]\" />" +
                                  "<script>!function(a,b,c){var d,e=document,f=e.getElementsByTagName(\"SCRIPT\")," +
                                  "g=f[f.length-1].previousElementSibling," +
                                  "h=e.defaultView&&e.defaultView.getComputedStyle?e.defaultView.getComputedStyle(g):g.currentStyle;" +
                                  "if(h&&h[a]!==b)for(d=0;d<c.length;d++)e.write('<link rel=\"stylesheet\" href=\"'+c[d]+'\"/>')}(" +
                                  "\"JavaScriptEncode[[visibility]]\",\"JavaScriptEncode[[hidden]]\"," +
                                  "[\"JavaScriptEncode[[HtmlEncode[[/fallback.css?v=f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk]]]]\"]);" +
                                  "</script>";
            var mixed = new DefaultTagHelperContent();

            mixed.Append("HTML encoded");
            mixed.AppendHtml(" and contains \"quotes\"");
            var context = MakeTagHelperContext(
                attributes: new TagHelperAttributeList
            {
                { "asp-append-version", "true" },
                { "asp-fallback-href-include", "**/fallback.css" },
                { "asp-fallback-test-class", "hidden" },
                { "asp-fallback-test-property", "visibility" },
                { "asp-fallback-test-value", "hidden" },
                { "encoded", new HtmlString("contains \"quotes\"") },
                { "href", "/css/site.css" },
                { "literal", "all HTML encoded" },
                { "mixed", mixed },
            });
            var output = MakeTagHelperOutput(
                "link",
                attributes: new TagHelperAttributeList
            {
                { "encoded", new HtmlString("contains \"quotes\"") },
                { "literal", "all HTML encoded" },
                { "mixed", mixed },
            });
            var hostingEnvironment = MakeHostingEnvironment();
            var viewContext        = MakeViewContext();
            var globbingUrlBuilder = new Mock <GlobbingUrlBuilder>(
                new TestFileProvider(),
                Mock.Of <IMemoryCache>(),
                PathString.Empty);

            globbingUrlBuilder.Setup(g => g.BuildUrlList(null, "**/fallback.css", null))
            .Returns(new[] { "/fallback.css" });

            var helper = new LinkTagHelper(
                MakeHostingEnvironment(),
                MakeCache(),
                new HtmlTestEncoder(),
                new JavaScriptTestEncoder(),
                MakeUrlHelperFactory())
            {
                AppendVersion        = true,
                FallbackHrefInclude  = "**/fallback.css",
                FallbackTestClass    = "hidden",
                FallbackTestProperty = "visibility",
                FallbackTestValue    = "hidden",
                GlobbingUrlBuilder   = globbingUrlBuilder.Object,
                Href        = "/css/site.css",
                ViewContext = viewContext,
            };

            // Act
            helper.Process(context, output);

            // Assert
            Assert.Equal("link", output.TagName);
            Assert.Equal("/css/site.css?v=f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk", output.Attributes["href"].Value);
            var content = HtmlContentUtilities.HtmlContentToString(output, new HtmlTestEncoder());

            Assert.Equal(expectedContent, content);
        }