Mike Borozdin's Blog

A blog about programming, web and IT in general

Creating a Simple Ad Rotation User Control with LINQ to XML

Download files

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 <div> 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.

Download files


Tags: ,
Posted by Mike Borozdin on Saturday, August 30, 2008 2:43 PM GMT
  Shout it Kick it!  
Permalink | Comments (3) | Post RSSRSS comment feed

Comments

DotNetKicks.com

Saturday, August 30, 2008 7:45 AM GMT

trackback

Trackback from DotNetKicks.com

Creating a Simple Ad Rotation User Control with LINQ to XML

tratata Russia

Tuesday, September 30, 2008 11:14 PM GMT

tratata

помоему есть аналогичный контрол в библиотеке контролов асп.нет )
<asp:AdRotator id=myAdRotator runat=server AdvertisementFile="MyAds.xml" BorderWidth=2 />
зачем изобретать велосипед?

Mike Borozdin Russia

Wednesday, October 01, 2008 1:08 AM GMT

Mike Borozdin

tratata asks why I re-invent the wheel by writing my own ad rotating control. As I have already mentioned in the article, I'm doing this because the standard ASP.NET control can only show image ads, it cannot show AdSense ads, for example.

tratata,

Потому что, стандартный контрол может отображать только картинки, HTML код туда не запихнешь, тот же AdSense не поставишь. Я это написал в начале статьи.

Comments are closed