Compartir a través de


Walkthrough: Displaying and Tracking Advertisements with the AdRotator Control

Web sites frequently display advertisements or similar dynamic content that invites users to visit another site. ASP.NET provides the AdRotator control, which simplifies this task. The AdRotator control displays a graphic representing an ad, randomly selecting the ad from a list that you create. You can then track how frequently an ad is viewed and how frequently users click it.

This walkthrough illustrates how to use the AdRotator control to display ads and provides a simple way to track ad responses. Tasks illustrated in this walkthrough include the following:

  • Creating a list of ads to display.

  • Displaying ads on a page.

  • Creating a way to track the number of times an ad is clicked.

  • Displaying statistics about ad clicks.

Prerequisites

In order to complete this walkthrough, you will need the following:

Creating the Web Site

If you have already created a Web site in Visual Web Developer by completing Walkthrough: Creating a Basic Web Page in Visual Web Developer, you can use that Web site and go to the next section. Otherwise, create a new Web site and page by following these steps.

To create a file system Web site

  1. Open Visual Web Developer.

  2. On the File menu, click New Web Site.

    The New Web Site dialog box appears.

  3. Under Visual Studio installed templates, click ASP.NET Web Site.

  4. In the Location box, click File System, and then type the name of the folder where you want to keep the pages of the Web site.

    For example, type the folder name C:\WebSite.

  5. In the Languages list, click the programming language that you prefer to work in.

    The programming language that you choose will be the default for your Web site, but you can set the programming language for each page individually.

  6. Click OK.

    Visual Studio creates the folder and a new page named Default.aspx.

Creating Advertisements

Ads are graphics that are displayed on the page with a target URL; when users click the graphic, they are redirected to the target site. Therefore, you need graphics files to serve as advertisements.

Note

Later sections of this walkthrough assume that are you using graphics that are named according to the following procedure. If you use existing graphics, make sure that you substitute the appropriate file names later in the walkthrough.

Start by creating a folder in the Web site to store graphics.

To create an Images folder

  1. In Solution Explorer, right-click the name of the Web site, click New Folder, and then name the folder Images.

  2. If you have existing graphics to use as ads, copy them to the new folder. Otherwise, follow the next procedure to create some images.

If you already have some graphics that you can use to represent ads, you can use those. Otherwise, the following procedure suggests one way that you can create graphics that are suited for this walkthrough.

To create graphics to serve as ads

  1. In Microsoft Windows, open Paint.

  2. On the Image menu, click Attributes.

  3. In the Attributes dialog box, set Width to 250 and Height to 50, and then click OK.

  4. From the Toolbox, drag the text tool onto the graphic, and then type some text that will help you identify the ad

  5. In the <Websitename>\Images folder, save the graphic as <Websitename>\Images\Contoso_ad.gif.

  6. Create a second graphic, and then save it as <Websitename>\Images\ASPNET_ad.gif.

  7. Close Paint.

Creating a List of Ads

As soon as you have graphics for the ads, you must create a list of ads that the AdRotator control can read. The list is in the form of an XML file.

To create an XML file of ads

  1. In Solution Explorer, right-click App_Data, and then click Add New Item.

    Note

    When you put the XML file into the App_Data folder, the file automatically has the correct permissions to allow ASP.NET to read the file at run time. Putting the XML file in the App_Data folder helps to protect the file from being viewed in a browser, because the App_Data folder is marked as nonbrowsable.

  2. Under Visual Studio installed templates, click XML File.

  3. In the Name box, type Sample.ads.

    Note

    Use the .ads extension.

  4. Click Add.

    A new XML file is created that contains only the XML directive.

  5. Copy the following XML into the file, overwriting the XML directive.

    <?xml version="1.0" encoding="utf-8" ?>
    <Advertisements>
      <Ad>
        <ImageUrl>~/images/Contoso_ad.gif</ImageUrl>
        <NavigateUrl>https://www.contoso.com</NavigateUrl>
        <AlternateText>Ad for Contoso.com</AlternateText>
      </Ad>
      <Ad>
        <ImageUrl>~/images/ASPNET_ad.gif</ImageUrl>
        <NavigateUrl>https://www.asp.net</NavigateUrl>
        <AlternateText>Ad for ASP.NET Web site</AlternateText>
      </Ad>
    </Advertisements>
    

    Note

    If your graphics files have different file names, change the names in the <ImageUrl> elements accordingly.

    This XML file contains <Ad> elements for two advertisements corresponding to the two graphics files that you have created. In a real application, the URLs in the <NavigateUrl> elements would refer to the advertisers' Web sites.

    Note

    Additional elements are available for defining ads. For detailed information, see AdvertisementFile.

  6. Save the file, and then close it.

