Dont execute code on page reload

I have an asp page which when loads, sends notification emails and adds data to a Mysql database.people refreshing the page or when navigating back to the page using the browser, this script is run again. So to stop the code to execute again on page reload insert the below code into the page.

CODE:
<%
if Request.Cookies("Mail")<>"" then
Response.Write "cant mail twice!!"
else
Response.Cookies("mail")="Ams"
Response.Write "Mailed!!"
//Put your insert/mail code here.
end if
%>

How To Use On Error Resume Next

Often when using ASP or Active Server Pages with VBScript you will find it necessary to check for errors when you do certain things that may fail and then handle it accordingly. Things like opening a database connection or writing to a text file come to mind.

Generally if an error is encountered in your .asp file, the processing of your script stops and an error message is returned to the browser. If you want to continue processing your page even if an error is encountered, include the following line at the beginning of your .asp file:

<% On Error Resume Next %>

That being said just ignoring errors in your code is not a very good idea. What you really want to do is handle the error in some way.

The example below opens a database connection and shows you how to trap a potential error and do whatever you want because of it. In this case we are simply displaying the error.

<%
ConnectionString = "DBQ=c:\inetpub\wwwroot\mysite\data\mydatabase.mdb;Driver={Microsoft Access Driver (*.mdb)};"

'*** This code checks the ConnectionString info you entered and reports back the error code if it is not ok
Err.Clear
On Error Resume Next
Set ConnPasswords = Server.CreateObject("ADODB.Connection")
ConnPasswords.Open ConnectionString

If Err.Number <> 0 Then

Response.Write (Err.Description& "<br><br>")

