.Net – ASPX – Avoid Parser Error when commenting out code


While trying out different code snippets as I worked on tweaking an ASPX app, I ran into a parser error.

BTW, the enhancement is detailed here.

Let us quickly go over the parser error.


Parser Error



<asp:TemplateColumn HeaderText="Link" >


				NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "eventLink") %>'

			NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "eventLink") %>'


Parser Error




Parser Error

Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. 

Parser Error Message: Databinding expressions are only supported on objects that have a DataBinding event. System.Web.UI.WebControls.HyperLinkColumn does not have a DataBinding event.

Source Error: 


Here is the change.

Basically, it is to replace “<!–” and “–>” with “<%–” and “–%>“.

<asp:TemplateColumn HeaderText="Link" >


				NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "eventLink") %>'

			NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "eventLink") %>'



Crediting Scott Guthrie

Tip/Trick: Using Server Side Comments with ASP.NET 2.0

ASP.Net – DataGrid – Adding Hyperlink Column



There is a dated Black-book web site that I wrote to keep up with people and appointments years ago.

Here is what the Appointments page looks like:

List Appointments


Edit Appointment




Lately, I have found more and more the need to isolate the corresponding web link into its own entry field and not just mushroom it into the comments multi-edit box.

Edit Appointment


List Appointments




I had a little problem and had to have my brother help me with .Net code to add an hyperlink to a Data Grid.

And, so wanted to place it online for anyone else rusty with ASP.Net

Code line

<asp:DataGrid id="gridContactEventInfo" BorderColor="black" BorderWidth="1" CellPadding="3" AutoGenerateColumns="false" runat="server" font-size="8" width='100%'>

 <HeaderStyle BackColor="#9FBCE3">

 <ItemStyle BackColor="#EEF2F7">
 <AlternatingItemStyle BackColor="#EEEEEE">                                 
	 <asp:BoundColumn HeaderText="Event" DataField="eventName" /> 

		<asp:TemplateColumn HeaderText="Link" >


					NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "eventLink") %>'




Quick Explanation

  1. Added asp:TemplateColumn
  2. Added ItemTemplate
  3. Added asp:HyperLink
    • Added NavigateUrl='<%# DataBinder.Eval(Container.DataItem, “eventLink”) %>’


ASP.Net – DataGrid – Sorting


Yearns ago I developed an electronic’s black-book. It is very basic and rudimentary.  It allows me to jot down names and contact details.

Here is what the screen looks like:


A couple of days ago, I wanted to find someone I met a few months ago. Unfortunately, I could not remember the person’s name, but I remembered how I met the person and noted that it is a very recent acquaintance.

And, so I know sorting by name is the way to go, but I also know that the sorted by column never quite worked.

So this is a good opportunity to clear that up.


When adding the ability to sort a DataGrid via exposing individual Column sorting, there are a few things to keep in mind.

  1. Datagrid
    • Set AllowSorting to true i.e. AllowSorting=”True”
    • Set OnSortCommand to an event function i.e. OnSortCommand = “gridSortEvent”
    • On each sort-able column, be sure to set
      • HeaderText
      • DataField
      • SortExpression
  2. In the code behind
    • From Database, feed in SQL Query and get unsorted RecordSet
      • Persist Query Result in DataSet
      • Capture DataSet’s default view in a variable ( objDefaultView )
      • Save default view in a Session Variable
    • Have a helper function that we called getSortDirection. It receives the sortColumn and compares that sortColumn with the previous callback’s sortColumn.
      • Determine Sort Direction
        • If previous sortColumn is empty, then set to default of ASC
        • If previous sortColumn is the same as current, then toggles sortDirection
        • If previous sortColumn is different than current, then assumes ASC
      • Preserve Sort Column and Sort Direction
        • We used viewState to preserve the passed-in sortColumn and derived sortDirection
      • Return sortDirection
    • Have the event handling function ( gridContactSortEvent )
      • It gets passed the DataGridSortCommandEventArgs argument
      • We extract the sortExpression from the argument
      • We call the helper function mentioned above ( getSortDirection )
      • We concatenate our two sort arguments (sortColumn and sortDirection) and create a new variable sortColumnAndDir
      • Retrieve the session variable gridContact and casts it as a DataView; saved as dv
      • Set the Sort property of the dataview (dv) to the variable sortColumnAndDir
      • Set the grid DataSource to the saved variable dv
      • Invoke grid’s DataBind method




   <form id='frmCover'


   <HeaderStyle BackColor='#9FBCE3'>

   <ItemStyle BackColor='#EEF2F7'>

   <AlternatingItemStyle BackColor='#F5F9FD'>









          HeaderText='Created On'


	  HeaderText='Created On'



             text='<%# Eval('dateCreated', '{0:d}') %>' 







Code Behind – C#

