My favorite extension methods: HtmlEncode shortcut

This is the second installment in my series highlighting my personal favorite .NET extension methods.  We’ve already talked about a String.Format shortcut.  Now we’re on to making the HtmlEncode function readily accessible.
Any time you are showing user-entered content as text on a web page, it is important to HtmlEncode the string so as to prevent execution of any rogue scripts.  The following is a two part implementation of the .NET HtmlEncode that makes this useful function much more accessible.
Part 1 is a wrapper around the base .NET function with an overload to pass in your own value to display if the value to encode is empty.
Public Shared Function HtmlEncode(ByVal value As String) As String
        Dim context As HttpContext = System.Web.HttpContext.Current
        If Not context Is Nothing Then
            Dim Server As HttpServerUtility = context.Server
            If value Is Nothing OrElse Trim(value) = "" Then
                Return "{none}"
            Else
                Dim sText As String = Server.HtmlEncode(value)
                Dim sCRLF As String = vbCrLf
                sText = Replace(sText, sCRLF, "<br>")
                Return sText
            End If
        Else
            Throw New Exception("This function must be called from an ASP.Net application.")
        End If
    End Function

    Public Shared Function HtmlEncode(ByVal value As String, ByVal mapEmptyTo As String) As String
        Dim context As HttpContext = System.Web.HttpContext.Current
        If Not context Is Nothing Then
            Dim Server As HttpServerUtility = context.Server
            If value Is Nothing OrElse Trim(value) = "" Then
                Return mapEmptyTo
            Else
                Dim sText As String = Server.HtmlEncode(value)
                Dim sCRLF As String = vbCrLf
                sText = Replace(sText, sCRLF, "<br>")
                Return sText
            End If
        Else
            Throw New Exception("This function must be called from an ASP.Net application.")
        End If
    End Function
The second part is an extension method to let you call the HtmlEncode function from any string, again with an overload to let you pass in your own empty value text.
   <Extension()> _
   Public Function HtmlEncode(ByVal value As String) As String
       Return Functions.HtmlEncode(value, "{none}")
   End Function
   <Extension()> _
   Public Function HtmlEncode(ByVal value As String, ByVal mapEmptyTo As String) As String
       Return Functions.HtmlEncode(value, mapEmptyTo)
   End Function

Posted

in

,

by

Comments

Leave a Reply