(c) 2002 Visual Studio magazine 
Fawcette Technical Publications

Issue: February 2002
Section: Q&A

VB.NET	Control ASP.NET Events
Listing 1	Build HttpModules to take full control over the events that occur in your ASP.NET Web application. You can intercept Web requests before they're processed, and manipulate, redirect, or reject them. You can also respond to other events such as errors that occur in your Web application.

Imports System
Imports System.Web

Namespace ArticleModule
	Public Class Redirector : Implements _
		IHttpModule
		Public Sub Init(application As _
			HttpApplication) _
			Implements IHttpModule.Init

			'assign event handler to examine 
			'incoming page requests
			AddHandler application.BeginRequest, _
				AddressOf Application_BeginRequest
		End Sub

		Public Sub Application_BeginRequest( _
			sender As Object, e As EventArgs)
			'cast sender into instance of 
			'HttpApplication class
			Dim application As HttpApplication = _
				CType(sender,HttpApplication)

			'get the virtual path of the current 
			'request
			Dim path As String = _
				application.Request.Path

			'determine if the user is navigating to 
			'an article URL
			If path.ToLower().StartsWith( _
				"/articles/") Then
				'split the path into components
				Dim parts As String() = _
					path.Split("/".ToCharArray())

				'extract the article info
				Dim column As String = parts(2)
				Dim year As String = parts(3)
				Dim month As String = parts(4)
				Dim day As String = parts(5)
				
				'transfer the request to the real 
				'URL
				application.Context.RewritePath( _
					"/article.aspx?column=" & _
					column & "&year=" & year & _
					"&month=" & month & "&day=" & _
					day)
			End If
		End Sub

		Public Sub Dispose() _
			Implements IHttpModule.Dispose

			'nothing needs to be done here
		End Sub
	End Class
End Namespace

XML	Store Banner Ads
Listing A	This ads.xml file stores the different banner ads that are displayed to the user. The AdRotator control goes through this XML file and displays one of the ads randomly.  

<Advertisements>
	<Ad>
		<ImageUrl>images/practicalaspbanner.gif
			</ImageUrl>
		<NavigateUrl>http://www.practicalasp.net
			</NavigateUrl>
		<AlternateText>Practical asp.net
			</AlternateText>
		<ID>2</ID>
		<Impressions>10</Impressions>
	</Ad>
	<Ad>
		<ImageUrl>images/eraserver_banner.gif
			</ImageUrl>
		<NavigateUrl>http://www.eraserver.net
			</NavigateUrl>
		<AlternateText>Eraserver</AlternateText>
		<ID>4</ID>
		<Impressions>10</Impressions>
	</Ad>
	<Ad>
		<ImageUrl>images/asppagesbanner468x60.gif
			</ImageUrl>
		<NavigateUrl>http://www.asppages.com
			</NavigateUrl>
		<AlternateText>ASPPages</AlternateText>
		<ID>5</ID>
		<Impressions>10</Impressions>
	</Ad>
</Advertisements>

ASP.NET, C#
Listing 2	This AdRotator.aspx page contains an AdRotator control and the code to hook it to the Global method called GlobalOnAdCreated. The GlobalOnAdCreated method is executed when an ad is chosen and displayed to the user.

<%@ Page Language="C#"%>
<%@ Import Namespace="ExtendedLibrary" %>

<html>

<head><title>Ad Rotator Example</title></head>

<script runat="server">

void Page_Load(Object sender, EventArgs e) {

	adRotator.AdCreated += new AdCreatedEventHandler(
		ExtendedLibrary.AdServe.GlobalOnAdCreated);

}

</script>

<body>

<asp:AdRotator 
	id="adRotator" 
	AdvertisementFile="ads.xml" 
	BorderWidth="1" 
	runat=server />

</body>

</html>

C#	Record View and Click Events
Listing B	The AdServe.cs C# component handles the logic for the AdCreated method.  This method records the ad's view and click events to the database.

namespace ExtendedLibrary {

	using System;
	using System.Data;
	using System.Data.SQL;
	using System.Web;
	using System.Web.UI;
	using System.Web.UI.WebControls;
	using System.Collections;

	public class AdServe {

		static String m_ConnectionString;

		public static String ConnectionString {

		get {

			if (m_ConnectionString == null) {

				Hashtable appSettings = 
					(Hashtable) HttpContext.Current.GetConfig("appsettings");

				m_ConnectionString = (String) appSettings["AdServeDSN"];

				if (m_ConnectionString == null) {
					throw new Exception("DSN Value 
						not set in Config.web");
				}

			}

			return m_ConnectionString;

			}
		}

		static public void GlobalOnAdCreated(object 
			sender, AdCreatedEventArgs e) {

			AdView(e.NavigateUrl);
			e.NavigateUrl = "adtrack.aspx?pageurl=" 
				+ e.NavigateUrl;

		}

		static public void AdClick(string url) {

			// Create Instance of Connection and 
			// Command Object
			SQLConnection myConnection = new 
				SQLConnection(ConnectionString);
			SQLCommand myCommand = new SQLCommand(
				"TrackClick", myConnection);

			// Mark the Command as a SPROC
			myCommand.CommandType = 
				CommandType.StoredProcedure;

			SQLParameter parameterUrl = new SQLParameter("@URL", SQLDataType.VarChar, 150);
			parameterUrl.Value = url;
			myCommand.Parameters.Add(parameterUrl);

			try {
				// Open the connection and execute 
				// the Command
				myConnection.Open();
				myCommand.ExecuteNonQuery();
			}
			catch (Exception e){
				// An error occurred, pass the 
				// exception up
				throw e;
			}
			finally {
				// Close the Connection
				if (myConnection.State == 
					DBObjectState.Open)
					myConnection.Close();
			}

		}

		static public void AdView(string url) {

			// Create Instance of Connection and 
			// Command Object
			SQLConnection myConnection = new 
				SQLConnection(ConnectionString);
			SQLCommand myCommand = new SQLCommand(
				"TrackView", myConnection);

			// Mark the Command as a SPROC
			myCommand.CommandType = 
				CommandType.StoredProcedure;

			SQLParameter parameterUrl = new 
				SQLParameter("@URL", 
				SQLDataType.VarChar, 150);
			parameterUrl.Value = url;
			myCommand.Parameters.Add(parameterUrl);

			try {
			// Open the connection and execute the 
			// Command
				myConnection.Open();
				myCommand.ExecuteNonQuery();
			}
			catch (Exception e){
				// An error occurred, pass the 
				// exception up
				throw e;
			}
			finally {
				// Close the Connection
				if (myConnection.State == 
					DBObjectState.Open)
				myConnection.Close();
			}
		}
	}
}

ASP.NET, C#		Track Ads
Listing 3	This code calls AdTrack.aspx page whenever users click on an ad.  This page executes the AdClick method shown in Listing B, which records the click in the database.

<%@ Page Description="ASP+ document"%>
<%@ Import Namespace="ExtendedLibrary" %>

<html>
<head>
<title></title>
</head>

<script language="C#" runat="server">

void Page_Load(Object Src, EventArgs E ) {

	if (Request.Params["pageurl"] != null) {

		AdServe.AdClick(Request.Params["pageurl"]);
		Page.Navigate(Request.Params["pageurl"]);

	}
}

</script>

<body></body>

</html>