namespace addressBook

    using System;
    using System.Collections;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.ComponentModel;
    using System.Data;
    using System.Data.OleDb;
    using System.Web.Security;
    using System.Text;    //StringBuilder
    using System.Configuration;    

    public class frmCover : System.Web.UI.Page

       private DataView getRecordSetNames
	      String strContactFilter

	   if (
                    (strMemberID == null)
                 || (strMemberID == string.Empty)
		return null;

            OleDbDataAdapter objDbAdapter = null;
	    DataSet objDataSet;
	    DataView objDataView;
	    OleDbCommand objOleDBCommand;

	    strSQLQuery = &quot;dbo.usp_GetContactsForMember&quot;;

	    objOleDBCommand = new OleDbCommand();
	    objOleDBCommand.Connection = objConnection;
                 = CommandType.StoredProcedure;
	    objOleDBCommand.CommandText = strSQLQuery;

            OleDbParameter objDBParametemItemMemberID =
                             new OleDbParameter();
                             = OleDbType.VarChar;
            objDBParametemItemMemberID.Size = 88;
            objDBParametemItemMemberID.Value =

            OleDbParameter objDBParametemItemContactFP =
                            new OleDbParameter();
                           = OleDbType.VarChar;
            objDBParametemItemContactFP.Size = 88;
            objDBParametemItemContactFP.Value =


            objDbAdapter = new OleDbDataAdapter();
            objDbAdapter.SelectCommand = objOleDBCommand;

            objDataSet = new DataSet(&quot;namedetails&quot;);


	    objDataView =

	    objDataView.RowFilter = String.Empty;

	    return objDataView;


	private void loadNamesGrid(
                                      String strContactFillter

		//ICollection objNames;
		DataView    objNames;

		//get Names
		objNames = getRecordSetNames

		//set data source
		gridContact.DataSource = objNames;

		//data Bind

                //save Grid's default view as a
                //session var
		Session[&quot;gridContact&quot;] = objNames;


	private string getSortDirection(string column)

	   // By default, set the sort direction to asc
	   string sortDirection = &quot;ASC&quot;;

	   // Retrieve the last column that was sorted.
	   string sortExpression = (string)

           string lastDirection = null;

	   if (sortExpression != null)
	      // Check if the same column is being sorted
	      // Otherwise, the default value can be
	      if (sortExpression == column)
		lastDirection = (string)

		if ((lastDirection != null) &amp;&amp; (lastDirection == &quot;ASC&quot;))
		   sortDirection = &quot;DESC&quot;;

	      } // if sortExpression == column

	  } // if sortExpression is not null

	  // Save new values in ViewState.
	  ViewState[&quot;gridContactSortDirection&quot;] = sortDirection;
	  ViewState[&quot;gridContactSortExpression&quot;] = column;

	  return sortDirection;

	} // getSortDirection

       protected void gridContactSortEvent(
                                             Object sender
					   , DataGridSortCommandEventArgs e

 	   DataView dv = (DataView)Session[&quot;gridContact&quot;];
	   String strSortColumn = e.SortExpression;

	   String strSortDir = getSortDirection(strSortColumn);

	   String strSortColumnANDDir = strSortColumn + &quot; &quot; + strSortDir;

	   // The DataView provides an easy way to sort.
	   // Simply set the Sort property with
	   // the name of the field to sort by.
	   // dv.Sort = e.SortExpression;
	   dv.Sort = strSortColumnANDDir;

	   // Re-bind the data source and specify that it should be sorted
	   // by the field specified in the SortExpression property.
	   gridContact.DataSource = dv;

 	} // gridContactSortEvent

    } // public class frmCover : System.Web.UI.Page

} //namespace


Post Code Changes

Our code changes bore dividend, as here is the result:

Grid Sorted by Name – Ascending


Grid Sorted by Name – Descending




Couple of things.  We increased session state usage by maintaining the results of the original query in a session variable.

As that data was saved in a session variable, we did not have to pass along the user’s intended sort column and direction to the database.

We needed a bit of code to determine sort direction as the DataGrid does not appear to keep that as part of it’s session state.

Please be sure to maintain database column’s datatype fidelity as much as possible. That is, keep data and formatting different.  This is achievable by exposing two data columns, or using the core column in the DB and using TemplateColumn and ItemTemplate in the ASPX code to perform formatting.

The big realization for me is that I actually need to handle the event for sorting, as it is not handled intrinsically by setting “AllowSorting“.



Microsoft Reference



Microsoft Reference



IIS – ASP & ASP.Net – Session State Management – In Process


I have a few ASP.Net applications running on a MS Windows 2003 box.

Occasionally, the applications error out.




Procedure or function 'listDatesWithEventsForMonth' expects parameter '@memberIdentifier', which was not supplied.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Data.OleDb.OleDbException: Procedure or function 'listDatesWithEventsForMonth' expects parameter '@memberIdentifier', which was not supplied.

