1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
4 
5 using System;
6 using System.IO;
7 
8 namespace Microsoft.Framework.WebEncoders
9 {
10     /// <summary>
11     /// Helpful extension methods for the encoder classes.
12     /// </summary>
13     internal static class EncoderExtensions
14     {
15         /// <summary>
16         /// HTML-encodes a string and writes the result to the supplied output.
17         /// </summary>
18         /// <remarks>
19         /// The encoded value is also safe for inclusion inside an HTML attribute
20         /// as long as the attribute value is surrounded by single or double quotes.
21         /// </remarks>
HtmlEncode(this IHtmlEncoder htmlEncoder, string value, TextWriter output)22         public static void HtmlEncode(this IHtmlEncoder htmlEncoder, string value, TextWriter output)
23         {
24             if (htmlEncoder == null)
25             {
26                 throw new ArgumentNullException(nameof(htmlEncoder));
27             }
28 
29             if (!String.IsNullOrEmpty(value))
30             {
31                 htmlEncoder.HtmlEncode(value, 0, value.Length, output);
32             }
33         }
34 
35         /// <summary>
36         /// JavaScript-escapes a string and writes the result to the supplied output.
37         /// </summary>
JavaScriptStringEncode(this IJavaScriptStringEncoder javaScriptStringEncoder, string value, TextWriter output)38         public static void JavaScriptStringEncode(this IJavaScriptStringEncoder javaScriptStringEncoder, string value, TextWriter output)
39         {
40             if (javaScriptStringEncoder == null)
41             {
42                 throw new ArgumentNullException(nameof(javaScriptStringEncoder));
43             }
44 
45             if (!String.IsNullOrEmpty(value))
46             {
47                 javaScriptStringEncoder.JavaScriptStringEncode(value, 0, value.Length, output);
48             }
49         }
50 
51         /// <summary>
52         /// URL-encodes a string and writes the result to the supplied output.
53         /// </summary>
54         /// <remarks>
55         /// The encoded value is safe for use in the segment, query, or
56         /// fragment portion of a URI.
57         /// </remarks>
UrlEncode(this IUrlEncoder urlEncoder, string value, TextWriter output)58         public static void UrlEncode(this IUrlEncoder urlEncoder, string value, TextWriter output)
59         {
60             if (urlEncoder == null)
61             {
62                 throw new ArgumentNullException(nameof(urlEncoder));
63             }
64 
65             if (!String.IsNullOrEmpty(value))
66             {
67                 urlEncoder.UrlEncode(value, 0, value.Length, output);
68             }
69         }
70     }
71 }
72