Home > Articles > Programming > Visual Basic

This chapter is from the book

Creating ASP Files

To create ASP files, you can use a text editor such as Notepad or a more advanced tool such as Visual InterDev. In any case, your ASP file can consist of any mix of HTML and code. However, some of your pages will probably contain all code, whereas others will have only standard HTML. The code you write in an ASP file is script code, like the VBScript code discussed in Chapter 30, "Using VBScript."

In the following section, you create and experiment with a simple ASP file. Subsequent sections explore more involved issues in creating ASP files.

Creating a Simple ASP File

Using the same code shown earlier in Listing 31.1 and the virtual /test directory you created in the preceding section, you can create a basic ASP file and experiment with using it. Follow these steps:

  1. Enter the following code in Notepad or another text editor:

  2. <HTML>
    <BODY>
    
    The Current date and time is
    <%
       Dim sTime
       sTime = Now
       Response.Write(sTime)
    %>
    
    </BODY>
    </HTML>
  3. Name the file THETIME.ASP and save it to the /test directory.

  4. Open the file in your browser using the URL http://myserver/test/thetime.asp,

  5. where myserver is the name of your NT server or PC.

    If your code does not run, but is instead displayed onscreen, make sure that the file has an .ASP extension and that the virtual directory has the correct permissions.

NOTE

Microsoft's Web server software allows you to specify default document names (usually DEFAULT.ASP and DEFAULT.HTM). This means a user does not have to carry the URL out to the file level—for example, http://myserver/test/ automatically displays the DEFAULT.ASP or DEFAULT.HTM file if they exist in the /test directory.

Using Server-Side Scripting Tags

When processing an ASP file, the Web server executes only the code designated as server-side script. All other parts of an ASP file are sent directly back to the browser. In your ASP files, the server-side code can be marked in a couple of different ways:

  • Use the HTML <SCRIPT> tag with the RUNAT=SERVER option.

  • Use <% and %> to mark the beginning and end of the server-side script. This syntax is shorter and is the one I recommend.

However you decide to mark the script, make sure to place it within the script delimiters, as in the following examples:

<SCRIPT LANGUAGE="VBSCRIPT" RUNAT="SERVER">
Dim i
For i = 1 to 10
    Response.Write ("This is line " & i & "<BR>")
Next
</SCRIPT>

The same code can also be marked with the shorter tags:

<%
Dim i
For i = 1 to 10
    Response.Write ("This is line " & i & "<BR>")
Next
%>

Notice that you do not need to specify a scripting language in the second example. This is because the default scripting language for ASP files is VBScript. However, the default scripting language is a configurable option, so you might want to place the following line at the beginning of each of your ASP files:

<%@ LANGUAGE="VBSCRIPT" %>

This line is a directive to the script engine that sets the default language to VBScript for the current ASP page. Although your script tags can be placed anywhere in the ASP file, there are a few restrictions:

  • Certain directives and options, such as the previous line of code and the Option Explicit statement, must be placed at the very beginning of the file, even before the <HTML> tag.

  • If your page is used to redirect the user to another side, you cannot send any HTML back to the browser. (You get a demonstration of this in an upcoming section.)

  • You cannot enter straight HTML inside the script tags, unless you use the Response.Write statement.

Also, keep in mind that the code you are entering is VBScript, not the full-featured Visual Basic language. There are some differences and limitations, as discussed in Chapter 30, "Using VBScript."

See "Introduction to VBScript," p. 666.

      See "The VBScript Language," p. 673.

Simple but Dynamic Web Pages

Now that you know the basics, let's write another simple ASP file. At my office, there is a computer named cdtower which, as you might have guessed, is attached to a tower of CD-ROM drives. The purpose of the machine is to allow people on the LAN to connect and install software. However, because people are always swapping and borrowing CD-ROMs, it is hard to know at a given time which CD is in each drive. It would be great if there were a way to automatically keep track of the CDs on a Web page. Fortunately, with Personal Web Server and Active Server Pages, this task is very easy to accomplish.

