Docstoc

Scripting examples

Document Sample
Scripting examples Powered By Docstoc
					                                                               C U S T O M E R   S U P P O R T




                                                               www.fasthosts.co.uk




                                  Scripting examples




This guide provides an introduction and example scripts for:

 •   Sending email using JMail
 •   Using CDO in ASP to send email
 •   Scripting ASP with Access databases
 •   Scripting ASP with MS SQL databases
Contents

Introduction                                                3
Sending email from your web server                          4
        JMail walkthrough                                   5
        JMail full code                                     7
        CDO                                                 9
Scripting with Access databases                            12
        Using ADO to connect to an Access database          14
Scripting SQL with ASP                                      16
        Using ADO to connect to a MS SQL database          17
Further reading ___________________________________________ 18




                          ASP scripting examples            Page 2
Introduction

Whilst many of the code examples provided in this guide are applicable to any
Windows based web server, the information provided is designed for
customers using Fasthosts web servers; some parameters may not be valid on
other hosting platforms.




        Important: You are responsible for the misuse of any scripts on your
        website. Please read the following article on securing your web
        scripts for further details:
        http://www.fasthosts.co.uk/knowledge-base/?article_id=1027



Unfortunately we are unable to provide email and telephone support for
scripting, but you’ll find a wealth of information about ASP at:
http://msdn2.microsoft.com/en-us/library/ms972337.aspx




                            ASP scripting examples                        Page 3
Sending email from your web server

Before we go into detail on how to get your form working, let's look at some
ground rules that will ensure your mail isn't blocked:


    •   Fasthosts redirects all web based mail to an SMTP Filter System.
        Emails must have either a valid "from" or "to" address which is a
        mailbox hosted with Fasthosts. Any email that does not fulfil this
        criterion will not be delivered. If you are sending email to a customer
        who has given you his email address, you need to use the domain
        name of your website.


    •   Fasthosts' SMTP Filter System rate limits outgoing mail from any
        domain, to prevent bulk emailing. Our limits are set to allow normal
        form-based email activity to pass unhindered, but stop any
        persistent attempt to send bulk mail.


    •   The SMTP Filter System will prevent mass emailing (spam).
        All attempts to send bulk emails are logged and may result in the
        unfortunate suspension of your website, in accordance with our
        misuse policies.




                           ASP scripting examples                       Page 4
JMail walkthrough
The first thing to do is to make sure your form in the submitting page is correct.
In its simplest form it should look like this:


<form action="jmail.asp" method="post" name="mailform">
        <input name="email" type="text" size="40">
        <input name="email_submit" type="submit"
value="send mail">
</form>


Now to the real scripting (using the example form above, we’re now talking about
the code in the “jmail.asp” file).


First initialise the variables. Although this isn't strictly necessary, it is good
programming practice to do so.


dim JMail, intComp, strReferer, strServer, strClientIP,
strServerIP, blnSpam


Next set up the JMail object:


Set JMail = Server.CreateObject("JMail.SMTPMail")


Now obtain some information about the website using the
request.servervariables object.


Note that we get the referrer page here. This is the page that carried out the page
post operation.
strReferer = request.servervariables("HTTP_REFERER")
strServer = Replace(request.servervariables("SERVER_NAME"),"www.","")
strClientIP = request.servervariables("REMOTE_ADDR")
strServerIP = request.servervariables("LOCAL_ADDR")




         Note: Users behind firewalls, like Norton Personal Firewall, might
         experience problems with the execution of this script. In these cases, the
         ("HTTP_REFERER") value is usually stripped out by the firewall, causing
         the script to fail at this step.




                                ASP scripting examples                               Page 5
Next, use this information to check that the posting page is on the same website
as the script. This prevents other people from using your script for bulk emailing.


intComp = inStr(strReferer, strServer)
        If intComp > 0 Then
        blnSpam = False
Else
        ' Spam Attempt Block
        blnSpam = True
End If


Next, populate the JMail object with the correct data. Note that the server
information is used to set up the sender and the SMTP server. The recipient is
obtained from the request object.


JMail.ServerAddress = "smtp." & strServer & ":25"
JMail.Sender = "noreply@" & strServer
JMail.Subject = "JMail Example" & " Sent @ " & now()
JMail.AddRecipient request.form("email")
JMail.Body = "This test mail sent from: " & strServerIP &
" using the JMail component on the server."
JMail.Priority = 3
JMail.AddHeader "Originating-IP", strClientIP



The following code checks that the referrer is correct, and if so, sends the email to
the SMTP server:


