HomeASP.NET Programming an In-Text Advertising System ...
Programming an In-Text Advertising System under ASP.NET 3.5
Now, with the general requirements, architecture, and database definition in mind, in this installment, we are going to delve into the core code programming of the in-text ad system. But first of all, let’s familiarize ourselves with the invoking relationships between the files.
Contributed by Xianzhong Zhu Rating: / 7 January 21, 2009
According to the explanations in the first part of the series, the core of an in-text advertising system mainly focuses upon the post and rendering of the in-text ads. In this system, this is divided into six parts: the CSS files, JavaScript files, the server-side code files under folder App_Code, and three generic handlers, i.e. AdArray.ashx, AD.ashx, and redirect.ashx. For a better understanding of the invoking relationships of the six parts and related files, please refer to Figure 1 below.
Figure 1—the invoking relationships of the fix parts
Next, let’s research each of the six parts shown in Figure 1.
The cascade style sheet file
In the in-text ad system, we use the CSS file stylesheet.css to place all the style-related CSS code, where the code mainly relates to the ad window definition. The following gives the related CSS code definitions:
body {/*the general page style definition */
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
line-height: 150%;
}
a {/*hyperlink style definition */
color: #0000CC;
text-decoration: underline;
}
.STYLE1 {color: #FF3300}
#AdShowBoxContent p {/*the p element related style definition inside the ad window */
white-space: nowrap;
margin: 0px;
padding-top: 3px;
padding-bottom: 2px;
overflow: hidden;
width:170px;
text-overflow:ellipsis;
}
#AdShowBox {/*ad window style definition*/
background-color: whiteSmoke;
font-size: 12px;
line-height: 150%;
font-family: Arial, Helvetica, sans-serif;
border: 1px solid Red;
display: none;
}
#AdShowBoxBartitle {/*the header title inside the ad window style definition */
float: left;
font-weight: bold;
color: #0066FF;
}
#AdShowBoxBarClose {/* style definition for the ‘close’ button inside the ad window*/
float: right;
font-size: 14px;
font-weight: bold;
color: #FF0000;
}
#AdShowBoxBar {/* the header style definition inside the ad window */
background-color:menu;
padding-top: 4px;
padding-right: 5px;
padding-left: 10px;
margin-right: auto;
margin-left: auto;
height: 22px;
}
#AdShowBoxContent {/* style definition for the contents inside the ad window */
padding-top: 5px;
padding-right: 10px;
padding-bottom: 5px;
padding-left: 10px;
}
#AdShowBoxContent a {/* style definition for the a element inside the ad window */
color: #0066FF;
text-decoration: underline;
}
In the above CSS code, the key contents relate to the ad window and related elements' style definitions. Of course, they are also easy to understand with the embedded explanations. Well, let’s go on to check out the main JavaScript files defined in the ad system.
There are mainly three script files defined in this system, i.e. xmlhttp.js, ad.js and getAd.js. First, the xmlhttp.js file encapsulates the Ajax core (i.e. XMLHTTP) related calling code. Here, we are not going to delve into it because most developers are familiar with the basic Ajax-related concepts. You can refer to the source code to find out the details.
The second script file, ad.js, is really the core script. It takes the responsibility of rendering the in-text ad contents. The third script file, getAd.js, encapsulates the ad placing related code, which, in fact, further invokes several other files.
Now, let’s first look more closely at file getAd.js:
Wherein, the adArray.ashx file is responsible for generating the ad keyword array dynamically, whose detailed implementation will be discussed later. The ad.js file, however, takes charge of generating the concrete ad code. To more clearly comprehend this file, Figure 2 shows the invoking relationships between the several functions inside of it.
Figure 2—the invoking relationships between the several functions inside the ad.js file
Now, let’s delve into the implementation of the matchAds function. First of all, we should create an HTML <div/> element that represents the ad window to show and specify the related attributes and styles as follows:
Next, continue to work with the matched element, to get its attribute innerHTML and iterate through it to find out all the keywords and replace them with the ad styled hyperlinks:
As you’ve seen, inside the matchAds function, the other functions (in Figure 2 above) are invoked, where the showAdsearch function undertakes the task of obtaining the ad contents related to some specified keyword, the moveAdBox function is responsible for moving the ad window, and the hiddenAdShowBox function can hide the ad window when needed. For brevity, we omit their code listings here.
When you download the source code accompanying this article, you will see that there are three .cs files, i.e. Tools.cs, ValidateCode.cs, and Sql. under the sub-folder App_Code of the sample website. First, the Tools.cs file holds the definition of the Tools class, which contains a static method named Encrypt(). This method is used to encrypt the password of the logged-in user, which used the DES encrypting algorithm provided by .NET framework. Since this strays from the main point of this article, we won’t dwell upon it any more. You can refer to the source code for details.
Second, the ValidateCode.cs file is used to generate the verifying code that you usually see on today’s web pages, which will be discussed in the next section below.
Finally, let’s take a look at the sql.cs file, which encapsulates the server-side database-related operations. On the whole, the Sql class defines four methods named getMyDataSet, ExecuteSql, getDataSet, and exec, respectively. Below I first list the codes for the getMyDataSet method:
public DataSet getMyDataSet(string sql)
{
command.Connection = Con;//setup the command object
command.CommandText = sql;
DataSet dt = new DataSet();//initialize the DataSet object
SqlDataAdapter da = new SqlDataAdapter(command);
Con.Open();
da.Fill(dt);//execute sentence
command.Connection.Close();//Close sentence
return dt;
}
Next, the ExecuteSql method is responsible for executing a non-query typed SQL query. Below I've indicated the related coding:
public int ExecuteSql(string sql)
{
if (Con.State != ConnectionState.Open)
Con.Open();//if the connection is closed, then open it
SqlCommand Com = new SqlCommand(sql, Con);
int result = Com.ExecuteNonQuery();//execute non-query sql clause
Con.Close();
return result;
}
Since the above code is basic database operation programming using C#, and there are also necessary comments, it’s unnecessary to give any further explanation. The implementations of the other two methods, i.e. getDataSet and exec, are given as follows:
public DataSet getDataSet(string produreName)
{
command.Connection = Con;//assign the connection object
command.CommandType = CommandType.StoredProcedure;//specify the execute type
command.CommandText = produreName;//assign the name of the SP to be executed
DataSet dt = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(command);
Con.Open();//open the connection
da.Fill(dt);//fill data
command.Connection.Close();
return dt;//return the dataset
}
//Input:name of the stored procedure; execute non-query sql clause
public bool exec(string produreName)
{
bool flag = false;//identify whether the task is finished as expected; set to false at the beginning
Now, we’ll check out the three generic handlers one by one.
AdArray.ashx
The first handler, AdArray.ashx, is used to generate the ad data related array to be used on the client side:
public class adArray : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";//the output type
string result="var Ads=new Array(";//specify the script variable to be returned
Sql s =new Sql();
System.Data .DataSet ds=s.getMyDataSet("select name from keyarray ");//obtain the ad keyword
for(int i=0;i<ds.Tables[0].Rows.Count;i++)//append the obtained keyword to the string
result += "'" + ds.Tables[0].Rows[i][0].ToString() + "',";
if (result.EndsWith(","))//clear out the unwanted ',' character at the end of the string
result = result.Substring(0,result.Length-1);
result +=");";
context.Response.Write(result);//output the script variable
}
public bool IsReusable {//not reusable
get {
return false;
}
}
}
As you’ve seen, the main function of the adArray handler searches an advertisement key word from the database, then generates an advertisement key word array according to the specified format, and finally returns the data to the client side. Next, let’s check out the second handler, AD.ashx.
AD.ashx
The second handler, AD.ashx, will render the concrete ad contents related to some special ad keyword. In detail, it will query the corresponding ad contents from the tableaddefined in the AD.mdf database, and then return the data to the client side with some special format, which will finally be rendered on the client side. Below I've listed the associated code for the AD.ashx handler:
public class AD : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string result = "";//the returned ad content
Sql s = new Sql();
string key = HttpContext.Current.Request.QueryString["key"];//the specified ad keyword
string username = HttpContext.Current.Request.QueryString["username"];// the account of the website host who places the ad
string str = "select description ,url from ad inner join keyarray on ad.keyid=keyarray.id where keyarray.name='"+key+"' order by ad.id desc";
System.Data.DataSet ds = s.getMyDataSet(str);//obtain the ad content
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)//append all the relevant ad content to the string
{
result += "<a target="_blank" href="Redirect.ashx?username=" + username;
Finally, let’s look at the third and last handler—redirect.ashx. As the name hints, this handler sees to record the hit count of the related ad, and also bears the responsibility of redirecting the current user to the website where the real ad-targeted contents exists. The following is the related code for the redirect.ashx handler:
public class redirect : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string username = HttpContext.Current.Request.QueryString["username"];//the account of the website host who places the ad
string url = HttpContext.Current.Request.QueryString["url"];//the url to redirect
Sql s = new Sql();
s.ExecuteSql("insert into hit(username,url)values('"+username+"','"+url +"')");//insert the ad data
HttpContext.Current.Response.Redirect(url);//navigate the ad related website page
In this installment, we mainly focused upon the core code programming of the in-text ad system. As you’ve seen, the real work is around the client side JavaScript programming. To gain a better understanding of this, you should first comprehend the invoking relationships between the script files. Then, we explored parts of the server side programming, such as the password encrypting, basic database operation encapsulation, and all three higher generic handlers, which are mainly leveraged to process and provide ad-related data to the client side scripts.
In the third and last part of the in-text advertising system, we’ll shift to discussing the entire website owner- and administrator-related server-side programming and see how the items we discussed in this part will fit together. Please stay tuned for the final installment.