Introduction
This is a simple ad rotator class that reads an XML file and returns the details of the ad. Microsoft Ad Rotator control is good, but it is not very flexible to use. I wanted a way to be able to have access to the URL, image, or text of my ad at certain times which Ad Rotator can't do. Also, the MS Ad Rotator stretches the image, which doesn't look really good all the time.
What is required?
The XML file which has the details of the ads, an Image
control, a Label
, and a Hyperlink
control.
Using the Code
namespace RahmanAdRotator
{
public class AdRotator
{
private string url;
private string img;
private string text;
private string xfile;
private int thisAd;
public AdRotator(string xmlFile,int frequency)
{
}
public AdRotator(string xmlFile)
{
xfile=xmlFile;
generateRandom();
readXML();
}
public string getURL()
{
return url;
}
public string getImage()
{
return img;
}
public string getText()
{
return text;
}
private void generateRandom()
{
int ctr = totalRecords();
Random rnd = new Random();
thisAd = rnd.Next(1,ctr+1);
}
private int totalRecords()
{
DataSet ds = new DataSet();
ds.ReadXml(xfile);
int ctr=ds.Tables[0].Rows.Count;
return ctr;
}
private void readXML()
{
DataSet ds = new DataSet();
ds.ReadXml(xfile);
int ctr=1;
foreach(DataRow row in ds.Tables[0].Rows)
{
if (ctr==thisAd)
{
img = row["ImageURL"].ToString();
url = row["NavigateUrl"].ToString();
text = row["AlternateText"].ToString();
break;
}
else
{
ctr = ctr+1;
}
}
}
}
}
Testing the Code
private void Page_Load(object sender, System.EventArgs e)
{
string imgPath = @"c:\inetpub\wwwroot\MobileShop\MobileImages\Nokia\";
AdRotator ad = new AdRotator(@"c:\inetpub\wwwroot\MobileShop\Adverts.xml");
Image1.ImageUrl = imgPath + ad.getImage();
Label1.Text = ad.getText();
}
Improvements
I ignored the frequency of the ad as Microsoft has it in the Ad Rotator control and it can be added. There could be a lot more options that could be added! It is just an example of doing it!