Using Substitution Control to Display Ads
I was reworking the ads on GridViewGuy when I noticed that I am caching the whole page which is also caching the ads. This means you will see the same ads during the duration of the cached page. The ads are part of the user control but now we need some mechanism that the ads are not cached but the whole page does. Luckly, ASP.NET 2.0 includes the Substitution Control which allows the portions of the page to be not cached.
First add the Substitution control on the page.
<asp:Substitution ID="Substitution1" runat="server" MethodName="GetAds" />
Next, create the method GetAds which have to be static method.
private static Page myPage = new Page();
protected static string GetAds(HttpContext context)
{
// The ads script is being cached since the script will remain the same and ads are selected based on the content
// of the page
// Offcourse this varies from website to website
if (context.Cache["Ads"] == null)
{
Control ads = myPage.LoadControl("~/MyAds.ascx");
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
ads.RenderControl(htw);
context.Cache.Insert("Ads", sw.ToString());
}
// return the ads script
return context.Cache["Ads"] as String;
}
The idea is to load the user control which contains the actual ad and use the HtmlTextWriter to convert the user control into pure html which can later be rendered on the page. If you notice I am also caching the html generated by the HtmlTextWriter. This is because the script used to generate the ad will always remain the same. Using, this way the page will be cached but the ads will not be cached and hence the user will see a different ad depending on the content of their website.