Saturday, 15 November 2008

Extension Methods with VB and .Net 3.5

Introduction

Extension Methods are a wonderful thing. They provide great ways to control the output of say Strings, DateTimes etc or to specifically convert DateTimes to a nullable object. They provide a way of adding new methods to already public available methods such as string. or datetime.now. so you dont have to write helper functions or sub-classes etc.

In this article I will explain some simple ways in which you could use this in a real world scenario. This article is for VB.Net but could be converted to C# easily. Note points are added if there are language differences.

Scenario
You are required to build a website or application and you must code some dynamic HTML to be rendered to the client or sent in an HTML email etc. You need a way in which to write well formatted text and reduce the amount of code you write.

Method

Let us begin. Firstly, in your project under the App_Code folder, add a new module (With ASP.Net you can only add a class. Add this but change the statement “Public Class” to “Public Module”) and call it HTMLExtensionMethods and then open it.
Now add the following import: Imports System.Runtime.CompilerServices

Note: With C# you only need to add the class and do not need to reference compiler service.

Your new module should look like this:

Imports Microsoft.VisualBasic
Imports System.Runtime.CompilerServices

Public Module HTMLExtensionMethods

End Module

To add an extension method all you need to do is write a new function that returns an object. You must add a parameter that is identical to the method you are extending. i.e. If you were extending the system.string method, the InputValue must also be a string. In order for it to be visible to the compiler and thus show in the intellisense, you must add the attribute: .

_
Public Function MethodName(ByVal InputValue As String) As String

End Function

The above shows the complete function. This function is an extension of the public system.string method. This is because the input value is also a string.

So now all we need to do is add some functionality to this module (or class) and use it in our project. I will now add some functions below as an example.

_
Public Function ToHTMLBoldString(ByVal InputValue As String) As String
Return String.Concat("", HttpUtility.HtmlEncode(InputValue), "")
End Function

_
Public Function ToHTMLItalicString(ByVal InputValue As String) As String
Return String.Concat("", HttpUtility.HtmlEncode(InputValue), "")
End Function

_
Public Function ToHTMLUnderlineString(ByVal InputValue As String) As String
Return String.Concat("", HttpUtility.HtmlEncode(InputValue), "")
End Function

_
Public Function ToHTMLParagraphString(ByVal InputValue As String) As String
Return String.Concat("

", HttpUtility.HtmlEncode(InputValue), "

")
End Function

_
Public Function ToHTMLBlockQuoteString(ByVal InputValue As String) As String
Return String.Concat("
", HttpUtility.HtmlEncode(InputValue), "
")
End Function

Notice that I am using HttpUtility.HtmlEncode. This is important because the input may contain invalid HTML tags such as <>.

Once we have added our functions we can then use this in our main project code. Below shows how to write an HTML email using some of the functions above.

Dim msg As New Mail.MailMessage

Dim msgBody As New StringBuilder
Dim smtpClient As New Mail.SmtpClient

smtpClient.Port = 25
smtpClient.Host = "127.0.0.1"

msg.To.Add("someone@somewhere.com")
msg.IsBodyHtml = True
msg.Subject = "Test Email"

With msgBody
.Append("Dear Someone".ToHTMLParagraphString)
.Append("Thank you for showing me this. It was really handy.".ToHTMLParagraphString)
.Append("See you soon !!!".ToHTMLParagraphString)
End With

msg.Body = msgBody.ToString

smtpClient.Send(msg)

So finally, the output for this email is

Dear Someone


Thank you for showing me this. It was really handy.


See you soon !!!



The functions can be improved by adding parameters to it. The following will convert a string to a and parameter to an embeded mailto link.

_
Public Function ToHTMLMailtoString(ByVal InputValue As String, ByVal Subject As String) As String
Return String.Concat("", HttpUtility.HtmlEncode(InputValue), "")
End Function

Use this function in the same way and it will convert your email address (as InputValue) to a HTML mailto anchor. This could save quite a few lines of code.


Conclusion

I have only scratched the surface of extension methods. There is a miryadd of stuff you could do. But some really usful things might also be checking to see if the string you have typed is correctly formatted using a regular expression. For datetimes you could return dbnulls when a date is less than 01/01/1900 etc.








No comments:

Post a Comment

Please enter your comment