Response.Write("This means there is most likely a problem with the" & vbCrLf)
Response.Write("""ConnectionString"" info that you specified.<br>" & vbCrLf)
Response.End

End If
On Error GoTo 0
%>

We put the "On Error GoTo 0 at the end because that will essentially end the "on error resume next"
That is something you want to do so any later errors in your application do not get ignored without you knowing about it.

Below is another example. In this example our application logs user info in a text file when they sign in to a site.
We add "On Error Resume Next" here simply so no nasty error message come up if by chance write permissions to the text file do not exist.

<%
Set ObjMyFile = CreateObject("Scripting.FileSystemObject")
Err.Clear
On Error Resume Next
LogFileName = "aspprotect.log"
LogFileDirectory = "c:\somedirectory"

'Open Text File.. If doesn't exist create it and append to it .. If exists just append to it
Set WriteMyData = ObjMyFile.OpenTextFile(LogFileDirectory & "\" & LogFileName,8,True)
RowHeaderString = Session("User_ID") & vbTab
RowHeaderString = RowHeaderString & Session("Username") & vbTab
RowHeaderString = RowHeaderString & NOW & vbTab
RowHeaderString = RowHeaderString & Request.ServerVariables("REMOTE_ADDR")
WriteMyData.WriteLine(RowHeaderString)
WriteMyData.Close
On Error GoTo 0
%>

You have to be really careful using "On Error Resume Next".
Using the "On Error GoTo 0" helps tremendously though because at least you can stop it from ignoring errors later on in your code.

Sending email using CDOSYS

If you are using a Windows 2000 / 2003 Server, or even XP Pro chances are that CDOSYS is your best bet for sending email from Active Server Pages. That is because CDOSYS is installed on all of them by default. Gone are the days of using CDONTS which was the old way of sending email from ASP. CDOSYS is it's replacement.

That being said there are actually a lot of ways to configure and use CDOSYS. When I 1st started using CDOSYS I assumed the CDOSYS code I was using would work in any situation, but that is not the case. This is something most articles about CDOSYS do not mention so I am going to show you 3 different CDOSYS examples each sending email using a slightly different method.
  1. Method 1 involves sending email using a local pickup directory. Meaning you have the IIS SMTP Virtual Server Running. If you are on a local development machine this is probably for you. Under this scenario any emails you send from your scripts put a ".eml" file in the local pickup directory. Then hopefully the SMTP Virtual Server grabs the file and sends it off. The Virtual SMTP server is however known to hiccup and not send out the emails right away.
  2. Method 2 involves port forwarding. I am not exactly sure how you set that up on the server but the code I wrote for it works under that scenario. The hosting company known as Verio actually implements this with CDOSYS on their servers. I actually implemented this method in some of my software because of a customer that couldn't get emails to send on one of their servers.
  3. Method 3 involves sending the email using a remote mail server. This supports outgoing SMTP authentication should your server require that for outgoing emails. Many do these days. This method is also the best method to use because you are using a real email server with valid MX records. Many modern email systems block emails that do not have valid MX records and you want your emails to reach the recipients.
Method 1 ( Local Pickup Directory where server is running SMTP Virtual Server )

<%
Dim ObjSendMail
Dim iConf
Dim Flds

Set ObjSendMail = Server.CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
Set Flds = iConf.Fields

Flds("http://schemas.microsoft.com/cdo/configuration/sendusing") = 1

'**** Path below may need to be changed if it is not correct
Flds("http://schemas.microsoft.com/cdo/configuration/smtpserverpickupdirectory") = "c:\inetpub\mailroot\pickup"
Flds.Update

Set ObjSendMail.Configuration = iConf
ObjSendMail.To = "someone@someone.net"
ObjSendMail.Subject = "this is the subject"
ObjSendMail.From = "someone@someone.net"

' we are sending a text email.. simply switch the comments around to send an html email instead
'ObjSendMail.HTMLBody = "this is the body"
ObjSendMail.TextBody = "this is the body"

ObjSendMail.Send

Set ObjSendMail = Nothing
%>



Method 2 ( Using mail forwarding on port 25 )
Include this metatype library code on the page you use this emailing with code because there are some things in it this method needs. You can probably get rid of these two lines if you figure out what it references but I didn't take the time to look.





<%
Dim ObjSendMail
Dim iConf
Dim Flds

Set ObjSendMail = Server.CreateObject("CDO.Message")
Set iConf = Server.CreateObject("CDO.Configuration")

Set Flds = iConf.Fields
With Flds
.Item(cdoSendUsingMethod) = 2
.Item(cdoSMTPServer) = "mail-fwd"
.Item(cdoSMTPServerPort) = 25
.Item(cdoSMTPconnectiontimeout) = 10
.Update
End With

Set ObjSendMail.Configuration = iConf

Set ObjSendMail.Configuration = iConf
ObjSendMail.To = "someone@someone.net"
ObjSendMail.Subject = "this is the subject"
ObjSendMail.From = "someone@someone.net"

' we are sending a text email.. simply switch the comments around to send an html email instead
'ObjSendMail.HTMLBody = "this is the body"
ObjSendMail.TextBody = "this is the body"

ObjSendMail.Send

Set ObjSendMail = Nothing
Set iConf = Nothing
Set Flds = Nothing
%>


Method 3 ( Using remote mail server )

<%
Dim ObjSendMail
Set ObjSendMail = CreateObject("CDO.Message")

'This section provides the configuration information for the remote SMTP server.

ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'Send the message using the network (SMTP over the network).
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") ="mail.yoursite.com"
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False 'Use SSL for the connection (True or False)
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60

' If your server requires outgoing authentication uncomment the lines bleow and use a valid email address and password.
'ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'basic (clear-text) authentication
'ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername") ="somemail@yourserver.com"
'ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword") ="yourpassword"

ObjSendMail.Configuration.Fields.Update

'End remote SMTP server configuration section==

ObjSendMail.To = "someone@someone.net"
ObjSendMail.Subject = "this is the subject"
ObjSendMail.From = "someone@someone.net"

' we are sending a text email.. simply switch the comments around to send an html email instead
'ObjSendMail.HTMLBody = "this is the body"
ObjSendMail.TextBody = "this is the body"

ObjSendMail.Send

Set ObjSendMail = Nothing
%>

In addition to what you see here there are plenty of properties you can add to these examples.
Here are a few examples.

Carbon Copy
ObjSendMail.CC = "someone@someone.net"

Blind Carbon Copy
ObjSendMail.BCC = "someone@someone.net"

Send Attachment (we hard code it here, but you could specify the file path using Server.Mappath as well)
ObjSendMail
.AddAttachment "c:\myweb\somefile.jpg"

and a ton of other things you can do...
See Microsoft's CDOSYS Documentation


website templates

the best websites for free html templaes are as given below:

Examples for Alternating Table Row Colors

' ASP Version
strsql = "SELECT Adjective, Noun FROM DrSeussLines"
objRS.Open strsql,objCN,adOpenForwardOnly,adLockReadOnly,adCmdText
i = 0
Response.write "<table>"
Do While Not objRS.EOF
i = i + 1
Response.write "<tr class=""d" & (i And 1) & """>"
Response.write "<td>" & objRS(0) & "</td>"
Response.write "<td>" & objRS(1) & "</td>"
Response.write "</tr>" & vbCrLf
objRS.MoveNext
Loop
objRS.Close
Response.write "</table>"

// PHP Version
$query = "SELECT Adjective, Noun FROM DrSeussLines";
$result = mysql_query($query);
$i = 0;
print "<table>";
while(($row = mysql_fetch_row($result)) !== false) {
$i++;
print "<tr class=\"d".($i & 1)."\">";
print "<td>".$row[0]."</td>";
print "<td>".$row[1]."</td>";
print "</tr>\n";
}
mysql_free_result($result);
print "</table>";

For non-DB pages

Efficient Alternating Table Row Colors

To produce the same effect with less code, instead define two types of TR classes. Then, use inheritance to the TD tag. Read the example and the explanation will follow.

<style type="text/css">
tr.d0 td {
background-color: #CC9999; color: black;
}
tr.d1 td {
background-color: #9999CC; color: black;
}
</style>
<table>
<tr class="d0"><td>One</td><td>Fish</td></tr>
<tr class="d1"><td>Two</td><td>Fish</td></tr>
<tr class="d0"><td>Red</td><td>Fish</td></tr>
<tr class="d1"><td>Blue</td><td>Fish</td></tr>

Hide a table row on change of a select box

<html>
<head>
<title>change code</title>
<script language="javascript">
function changeCode()
{
if(document.getElementById('country').selectedIndex > 6)
{
document.getElementById('ukcode').style.display="none";
document.getElementById('ukcode').style.visibility="hidden";
document.getElementById('eucode').style.display="block";
document.getElementById('eucode').style.visibility="visible";
}
else
{
document.getElementById('eucode').style.display="none";
document.getElementById('eucode').style.visibility="hidden";
document.getElementById('ukcode').style.display="block";
document.getElementById('ukcode').style.visibility="visible";
}

}
</script>
</head>
<body onLoad="changeCode();">
<table>
<tr>
<td><strong>Country:</strong></td>
<td>
<select name="country" id="country" onChange="changeCode();">
<option value="UK" selected>United Kingdom</option>
<option value="NI" >N. Ireland</option>
<option value="BF" >BFPO</option>
<option value="CI" >Channel Islands</option>
<option value="SH" >Scottish Highlands</option>
<option value="NI" >-----------</option>
<option value="E1" >Europe 1</option>
<option value="E2" >Europe 2</option>
<option value="E3" >Europe 3</option>
<option value="E4" >Europe 4</option>

</select>
</td>
</tr>
<tr>
<td colspan="2">
<div id="ukcode" name="ukcode">
<strong>Postcode (UK):</strong>
<input type="text" name="postcode1" size="3" maxlength="20">
- <input type="text" name="postcode2" size="3" maxlength="4">
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div id="eucode" name="eucode">
<strong>Postcode (EU):</strong>
<input type="text" name="postcodeEU" size="8" maxlength="20">
</div>
</td>
</tr>
</table>
</body>

Text Box Characters Counter (IE, Opera, FireFox, & Safari)

In forms when using text boxes or text areas with limited character length (usually needed for forms that submit data to a database) it is always a good idea to tell the user how many characters they have remaining. This javascript snippet is especially useful for textarea fields since they can't be assigned a text limit in HTML but can be restricted using this code.

The following example shows how you can do this. This is a very simple and cute idea to help the user know exactly how many characters can be typed further. Do these small add-ons to your forms and they will look really professional. We recommend using this counter inside CMS solutions and custom built Admin Panels where your clients/visitors can be instructed to use all browsers like IE, Opera, FireFox, Netscape or Safari.



JavaScript to be pasted in head tags

<script language = "Javascript">
/**
* DHTML textbox character counter script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
*/

maxL=255;
var bName = navigator.appName;
function taLimit(taObj) {
if (taObj.value.length==maxL) return false;
return true;
}

function taCount(taObj,Cnt) {
objCnt=createObject(Cnt);
objVal=taObj.value;
if (objVal.length>maxL) objVal=objVal.substring(0,maxL);
if (objCnt) {
if(bName == "Netscape"){
objCnt.textContent=maxL-objVal.length;}
else{objCnt.innerText=maxL-objVal.length;}
}
return true;
}
function createObject(objId) {
if (document.getElementById) return document.getElementById(objId);
else if (document.layers) return eval("document." + objId);
else if (document.all) return eval("document.all." + objId);
else return eval("document." + objId);
}
</script>

html code to be pasted within body tags


<font> Maximum Number of characters for this text box is 255.<br>
<textarea onKeyPress="return taLimit(this)" onKeyUp="return taCount(this,'myCounter')" name="Description" rows=7 wrap="physical" cols=40>
</textarea>
<br><br>
You have <B><SPAN id=myCounter>255</SPAN></B> characters remaining
for your description...</font>

Creating a login script with ASP

login.asp

<%
Response.Expires = -1000 'Makes the browser not cache this page
Response.Buffer = True 'Buffers the content so our Response.Redirect will work
Session("UserLoggedIn") = ""
If Request.Form("login") = "true" Then
CheckLogin
Else
ShowLogin
End If

Sub ShowLogin
%>

<form name=form1 action=login.asp method=post>
User Name : <input type=text name=username><br>
Password : <input type=password name=userpwd><br>
<input type=hidden name=login value=true>
<input type=submit value="Login">
</form>
>%
End Sub

Sub CheckLogin
If LCase(Request.Form("username")) = "guest" And LCase(Request.Form("userpwd")) = "guest" Then
Session("UserLoggedIn") = "true"
Response.Redirect "protectedpage.asp"
Else
Response.Write("Login Failed.<br><br>")
ShowLogin
End If
End Sub
%>

Protectedpage.asp

<%
Response.Expires = -1000 'Makes the browser not cache this page
Response.Buffer = True 'Buffers the content so our Response.Redirect will work

If Session("UserLoggedIn") "true" Then
Response.Redirect("login.asp")
End If
%>

This page is full of password protected content. If you are reading this you entered

the correct name and password.


read more

ASP Sending e-mail with CDOSYS

CDOSYS is a built-in component in ASP. This component is used to send e-mails with ASP.
Sending e-mail with CDOSYS

CDO (Collaboration Data Objects) is a Microsoft technology that is designed to simplify the creation of messaging applications.

CDOSYS is a built-in component in ASP. We will show you how to use this component to send e-mail with ASP.
How about CDONTs?

Microsoft has discontinued the use of CDONTs on Windows 2000, Windows XP and Windows 2003. If you have used CDONTs in your ASP applications, you should update the code and use the new CDO technology.
Examples using CDOSYS

Sending a text e-mail:
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.TextBody="This is a message."
myMail.Send
set myMail=nothing
%>

Sending a text e-mail with Bcc and CC fields:
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.Bcc="someoneelse@somedomain.com"
myMail.Cc="someoneelse2@somedomain.com"
myMail.TextBody="This is a message."
myMail.Send
set myMail=nothing
%>

Sending an HTML e-mail:
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.HTMLBody = "<h1>This is a message.</h1>"
myMail.Send
set myMail=nothing
%>

Sending an HTML e-mail that sends a webpage from a website:
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.CreateMHTMLBody "http://www.w3schools.com/asp/"
myMail.Send
set myMail=nothing
%>

Sending an HTML e-mail that sends a webpage from a file on your computer:
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.CreateMHTMLBody "file://c:/mydocuments/test.htm"
myMail.Send
set myMail=nothing
%>

Sending a text e-mail with an Attachment:
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.TextBody="This is a message."
myMail.AddAttachment "c:\mydocuments\test.txt"
myMail.Send
set myMail=nothing
%>

Sending a text e-mail using a remote server:
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.TextBody="This is a message."
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
'Name or IP of remote SMTP server
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"
'Server port
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25
myMail.Configuration.Fields.Update
myMail.Send
set myMail=nothing
%>
insert variable in mail body:
" & Request.Form("firstname") & "

Dynamic Excel Reports with ASP

Sometimes it's useful to present data to users in Excel format, so they can easily manipulate the data themselves. In this article, a very simple technique for accomplishing this is demonstrated.

Technique

There are many situations in which you may wish to convert table data into an Excel spreadsheet format for the user. There are several methods available for doing this; I will describe in this article one of the simplest ones. It basically tricks the user's browser into thinking the HTML it is downloading is actually an Excel document, and then Excel does the rest of the work by parsing the HTML into a worksheet. Because of the way this works, although this technique is free and easy, it is also very limited in how it can be used. Also, this method only works if the client has Excel 97 or later installed.

If you need to generate Excel documents on the web server in any kind of scalable, robust, or customized fashion, the best tool available is OfficeWriter (formerly ExcelWriter) from SoftArtisans. AspAlliance author Andrew Mooney has written a fairly detailed review of an older version (v4) of ExcelWriter.

In order to create an Excel report dynamically, you must simply create a .asp file with the header of:

1 <% 2 Response.ContentType = "application/vnd.ms-excel"
3 %>

This informs the browser that the code to follow is Excel formatted, and Netscape or IE will prompt the user to Save or Open the file. When they Open the file, Excel is launched and the report is viewed by Excel. In order for Excel to understand your data, you need only to create an HTML table, which Excel 97 will then convert into its own format. NOTE: This must be the first line of code on the page! (Actually, it just has to be before any other header or HTML info is output to the browser, but put it at the top and it won't cause you problems)


Code

They also want to be able to manipulate this data using Excel, and perform some calculations on it. They created an Excel sheet using this code:

<%
Response.ContentType = "application/vnd.ms-excel"

set conntemp=server.createobject("adodb.connection")
cnpath="DBQ=" & server.mappath("/stevesmith/data/timesheet.mdb")
conntemp.Open "DRIVER={Microsoft Access Driver (*.mdb)}; " & cnpath
set RS=conntemp.execute("select * from donut")
%>
<TABLE BORDER=1>
<TR>
<%
' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
' % Loop through Fields Names and print out the Field Names
' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
j = 2 'row counter
For i = 0 to RS.Fields.Count - 1
%>
<TD><B><% = RS(i).Name %></B></TD>
<% Next %>
<TD><B>On Hand (calculated)</B></TD>
<TD><B>Gross (calculated)</B></TD>
</TR>
<%
' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
' % Loop through rows, displaying each field
' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Do While Not RS.EOF
%>
<TR>
<% For i = 0 to RS.Fields.Count - 1
%>
<TD VALIGN=TOP><% = RS(i) %></TD>
<% Next %>
<TD>=b<%=j%>-c<%=j%>-d<%=j%></TD>
<TD>=d<%=j%>*e<%=j</TD>
</TR>
<%
RS.MoveNext
j = j + 1
Loop
' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
' % Make sure to close the Result Set and the Connection object
' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
RS.Close
%>
<TR BGCOLOR=RED>
<TD>Totals</TD>
<TD>=SUM(B2:B6)</TD>
<TD>=SUM(C2:C6)</TD>
<TD>=SUM(D2:D6)</TD>
<TD>n/a</TD>
<TD>=SUM(F2:F6)</TD>
<TD>=SUM(G2:G6)</TD>
</TR>
</TABLE>