Displaying Ads on the Page

You will now configure a Web page to display the ads that you have created. In the following procedure, you will bind an AdRotator control to an XmlDataSource control. However, when using a static XML file, a data source control is not required, because the XML file can be set directly with the AdvertisementFile property of the AdRotator control.

To display ads on the page

  1. If you created a new Web site for this walkthrough, open the Default.aspx page.

  2. If you are using a Web site that existed before you started this walkthrough, add a new page by following these steps:

    1. In Solution Explorer, right-click the name of the Web site (for example, C:\WebSites), and then click Add New Item.

    2. Under Visual Studio installed templates, click Web Form.

    3. In the Name box, type TestAds.aspx.

    4. Click Add.

  3. Open TestAds.aspx and switch to Design view.

  4. From the Standard group in the Toolbox, drag an AdRotator control onto the page.

    The AdRotator Tasks shortcut menu appears.

  5. In the Choose Data Source list, click New data source.

    The Data Source Configuration wizard appears.

  6. Under Where will the application get data from, click XML File.

  7. In the Specify an ID for the data source box, leave the default, (XmlDataSource1).

  8. Click OK.

    The Configure Data Source dialog box appears.

  9. In the Data file box, enter ~/App_Data/Sample.ads, and then click OK.

    Alternatively, you can use Browse to locate the file:

    1. In the Select XML File dialog box, in the Files of type list, click All Files (*.*).

    2. Under Project Folders, click App_Data.

    3. Under Contents of Folder, click Sample.ads, click OK, and then click OK.

  10. From the Standard group in the Toolbox, drag a Button control onto the page.

    Note

    The exact layout of the page is not important.

    The Button control is on the page only so that you have a convenient way to post back the page to the server.

Now you will test the ads.

To test the ads

  1. Press CTRL+F5 to run the page.

    One of the two ads appears on the page.

  2. Click Button several times to cause the page to post back.

    The ad that appears randomly varies.

    Note

    Because there are only two ads, you might have to click Button several times before you see a different ad.

  3. Click an ad.

    You are redirected to the target page for that ad.

  4. Close the browser.

Tracking Ad Responses

At this point, your page just displays ads that users can click to jump to another page. In this part of the walkthrough, you will add functionality to keep track of how many times users click the ads. You will change the URL of the ads in the Sample.ads file to send the ad response to a redirection page, with information in the query string that identifies the ad and the ultimate destination.

You will then create a second XML file to store ad counter information. In a production Web site, you should not use an XML file to track ad clicks, because the XML file would not support much traffic. However, for purposes of this walkthrough, you will use an XML file for convenience, so that you do not have to configure database access. Additionally, in a production application, you would probably want more sophisticated click tracking, such as making sure that you are tracking unique visitors, tracking time and date information about clicks, and so on. Nevertheless, the overall strategy of using a redirection page to process clicks is the same regardless of how you choose to track the data.

Finally, you will create the redirection page, where you will accumulate counters for different ads, and then redirect again to the target page that the ad is intended to display.

To redirect ads to a tracking page

  1. Open the Sample.ads file.

  2. Set NavigateUrl to include the following:

    • The name of your redirection page (AdRedirector.aspx).

    • An identifier for each ad.

    • The page to which the ad ultimately points.

    The following code listing shows the Sample.ads XML file updated with URLs that specify the AdRedirector.aspx page. The ad identifier and target page are specified as a query string.

    Note

    Because the ampersand (&) is a reserved character in XML, the query string includes the entity reference &amp; instead.

    <?xml version="1.0" encoding="utf-8" ?>
    <Advertisements>
      <Ad>
        <ImageUrl>~/images/Contoso_ad.gif</ImageUrl>
        <NavigateUrl>AdRedirector.aspx?ad=Widgets&amp;target=https://www.contoso.com/widgets/</NavigateUrl>
        <AlternateText>Ad for Contoso.com</AlternateText>
      </Ad>
      <Ad>
        <ImageUrl>~/images/ASPNET_ad.gif</ImageUrl>
        <NavigateUrl>AdRedirector.aspx?ad=ASPNET&amp;target=https://www.asp.net</NavigateUrl>
        <AlternateText>Ad for ASP.NET Web site</AlternateText>
      </Ad>
    </Advertisements>
    
  3. Save the Sample.ads file, and then close it.

