Completing an In-Text Advertising System under an ASP.NET 3.5 Environment

In the second installment of this series, you saw the core client-side script programming and related server-side code. Now, in this third (and last) part, we will look at the programming associated with the presentation tier, i.e. the website owner- and administrator-related code as well as all of the other web pages.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 15
January 28, 2009
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Website owners and system administrators are the two most necessary users. In this example, website owners have the ability to obtain the ad code on the fly to place it inside their own websites; also, if logged in, they can view their own ad data. System administrators, however, own the rights to manage the ad keywords and related detailed content. This part will introduce to you the process of logging in, the member center of the website owners, how to manage the ad keywords, and so forth.

Designing the Login.aspx Page

In this system, the Login.aspx page bears the task of handling the login both of the website owners and the system administrator. Figure 1 indicates the related running-time snapshot.


Figure 1—the login page for all the website owners and the administrators

As you’ve seen above, the layout of the login page is rather typical and simple, where a verification code is nearly a MUST HAVE in today’s website construction.

Well, let’s look into the HTML code of the login.aspx page, as shown below.

<body>

<form id="Form1" style="text-align: center; width: 100%; margin-top: 100px" runat="server">

<span style="font-size: 14pt; color: #cc9966"><strong>The Backend Login<br />

<br />

</strong></span>

<table cellpadding="0" cellspacing="0" border="0" width="250" height="150">

<tr>

<td>

Account:</td>

<td>

<asp:TextBox ID="name" runat="server" Width="150px" BorderWidth="1px"></asp:TextBox>

<br />

</td>

</tr>

<tr>

<td>

Password:</td>

<td>

<asp:TextBox ID="pws" runat="server" Width="150px" BorderWidth="1px" TextMode="Password"></asp:TextBox>

</td>

</tr>

<tr>

<td colspan="2" style="text-align: center">

&nbsp;<iframe id="vali" name="vali" src="gif.aspx" width="66" height="20" marginwidth="0"

marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="No" style="top: 0px;

width: 89px; height: 35px;"></iframe>

</td>

</tr>

<tr>

<td>

Verifying code:&nbsp;</td>

<td style="text-align: left">

&nbsp;

<input id="userVer" runat="server" maxlength="6" name="text2" size="6" type="text"

style="height: 18px" />

&nbsp; &nbsp; <span style="color: #0000ff; cursor: pointer; text-decoration: underline"

onclick="javascript:document.getElementById('vali').contentWindow.location.reload();">

Refresh the verifying code</span>&nbsp;

</td>

</tr>

<tr>

<td style="text-align: center;" colspan="2">

<br />

<asp:Button ID="log" runat="server" Text="Login" Width="150px" BorderStyle="Solid" BorderWidth="1px"

BackColor="#E0E0E0" BorderColor="Gray" OnClick="log_Click"></asp:Button>

</td>

</tr>

</table>

</form>

</body>

Obviously, I’ve applied the typical table layout. Looking more closely, you can see that there are only two points worth noticing. One is the following line:

<iframe id="vali" name="vali" src="gif.aspx" ……></iframe>

The <iframe> element was frequently used in early web applications that needed to partially update a page. For details on this related programming, continue to read the next section. The other point worth noticing is this:

<span style="color: #0000ff; cursor: pointer; text-decoration: underline"

onclick="javascript:document.getElementById('vali').contentWindow.location.reload();">

Refresh the verifying code</span>

With this section, when you click the phrase "Refresh the verifying code," the related click event handler will be triggered to execute the related short script sentence, which will partially update the corresponding <iframe> area on the target page. For information on the use of this JavaScript, you can go here .

Next, let's take a look at the crucial code behind the Login.aspx page:

protected void log_Click(object sender, System.EventArgs e)