You use VBScript's FileSystemObject to determine the volume labels of each drive on a computer. By placing this VBScript code in an ASP file where the code executes on the server, you can have the volume labels of the server's CD drives displayed on a remote browser. The code, shown in Listing 31.2, is fairly straightforward.

Listing 31.2  VOLLABEL.ASP

<HTML>
<BODY>
<H1>Drive List</H1><HR>
<%
        Dim objFileSys
        Dim objDrives
        Dim objDrive

   'IGNORE DISK NOT READY ERRORS
   On Error Resume Next

        'CREATE REFERENCES TO FILE SYSTEM AND DRIVES COLLECTION
        Set objFileSys = Server.CreateObject("Scripting.FileSystemObject")
        Set objDrives = objFileSys.Drives

        'DISPLAY VOLUME LABELS
        For Each objDrive in objDrives
            if objDrive.DriveLetter > "C" Then
                Response.Write ("The CD in Drive " & objDrive.DriveLetter)
                Response.Write (" is " & objDrive.VolumeName & ". <BR> ")
             End If
        Next

        'CLEAN UP!
        Set objDrives = Nothing
        Set objFileSys = Nothing
%>
</BODY>
</HTML>

When a user accesses this page, the section of VBScript code executes on the Web server. The Web page in Listing 31.2 accomplishes its purpose, but leaves a lot to be desired in terms of formatting. It would appear neater if you used some HTML formatting codes, such as the <TABLE> tag. This can be easily accomplished by modifying the Response.Write statements. (As you probably have gathered by now, Response.Write is used in an ASP file to send HTML back to the browser.)

In your example, you display the VolumeID property of the Drive object. It would be nice to also display a more informative description. You can accomplish this by creating a custom function, sDescription, which returns a description for a given volume:

Function sDescription(sVolID)
  Select Case UCase(sVolID)
   Case "BACKUP0398"
     sDescription = "Backup of critical files 3/98"
   Case "DN_60ENUD2"
     sDescription = "Developer's Network CD #2"
   '
   ' Add more descriptions here
   '
     Case Else
     sDescription = "Unknown"
  End Select
End Function

You can create your own subroutines and functions in ASP files, just like Visual Basic. To create the sDescription function, simply enter the function at the top of the section of VBScript code. The scope of the function will be for the current ASP page; you can call it just like a standard VB function:

Response.Write sDescription(objDrive.VolumeName)

The final ASP page, with table and description enhancements, is shown in Figure 31.3.

Figure 31.3

An ASP file displays disk information.

Using Include Files

When you write VBScript code in Active Server Pages, you can create functions and subroutines at the beginning of your page, and call them throughout the Active Server Page. You might, for example, create a subroutine that accepts a number and generates HTML based on the number:

   Sub DisplayAmount(nAmount)
      Dim sHTML

      sHTML = "<FONT "
      If nAmount < 2000 Then sHTML = sHTML & "COLOR=RED"
      If nAmount > 4000 Then sHTML = sHTML & "COLOR=GREEN"
      sHTML = sHTML & ">"

      sHTML = sHTML & FormatCurrency(nAmount)
      sHTML = sHTML & "</FONT>"
      Response.Write sHTML
   End Sub

The DisplayAmount subroutine accepts a numeric value and then colors and formats it based on the value itself. Procedures like this one would be very useful in many ASP files, but there is no way to declare this subroutine as public to all ASP files. You could cut and paste it into each file, but maintaining all the copies of it would become a chore. The answer to this problem is to move the function to a separate file and include it where necessary. To include other files in the current ASP file, use the #INCLUDE statement. Two example files are as follows:

<!—#INCLUDE VIRTUAL = "/test/formatfuncs.asp"—>
<!— #INCLUDE FILE="C:\Inetpub\wwwroot\test\formatfuncs.asp" —>

The first line of code uses the virtual directory to specify an include file. The next statement uses the physical directory. Either way, the end result is that the contents of formatfuncs.asp are inserted into the current ASP file before script execution. Some common uses of the #INCLUDE directive are to add footers at the bottom of each Web page, such as the company name or e-mail address.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020