Although there is a built-in control for advertisement rotation in ASP.NET, it is capable of showing image ads only. However, in the real life you often have to deal with the ads that require some JavaScript code, for instance, you want to put there AdSense code or want to use Flash banners instead of images. Thus, if you want to rotate complex ads, you have to develop your own control. In this particular tutorial I'll show you how to create a very simple, but rather functional user control that will randomly show an ad from an XML file of the following format:
<Advertisements>
<Ad>
<Html>
<![CDATA[
Some HTML code
]]>
</Html>
</Ad>
<Ad>
<Html>
<![CDATA[
Some other HTML code
]]>
</Html>
</Ad>
</Advertisements>
Well, as you can see, it's very very simple, there is even no NavigateUrl element, but we don't even need, because we can always put a link into the HTML element, besides usually we use something similar to AdSense, so there is no need defining the URL. The control will accept have only one attribute - AdvertisementFile - which points to an XML file with ads. So, to ad a control, you just have to place a similar code:
<uc1:HtmlAdRotator runat="server" AdvertisementFile="~/App_Data/ads.xml" />
Let's start creating it. We should add a new user control to our web site, then put a that will hold the content of advertisements.
<div id="adContent" runat="server"></div>
In the code-behind we define the only attribute the user control has, please note that we use a neat feature of C# 3.0 that simplifies creation of properties. In the Page_Load() method we extract the data from the specified XML file and pick-up a random ad from there. We use LINQ to XML for XML file parsing.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
public partial class HtmlAdRotator : System.Web.UI.UserControl
{
public string AdvertisementFile { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
XDocument xAds = XDocument.Load(Server.MapPath(AdvertisementFile));
var ads = from a in xAds.Descendants("Ad")
select (string)a.Element("Html");
Random rand = new Random();
var ad = ads.ElementAt(rand.Next(ads.Count()));
adContent.InnerHtml = ad;
}
}
So, with ASP.NET you can easily build your own control suits your needs in a few minutes, while LINQ to XML helps you to extract the data in a very elegant way.
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way. My personal thoughts tend to change, hence the articles in this blog might not provide an accurate reflection of my present standpoint.
© Mike Borozdin