Source Error: 

Line 613:
Line 614:
Line 615:            objDBReader = objDBCommand.ExecuteReader();
Line 616:
Line 617:            while (objDBReader.Read())


Thoughts …

There is nothing more disconcerting than when an application wrote yearns ago, crash out so ungracefully on the original developer.

Yes, there are problems, but I am too lazy to fix them.

The problems include:

  1. Architectural – In Process Management
    • Should not be using in-process state management, but more so out of process.
      • In using out of process State Management, worker process recycling will not null out session states
      • Same with errant “Worker Process” that occasionally die
  2. Architectural – Web Garden
    • Insufficient consideration of multi worker processes
  3. Coding Issue
    • Why am I not sanitizing my variables; that is, when I read state data via session[x], I should make sure it is not null, before passing them it off to the DB
      • When null, display an error message and return to the most relevant screen depending on what is missing


Here is the code snippet:

        protected void getUserInfo()

            System.Security.Principal.IIdentity objIdentity;
            Boolean bAuthenticated;

            //get currently logged on user
            objIdentity = User.Identity;

            bAuthenticated = objIdentity.IsAuthenticated;

            strMemberName = objIdentity.Name;

            //get currently selected member
            if (Session["memberID"] != null)
            	strMemberID = Session["memberID"].ToString();


To sanitize the read in session variable, please change it a bit to something like this:

  protected void getUserInfo()

     System.Security.Principal.IIdentity objIdentity;
     Boolean bAuthenticated;          

     objIdentity = User.Identity;

     bAuthenticated = objIdentity.IsAuthenticated;

     strMemberName = objIdentity.Name;

     if (Session["memberID"] != null)
      	strMemberID = Session["memberID"].ToString();

     //On 2015-08-10, dadeniji
    if (     ( strMemberID == null)
          || ( strMemberID == String.Empty) )

	String strURLHome = "login.aspx";






Let us take to Google and see what type of bandage we can wool over this self induced wound.

Google Hits




  1. ASP.Net Configuration Settings – State Management
    • Session timeout ( in minutes ):
      • Change from 20 minutes to 300 minutes



ASP.Net Configuration Settings – State Management ( Before )

sessionStateSettings (before)


sessionStateSettings (after)


Application Pool

  1. Recycling
    • Recycle working process ( in minutes ):
      • Keep at 1740
  2. Performance
    • Idle Timeout
      • Shutdown Worker processes after being idle for ( time in minutes )
        • Changed from 20 minutes to 300 minutes
    • Web Garden
      • Maximum Number of Worker Processes
        • Left as 1


Recycling ( Before )

Application – Performance [ Before ]

Performance (Before)


Application – Performance [ After ]

Performance (After)



In summary, we are modifying the session state timeout on the web site, via the web.config file.

The change is to increase the idle time out from 20 minutes to 5 hours.  2 to 3 hours will likely have been sufficient, as this is not a heavily used web server and so we are likely not competing with other web sites nor users.

On the worker processes, which is fronted through the Application Pool configuration, we modified the idle timeout setting in similar fashion; changed from 20 minutes to 5 hours.

It goes without saying that the Application itself needs to be significantly cleaned-up. We need to possibly capture timeout notifications, and also sanitize data read in and not simply assume they are always valid.






Mining Application Logs – 2015/Feb


A few days a 3rd party web Application that I am working on started getting this error message:



Diagnostic Steps


Spoke to the onsite Vendor Support person and he blamed it on customization we are doing on our side.

And, so again, we are on our own.

As the Application is Microsoft; .Net, Classic ASP, C#, and Classic ASP, I am on safe grounds.

Launched Command Shell

Launched Command Shell and changed folder to application’s Inetpub folder.

Find Text


While one can use GUI tools to search, I personally find the built-in Windows Search tool hard to navigate.  And, so we will use findstr for our exercise.

For our current needs, here are the relevant parameters:

Argument Description  Usage
 /m Prints only the file name if a file contains a match. This allows us to print out matches and not worry about their contextual usage in corresponding file
 /p Skips files with non-printable characters. In our case, we have exes and dlls.  These are binary files and their contents is not available via normal textual parsing means nor editors.And, so for now we will skip them.
 /s Searches for matching files in the current directory and all sub-directories. Delve into sub-folders \ sub-directories, as well.
 /c Uses specified text as a literal search string. Findstr supports both literal and regular expression (RE) searches.In our case, we will edge towards literal as it is a bit simpler and we will avoid the relative complexity of RE; especially as we do not need it for our current simple need.




Let us use findstr to look for the text.

   findstr /p /s /c:"Please select a city"




   _translate\english.inc:t5078 = "Please select a country"
   _translate\englishus.inc:t5078 = "Please select a country"




Match ID