If NOT blnSpam Then
        JMail.Execute
        strResult = "Mail Sent."
Else
        strResult = "Mail Not Sent."
End If

After outputting whatever text you’d like to use to tell the client that the job is
done, clean up the objects we have used.
set jmail=nothing


That's it!


             Important: If you don't protect your scripts by checking the referrer, they
             will be open to abuse by bulk mailers. If this happens your website will
             be at risk of being suspended in accordance to our misuse policies.



                                  ASP scripting examples                           Page 6
JMail full code
<!-- ASP Code Section     -->

<%
        'initialise objects and variables
        dim JMail, intComp, strReferer, strServer,
strClientIP, strServerIP, blnSpam
        Set JMail =
Server.CreateObject("JMail.SMTPMail")

        'code to check if this page is being called
from a another page on the server
        strReferer =
request.servervariables("HTTP_REFERER")
        strServer =
Replace(request.servervariables("SERVER_NAME"),
"www.", "")
        strClientIP =
request.servervariables("REMOTE_ADDR")
        strServerIP =
request.servervariables("LOCAL_ADDR")
        intComp = inStr(strReferer, strServer)
        If intComp > 0 Then
                blnSpam = False
        Else
                ' Spam Attempt Block
                blnSpam = True
        End If



          ' This is my local SMTP server
          JMail.ServerAddress = "smtp." & strServer &
":25"

          ' This is me....
          JMail.Sender = "noreply@" & strServer
          JMail.Subject = "JMail Example" & " Sent @ "
& now()

        ' Get the recipients mailbox from a form
(note the lack of a equal sign).
        JMail.AddRecipient request.form("email")

        JMail.Body = "This test mail sent from: " &
strServerIP & " using the JMail component on the
server."
        JMail.Priority = 3

          JMail.AddHeader "Originating-IP", strClientIP

          'send mail



                  ASP scripting examples           Page 7
          If NOT blnSpam Then
                  JMail.Execute
                  strResult = "Mail Sent."
          Else
                  strResult = "Mail Not Sent."
          End If

%>
<!-- HTML Output Section -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">
<html>
        <head>
                <title>Xtreme Email Test</title>
        </head>
        <body topmargin="0" leftmargin="0"
style="font-family: Verdana; font-size: 8pt">

               <br>
               <%=strResult%><br>
               SMTP Server:
<%=JMail.ServerAddress%><br>
               SenderIP: <%=strClientIP%><br>
               ServerIP: <%=strServerIP%><br>
               Server: <%=strServer%><br>
               Referer: <%=strReferer%><br>
               Receiver:
<%=request.form("email")%><br>
               Sender: <%=JMail.Sender%><br>
               <br><br>

                    <a href="jmail.htm">Return to email
page</a>

                    <%
                             set jmail=nothing
                    %>

          </body>
</html>




                     ASP scripting examples          Page 8
Using CDO in ASP to send email


          Quick tip: We recommend you deliver email direct to our main SMTP
          server cluster for speed and efficiency rather than the local MS SMTP
          server. To do this you need to use the CDOSYS object rather than the
          CDONTS object. The code below demonstrates how to use this object
          and the CDO configuration object to send mail.


The first thing to do is to make sure your form in the submitting page is correct.
In its simplest form it should look like this:


<form action="cdonts.asp" method="post" name="mailform">
        <input name="email" type="text" size="40"/>
        <input name="email_submit" type="submit"
value="sendmail"/>
</form>

Now to the real scripting (using the example form above, we’re now talking about
the code in the “cdonts.asp” file).


First initialise the variables. Although this isn't strictly necessary, it is good
programming practice to do so.


dim oCdoMsg, oCdoConfg, strReferer, strServer,
strClientIP, strServerIP, blnSpam

Next set up the CDO object.


set oCdoMsg = server.createobject("CDO.Message")


Now obtain some information about the website using the request.servervariables
object.
Note that we get the referrer page here. This is the page that carried out the page
post operation.
strReferer = request.servervariables("HTTP_REFERER")
strServer = Replace(request.servervariables("SERVER_NAME"), "www.", "")
strClientIP = request.servervariables("REMOTE_ADDR")
strServerIP = request.servervariables("LOCAL_ADDR")
strFrom = "noreply@" & strServer




                                 ASP scripting examples                              Page 9
Next, use this information to check that the posting page is on the same website as
the script. This prevents other people from using your script for bulk emailing.


  intComp = inStr(strReferer, strServer)
        If intComp > 0 Then
             blnSpam = False
        Else
           ' Spam Attempt Block
             blnSpam = True
        End If