{

//judge the verifying code

if (userVer.Value.Trim().ToLower() != Session["sdf"].ToString().ToLower())

{

ClientScript.RegisterStartupScript(this.GetType(), "ab", "alert('Invalid verifying code!');", true);

return;

}

if (name.Text == "qucha" && pws.Text == "000000")//judge whether is an adminstrator;if so, then redirected to page admin1.aspx

{

Session["admin"] = "true";

Response.Redirect("admin1.aspx", true);

}

//verify the password and related account info

Sql s = new Sql();

SqlParameter para = new SqlParameter();//the returned parameters for the stored procedure

para.ParameterName = "@returnValue";

para.Direction = ParameterDirection.ReturnValue;

s.command.Parameters.Add(para);

s.command.Parameters.AddWithValue("@username",name.Text);

s.command.Parameters.AddWithValue("@userpass", Tools.Encrypt(pws.Text,"12345678"));

s.exec("userlogin");//execute the login related SP

if (para.Value.ToString()!="3")//login succeed

{

System.Web.Security.FormsAuthentication.SetAuthCookie(name.Text, true);

Response.Redirect("siteUser.aspx");

}

else//login fail

{

ClientScript.RegisterStartupScript(this.GetType(), "a", "alert('Invalid password');", true);

}

}

Because the website owners and the system administrator share the same login form, we have to make judgments respectively. When the user clicks the "Login" button, we first resolve the verifying code and judge whether it is correct; and if so, continue to judge whether the administrator is logging in (the correct account name and password are "qucha" and "000000" respectively). If the current user is the administrator, then he is navigated to the "admin1.aspx" page; otherwise, the website owner-related login code is executed.

If the current user has not been registered, then he is immediately registered and redirected to the member center (the siteUser.aspx page). If the current user has been registered, then his password is verified, and if all is okay, he will also be redirected to the member center (the siteUser.aspx page).

Note there is a shortcoming with the procedure above. We’ve used the hard-coded username and password, but in practical cases this is absolutely prohibited.

The Verification Code Programming

As hinted above, the verification code is generated through the "Gif.aspx" page.  Looking closely, you will find that the HTML coding of this page is empty, and all of the implementation logic is performed by invoking the ValidateCode server-side class, with which we generate the verification code-related picture. Below I've given the code for the gif.aspx.cs file:

protected void Page_Load(object sender, EventArgs e)

{

ValidateCode gif=new ValidateCode ();//verifying code

string valid ="";

MemoryStream ms = gif.Create ( out valid);

Session["sdf"] = valid;//store the verifying code

//first empty

Response.ClearContent();

Response.ContentType = "image/png";

Response.BinaryWrite(ms.ToArray());//output in the picture format

Response.End();

}

The principle used to generate the verifying code is: first generate a random number; use this number to generate a picture; put the picture into the memory stream; and finally output the picture from the memory stream to the web page. Since the implementation of the ValidateCode class is so tedious to code, we will not list it; you can refer to the downloadable source code for the details.

The Member Center: the siteUser.aspx page

The siteUser.aspx page serves as the member center for the website owner, where you can view your ad-related data, as well as obtain the ad code (which directs you as to where and how to put the code inside your own web page to advertise your products). Figure 2 indicates one of the running time snapshots of the page.


Figure 2—The siteUser.aspx page serves as the member center of the website owner

The whole layout of the page is simple, with a GridView control to display the ad- related data and a TextBox control (with the TextMode attribute set to MultiLine) to show the ad code.

Next, let’s take a quick look at the code behind the above page, as follows:

public partial class siteUser : System.Web.UI.Page

{

public string code = "";//the ad code

protected void Page_Load(object sender, EventArgs e)

{

if (!User.Identity.IsAuthenticated) Response.Redirect("login.aspx");//if not logged in, then go to page login.aspx

code = "<script type ="text/javascript" >var username='"+ User.Identity.Name+"'";

code+= "; </script><script type="text/javascript" src="js/getad.js"></script>";

TextBox1.Text = code;

string username = User.Identity.Name;//the user account

Sql s = new Sql();

//get the user's ad popularizing related data and show them

GridView1.DataSource = s.getMyDataSet("select * from hit where username='"+username +"'");

GridView1.DataBind();

}

}

