Displaying Advertisements


The AdRotator control enables you to randomly display different advertisements in a page. You can store the list of advertisements in either an XML file or in a database table.

The AdRotator control supports the following properties (this is not a complete list):

  • AdvertisementFileEnables you to specify the path to an XML file that contains a list of banner advertisements.

  • AlternateTextFieldEnables you to specify the name of the field for displaying alternate text for the banner advertisement image. The default value is AlternateText.

  • DataMemberEnables you to bind to a particular data member in the data source.

  • DataSourceEnables you to specify a data source programmatically for the list of banner advertisements.

  • DataSourceIDEnables you to bind to a data source declaratively.

  • ImageUrlFieldEnables you to specify the name of the field for the image URL for the banner advertisement. The default value for this field is ImageUrl.

  • KeywordFilterEnables you to filter advertisements by a single keyword.

  • NavigateUrlFieldEnables you to specify the name of the field for the advertisement link. The default value for this field is NavigateUrl.

  • TargetEnables you to open a new window when a user clicks the banner advertisement.

The AdRotator control also supports the following event:

  • AdCreatedRaised after the AdRotator control selects an advertisement but before the AdRotator control renders the advertisement.

Notice that the AdRotator control includes a KeywordFilter property. You can provide each banner advertisement with a keyword and then filter the advertisements displayed by the AdRotator control by using the value of the KeywordFilter property.

This property can be used in multiple ways. For example, if you are displaying more than one advertisement in the same page, then you can filter the advertisements by page regions. You can use the KeywordFilter to show the big banner advertisement on the top of the page and box ads on the side of the page.

You can also use the KeywordFilter property to filter advertisements by website section. For example, you might want to show different advertisements on your website's home page than on your website's search page.

Note

If you cache a page that contains an AdRotator control, then the AdRotator control is excluded from the cache. In other words, even if you cache a page, randomly selected banner advertisements are still displayed. The AdRotator control takes advantage of a new feature of the ASP.NET 2.0 Framework called post-cache substitution. You learn more about this feature in Chapter 23, "Caching Application Pages and Data."


Storing Advertisements in an XML File

You can store the list of advertisements that the AdRotator displays in an XML file by setting the AdRotator control's AdvertisementFile property. For example, the page in Listing 4.11 contains three AdRotator controls that retrieve banner advertisements from an XML file named AdList.xml (see Figure 4.8).

Listing 4.11. AdRotatorXML.aspx

[View full width]

<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR /xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head  runat="server">     <style type="text/css">         html         {             background-color:silver;         }         .content         {             background-color:white;             padding:10px;             border:solid 1px black;             margin:auto;             width:400px;             text-align:center;         }         .box         {             float:right;             padding:10px;             border-left:solid 1px black;         }         .clear         {             clear:both;         }     </style>     <title>AdRotator XML</title> </head> <body>     <form  runat="server">     <div >     <asp:AdRotator                  AdvertisementFile="~/App_Data/AdList.xml"         KeywordFilter="banner"         Css         Runat="server" />     <br />     <div >         <asp:AdRotator                          AdvertisementFile="~/App_Data/AdList.xml"             KeywordFilter="box"             Runat="server" />         <br /><br />         <asp:AdRotator                          AdvertisementFile="~/App_Data/AdList.xml"             KeywordFilter="box"             Runat="server" />     </div>     <br />Here is the body text in the page.     <br />Here is the body text in the page.     <br />Here is the body text in the page.     <br />Here is the body text in the page.     <br  />     </div>     </form> </body> </html> 

Figure 4.8. Displaying advertisements from an XML file.


The page in Listing 4.11 contains an AdRotator control that displays a banner advertisement at the top of the page. The page also contains two AdRotator controls that display box advertisements on the right of the page.

Notice that the first AdRotator has a KeyworldFilter property that has the value banner, and the remaining two AdRotator controls have KeywordFilter properties with the value box. The first AdRotator displays only banner advertisements, and the remaining two AdRotator controls display only box advertisements.

All three AdRotator controls get their list of banner advertisements from a file named AdList.xml. This file is located in the App_Data folder for security reasons. The files in the App_Data folder cannot be opened in a web browser.

Note

There is nothing wrong with assigning different XML files to different AdRotator controls. For example, you could create distinct BannerAd.xml and BoxAd.xml files and then you would not have to worry about the KeywordFilter property.


The file in Listing 4.12 contains the contents of the AdList.xml file.

Listing 4.12. AdList.xml