The next step is to create the XML file where you store counter information for the ad clicks. In a production Web site, you would not need this step, because you would write information to a database instead. Using an XML file in this walkthrough simplifies the steps that are required to track ad responses.

To create the XML file for tracking ad response

  1. In Solution Explorer, right-click the App_Data folder, and then click Add New Item.

  2. Under Templates, click XML File.

  3. In the Name box, type AdResponses.xml, and then click Add.

    A new XML file is created that contains only the XML directive.

  4. Copy the following XML into the file, overwriting the XML directive.

    <?xml version="1.0" standalone="yes"?>
    <adResponses>
      <ad adname="Widgets" hitCount="0" />
      <ad adname="ASPNET" hitCount="0" />
    </adResponses>
    

    The file contains elements that have two pieces of information, the ID of an ad and a counter.

    Note

    If you assigned different IDs to the ads in the Sample.ads file in the previous procedure when you created the query strings, make sure that the IDs in the AdResponses.xml file match those.

  5. Save the file, and then close it.

    Note

    Whether ASP.NET has Write permission for the XML file depends on which Web server you use. In this walkthrough, you will use the ASP.NET Development Server, which is included with Visual Web Developer and has write access to the XML file. If you were using Microsoft Internet Information Services (IIS), the IIS Web server worker process may not have write access to the XML file and you would have to explicitly set the Write permission. For more information on Web servers in Visual Web Developer, see Web Servers in Visual Web Developer.

Now you will create the redirection page, which captures information about the ad that was clicked, updates the counter for the ad, and then sends the request on to the page that is associated with the ad.

To create a Page_Load handler

  1. In Solution Explorer, right-click the name of the Web site (for example, C:\WebSites), and then click Add New Item.

  2. Under Visual Studio installed templates, click Web Form.

  3. In the Name box, type AdRedirector.aspx, and then click Add.

    This creates the page to which all ads will be directed when users click them. The page will not be displayed to users. Therefore, you will not put any controls on it.

  4. In Design view, double-click the page to create a Page_Load handler.

  5. Copy the following code into the handler (do not overwrite the skeleton handler declaration).

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
        Dim adName As String = Request.QueryString("ad")
        Dim redirect As String = Request.QueryString("target")
        If (adName Is Nothing Or redirect Is Nothing) Then
            redirect = "TestAds.aspx"
        End If
    
        Dim doc As System.Xml.XmlDocument
        Dim docPath As String = "~/App_Data/AdResponses.xml"
    
        doc = New System.Xml.XmlDocument()
        doc.Load(Server.MapPath(docPath))
        Dim root As System.Xml.XmlNode = doc.DocumentElement
        Dim xpathExpr As String
        xpathExpr = "descendant::ad[@adname='" & adName & "']"
        Dim adNode As System.Xml.XmlNode = _
            root.SelectSingleNode(xpathExpr)
        If adNode IsNot Nothing Then
            Dim ctr As Integer = _
                CInt(adNode.Attributes("hitCount").Value)
            ctr += 1
            Dim newAdNode As System.Xml.XmlNode = _
                adNode.CloneNode(False)
            newAdNode.Attributes("hitCount").Value = ctr.ToString()
            root.ReplaceChild(newAdNode, adNode)
            doc.Save(Server.MapPath(docPath))
        End If
        Response.Redirect(redirect)
    
    End Sub
    
    protected void Page_Load(object sender, EventArgs e)
    {
        String adName = Request.QueryString["ad"];
        String redirect = Request.QueryString["target"];
        if (adName == null | redirect == null)
            redirect = "TestAds.aspx";
    
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        String docPath = @"~/App_Data/AdResponses.xml";
        doc.Load(Server.MapPath(docPath));
        System.Xml.XmlNode root = doc.DocumentElement;
        System.Xml.XmlNode adNode =
            root.SelectSingleNode(
            @"descendant::ad[@adname='" + adName + "']");
        if (adNode != null)
        {
            int ctr =
                int.Parse(adNode.Attributes["hitCount"].Value);
            ctr += 1;
            System.Xml.XmlNode newAdNode = adNode.CloneNode(false);
            newAdNode.Attributes["hitCount"].Value = ctr.ToString();
            root.ReplaceChild(newAdNode, adNode);
            doc.Save(Server.MapPath(docPath));
        }
        Response.Redirect(redirect);
    }
    

    The code reads the ad ID and URL from the query string. It then uses XML methods to read the AdResponse.xml file into an XmlDocument object. The code locates the appropriate XML element using an XPath expression, extracts the hitCounter value, and then updates the hitCounter value. Next, the code creates a copy of the XML element by cloning, replaces the old element with the new one, and then writes the updated XML document back to disk. Finally, the code redirects to the URL for the ad.