Here, if the current user has not logged in, then he is redirected to the "Login.aspx" page; otherwise, the code sets up the contents of the TextBox control with the hard-coded script, and then obtains the current user specific ad data and shows it inside the GridView control. That’s all.

Next, let’s look at the system administrator-related pages.

Manage the Ad Keywords

There are two pages associated with the system administrator: the Admin1.aspx page and Admin2.aspx. The Admin1.aspx page seeks to manipulate the ad keywords, while the Admin2.aspx page takes care of managing the related ad contents. Figure 3 gives one of the running time snapshots for the Admin1.aspx page.


Figure 3—Admin2.aspx: managing the ad contents

As you’ve seen, the "Admin1.aspx" page uses a GridView control to manage the ad keywords. In this page, you can browse, remove, and add any of your favorite ad keywords.

The following responds to the HTML code of the "Admin1.aspx" page:

<body>

<form id="form1" runat="server">

<div><a href ="admin2.aspx">Go to manage the AD contents</a><br /><br />

<asp:GridView id="GridView1" runat="server" AutoGenerateColumns="False" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCommand="GridView1_RowCommand" AllowPaging="True" CellPadding="4" ForeColor="#333333" GridLines="None">

<Columns>

<asp:BoundField DataField="id" HeaderText="Code" />

<asp:BoundField DataField="name" HeaderText="Keyword" />

<asp:BoundField DataField="notes" HeaderText="Note" />

<asp:TemplateField HeaderText="delete">

<ItemTemplate>

<asp:LinkButton ID="LinkButton1" CommandName ="del" runat="server" CommandArgument='<%# Bind("id") %>'>Delete</asp:LinkButton>

</ItemTemplate>

</asp:TemplateField>

</Columns>

<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />

<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />

<EditRowStyle BackColor="#999999" />

<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />

<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />

<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />

<AlternatingRowStyle BackColor="White" ForeColor="#284775" />

</asp:GridView>

<br />

Keyword:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />

Note:<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

<br />

<br />

<asp:Button ID="Button1" runat="server" Text="Add" OnClick="Button1_Click" />

</div>

</form>

</body>

What about the code behind it? Below is the crucial part of the code:

protected void Page_Load(object sender, EventArgs e)

{

//not logged, then force to login first

if (Session["admin"]==null||Session["admin"].ToString() != "true") Response.Redirect("login.aspx");

if (!IsPostBack)

{

myDataBind();//data binding

}

}

//paging

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

GridView1.PageIndex = e.NewPageIndex;

myDataBind();

}

//delete

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

{

if (e.CommandName == "del")

{

string id = e.CommandArgument.ToString();

try

{

Sql s = new Sql();

s.ExecuteSql("delete from keyarray where id=" + id);//delete

myDataBind();

}

catch

{ }

}

}

//datasource binding

private void myDataBind()

{

Sql s = new Sql();

DataSet ds = s.getMyDataSet("select * from keyarray order by id desc");

GridView1.DataSource = ds;

GridView1.DataBind();

}

//add the ad keyword

protected void Button1_Click(object sender, EventArgs e)

{

int result;

Sql s = new Sql();

//add the ad keyword

result = s.ExecuteSql("insert into keyarray([name],notes) values('"+TextBox1.Text+"','"+ TextBox2.Text+"')");

string msg = "alert('Operation failed!')";

if (result == 1)//if peration succeeded,then prompt

{

TextBox2.Text = TextBox1.Text = "";

msg = "alert('Operation succeeded!')";

myDataBind();

}

//the client side prompt

ClientScript.RegisterStartupScript(this.GetType(), "asdf", msg, true);

}

As you’ve seen, the system first judges whether the current user is the valid administrator with the help of ASP.NET Sesson, and if not, it redirects him to the "login.aspx" page. Next, it makes the necessary preparations for the GridView control, i.e. binds data and adds related operating buttons. Finally, when the user clicks the "Add" button, a typical database INSERT operation is triggered to append the newly-populated ad keyword-related data to the backend database. That’s it.

Manage the Ad Contents