Next populate the CDO object with the correct data. Note that we use the server
information to set up the sender and the SMTP server. The recipient is obtained
from the request object.


oCdoMsg.to = request.form("email")
oCdoMsg.from = strFrom
oCdoMsg.Subject = "CDO Test Mail"
oCdoMsg.Textbody = "This test mail has been sent from
server "
oCdoMsg.Textbody = oCdoMsg.Textbody &
request.servervariables("LOCAL_ADDR") & " via CDO mail
objects."


The next section sets CDO to use our main SMTP server cluster rather than the
local MS SMTP Service. We recommend using our main SMTP servers.


strMSSchema =
"http://schemas.microsoft.com/cdo/configuration/"
Set oCdoConfg = Server.CreateObject("CDO.Configuration")
oCdoConfg.Fields.Item(strMSSchema & "sendusing") = 2
oCdoConfg.Fields.Item(strMSSchema & "smtpserver") =
"smtp.fasthosts.co.uk"
oCdoConfg.Fields.Update

Set oCdoMsg.Configuration = oCdoConfg




                             ASP scripting examples                          Page 10
The following code checks that the referrer is correct, and if so, sends the mail
through CDO to the local SMTP server queue.


If NOT blnSpam Then
oCdoMsg.send
strResult = "Mail Sent."
        Else
        strResult = "Mail Not Sent."
End If
response.write strResult

After outputting whatever text you’d like to tell the client that the job is done,
clean up the objects we have used.


set oCdoMsg = nothing
set oCdoConfg = nothing

That’s it!



             Important: If you don't protect your scripts by checking the referrer, they
             will be open to abuse by bulk mailers. If this happens your website will
             be at risk of being suspended in accordance to our misuse policies.




                                  ASP scripting examples                         Page 11
Scripting with Access databases

Whilst the following code examples are applicable to any Windows based
web server, the information provided is designed for customers using
Fasthosts web servers; some parameters, such as the methods used to derive
file paths, may not be valid on other hosting platforms.


Our ASP scripts are written in VBS; we do not provide JScript equivalents.
However, we do provide Perl equivalents using the same technologies.
Perl users should use the same OLE objects.


The current version of ADO installed on our servers is MDAC 2.8.
Detailed component information can be obtained from Microsoft or one of
the many scripting sites on the web.
Tip: Search on Google for "recordset.movenext" or similar.


Before looking at the code, the following points should be considered when
using Access databases in a shared hosting environment:


    •   All scripts run on a shared server, and thus what happens on one
        website has an effect on the stability of certain components on
        other websites on the same server. Access ADO is such
        a component. It is a shared resource, and should therefore be
        programmed correctly.


    •   The Jet access engine has a limited set of resources. Once these are
        exhausted, the script will generate errors. These are normally
        temporary in nature and can occur when server loading is very
        heavy. These are operating system limitations, and cannot be
        extended or isolated by us.




                       ASP scripting examples                         Page 12
•   You should only use Access 2000 or higher databases.
    If you use Access 97 you may receive the following error:-


    [Microsoft][ODBC Microsoft Access Driver] Cannot open database
    '(unknown)'. It may not be a database that your application
    recognizes, or the file may be corrupt.


    This is due to an issue in MDAC 2.5 and greater, and is only resolved
    by using a newer version of Access.


•   Use as few connections as possible. If you are using session and
    application based objects, use a single application based
    connection. Otherwise, use one per script, explicitly opening the
    connection at the start of the script, and then closing it at the end of
    the script.



•   Always use OLEDB connection strings instead of DSN connections.
    The provider to use for Access is "MICROSOFT.JET.OLEDB.4.0".
    See the connection string used below.




                   ASP scripting examples                           Page 13
Using ADO with ASP to connect to an Access database
on your website
Now to the code. First initialise the variables. This isn't strictly necessary, but it's
good programming practice to do so.


dim conn, strsql, rsuser, strMDBPath
    set conn=server.createobject("ADODB.Connection")
    set rsuser=server.createobject("ADODB.Recordset")

Next set up the database connection.
Always explicitly open the connection. Do not use a connection string with
objects such as a command or a recordset object. These implicitly open a
database connection which they then leave open to time out after the script
closes. This connection accesses the Northwinds database which is stored in the
PRIVATE directory below the website root folder. Note the use of the
Server.MapPath method to derive the correct path on the server.


