When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
Related Web Technologies
User Tips!
Coding Tips

Sample Chapters
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Stump the SQL Guru!
XML Info
Author an Article
Print this page.
Published: Wednesday, February 25, 2004

How to Implement Conditional Includes in ASP using VBScript

By Nathan Gibson

In almost every non-trivial computer program the amount of program code is quite large. To help manage this code, programmers like to chop up the code into smaller, more manageable pieces. This is where includes files enter the picture. Most programming languages allow the programmer to substitute entire blocks of code for a small statement that says "You can now find the code that was here, in a file over there". When the program runs it works just the same as the original, but is much easier to manage, because the code can be divided into logical units.

- continued -

For example all the user interface code can be kept in one file, the data structures in another and the program business logic in another. These files, then, can be included into a single page. Includes reduce the amount of code repetition needed because repeated code can be placed in one location - a single include file - and then included where needed. One of the major benefits of this is that if changes need to be made to the oft-repeated code, the changes only need to be made in one place - the include file.

ASP offers include-like behavior through server-side includes using the #include syntax to import, at runtime, the contents of one file into another. (For an in-depth look at server-side includes in ASP, be sure to read Scott Mitchell's article: The Low-Down on #include.) While server-side includes are a useful tool for ASP developers, one common complaint is that they do not allow conditional includes. In this article we'll examine how to extend ASP to allow for conditional server-side includes.

Defining "Conditional" Includes
A conditional include allows a file to be included or excluded from program execution depending on a given condition. The condition could be the time of day, the name or version of the operating system the program is running on, or anything else you may care to think up.

It is easy to see that includes help in the management of program code, but what would you use conditional includes for? Wouldn't it be good to be able to include a file without having to worry if the file has already been included by another file that has also been included in the current ASP page. A common situation that occurs in ASP is where one file includes two files, and one of those files another also includes the other file that was included by the first.

For example, imagine that page1.asp includes includefile1.asp and also includefile2.asp, but includefile1.asp also includes includefile2.asp. If this situation occurs there will likely be an error or some unexpected behavior since includefile2.asp is being included twice. To avoid this undesired circumstance, the code typically has to be edited so that these include files are included more than once. In the example above, includefile2.asp must only be included by one of the files: either page1.asp or includefile1.asp, but not both.

As the number of files in a project increases and the dependencies between the files become more complicated it becomes a chore for the programmer to manage the order of the include statements. A conditional include can be placed in both files that wish to include a file. If the file has not already been included by another file it will be included. If the file has already been included by another it can be skipped. This is only one of many uses for conditional includes. You may want to write a program that can be installed on several different computers with varying capabilities and configurations, and be able to deploy without having to change any code. Conditional includes can help allow this to happen.

Many other programming languages allow you to do a conditional include, even plain vanilla ANSI C allows conditional includes. Until now it was though impossible to do in plain ASP and VBScript, but below I will show you how it can be done.

Allowing for Conditional Includes
In ASP you can use the following syntax to include code from files into your current ASP page.
<!--#include file="includefile.asp"-->

The problem is caused by the order that the IIS web server processes ASP page requests. The file is included before any ASP code is able to run. This means that code like the following doesn't work as most would expect.
<% If I_want_to_include_file_1 = True Then %>
  <!--#include file="includefile1.asp"-->
<% Else %>
  <!--#include file="includefile2.asp"-->
<% End If %>

The code will run, except both files will be included no matter what. The code in both files is substituted into the current page before the If statement can choose which one to use. When the include files are large this becomes a performance issue and can also cause problems when both files define a function or variable with the same name.

Conditional Includes - a Solution
Most programs include both variable declarations and function definitions. Imagine we have the following include file, named include1.asp, with the following content:

Dim a
a = 7

Function f(byVal x)
  f = x * x
End Function

Now, imagine we have a second page, include2.asp with the following content:

Dim a
a = 3

Function f(byVal x)
  f = (2 * x) + 1
End Function

The page that will include these files - page.asp - will look like:

Dim strInclude
Dim I_want_to_include_file_1
I_want_to_include_file_1 = True

If I_want_to_include_file_1 = True Then
  strInclude = getMappedFileAsString("include1.asp")
  strInclude = getMappedFileAsString("include2.asp")
End If

Execute strInclude

Because this method does not use the built-in IIS include, the code will be run when the page is run, but only one file will be included. The code for the getMappedFileAsString(filepath) function is shown below. Essentially it grabs the complete contents of the specified filepath, returning the file's contents as a string.

Function getMappedFileAsString(byVal strFilename)
  Const ForReading = 1

  Dim fso
  Set fso = Server.CreateObject("Scripting.FilesystemObject")
  Dim ts
  Set ts = fso.OpenTextFile(Server.MapPath(strFilename), ForReading)

  getMappedFileAsString = ts.ReadAll
  Set ts = nothing
  Set fso = Nothing
End Function

After the file's contents have been retrieved as a string, it is executed using the Execute statement. Execute can be used to dynamically execute statements passed in as a string. For more information be sure to read the technical docs.

A comment from 4Guys reader Christian Holm...

Here is a function that fixes the includes, so that they can contain a mixture of HTML and ASP script...

function fixInclude(content)

   'position for  aspStartTag

   'position for aspEndTag
   pos2=instr(content,"%"& ">")

   'if there exists aspStartTag
   if pos1>0 then

      'text content  before aspStartTag
      before= mid(content,1,pos1-1)

      'remove linebreaks

      'put content into a response.write
      before=vbcrlf & "response.write "" " & before & """" &vbcrlf

      'get code content between aspStartTag  and  aspEndTag
      middle= mid(content,pos1+2,(pos2-pos1-2))

      'get text content after aspEndTag

      'recurse through the rest
      out=before & middle & fixInclude(after)

   'did not find any aspStartTags
      'remove linebreaks in file
      out=vbcrlf & "response.write""" & content &""""
   end if

end function

execute (fixInclude(getMappedFileAsString("dummy.asp")))

Caveats with This Approach
Like all things there are some side effects from the inner workings of the include mechanism. Here are some of the more important ones:

  • All the included variables will only be visible (in scope) from where the conditional include happens. If the include happens inside a function it will only be visible inside that function. If done globally, outside any function it will be global for that page and for any page that is included by that page in the regular ASP way.
  • Included functions are visible even outside the functions from where the include takes place, when they are called in the same ASP page.
  • Include files may be included over and over without any error occurring. Although without a little extra help they may still be parsed multiple times.
  • Because the Execute statement executes the VBScript code you need to remove the ASP tags - <% and %> - from the include files as they are not valid VBScript. This means you may need to be careful if you want to switch between VBScript and HTML in an include file. Although if you are just declaring functions and variables this will not make much difference. In fact with a little effort it would be possible to leave the ASP tags in the include files and strip them out before you send the string to the execute statement.

Further Enhancements
This method of conditional includes can be extended to work as a HTTP include mechanism where files from another computer connected by an Intranet or the Internet, so that ASP code can be distributed and managed at different locations.

In VBScript you can actually use a variable before it is declared. To help restrict the scope of variables and this sort of frowned upon behavior it should now be possible to clean up some of the traditional ASP code into a more modular form. I may even be possible to create a full object oriented VBScript program! With Inheritance!

I hope to bring you some more examples of these possibilities in the future. Until then, see what helpful things you can do with a few conditional includes.

Happy Programming!

  • By Nathan Gibson

  • ASP.NET [1.x] [2.0] | ASPFAQs.com | Advertise | Feedback | Author an Article