Thursday, October 20, 2005
« Programmatically access Perfmon counter ... | Main | HTML Select List options »

So I was looking for a way to 'randomly' display a picture from a given directory. I was going to get all crazy, and do a bunch of file system operations, and then some randomization on that. After I had started, I stopped. I thought this does not need to be so complicated!

I talked to a few friends, who thought my approach seemed fine. But to be quite honest I was in a lazy mood and decided that I didn't feel like comming up with some complicated solution for something that seems so easy. Then it hit me. Isn't there some AdRotator thing in .NET? Yeah there is, and it's slick.

I simply added the following code to my .aspx page.

<asp:AdRotator id="ar1" AdvertisementFile="headers.xml" BorderWidth="0" runat=server />

Well I'm not really using Ads. I have a header graphic similar to a banner ad, but I wanted it to be random each time the page loaded. The cool thing about using this control is that there is no codebehind logic to worry about.

There is then an xml file in this case called headers.xml with the followng structure:

<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>

<Ad>
<ImageUrl>images/header/header1_noglow.jpg</ImageUrl>
<AlternateText>Alt Text</AlternateText>
<Impressions>1</Impressions>
</Ad>

<Ad>
<ImageUrl>images/header/header_sky2.jpg</ImageUrl>
<AlternateText>Alt Text</AlternateText>
<Impressions>1</Impressions>
</Ad>

<Ad>
<ImageUrl>images/header/header_sky.jpg</ImageUrl>
<AlternateText>Alt Text</AlternateText>
<Impressions>1</Impressions>
</Ad>

<Ad>
<ImageUrl>images/header/header_window.jpg</ImageUrl>
<AlternateText>Alt Text</AlternateText>
<Impressions>1</Impressions>
</Ad>

</Advertisements>

Here are the arguments that you can configure in the XML file, and what they do on the front end.

  • ImageUrl - An absolute or relative url to image file
  • NavigateUrl - The location to navigate to when the image is clicked, if you leave this out, clicking the image does nothing
  • AlternateText - The 'alt' text to be displayed on the image
  • Keyword - Specifies a category for the ad that the page can filter on
  • Impressions - A number that indicated the 'weight' of the ad in the schedule of rotation relative to other ads in the file. The larger the number, the more often it will be displayed

So this is really basic stuff, but something I've always ignored in the past. So if you want a way to display a discrete set of images randomly, this might be the ticket.