From the matches above, we appear to be dealing with an App that has a bit of Internationalization.  That is, it supports various languages through IDs and “culture” specific resource files.

This time, I do not want to print out the specific matching lines, just the actual file names.

   findstr /M /p /s /c:"t5078" *.* | more






Review HTML\jQuery File

In the GridCache\js\jQuery.VC.js file, we find matches for t5078 and t5079.


     var cz = 0;
	e.find("#selCountry option:selected").each(function() {
		if (cz == 0) {
			cz = b(this).attr("value")

	if (cz <= 0) {

	var y = 0;
	e.find("#selRegion option:selected").each(function() {
		if (y == 0) {
			y = b(this).attr("value")
	if (y <= 0) {



Review ASP File

Next was to review some of the Server-side ASP files:


  <strong><%= t1 %>:</strong>
  <span id="summary_location">
    <% if isArray(arr_locationDetails) and int_serviceOnly = 0 then response.write arr_locationDetails(1,0) end if %>


Invoke Stored Procedure

Let us invoked our Stored Procedure and pass in the arguments we are most interested in.


  set oRS_getForm = server.createObject("ADODB.recordset")
  oRS_getForm.CursorLocation = 3

  on error resume next

  oRS_getForm.open "{call dbo.sp_displayForm ("&userDefinedLocation&", "&int_roomID&","&Session("LanguageID")&", "&Session("UserID")&", "&userDefinedBusinessUnit&", "&Session("countryID")&", "&int_bookingID&", '"&userDefinedFloor&"', "&session("filterGrid")&", "&int_managedBooking&", "& int_editSeries&", '"& dt_currentDateAndTime &"', "&session("outlook")&", "&int_serviceOnly&", "&int_deliveryPoint&")}", oConn

  set colErrs = oConn.Errors

  if oConn.Errors.Count <> 0 then 

    response.Write t1499
    For Each objError In colErrs 
        call logErrorData(objError.Number, objError.Description, "Form", "sp_displayForm")
    set oConn = nothing

 end if


Retrieve Database Record Set

In the code below, we can see that on the third getRows we bring back the recordset that we are most interested in (arr_locationDetails).


 if oRS_getForm.recordcount <> 0 then arr_userDetails = oRS_getForm.getRows() end if
 set oRS_getForm = oRS_getForm.nextRecordset()

 if oRS_getForm.recordcount <> 0 then arr_siteSetup = oRS_getForm.getRows() end if
 set oRS_getForm = oRS_getForm.nextRecordset()

 if oRS_getForm.recordcount <> 0 then arr_locationDetails = oRS_getForm.getRows() end if
 set oRS_getForm = oRS_getForm.nextRecordset()

 if oRS_getForm.recordcount <> 0 then arr_resourceNamingDetails = oRS_getForm.getRows() end if
 set oRS_getForm = oRS_getForm.nextRecordset()

 if oRS_getForm.recordcount <> 0 then arr_colours = oRS_getForm.getRows() end if
 set oRS_getForm = oRS_getForm.nextRecordset()

 if oRS_getForm.recordcount <> 0 then arr_messages = oRS_getForm.getRows() end if


Stored Procedure Code

Get Location & Business Unit

           l.pkLocationID, l.LocationName, l.fkCountryID, isNull(l.att, 0), isNull(CostCentreMandatory, 1) AS CostCentreMandatory    
         , l.fkRegionID as regionID ,l.CCPaymentCostCodeEnabled CCPaymentCostCodeEnabled 
  FROM dbo.tblLocationBusinessUnit lbu     
        INNER JOIN dbo.tblLocation l 
         ON l.pkLocationID = lbu.fkLocationID    
  WHERE fkBusinessUnitID = @businessUnit    


Database Error Log

We went through some more files and finally reviewed the Application’s Error Log Tables.


set nocount on

set dateformat dmy

declare @dateCutoff datetime
declare @VENDOR_TAG varchar(60)

set @VENDOR_TAG = 'BR'
set @dateCutoff = '19/3/2015'

declare @errorListIgnore TABLE
    [errorDescription] varchar(60)

declare @errorListInclude TABLE
    [errorDescription] varchar(60)

insert into @errorListIgnore
    , ('GridCache:InsertCache')
    , ('Cache removed reason: Removed')
    , ('found file')
    , ('Host')

insert into @errorListInclude
      ('Sequence contains no elements')

select top 1500
          'using ignore list' as 
        , replace(tblCE.errorNumber, @VENDOR_TAG, '') as [errorNumber]
        , errorDescription
        , replace(tblCE.[filename], @VENDOR_TAG, '') as [filename]
        , errorDescription
        , storedProcedure
        , replace(tblCE.datetime, @VENDOR_TAG, '') as [datetime]
from   dbo.tblBRError tblCE
where  errorDescription not in ( select tblL.[errorDescription] from @errorListIgnore tblL)
and    [datetime] < @dateCutoff
order by pkErrorID desc

select top 1500
          'using include list' as 
        , replace(tblCE.errorNumber, @VENDOR_TAG, '') as [errorNumber]
        , errorDescription
        , replace(tblCE.[filename], @VENDOR_TAG, '') as [filename]
        , errorDescription
        , storedProcedure
        , replace(tblCE.datetime, @VENDOR_TAG, '') as [datetime]
from   dbo.tblBRError tblCE
where  errorDescription in ( select tblL.[errorDescription] from @errorListInclude tblL)
and    [datetime] < @dateCutoff
order by pkErrorID desc


Thank goodness for Application’s Logging, we found entries such as:



Error Entries
   at RNM..DAL.User.UserDAL.GetUserdefaultSettingsDB(Int32 userID)
at RNM..DAL.User.UserDAL.GetUserDefaultSettingsByID(Int32 userID)
at RNM..BLL.User.UserBLL.GetUserDefaultSettingsByID(Int32 userID)
  at RNM..Utilities.ExceptionManager.HandleException(Exception hExp, String dataToLog, Boolean throwException)
at RNM..BLL.User.UserBLL.GetUserDefaultSettingsByID(Int32 userID)
at RNM..BLL.User.UserBLL.GetUserDefaultSettingsByResourceID(Int32 userID, EnumResource resource)
 Timezone name not found







There are a couple of Database support tables that are pertinent to us.

  • dbo.tblBusinessUnit
  • dbo.tblLocationBusinessUnit
  • dbo.tblLocation
  • dbo.tblUserdefaultView


I have intentionally obfuscated error messages and simplified our problem solving passageway for several reasons:

  • The Application is only used by a few companies
  • The Vendor does not have a broad support web site
  • I am too old to have the Vendor close some of our tool-sets and have to rely on them ever more; or worse still resort to more rudimentary techniques



It has been a taxing week.  And, so I have to listen and share

Patrick Anthony – No Pretense (Official Music Video)



Microsoft – Classic ASP – Error Suppressed


The last few weeks I have been battling with a Vendor application that uses a mix of Classic ASP and ASP.Net.  Not to keep the beating to myself, I will like to share some of my bruised ego.



Classic ASP

We will focus on the Classic ASP code.  There are many reasons for this singular focus; and inclusive:

  • Historical
    • Classic ASP was introduced in 1996
    • It was Microsoft’s first server side scripting engine for generating web pages
  • Tooling
    • It is based on VBScript and JScript
    • ASP 2.0 provided six built-in objects: Application, ASPError, Request, Response, Server, and Session
    • It has being in support for accessing COM and Dlls


As a tool developed in 1996,  almost 20 years ago, it is increasingly difficult to elegantly support it.


Sample Code

Let us create a sample app


Err Suppressed
<@% Page Language=VBScript 	Explicit=True Debug=True %>
<% Response.Buffer = True %>
<!--#include file="errorHandler/errorHandler.inc"-->


	Const ERR_HANDLER_CUSTOMIZED = "/errorHandler/errorHandler500Customized.asp"


	dim strDate
	dim iNumberofEntries
	dim objDictModule
	dim allKeys
	dim allItems
	dim dictKey
	dim dictItem
	Dim i
	Dim iMax	

	dim objNullObject
	dim objErr

	dim numerator
	dim divisor
	dim result

	dim strItem
	dim iErrType

        dim strPagename

        strPagename = Request.ServerVariables("SCRIPT_NAME") 

        if (ON_ERROR_RESUME_NEXT) then

		On error resume next

	end if


	if (iErrType = ERR_TYPE_DIVIDEBYZERO) then

		numerator = 1000
		divisor = 0
		result = a / b



	end if

	set objErr = Err

	set objDictModule = getErrorObjectAsDictionary(objErr)

	set Session(ERR_OBJECT_CUSTOM) = objDictModule

	if ( (Err.Number <> 0) and (ON_ERROR_PROCEED_ERRORHANDLERPAGE = true) ) Then

           'store calling page name
           Session(ERR_OBJECT_CUSTOM).add "Err.Referrer", strPagename

           Response.Redirect ERR_HANDLER_CUSTOMIZED

	end if



In the code above, we have intentionally added the usual suspects; that is things we know will cause trouble:

  • Divide by 0
  • Reference a null object ( objNullObject.Sleep )


IIS Configuration – ASP

Let us make sure that IIS is sufficiently for debugging ASP.

  • Via “Control Panel” \ “Administrative Tools” \ Internet Information Services (IIS) Manager
    • In the left panel, Under Sites, Select the Web Site
    • In the right panel, make sure that the Features View is active
    • In the Features view, within the IIS panel, select ASP


Features View



ASP Configuration



The important configurable items are:

  • Debugging Properties – Set to True
    • Calculate Line Numbers
    • Catch COM Component Exceptions
    • Enable Client-side debugging
    • Enable Log Error Requests
    • Enable Server-side Debugging
    • Log Errors to NT Log
    • Send Errors to Browser
  • Script Language
    • VBScript


Error Message

Upon launching a Web Browser, IE in this case, we run into a ditch.

Here is what we get:



Not a very intuitive error message as we had “Show Friendly HTTP error messages“.

Current Setting:



More Intuitive Message

Via “Internet Options”, we turned off “Show friendly HTTP error messages”.

And, we now have a good error number,  error message, and source file name & offending line number.




 IIS Log

IIS Logs also contain helpful data.



Our IIS Log contains definite and helpful error; here they are:

  • We have .Net CLR2 and CLR3 installed
  • Our error line is 57
  • Our error code is 800a006
  • Our error description is Overflow



Sample Code – “On Error Resume Next”

Let us change the code a bit by setting “On error resume next


    'Const ON_ERROR_RESUME_NEXT = false
     Const ON_ERROR_RESUME_NEXT = true

Once we set “On error resume next”, our error is no longer visible …

Browser – IE


Browser - IISLog

Checked IISLog, and no errors registered


Error Handling

It is obvious that silencing our errors is a bit problematic; as we still have them, but we are not aware of them. Furthermore, the work we greatly want to do, is yet undone. Let us handle our error, and send the user to an informative error page.




As we have now indicated that we want to handle our error, though it is silent, we wrote additional modules:


Classic ASP supports a couple of ways to organize code, source code modules & Com components.  In this post, we will take the quick and simple path of having the code in an included file (errorhandler/errorHandler.inc).

Though not required, we placed in its own folder, as well.


  <!--#include file="errorHandler/errorHandler.inc"-->



Here is our included file.


Const ERR_OBJECT_CUSTOM = "customErrorCollection"

Function getErrorObjectAsDictionary (objErr)

     Dim objList
     Dim objASPError

     Set objList = CreateObject("Scripting.Dictionary")
     objList.add "Err.Number", objErr.Number
     objList.add "Err.Description", objErr.Description

     set objASPError = Server.GetLastError()

     objList.add "ASPError.ASPCode", objASPError.ASPCode
     objList.add "ASPError.ASPDescription", objASPError.ASPDescription
     objList.add "ASPError.Description", objASPError.Description
     objList.add "ASPError.Source", objASPError.Source
     objList.add "ASPError.Number", objASPError.Number
     objList.add "ASPError.File", objASPError.File
     objList.add "ASPError.Line", objASPError.Line

     rem we used set as objList is an object and not a simple datatype (int\string)
     Set getErrorObjectAsDictionary = objList

End Function



The errorHandler.inc is an interesting code-line:

  • We are a generic collection object (Scripting.Dictionary)
  • We captured both the err.number and err.description properties into our collection
  • We also performed a Server.GetLastError call and captured the resultant object’s property, as well
  • Noticed that we used set at the end of the function to return a complex object





Err Handler - 500 - Customized

<@% Page Language=VBScript 	Explicit=True Debug=True	EnableSessionState=True	%>
<!--#include file="errorHandler.inc"-->



	 Dim objError
	 Dim objDictModule
	 Dim errNumber
	 Dim errDescription

	 Dim objErr
	 Dim objErrDict

	 Dim strBuffer

<table border="1">
<table border="0" width="653">
<tr style="background-color: #ff9900;">
<td colspan=3 col align='center'><strong>Error Items</strong></td>
<tr style="background-color: Gainsboro;">
	Access Err Object
<tr style="background-color: beige;">
<td><strong><%= CSTR(Err.Number) %></strong></td>
<tr style="background-color: beige;">
<td><strong><%= Err.Description %></strong></td>

	strBuffer = ""
	CONST COLOR_ROW = "beige"
	CONST COLOR_ROW_ALTERNATE = "blanchedalmond"

	Dim strRowColor
	Dim strItem

	If isObject(Session(ERR_OBJECT_CUSTOM)) = false then


		set objDictModule = Session(ERR_OBJECT_CUSTOM)

		if (objDictModule is Nothing) Then


			'retrieve all the keys and items from the Dictionary and print them out
			allKeys = objDictModule.Keys   'Get all the keys into an array
			allItems = objDictModule.Items 'Get all the items into an array 

			For i = 0 To objDictModule.Count - 1 'Iterate through the array

			  dictKey = allKeys(i)   'This is the key value
			  dictItem = allItems(i) 'This is the item value

			  if ( (i mod 2) = 0) then
				strRowColor = COLOR_ROW
			    strRowColor = COLOR_ROW_ALTERNATE
			  end if	

			  strItem = "
<tr style='background-color: " & strRowColor & "';>"
			  strBuffer = strBuffer & strItem

			  strItem = "
<td>" & cstr(i+1) & "</td>
			  strBuffer = strBuffer & strItem

			  strItem = "
<td>" & dictKey & "</td>
			  strBuffer = strBuffer & strItem

			  strItem = "
<td>" & dictItem & "</td>
			  strBuffer = strBuffer & strItem

			  strItem = "</tr>
			  strBuffer = strBuffer & strItem


		end if

	end if

	Response.Write strBuffer






Here is a quick explanation

  • We checked Err.Number and Err.Description
  • We checked the Session Object that was “set” in the previous page
  • Notice the use of IsObject to ensure that our session variable is previously set



Browser Output:





From the screen above, we will notice a few things:

  • We lost our original error; that is why when the new page calls err.number and err.description we have 0 and empty
  • Thankfully, our session data was preserved



It appears that when we use “on error resume next” and post to another page, our err object ( Err.Number and Err.Description ) is automatically reset.


Application Level



From the example above, we can see that the “on error resume next” statement, prevents error trapping through code.

What about error trapping that is implicitly handled in web.config



Edit Custom Error Page:

Here is how to configure Error Page via “IIS Management Console”




Error Message

In our case, we tweaked our website’s configuration quite a bit. We reviewed and played around with the Application Pool and the actual web site.

Error Text:

Error Message: This site is in an application pool that is running in Classic mode. When running in this mode, custom errors apply to all content except ASP.Net content.

Error Image:



The error message hints that we need to change our Application Pool’s managed pipeline from Classic to Integrated.


Application Pool

ApplicationPool - MangedPipelineMode - Integrated


Error Pages – Feature Settings

It is also important that we set/review the default “Error Pages” settings.


CustomErrorPage - Edit Features


We want to set “Error Page Settings” / “Custom Error Pages” to “Custom error pages”.

If set to :

  • Detailed errors (everyone sees the detailed errors)
  • Detailed errors for local requests and custom error pages for remote requests ( when viewed locally on the web server one sees the detailed error message; and when viewed away from the web server, one sees our custom error page)


Source Code

Here is what our web.config looks like:


<?xml version="1.0" encoding="UTF-8"?>


                <add value="ErrSupressed.asp" />

                <remove path="*" />
                <add path="*">
                        <add provider="ASP" verbosity="Verbose" />
                        <add provider="ASPNET" areas="Infrastructure,Module,Page,AppServices" verbosity="Verbose" />
                        <add provider="ISAPI Extension" verbosity="Verbose" />
                        <add provider="WWW Server" areas="Authentication,Security,Filter,StaticFile,CGI,Compression,Cache,RequestNotifications,Module,FastCGI" verbosity="Verbose" />
                    <failureDefinitions timeTaken="00:00:00" statusCodes="100-999" />

        <httpErrors errorMode="Custom">
            <remove statusCode="500" subStatusCode="-1" />





There are a few things going on in the web.config file indicated above; and those are:

  • We are using our great friend – traceFailedRequests; whenever an error occurs an XML file is generated
  • We are using trapping on HTTPErrors
    • We are using ErrorMode is Custom :- This is we have our our own custom code
    • HTTP Error = 500
      • We call /errorHandler/errorHandler500Customized.asp
      • responseMode = ExecuteURL



Once we add a web.config page, we will have instituted an Application wide error handling pathway.

The Application wide pathway will work for all cases, except when “on error resume next” is in-effect.


How do we test?

How do we investigate whether we can handle errors implicitly?

We will remove “on error resume next”.

rem Const ON_ERROR_RESUME_NEXT = true


Just-In-Time Debugger:



We will not trod down the Debugging trek; and so we will skip initiating the debugger by choosing “No, cancel debugging“.


Here is what we see when a code error and IIS itself triggers our error page




We can see that we have lost useful error data.  Earlier we preserved them by saving them to session variables and then transferring processing to the Error Page.

Spent all weekend trying to get to them when IIS auto-invokes the error page, but not smart enough.


On error goto 0

“On error goto 0” return us back to sanity.  I will suggest that for each “on error resume next”, a corresponding  “on error goto 0” be added as a complement.


Exception Handling

Modern languages idiom rely on try/catch/finally exception paradigm.


Source Control


To make it easier to share and review our simple App, we have place it on Github.



Where did Classic ASP come from?

Accordingly to Wikipedia, Classic ASP was introduced as part of NT Option Pack in 1996.  And, discontinued 4 years later in 2000.

NT Option Pack is one of the most important product release from Microsoft.  Keeping in mind that it was a midterm release between Windows NT 4.0 and Windows 2000, and Microsoft was trying to stem the tide of competing products; and so everything along with the Kitchen Sink and the proverbial workman’s hamburger was included.

According to Windows NT Option Pack, here is what was bundled within it:

  • Certificate Server – Microsoft Certificate Server provides customization services for issuing and managing certificates used in software security systems employing public-key cryptography.
  • FrontPage Server Extensions
  • Index Server – It allows you to easily perform full-text searches and retrieve all types of information from any Web browser.
  • Internet Connection Services for RAS – Remote Access Service
  • Internet Information Server (IIS) version 4.0
  • Mail and News Services – Microsoft SMTP Service uses the standard Internet protocol Simple Mail Transfer Protocol (SMTP) to transport and deliver messages
  • The Microsoft NNTP Service – Newsgroup
  • The Microsoft Data Access Components (MDAC) – ActiveX Data Objects and the Microsoft Access driver
  • Microsoft Management Console (MMC) – Uniform interface for managing server application
  • Microsoft Message Queue Server (MSMQ) – communicate with other application programs quickly, reliably, and asynchronously by sending and receiving messages
  • Microsoft Transaction Server (MTS) – component-based transaction processing system for developing, deploying, and managing high-performance, scalable, and robust applications
  • Site Server – Comprehensive Web site environment for enhancing, deploying, and managing rich intranet and Internet Web sites
  • Microsoft SNA Server – comprehensive gateway and application integration platform that enables communications with midrange ( AS/40)0 and mainframe systems
  • Windows Script Host – a language-independent scripting host for ActiveX™ scripting engines



Once again, I will dedicate this post to a public commit-er, former Microsoft engineer, Eric Lippert. I referenced an important blog post by him in the Reference section below.

Eric blogs @ http://ericlippert.com/ and he has an interesting post @ “Eric Lippert Dissects CVE-2014-6332, a 19 year-old Microsoft bug” ( http://security.coverity.com/blog/2014/Nov/eric-lippert-dissects-cve-2014-6332-a-19-year-old-microsoft-bug.html )



For a product released in 1996 and deprecated in 2000; ASP has obvious staying power.

For the sake of the numerous companies and products that continue to rely on it, I wish keen attention, knowledge and courage.

For sustenance engineers, keep an eye out for “On error resume next“.



Reference – httpErrors and customErrors




Blog and Q/A


IIS – Custom Errors – Sample Code




3rd Party Vendor



Storing & Transfering Data


Collection Object

Dictionary Object


Session Variables





Best Practices

ASP Error Handling – Reference


ASP Error Handling – Sample


Including File


Test Object




Error Handling


Page Transition

Move to new page





“On Error Resume Next ” Stories



Microsoft – Internet Information Server (IIS) – Include Files


Here is a follow-up post to an earlier one titled “Microsoft – Internet Information Server – Error – An error occurred on the server when processing the URL. Please contact the system administrator”  ( https://danieladeniji.wordpress.com/2014/08/22/microsoft-internet-information-server-error-an-error-occurred-on-the-server-when-processing-the-url-please-contact-the-system-administrator/ )


Error Message


Th error message read:


An error occurred on the server when processing the URL. Please contact the system administrator.


An error occurred on the server when processing the URL


Failed Request Tracing Rules

Here is the important data we uncovered through “Failed Request Tracing Rules”.






Source Code


We can resolve the problem by replacing “include virtual” with “include file”.



Here is our included file.


	Const CompanyName = "Dell"
	Const VersionNumber = "v 1"




Here is the Source Code that unsuccessfully attempts to incorporate the included file using “include virtual


<!-- #include virtual ="/customize/header.inc" -->


	Response.Write "Hello - My name is Sam"




Here is the Source Code that successfully incorporates the included file using “include file“.


<!-- #include file = "customize/header.inc" -->


	Response.Write "Company Name:  " + CompanyName + "</BR>"
Version #: <%= VersionNumber %>



Top Level Web Site


We can also address the problem by making our web site a top level web site.

And, so we create the site as a top level web site.

In the image below that site is known as LabVDIR.



Site Bindings

Once we create a new top level website, we will likely have conflicts with our existing web site.

To address let us change the new site’s bindings.

To do so, please follow the following sequence:

  • Select the web site
  • Right click on your selection and from the drop-down menu select “Edit Bindings”





As we will like to keep using the default HTTP port of 80, we will avoid conflicts by invoking a unique “Host name“.

The usual path is that one chooses an host name and then create corresponding aliases name using DNS or host file entries.

But, we will go with the new novel thoughts that have public DNS domain names that point to localhost.

The public DNS name that came by via Goggling is localtest.me.  Please visit http://readme.localtest.me/ and read more.

Here is where we arrive:





Include File” works, but it is a bit restrictive as one has to maintain strict folder structures.

Top Level Web Site” works, as well.  But, keep in mind that you are essentially creating a distinct web site and duplicating some configuration changes.

ASP.Net uses web.config files and so hopefully some of the configurations will carry over.





References – LocalHost