You will now test to confirm that the ad counters for the ads are working.

To test ad response tracking

  1. Open the page that contains the AdRotator control, and then press CTRL+F5.

  2. Click the ad.

    You are redirected to the target page for that ad.

  3. In the browser, click Back to return to the ad page.

  4. Either click the ad again or click Button to display a different ad, and then click the ad.

  5. Continue until you have clicked each ad at least one time, and one or more ads more than one time.

  6. Close the browser.

  7. In Visual Web Developer, open the AdResponse.xml file and verify that the counters for the ads reflect the number of clicks from your test.

  8. Close the AdResponse.xml file.

Displaying Ad Counter Data

For the final part of the walkthrough, you will create a page that displays the ad counter information, which is more convenient than manually examining the XML file.

To create a page to display the ad response data

  1. In Solution Explorer, right-click the name of the Web site, and then click Add New Item.

  2. Under Visual Studio installed templates, click Web Form.

  3. In the Name box, type ViewAdData.aspx.

  4. Click Add.

  5. Switch to Design view.

  6. From the Data group in the Toolbox,, drag an XmlDataSource control onto the page.

  7. On the XmlDataSource Tasks shortcut menu, click Configure Data Source.

    The Configure Data Source <Datasourcename> dialog boxappears.

  8. In the Data file box, type ~/App_Data/AdResponses.xml.

    Alternatively, you can use Browse to locate the file.

  9. Click OK.

  10. From the Data group in the Toolbox, drag a GridView control onto the page.

  11. On the GridView Tasks shortcut menu, in the Choose Data Source list, click XmlDataSource1.

  12. Press CTRL+F5 to run the page.

    The page displays the ad response data in a grid.

  13. Close the browser.

Next Steps

There are more features available in the AdRotator control than have been illustrated in this walkthrough. You might want to explore these features in the following ways:

  • Use additional attributes when you create ads in the XML file.

    For example, you can use the Impressions element to control how often an advertisement is selected relative to the other advertisements in the advertisement file. The higher the value, the more likely the ad will be selected. For detailed information, see AdvertisementFile.

  • Use a database to track ad responses.

    Note

    In a production application, do not use an XML file to track ad responses, because it will not scale to support many users. This walkthrough uses an XML file for ad responses only to simplify the walkthrough and to make is to that you do not have to configure a database.

  • Track additional information about ad clicks.

    You might want to make sure that you are tracking unique visitors, perhaps by writing a cookie to the browser, if the user has clicked the ad within the last day, or by tracking the IP address of the browser when you store click information. You might also aggregate click information by date and time, and perhaps track ad information according to other dynamic content on the source page, which can help you analyze traffic patterns.

  • Bind the AdRotator control to its data using a different data source control.

    For example, you can store advertisement data in a database. If you do, you can add a data source control to the page and configure it to use a query to obtain advertisement data. You can then bind the AdRotator control to the data source control. For detailed information, see How to: Display Ads From a Database Using the AdRotator Web Server Control.

See Also

Reference

AdRotator Web Server Control Overview