Using Response.Filter in ASP.NET
http://www.webtropy.com/projects/textonly/
I was once asked if it were possible to easily create "Text only" versions of websites, so that they wouldn’t cost a fortune to look at when using a smart phone or PDA – which can cost 2 euros per megabyte, or more. I had forgotten about it for a while until I picked up the september 2004 edition of MSDN, which was sitting under my coffee table, and came across an article about Response.Filter, and it’s application for custom ASP.NET traces.
I developed this in VS.NET 2005 / .NET 2.0, but the code is the same for previous versions.
I activate the filter from a button click thus:
void Button1_Click(object sender, EventArgs e)
{
Response.Filter = new TextOnlySteam(Response.Filter);
}
And now, I define my custom stream, TextOnlyStream
public class TextOnlySteam : MemoryStream
{
private Stream strmOutput;
/// <summary>
/// Constructor, initializes the output stream
/// </summary>
public TextOnlySteam(Stream strmConstructor)
{
strmOutput = strmConstructor;
}
/// <summary>
/// Replaces occurrances of src="whatever.jpg" with src=""
/// </summary>
public override void Write(byte[] buffer, int offset, int count)
{
Encoding enc = HttpContext.Current.Response.ContentEncoding;
string strHtml = enc.GetString(buffer, offset, count);
strHtml = Regex.Replace(strHtml, "src=\"\w.*\"", "src=""",
RegexOptions.IgnoreCase);
byte[] bHtml = enc.GetBytes(strHtml);
strmOutput.Write(bHtml, 0, strHtml.Length);
}
}
The code should be improved to support other types of image inclusion such as table background and the CSS background url tag. Also, HTML does not dictate that inverted commas need to delimit tag parameters, apostrophes, or spaces can suffice. For this I would expect that I would use the HTML Agility pack to normalize the HTML to XML before parsing.
Oh, and I also set live two new sites www.listOfTaxis.info and www.listOfBanks.info (the DNS mightn’t propogate until monday morning)