<?xml version="1.0" encoding="utf-8" ?> <Advertisements>   <!-- Banner Advertisements -->   <Ad>     <ImageUrl>~/Ads/BannerAd1.gif</ImageUrl>     <Width>300</Width>     <Height>50</Height>     <NavigateUrl>http://www.AspWorkshops.com</NavigateUrl>     <AlternateText>Banner Advertisement 1</AlternateText>     <Impressions>50</Impressions>     <Keyword>banner</Keyword>   </Ad>   <Ad>     <ImageUrl>~/Ads/BannerAd2.gif</ImageUrl>     <Width>300</Width>     <Height>50</Height>     <NavigateUrl>http://www.AspWorkshops.com</NavigateUrl>     <AlternateText>Banner Advertisement 2</AlternateText>     <Impressions>25</Impressions>     <Keyword>banner</Keyword>   </Ad>   <Ad>     <ImageUrl>~/Ads/BannerAd3.gif</ImageUrl>     <Width>300</Width>     <Height>50</Height>     <NavigateUrl>http://www.AspWorkshops.com</NavigateUrl>     <AlternateText>Banner Advertisement 3</AlternateText>     <Impressions>25</Impressions>     <Keyword>banner</Keyword>   </Ad>   <!-- Box Advertisements -->   <Ad>     <ImageUrl>~/Ads/BoxAd1.gif</ImageUrl>     <Width>150</Width>     <Height>150</Height>     <NavigateUrl>http://www.AspWorkshops.com</NavigateUrl>     <AlternateText>Box Advertisement 1</AlternateText>     <Impressions>50</Impressions>     <Keyword>box</Keyword>   </Ad>   <Ad>     <ImageUrl>~/Ads/BoxAd2.gif</ImageUrl>     <Width>150</Width>     <Height>150</Height>     <NavigateUrl>http://www.AspWorkshops.com</NavigateUrl>     <AlternateText>Box Advertisement 2</AlternateText>     <Impressions>50</Impressions>     <Keyword>box</Keyword>   </Ad>  </Advertisements> 

The Impressions attribute in the file in Listing 4.12 determines how often each banner advertisement is displayed. For example, the first banner advertisement is displayed 50% of the time, and the remaining two banner advertisements are displayed 25% of the time.

Storing Advertisements in a Database Table

Rather than store the list of advertisements in an XML file, you can store the list in a database table. For example, the AdRotator control contained in Listing 4.13 is bound to a SqlDataSource control. The SqlDataSource control represents the contents of a database table named AdList, which is located in a SQL Express database named AdListDB.

Listing 4.13. AdRotatorDatabase.aspx

[View full width]

<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR /xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head  runat="server">     <title>AdRotator Database</title> </head> <body>     <form  runat="server">     <div>     <asp:AdRotator                  DataSource         Runat="server" />     <asp:SqlDataSource                  ConnectionString="Server=.\SQLExpress;Integrated Security=True;             AttachDbFileName=|DataDirectory|AdListDB.mdf;User Instance=True"         SelectCommand="SELECT ImageUrl, Width, Height, NavigateUrl, AlternateText, Keyword , Impressions             FROM AdList"         Runat="server" />     </div>     </form> </body> </html> 

To use the page in Listing 4.13, you need to create the AdList database table. This table has the following schema:

Column Name

Data Type

Id

Int (IDENTITY)

ImageUrl

Varchar(250)

Width

Int

Height

Int

NavigateUrl

Varchar(250)

AlternateText

NVarchar(100)

Keyword

NVarchar(50)

Impressions

Int


Notice that the columns in the AdList database table correspond to the attributes in the AdList.xml file discussed in the previous section.

Tracking Impressions and Transfers

Normally, when you are displaying advertisements, you are doing it to make money. Your advertisers will want statistics on how often their advertisements were displayed (the number of impressions) and how often their advertisements were clicked (the number of transfers).

To track the number of times that an advertisement is displayed, you need to handle the AdRotator control's AdCreated event. To track the number of times that an advertisement is clicked, you need to create a redirect handler.

Warning

If you create an event handler for the AdCreated event and you cache the page, the content rendered by the AdRotator control will also be cached. When handling the AdCreated event, use partial page caching to cache only part of a page and not the AdRotator control itself.


The page in Listing 4.14 displays a banner advertisement with the AdRotator control. The page includes an event handler for the AdRotator control's AdCreated event.

Listing 4.14. AdRotatorTrack.aspx

[View full width]

<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR /xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server">     Sub AdRotator1_AdCreated(ByVal sender As Object, ByVal e As AdCreatedEventArgs)         ' Update Impressions         srcAds.InsertParameters("AdId").DefaultValue = e.AdProperties("Id").ToString()         srcAds.Insert()         ' Change NavigateUrl to redirect page         e.NavigateUrl = "~/AdHandler.ashx?Id").ToString()     End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head  runat="server">     <title>AdRotator Track</title> </head> <body>     <form  runat="server">     <div>     <asp:AdRotator                  DataSource         OnAdCreated="AdRotator1_AdCreated"         Runat="server" />     <asp:SqlDataSource                  ConnectionString="Server=.\SQLExpress;Integrated Security=True;             AttachDbFileName=|DataDirectory|AdListDB.mdf;User Instance=True"         SelectCommand="SELECT Id, ImageUrl, Width, Height, NavigateUrl, AlternateText,  Keyword, Impressions             FROM AdList"         InsertCommand="INSERT AdStats (AdId, EntryDate, Type) VALUES (@AdId, GetDate(), 0)"         Runat="server">         <InsertParameters>         <asp:Parameter Name="AdId" Type="int32" />         </InsertParameters>      </asp:SqlDataSource>     </div>     </form> </body> </html> 