strMDBpath = Server.MapPath("..\private\northwind.mdb")
conn.open "PROVIDER=MICROSOFT.JET.OLEDB.4.0;DATA
SOURCE=" & strMDBPath

Now open the recordset using the current connection.
In this case we are querying the customer table.


strsql = "select top 10 (city) from customers"
rsuser.open strsql,conn,1,2

With the recordset now open, we iterate through it and output the results to the
page. Note that we don't need to use the movefirst method as the recordset
points to the first record by default when opened. With an empty recordset, the
loop exits immediately without errors.


Do while not rsuser.eof
        response.write rsuser("City") & "<br>"
        rsuser.movenext
Loop

Finally, we close the objects used.




                              ASP scripting examples                             Page 14
rsuser.close
conn.close
set rsuser=nothing
set conn = nothing




                     ASP scripting examples   Page 15
Scripting SQL with ASP

Whilst the following code examples are applicable to any Windows based
web server, the information provided is designed for customers using
Fasthosts web servers; some parameters, such as the methods used to
derive file paths, may not be valid on other hosting platforms.


Our ASP scripts are written in VBS; we do not provide JScript equivalents.
However, we do provide Perl equivalents using the same technologies.
Perl users should use the same OLE objects.


Before going into details on the scripts, there is some general information
about MS SQL databases and their use in a shared hosting
environment, that you need to understand:


    •   Use as few connections as possible. If you are using session and
        application based objects, use a single application based
        connection. Otherwise, use one per script. Explicitly open the
        connection, and close it at the end of the script.


    •   Although we support ODBC connections, we recommend using
        DSNless OLEDB connections to any database. These are more
        efficient, and are demonstrated in the code example below.




                       ASP scripting examples                         Page 16
Using ADO to connect to a MS SQL database

Now to the code. First initialise the variables. This isn't strictly necessary, but it's
good programming practice to do so.


dim conn, strsql, rsuser
set conn = server.createobject("ADODB.Connection")
set rsuser= server.createobject("ADODB.Recordset")

Next set up the database connection.
Always explicitly open the connection. Do not use connection strings with objects
such as a command or a recordset object. These implicitly open a database
connection which they then leave open to time out after the script closes.
This accesses the database PUBS on server 213.171.193.129 using the username and
password provided.


conn.open "PROVIDER=MSDASQL;DRIVER={SQL
Server};SERVER=213.171.193.129;UID=nnnnnnn;PWD=xxxxxxxx;DATABASE= pubs"


Now open the resordset using the current connection. In this case we are querying
the titles table.
strsql = "select title from titles"
rsuser.open
strsql,conn,1,2

With the recordset now open, we can iterate through it. Note that we don't need to
use the movefirst method as the recordset points to the first record by default when
opened. With an empty recordset, the loop exits immediately without errors.
Do while not rsuser.eof
        response.write rsuser("Title") & "<br>"
        rsuser.movenext
Loop

Finally we close the objects used.
rsuser.close
conn.close
set rsuser=nothing
set conn = nothing




                                 ASP scripting examples                             Page 17
Further reading
Unfortunately we are unable to provide email and telephone support for
scripting, but you’ll find a whole range of information available online to help
you along the way.


Fasthosts knowledge base articles
    •   Securing your web scripts
        http://www.fasthosts.co.uk/knowledge-base/?article_id=1027

    •   ASP and ASP.NET upload file size limits
        http://www.fasthosts.co.uk/knowledge-base/?article_id=1030

    •   Sending email from web scripts
        http://www.fasthosts.co.uk/knowledge-base/?article_id=65

    •   MS Access database problems
        http://www.fasthosts.co.uk/knowledge-base/?article_id=122



Microsoft.com website - ASP articles
    •   Active Server Pages Tutorial
        http://msdn2.microsoft.com/en-us/library/ms972337.aspx

    •   25+ Tips to improve performance and style
        http://msdn2.microsoft.com/en-us/library/ms972335.aspx

    •   Active Server Pages: Frequently asked questions
        http://msdn2.microsoft.com/en-us/library/ms972347.aspx

    •   ASP Conventions
        http://msdn2.microsoft.com/en-us/library/ms972100.aspx

    •   ASP Troubleshooting tips and techniques
        http://msdn2.microsoft.com/en-us/library/ms972336.aspx

    •   Microsoft scripting home page
        http://msdn2.microsoft.com/en-us/library/ms950396.aspx




                          ASP scripting examples                          Page 18

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:10
posted:10/6/2011
language:English
pages:18