If you click the "Go to manage the AD contents" hyperlink at the top of the "Admin1.aspx" page, you will be navigated to the "Admin2.aspx" page, where you can manage the specified keyword-related ad contents—browse, add, and delete some items. Figure 4 indicates the running time snapshot of the "Admin2.aspx" page.


Figure 4—Admin2.aspx: managing the ad contents

As you’ve seen from the figure, there are one-to-many relationships between the ad keywords and the contents. For example, the CSS keyword is bound to two items of content: "google" and "search engine." The basic coding logic of this page quite resembles that of the "‘Admin1.aspx" page. Here we only give the server-side code related to the "Admin2.aspx" page:

public partial class admin2 : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

//not logged, then force to login first

if (Session["admin"]==null||Session["admin"].ToString() != "true") Response.Redirect("login.aspx");

if (!IsPostBack)

{

myDataBind();//data binding

}

}

//paging

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

GridView1.PageIndex = e.NewPageIndex;

myDataBind();

}

//delete

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

{

if (e.CommandName == "del")

{

string id = e.CommandArgument.ToString();

try

{

Sql s = new Sql();

s.ExecuteSql("delete from ad where id=" + id);//delete

myDataBind();

}

catch

{ }

}

}

//datasource binding

private void myDataBind()

{

Sql s = new Sql();

string str = "select ad.*,keyarray.name from ad inner join keyarray on ad.keyid=keyarray.id order by ad.id desc";

DataSet ds = s.getMyDataSet(str);//add the ad contents

GridView1.DataSource = ds;

GridView1.DataBind();

}

//add the ad content

protected void Button1_Click(object sender, EventArgs e)

{

int result;

Sql s = new Sql();

//add the ad content

result =s.ExecuteSql("insert into ad(keyid,description,url) values('"+ DropDownList1.SelectedValue +"','"+ TextBox2.Text+"','"+ TextBox1.Text+"')");

string msg = "alert('Operation failed!')";

if (result == 1)//if peration succeeded,then prompt

{

TextBox2.Text = TextBox1.Text = "";

msg = "alert('Operation succeeded!')";

myDataBind();

}

//the client side prompt

ClientScript.RegisterStartupScript(this.GetType(), "asdf", msg, true);

}

}

In the above code, we’ve also provided enough comments. So we won’t waste any more words on details.

Summary

In-text advertising is a new form of advertising through the Internet. In this series of articles, we have constructed a simple in-text ad system. Despite its simplicity, we’ve given you the basic idea and the core routine involved in developing a real-life in-text ad application. And of course, due to its simplicity, it has numerous points that need to be perfected. For example, in practical systems, you’d better add the following supports:

1. Make the user center for the advertisers facilitate the placing of ads as well as allow them to view their own advertising effects.

2. Provide support for preventing practical fraud and spiteful clicking so as to insure the correctness of the system.

3. Add support for the on-line payment so as to facilitate the advertisers in adding ad rates for their ads online, and enable the website owners to obtain their own ad income in the online mode.

4. Categorize the websites and ad keywords. For example, you can have some specified category-related websites which can only exhibit ad keywords relating to this category. The final aim is to better the effect of the advertisement.

-DOWNLOAD SOURCE-

blog comments powered by Disqus
ASP.NET ARTICLES

- Implementing ASP.NET 4.0 Page.MetaDescriptio...
- ASP.Net Development Tips
- Intro to Sessions in ASP.Net
- Google Maps API Introduction in ASP.NET usin...
- Creating an ASP.NET 3.5 Gridview Image Galle...
- Encrypt QueryString in ASP.NET 3.5 using VB....
- ASP.NET 3.5 Drop Down List Controls
- Connect to Access Database with ASP.Net
- Secure Audio Streaming with ASP.Net and Flash
- Dynamic Sitemap and Navigation in ASP.Net
- Implement Gzip and Deflate Compression in AS...
- Run ASP.Net in Ubuntu with Apache
- ASP.Net Mono Website Contact Forms
- ASP.Net URL Rewriting Methods
- Murach`s ASP.NET 4 Web Programming with C# 2...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 3 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials