Geeks With Blogs

News

Locations of visitors to this page

View ► Sanjay Uttam [sanjay.uttam@gmail.com]'s profile on LinkedIn


Add to Google Reader or Homepage




Sanjay Uttam Predominantly .NET

I was recently combing through my code and adding HTMLEncode()s where necessary.  By the way, don't leave this to the end - you have no excuse since you're reading this post. 

The first thought that comes to mind to add this is simple, add a central function, perhaps a shared (vb) or static (c#) function to handle this.  It'd likely look something like:

Public Function HTMLEncode(ByVal s As String) As String
 Return If(Not String.IsNullOrEmpty(s), System.Web.HttpUtility.HtmlEncode(s), s) 
End Function 

Alright, that’s not terrible – so I have to go into each web form and modify. That means I will have web form code that looks like this: (Below is within a repeater)

<%# ApplicationUtils.HTMLEncode(Eval("Association"))%> 

I guess life could be worse. That does the job, but it’s a lot to type, and it could be a bit more elegant. An easier way to do this is is by leveraging a new .NET 3.0 (VB & C#) language feature (actually to be clear it’s really a smart compiler, but hey, whatever). This feature is method extensions. Basically, you can create a method to execute on your type just like .ToString(). In my case, I added the following code…

Public Module StringExtensions 
<system.runtime.compilerservices.extension()> _
Public Function HTMLEncode(ByVal s As String) As String
            Return If(Not String.IsNullOrEmpty(s), System.Web.HttpUtility.HtmlEncode(s), s)        
End Function    
End Module

That means instead of the code above, I can just do this…

<%# Eval("Association").ToString().HTMLEncode()%> 

That’s it. This is a pretty trivial example but there are probably tons of instances where this would be handy. In my case, I liked it for the sheer lack of typing (Less typing less errors!) and the fact that I think it’s much more intuitive for someone to look at

SomeVariable.ToString().HTMLEncode()

...rather than

ApplicationUtils.HTMLEncode(whatever). 

Of course, either way you’re going to want to wrap the HttpUtility.HTMLEncode() .NET provided logic in some function, so you have a single point of control for your code/logic.

Here is the MSDN link on extension methods in C#...the syntax is slightly different between VB.NET and C#

Posted on Saturday, November 1, 2008 3:46 PM C# , VB.NET , Visual Studio 2008 , .NET 3.0 | Back to top

Copyright © Sanjay Uttam | Powered by: GeeksWithBlogs.net