Tag: best practices

  • 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
  • My favorite Extension methods: String.Format shortcut

    This is the first entry in a short series highlighting some of my favorite extension methods.

    It’s a generally accepted best practice to use the String.Format() method to assemble string values that merge text and variables.

    Using an Extension Method (.NET 3.5 or greater) makes accessing the String.Format function even easier.

    Now, for any string value, you can simply use the following

    "The quick brown fox {0}".Fmt("jumped over the lazy dog.")

    Here’s the code for the extension method and various overloads:

    <Extension()>_
    Public Function Fmt(ByVal format As String, ByVal arg0 As Object) As String
      Return String.Format(format, arg0)
    End Function
    
    <Extension()>_
    Public Function Fmt(ByVal format As String, ByVal arg0 As Object, ByVal arg1 As Object) As String
      Return String.Format(format, arg0, arg1)
    End Function
    
    <Extension()>_
    Public Function Fmt(ByVal format As String, ByVal arg0 As Object, ByVal arg1 As Object, ByVal arg2 As Object) As String
      Return String.Format(format, arg0, arg1, arg2)
    End Function
    
    <Extension()>_
    Public Function Fmt(ByVal format As String, ByVal ParamArray args() As Object) As String
      Return String.Format(format, args)
    End Function
  • Simple API Documentation guidelines

    This month’s issue of MSDN Magazine had a great article from Peter Gruenbaum titled A Coder’s Guide to Writing API Documentation.  Let’s face it, documentation of the code we write is typically an afterthough, rarely given the attention it deserves, and is the first thing we point to (when it is lacking, that is) to complain about the ramp up time required for supporting a system.

    I particularly liked one table Peter included in his article that laid out some basic guidelines for structuring documentation according to the type of code snippet we are annotating.  I think by following these simple guidelines, any developer can have a big impact on their codebase.

    Type Guideline Examples
    Class Start with a word like “Represents” “Represents a user’s photo album.”
    Methods and functions Start with a verb “Returns the number of contacts for the specified area.”

    “Pauses the video.”

    Properties Use a noun or start with verbs such as “Gets” or “Gets and sets” “The user’s tasks.”

    “Gets and sets a collection of the user’s tasks.”

    Events Start with a phrase such as “Raised when” or “Occurs when” “Raised when the response from server is received.”
    XML elements Use a noun-based phrase “The city’s postal code.”
    Boolean values For Boolean properties, start with “Indicates whether”; for Boolean return values on methods and functions, start with “Returns whether” “Indicates whether the control is visible.”

    “Returns whether two regions intersect.”

    I am a well documented fan and stickler for good commenting in code.  I have been in too many organizations that refuse to make time or priority to do the necessary effort, but then love to complain when it isn’t sufficient.  By using these basic guidelines, it seems reasonable that at least every public class, property and method can carry some descriptive notes that will aide the next developer who consumes those assets.

    Start small, and I’m sure you’ll find that it has a big impact later on.  Future ranks of developers who inherit your code will undoubtedly thank you for your diligence.