Friday, March 6, 2009

Pull the html from a different page

I will demo a small interesting feature of ASP.NET which is unknown to many people. One of the hardest things in asp.net is to build a html strings in order to send a mail. Hardest - in the sense I mean to construct a good html. However a lot of developers will try to construct all the html by making use of StringBuilder objects. Sadly many people I saw were using the strings which leave the Garbage Collector to have work more.

Well. What if you have want to format your email text is a really good manner. Or what if you want to mail the page that is already existing. However you need to get all the html from a different page. A browser can get the html generated by your ASP.NET application and IIS. While a browser can get the html why cannot your application get the html of a page. Yes, you can get the html page of your aspx page.



This feature is provided in ASP.NET by the System.Net namespace. You can create an instance of the WebClient class.



using System.Net;

.....

.....

//The parameter url is to be the full url of your web page. It cannot be physical path. For eg., Http://www.google.com/test.aspx instead of ~/test.aspx

public string getTheHtmlOutput(string url)

{

string myHtmlOutput=string.Empty;

WebClient HtmlClient=new WebClient();



//Executes the page(url) that is passed and retrieves the html in the byte array.

byte[] outputBytes=HtmlClient.DownloadData(url);

myHtmlOutput=Encoding.Default.GetString(outputBytes);

return myHtmlOutput;

}



This method will return the html of some other page in your application. However, there are even some issue behind this such as execution time. And what if there is an error in the different page. Should the error will be mailed if you are using the page for mailing purposes. However, the raising errors in this way is very rare case.

No comments:

Post a Comment