Microsoft广告轮播的替代方案






2.60/5 (3投票s)
一个从 XML 文件返回广告详情的类。
引言
这是一个简单的广告轮播类,它读取 XML 文件并返回广告的详细信息。 Microsoft Ad Rotator 控件很好,但使用起来不够灵活。 我希望能够在特定时间访问广告的 URL、图像或文本,而 Ad Rotator 无法做到这一点。 此外,MS Ad Rotator 会拉伸图像,这有时看起来不太好。
需要什么?
包含广告详情的 XML 文件,一个 Image
控件,一个 Label
,以及一个 Hyperlink
控件。
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)
{
}
//construction that gets the xml file from the user
public AdRotator(string xmlFile)
{
xfile=xmlFile;
generateRandom();
readXML();
}
public string getURL()
{
return url;
}
public string getImage()
{
return img;
}
public string getText()
{
return text;
}
//this sub generate a random no as the random Ad
private void generateRandom()
{
int ctr = totalRecords();
Random rnd = new Random();
thisAd = rnd.Next(1,ctr+1);
}
//this sub counts total number of records from the xml file.
private int totalRecords()
{
DataSet ds = new DataSet();
ds.ReadXml(xfile);
int ctr=ds.Tables[0].Rows.Count;
return ctr;
}
//this sub reads the xml file and loops through the records
//and matchs the random no with the record. If matched then return it.
private void readXML()
{
DataSet ds = new DataSet();
ds.ReadXml(xfile);
int ctr=1;
//These Column names are standard Microsoft column
//names for ad rotator control eg ImageURL
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;
}
}
}
}
}
测试代码
private void Page_Load(object sender, System.EventArgs e)
{
//Set your own path!
string imgPath = @"c:\inetpub\wwwroot\MobileShop\MobileImages\Nokia\";
//Create an instance of the Adrotator and pass the path of the xml file
AdRotator ad = new AdRotator(@"c:\inetpub\wwwroot\MobileShop\Adverts.xml");
//use the methods to get the details of the add
Image1.ImageUrl = imgPath + ad.getImage();
Label1.Text = ad.getText();
}
改进
我忽略了广告的频率,就像 Microsoft 在 Ad Rotator 控件中所做的那样,可以添加它。 还可以添加更多选项! 这只是一个示例!