The AdCreated event handler does two things. First, it inserts a new record into a database table named AdStats, which records an advertisement impression. Second, the handler modifies the NavigateUrl so that the user is redirected to a handler named AdHandler.ashx.

The AdStats database table looks like this:

Column Name

Data Type

Id

Int (IDENTITY)

AdId

Int

EntryDate

DateTime

Type

Int


The Type column is used to record the type of entry. The value 0 represents an advertisement impression, and the value 1 represents an advertisement transfer.

When you click an advertisement, you link to a file named AdHandler.ashx. This file is contained in Listing 4.15.

Listing 4.15. AdHandler.ashx

[View full width]

<%@ WebHandler Language="VB"  %> Imports System Imports System.Web Imports System.Data imports System.Data.SqlClient Public Class AdHandler     Implements IHttpHandler     Const conString As String = "Server=.\SQLExpress;Integrated  Security=True;AttachDbFileName=|DataDirectory|AdListDB.mdf;User Instance=True"     Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest         Dim AdId As Integer = Int32.Parse(context.Request("Id"))         Dim con As New SqlConnection(conString)         Dim navigateUrl As String = String.Empty         Using con             con.Open()             UpdateTransferStats(AdId, con)             navigateUrl = GetNavigateUrl(AdId, con)         End Using         If Not String.IsNullOrEmpty(navigateUrl) Then             context.Response.Redirect(navigateUrl)         End If     End Sub     Sub UpdateTransferStats(ByVal advertisementId As Integer, ByVal con As SqlConnection)         Dim cmdText As String = "INSERT AdStats (AdId, EntryDate, Type) VALUES "& _             "(@AdId, GetDate(), 1)"         Dim cmd As New SqlCommand(cmdText, con)         cmd.Parameters.AddWithValue("@AdId", advertisementId)         cmd.ExecuteNonQuery()     End Sub     Function GetNavigateUrl(ByVal advertisementId As Integer, ByVal con As SqlConnection)  As String         Dim cmdText As String = "SELECT NavigateUrl FROM AdList WHERE Id=@AdId"         Dim cmd As New SqlCommand(cmdText, con)         cmd.Parameters.AddWithValue("@AdId", advertisementId)         Return cmd.ExecuteScalar().ToString()     End Function     Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable         Get             Return False         End Get     End Property  End Class 

The handler in Listing 4.15 performs two tasks. First, it inserts a new record into the AdStats database table, recording the fact that a transfer is taking place. Next, it grabs the NavigateUrl from the AdList database table and sends the user to the advertiser's website.

The final page displays advertiser statistics from the AdStats database table (see Figure 4.9). This page is contained in Listing 4.16.

Figure 4.9. Displaying advertiser statistics.


Listing 4.16. AdRotatorStats.aspx

[View full width]

<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR /xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head  runat="server">     <style type="text/css">         .grid td,.grid th         {             border-bottom:solid 1px black;             padding:5px;         }     </style>     <title>AdRotator Statistics</title> </head> <body>     <form  runat="server">     <div>     <h1>Advertisement Statistics</h1>     Impressions represent the number of times an advertisement has been viewed.     Transfers represent the number of times an advertisement has been clicked.     <h2>Impressions</h2>     <asp:GridView                  DataSource         AutoGenerateColumns="false"         GridLines="None"         Css         Runat="server">         <Columns>         <asp:BoundField             DataField="AdId"             HeaderText="Advertisement Id" />         <asp:BoundField             DataField="Impressions"             HeaderText="Impressions" />         </Columns>     </asp:GridView>     <asp:SqlDataSource                  ConnectionString="Server=.\SQLExpress;Integrated Security=True;             AttachDbFileName=|DataDirectory|AdListDB.mdf;User Instance=True"         SelectCommand="SELECT AdId,Count(*) As Impressions             FROM AdStats             WHERE Type=0             GROUP BY AdId             ORDER BY Impressions DESC"         Runat="server" />     <h2>Transfers</h2>     <asp:GridView                  DataSource         AutoGenerateColumns="false"         GridLines="None"         Css         Runat="server">         <Columns>         <asp:BoundField             DataField="AdId"             HeaderText="Advertisement Id" />         <asp:BoundField             DataField="Transfers"             HeaderText="Transfers" />         </Columns>     </asp:GridView>     <asp:SqlDataSource                  ConnectionString="Server=.\SQLExpress;Integrated Security=True;             AttachDbFileName=|DataDirectory|AdListDB.mdf;User Instance=True"         SelectCommand="SELECT AdId,Count(*) As Transfers             FROM AdStats             WHERE Type=1             GROUP BY AdId             ORDER BY Transfers DESC"         Runat="server" />     </div>     </form> </body> </html> 

The page in Listing 4.16 contains two GridView controls bound to two SqlDataSource controls. The first GridView displays statistics on impressions, and the second GridView displays statistics on transfers.




ASP. NET 2.0 Unleashed
ASP.NET 2.0 Unleashed
ISBN: 0672328232
EAN: 2147483647
Year: 2006
Pages: 276

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net