June 11, 2008

Safer Email Address-2

In our previous article Safer Email Addresses we discussed how encoded email addresses are good against the email capture programs. Here we will see how to achieve this in ASP.NET.
Create a class called BasePage and inherit the System.Web.UI.Page and then inherit all your webpages from this BasePage.
Put following code in your BasePage.

protected override void Render(HtmlTextWriter writer)
{
StringWriter stringWriter
= new StringWriter();
HtmlTextWriter interceptedHtmlWriter
= new HtmlTextWriter(stringWriter, " ");
base.Render(interceptedHtmlWriter);
string interceptedHtml = stringWriter.ToString();
interceptedHtml
= ReplaceEmailAddresses(interceptedHtml);
writer.Write(interceptedHtml);
}
private string ReplaceEmailAddresses(string content) {
Regex emailMatcher
= new Regex("([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}");
MatchCollection matchesFound
= emailMatcher.Matches(content);
foreach (Match m in matchesFound) {
content
= Regex.Replace(content, m.Value, EncodeEmail(m.Value));
}
return content;
}

private string EncodeEmail(string p)
{
string encoded = string.Empty;
foreach (char c in p) {
encoded
+= "&#" + Convert.ToInt32(c).ToString()+";";
}
return encoded;
}

Hope this helps....

Submit this story to DotNetKicks

2 comments:

Anonymous said...

Bhai, Kai lakho navu have... Waiting for your new article.....

Jalpesh Vadgama said...

Hi paresh,

This is jalpesh remember we have studied together in MCA at saurashtra university. It's good to hear from you.

Check out my blog at
http://jalpesh.blogspot.com