ࡱ>    q` rbjbjqPqP k::j)x x x x x x x  8 [JXX"zzzO> L[N[N[N[N[N[N[$^h`@r[x J^OJJr[x x zzw[J,#x zx zL[JL[~@*x x $KzL H4av) or in OBJECT tags with the RUNAT=Server property set. Since the entire ASP is parsed into HTML, the client sees absolutely no ASP code. The browser collects this HTML text and parses it, determining how to display those colorful animated gifs and blinking text we've all come to love.  You'll note that there are again just three steps, although the second step is a bit more involved. The whole process starts with the client requesting a file with .ASP extension. The web server notes the extension, and since it has an .ASP extension (as opposed to a .txt, .htm or .html), the server parses the contents of the requested file before sending it to the client. So when you view an ASP file through IE or Netscape, your browser doesn't know that the .asp file is any different from a standard .html file One of the things that make ASP a bit tricky for beginners is the fact that there are two kinds of scripting: client-side scripting server side scripting Client-side scripting is HTML code that the browser interprets. For example, you can have a message box appear when a page is loaded by adding: alert("Hello, world!"); at the bottom of your HTML page. This is client-side scripting. The web server makes no note of client-side code; it just sends it to the client like regular HTML text. It is the client's responsibility to process client-side scripts. Server-side scripts are scripts that the server processes. ASP is a server-side script, since the web server completely processes all ASP scripts before sending the HTML content to the client. Since server-side scripts are handled by the server, the client does not interact with the server-side scripts. In fact, with ASP, since all ASP code is processed before the client obtains the server-side script, it is impossible for the ASP to make use of client-side actions without requiring a round trip to the server. You can insert server-side variables into client-side script. Since the server-side script will be processed before the client receives the HTML content, and since client-side scripts are synonymous with HTML content, you can write server-side script variables to the client-side scripts rather simply. alert (" "); What you cannot do is have server-side script make use of client-side variables, methods, or events. Since the server-side script has completely been processed by the time any client-side code is processed, client-side code cannot impact the server-side code in any way. What is an .asp File? Active Server Pages (ASP) is built around files with the file name extension .asp. An .asp file is a text file and can contain any combination of the following: Text HTML tags Script commands. A script command instructs your computer to do something, such as assign a value to a variable. Its easy to create an .asp file: Just rename any HTML file, replacing the existing .htm or .html file name extension with .asp. To make the .asp script file available to web users, save the new file in a web publishing directory. When you view the file with your browser, you see that ASP processes and returns HTML, just as before. What is a Script? A script is a series of script commands. A script can, for example: Assign a value to a variable. A variable is a named storage location that can contain data, such as a value. Instruct the Web server to send something, such as the value of a variable, to a browser. An instruction that sends a value to a browser is an output expression. Combine commands into procedures. A procedure is a named sequence of commands and statements that acts as a unit. Executing a script sends the series of commands to a scripting engine, which interprets and relays them to your computer. Scripts are written in languages that have specific rules; thus, if you want to use a given scripting language, your server must run the scripting engine that understands the language. ASP provides scripting engines for the VBScript and JScript scripting languages. Your primary scripting languagethat is, the language that ASP assumes you are using if you don't specify a languageis VBScript by default. Delimiters HTML tags are differentiated from text by delimiters. A delimiter is a character or sequence of characters that marks the beginning or end of a unit. In the case of HTML, these delimiters are the less than (<) and greater than (>) symbols. Similarly, ASP script commands and output expressions are differentiated from both text and HTML tags by delimiters. ASP uses the delimiters <% and %> to enclose script commands. For example, the command <% sport = "climbing" %> assigns the value climbing to the variable sport. ASP uses the delimiters <%= and %> to enclose output expressions. For example, the output expression <%= sport %> sends the value climbing (the current value of the variable) to the browser. Statements A statement, in VBScript and other scripting languages, is a syntactically complete unit that expresses one kind of action, declaration, or definition. The conditional If...Then...Else statement that appears below is a common VBScript statement. <% If Time >=#12:00:00 AM# And Time < #12:00:00 PM# Then greeting = "Good Morning!" Else greeting = "Hello!" End If %> This statement stores either the value "Good Morning!" or the value "Hello!" in the variable greeting. It does not send any values to the client browser. The following lines send the value, in green, to the client browser: <%= greeting %> Thus, a user viewing this script before 12:00 noon (in the Web servers time zone) would see Good Morning! A user viewing the script at or after 12:00 noon would see Hello! Script Tags The statements, expressions, commands, and procedures that you use within script delimiters must be valid for your default primary scripting language. ASP is shipped with the default primary scripting language set to VBScript. However, with ASP you can use other scripting languages; just use the HTML script tags , together with the LANGUAGE and RUNAT attributes, to enclose complete procedures written in any language for which you have the scripting engine. For example, the following .asp file processes the VBScript function Add. <% function Add (A,B) Add = A + B end Function %> <% Response.Write Add (2,3) %> Comments and Concatenation Single quote is used to give comment to lines in ASP. There is no multi line comment. <% Response.Write (This is not a Comment) Response.Write (This is a Comment) %> & character is used for concatenation. Hello World!!!! Now let us write our first program for Hello World. Hello, World ! <% Response.Write Hello, World! %>
<%= "Hello, World! From Another Style" %> Displaying Date To display date in your web page, Date function is used. This gives current date. To display current time, use Time function. To display both date and time use Now function. Date and Time <%= Date %>
<%= Time %>
<%= Now %> From the current date and time user can also get the individual elements like Year, Date, Month, Hour, Minute and Second by using above functions. Date and Time <% Response.Write "Year: " & Year (Now) Response.Write "
" Response.Write "Month: " & Month (Now) Response.Write "
" Response.Write "MonthName: " & MonthName (Month(Now)) Response.Write "
" Response.Write "Hour: " & Hour (Now) Response.Write "
" Response.Write "Minute: " & Minute (Now) Response.Write "
" Response.Write "Second: " & Second (Now) %> Variables and Constructs A variable is declared using dim keyword while using VBScript as scripting language. All variables are of type variant. The variable type is defined when the value is stored in it. The programmer need not to worry about the type of variable. By default variable declaration is not compulsory. However, it is best practice to always declare the variable before using it. Option explicit directive is used to make variable declaration compulsory. <% Option Explicit Dim firstVar %> Option Explicit must compulsorily be the first line of your ASP page else, the server generates error. A variable is declared using var keyword while using JavaScript as scripting language. While using JavaScript, ASP commands should be ended with semicolon. If-Then-Else Example: <% Dim x x=TRUE If x=TRUE then Response.Write OK Else Response.Write ERROR End If %> Some important points should be followed: The condition after the If must be followed by the Then keyword. If only a single statement is to be executed in the Then block, it may directly follow the Then on the same line. If there are multiple statements to execute in the Then-block, the first statement should begin on the line after Then. The Else-block is optional. The complete set of statements in the Then-block as well as the Else block need to be closed by the End If keyword. This is very important, and the source of many hard-to-locate errors. For-Next Loop Example: <% For i = 1 to 10 Response.Write "Number = " & i Response.Write "
" Next %> Next keyword is used to indicate the end of For loop. Each Next statement encountered is automatically assumed to complete the immediately preceding For statement. <% For i = 1 to 8 For j =1 to 8 Response.Write X Next Response.Write
Next %> For-Each Loop To iterate through the items in a collection one by one, for-each loop is used. Including Other Files Server-Side Includes (SSI) is a mechanism you can use to insert information into a file prior to processing. As we have the #include statement in C, we have the #include directive here. The purpose is exactly similar: #INCLUDE actually includes the said file at the given location. Any script that is present within that file is automatically executed. Include files are typically used to store application-wide functions and procedures, as well as various utility functions, You can put such functions in 1 file, and include that in all files you need. Use the following syntax: Here you must type either VIRTUAL or FILE, which are keywords that indicate the type of path you are using to include the file, and filename is the path and file name of the file you want to include. Included files do not require a special file-name extension; however, Microsoft recommends giving included files an .inc file-name extension to distinguish them from other types of files. Using the Virtual Keyword Use the Virtual keyword to indicate a path beginning with a virtual directory. For example, if a file named footer.inc resides in a virtual directory named /myapp, the following line would insert the contents of footer.inc into the file containing the line: Using the File Keyword Use the File keyword to indicate a relative path. A relative path begins with the directory that contains the including file. For example, if you have a file in the directory myapp, and the file header1.inc is in myapp/headers, the following line would insert header1.inc in your file: Note that the path to the included file, headers/header1.inc, is relative to the including file; if the script containing this include statement is not in the directory /myapp, the statement would not work. Including Files: Tips and Cautions An included file can, in turn, include other files. An .asp file can also include the same file more than once, provided that the statements do not cause a loop. For example, if the file first.asp includes the file second.inc, second.inc must not in turn include first.asp. Nor can a file include itself. ASP detects such loop or nesting errors, generates an error message, and stops processing the requested .asp file. ASP includes files before executing script commands. Therefore, you cannot use a script command to build the name of an included file. For example, the following script would not open the file header1.inc because ASP attempts to execute the #Include directive before it assigns a file name to the variable name. <% name=(header1 & ".inc") %> Scripts commands and procedures must be entirely contained within the script delimiters <% and %>, the HTML tags , or the HTML tags and . That is, you cannot open a script delimiter in an including .asp file, and then close the delimiter in an included file; the script or script command must be a complete unit. For example, the following script would not work: <% For i = 1 To n statements in main file Next %> The following script would work: <% For i = 1 to n statements in main file %> <% Next %> Collections A collection is similar to a data structure or array. Individual items in the collection are accessed via a unique key assigned to that item. They give unique and extended information about the object. In a large company, you can have a manufacturing component, a sales component, a human resources component, and so on. In making an analogy to ASP object collections, think of these company components as exposing specific attributes of the company. ASP OBJECTS (BUILT IN OBJECTS) Request Object The Request object provides access to all of the information that is passed in a request from the browser to the server. This information is stored among five types of Request collections. Properties 1) TotalBytes Description: This is the read only property. It specifies the total number of bytes the client is sending in the body of the request. The value returned by TotalBytes can be used as the argument of Request.BinaryRead(Count). Syntax: Request.TotalBytes Exqmple:
Name:
Age:
Sex:

<% Dim ByteCount ByteCount = Request.TotalBytes Response.Write("ByteCount = " & ByteCount & " bytes") %> Methods 1) BinaryRead Description: This method retrieves the data that was sent to the server from the user as part of an HTTP POST (i.e. an HTML FORM request). The data read is stored in an array which is a variant, structure-like array that, in addition to storing the data. You can write binary data into the response stream (info sent to a client) by using the Response.BinaryWrite(BinaryData) method. The BinaryData argument is simply the output (the SafeArray) from Request.BinaryRead. For example, you could retrieve an image from a database with Request.BinaryRead and send it to a client using Response.BinaryWrite. Using Request.Form after calling BinaryRead, and vice-versa, will cause an error. There is one mandatory argument. Syntax: Request.BinaryRead(Count) where, count: contains the number of bytes to read Example: <% dim bytecount dim binread bytecount = Request.TotalBytes binread = Request.BinaryRead(bytecount) if byteCount <> 0 then Response.Write "Bytes Read: "&bytecount end if %> Collections ClientCertificate Description: This collection retrieves the certification fields from a request issued by the web browser. If a web browser uses the SSL protocol (in other words, it uses a URL starting with https:// instead of http://) to connect to a server , the browser sends the certification fields. SSL also known as Secure Socket Layer is be used to send data in a secure way. If no certificate is sent, the ClientCertificate collection returns EMPTY. Syntax: Request.ClientCertificate(Key [SubField]) where, Key: is used to specify the name of the field to retrieve from the client certification, a compulsory argument. Possible values are: Issuer: is a string containing the subfield values that provide information about the issuer of the certificate. SerialNumber: is a string that contains the certification serial number. Subject: is a string containing the subfield values that provide information about the subject of the certificate. ValidFrom: is the date when the certificate becomes valid. ValidUntil: is the expiration date of the certificate SubField: is used to get an individual field in Issuser or Subject key SubField: This is the optional argument which is used only with the Issuer or the Subject key fields. It is added to the key field as a suffix. Possible values are: C: is the name of the country of origin. CN: is the common name of the user. GN: is a given name. I: is a set of initials. L: is a locality. O: is the company or organization name. OU: is the name of the organizational unit. S: is a state or province. T: is the title of the person or organization. Example: This certification is valid from <%= Request.ClientCertificate("ValidFrom") %> until <%= Request.ClientCertificate("ValidUntil") %> Cookies Description: The Cookies collection property contains the values of the cookies sent in the request. The Cookies collection property allows you to access the values of the browser cookies sent in by requests. Cookies are small files, which stores information on the clients system. Websites like Hotmail, Yahoo and even TopXML uses cookies. Some websites like GMail doesnt even work if you have cookies disabled. These mentioned websites uses cookies to store the username and password in a cookie, so that each time you visit the website, you dont need to login again. You can either create a new cookie or override the existing value. Syntax: Request.Cookies(cookie name)[(key)|.attribute] where, cookiename: specifies the cookie whose value should be retrieved. key: specifies which value from the cookie dictionary to retrieve. attribute: The optional argument which is the boolean variable HasKeys. True indicates that the cookie contains keys. False indicates that the cookie does not contains keys To determine whether a cookie is a cookie dictionary (whether the cookie has keys), use the following script. <%= Request.Cookies("myCookie").HasKeys %> Example: <% for each objCK In Request.Cookies Response.Write objCK & " = " & Request.Cookies(objCK) & "
" Next %> Form Description: The Form collection allows you to retrieve the information input into an HTML form on the client and sent to the server using the POST method. This information resides in the body of the HTTP request sent by the client. Most forums use this property to post new threads or replies. Syntax: Request.Form(element)[(index)|.Count] where, element: is the name of the
element which is used to retrieve a value. index: is an optional parameter which is used when the element argument has more than one value. It is an integer, ranging from 1 to Request.Form(Element).Count, which is used to select values from a element. Count is the total number of multiple values. Example: First Name:
Favourite IceCream Flavour:
<%=Request.Form("fnm")%> <%=Request.Form("flavour")%> <% For i = 1 To Request.Form("flavor").Count Response.Write Request.Form("flavor")(i) & "
" Next %> If you refer to an element without an index and that element contains multiple values, your code will return a comma-delimited string. Query String Description: The QueryString collection retrieves the values of the variables in the HTTP query string. The HTTP query string is specified by the values following the question mark (?). Several different processes can generate a query string. For example, the anchor tag string sample Generates a variable named string with the value "this is a sample". Query strings are also generated by sending a form, or by a user typing a query into the address box of their browser. The Request.QueryString property can be used to retrieve the values from a form, which is posted via the GET method. The query string stores the values in a pair combination after the? sign in the URL. It looks like this: Elementname=Value. The QueryString collection is less capable than the Form collection, since there is a limit to the amount of data that can be sent in the header of an HTTP request. This limit is around 2000 characters. More characters than this, sent as part of the QueryString, will not be processed, although the script still executes. Syntax: Request.QueryString(variable)[(index)|.Count] where, variable: specifies the name of the variable in the query string whose value is to be retrieve. index: is the optional argument which is used when the variable argument has more than one value. It is an integer, ranging from 1 to Request.QueryString(Variable).Count, which is used to select values from the variable. Count is the total number of multiple values. Example: <% if Request.QueryString("username") <> "" then Response.Write "Welcome " & Request.QueryString("Username") end if %>
Username:
<% For i = 1 To Request.QueryString("username").Count Response.Write Request.QueryString("username ")(i) & "
" Next %> ServerVariables Description: The ServerVariables collection retrieves the values of predefined server environmental variables in the context of the clients specific HTTP request of the web server. This allows access to the HTTP headers. Syntax: Request.ServerVariables (server environment variable) where, ALL_HTTP: This variable can be used to retrieve all HTTP headers. This variables places the HTTP_ prefix before the header name and the header name is always in capital. ALL_RAW: This variable retrieves all headers in raw form. The values appear in the same as they are sent. It does not add a prefix like All_HTTP does. APP_POOL_ID: This variable returns the name of the application pool that is running in IIS worker process. This variable is not available in IIS 5.1 or below. Running this server variable on IIS 6.0 returns: DefaultAppPool APPL_MD_PATH: This variable can be used to retrieve the metabase path of the application. Running this on my localhost returns: APPL_MD_PATH: /LM/W3SVC/1/Root/ASP_Examples APPL_PHYSICAL_PATH: This variable can be used to retrieve the physical path corresponding to the metabase path in APPL_MD_PATH. On my system when I run the asp examples for this reference, it returns: APPL_PHYSICAL_PATH: C:\Simulate_D\Customers\TopXML\References\ASP_Examples\ AUTH_PASSWORD: This variable retrieves the password entered in the client's authentication dialog. This variable is available only if basic authentication is used. AUTH_TYPE: This is the authentication method that the server uses to validate users when they access a protected script. If you are not using any authentication it will return: Negotiate. AUTH_USER: This is the name of the user. Running this on my localhost returns: SONU_LAPTOP\sonu (in the format machinename\login) CACHE_URL: This value returns the name of the URL. It is only used in ISAPI applications. This value can be only used for IIS 5.1 or below. CERT_COOKIE: This is the unique ID from the client certificate. It is returned as a string. CERT_FLAGS: CERT_FLAGS is a two-bit value, bit 0 and bit 1. Bit 0 returns 1 if the client certificate is available. If it's invalid then bit 1 return 1. Invalid means the issuer is not found in the list of verified certificate issuers that resides on the web server). Note that these two bit values correspond to ceCertPresent and ceUnrecognizedIssuer constants. CERT_ISSUER: The issuer of the client certificate, if one exists. The value of this element is a comma-delimited string that contains the subfields for each of the possible subelements described in the Issuer element section of the ClientCertificate collection explanation earlier in this chapter. CERT_KEYSIZE: This value can be used to return the number of bits in a SSL connection. For example 64 or 128. CERT_SECRETKEYSIZE: This value can be used to return the number of bits in the server certificate. For example 1024. CERT_SERIALNUMBER: his value returns the serial number of the client certificate. CERT_SERVER_ISSUER: This value returns the issuer field of the server. CERT_SERVER_SUBJECT: This value returns the subject field of the server certificate. CERT_SUBJECT: This value returns the subject field of the client certificate. This returns a comma-delimited string containing the subfields described in the Subject element section of the ClientCertificate collection description. CONTENT_LENGTH: This value returns the length of the content. Running this example on my localhost returns: 0 CONTENT_TYPE: This value returns the type of the content, which can be GET, POST or PUT. GATEWAY_INTERFACE: This value returns the revision of the CGI specification used by the server. On my localhost it returns: CGI/1.1 HTTP_ [HeaderName]: The value sent in the HTTP header called headername. To retrieve the value of any HTTP header not mentioned in this list (including custom headers), you must prefix the header name with HTTP_. Attempting to retrieve a nonexistent header returns an empty string, not an error. HTTP_ACCEPT: This value returns the value of the accept header, which contains a list of accepted formats like: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel. On my system it returns: */* HTTP_ACCEPT_LANGUAGE: This value returns the language, which is used for the content. On my system it returns en-us HTTP_COOKIE: This value returns the cookie string. On my system it returns: _Tab_Admin_Preview0=True;_Module4_Visible=true;Module335_Visible=true; .DOTNETNUKE=265948BAB1E6ACCDF503CBA5A4C12... HTTP_REFERER: This value returns the original URL when a redirect has occurred. It can be used in website statistics to show the original URL from where the visitor came from. HTTP_USER_AGENT: This value returns information about the client browser. On my system it returns: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SYMPA; MyIE2; SV1; .NET CLR 1.1.4322) HTTPS: This value returns either ON if the request was made securely or OFF if the request came through a non-secure channel. When used on the URL http://www.topxml.com/default.asp the returned result is OFF. When used on the URL https://www.topxml.com/default.asp the returned result is ON. HTTP_KEYSIZE: This value returns the number of bits in a SSL connection. HTTP_SECRETKEYSIZE: This value can be used to return the number of bits in the server certificate. HTTPS_SERVER_ISSUER: This value returns the issuer field of the server certificate. HTTPS_SERVER_SUBJECT: This value returns the subject field of the server certificate. INSTANCE_ID: This value returns the ID of the IIS instance. On my localhost it returns: 1 INSTANCE_META_PATH: This value is the meta base path for the instance of IIS that responds to a request. On my localhost it returns: /LM/W3SVC/1 LOCAL_ADDR: This value returns the server address on which the request came in. If you use localhost, then it will return: 127.0.0.1, but if you use the domain name then it will return the public IP. LOGON_USER: This value returns the windows account that the user is logged in, regardless of the security type you are using (anonymous, basic, or Windows NT challenge/response). On my system it returns: SONU_LAPTOP\sonu PATH_INFO: This value returns the extra path information. If yo use this variable on: http://sonu_laptop/mydir/test.asp then it will return: /mydir/test.asp PATH_TRANSLATED: This value returns the translated version of the PATH_INFO from virtual to physical mapping. QUERY_STRING: This value returns the query information stored in the string. When used on the URL: http://www.topxml.com/code/default.asp?p=3&id=v20040906064945&ms=10&l=&sw=All the returned result is only the querystring p=3&id=v20040906064945&ms=10&l=&sw=All REMOTE_ADDR: This value returns the remote IP address. REMOTE_HOST: This value returns the remote host name. REMOTE_USER: This value returns an unmapped username sent by the user. REQUEST_METHOD: This value returns the method used to make the request, such as GET, POST, HEAD SCRIPT_NAME: This value returns the virtual path of the script. When used on this url http://www.topxml.com/asp/default.asp it will return /asp/default.asp. SERVER_NAME: This value returns the servers hostname, DSN or IP. On http://www.topxml.com/default.asp it returns www.topxml.com SERVER_PORT: This value returns the port on which the request was sent. Usually its port 80. SERVER_PORT_SECURE: This value returns the sting that contains either 0 or 1. 1 means that it is handled on a secure port and 0 means that it not a handled on a secure port. When used on the URL http://www.topxml.com/default.asp the returned result is 0. When used on the URL https://www.topxml.com/default.asp the returned result is 1. SERVER_PROTOCOL: This value returns the name and revision about the request information protocol. SERVER_SOFTWARE: This value returns the name and version of the software that response to the request. If IIS 5.1 is installed, this variable returns Microsoft-IIS/5.1. URL: This value returns the base portion of the URL. When used on this url http://www.topxml.com/asp/default.asp it will return /asp/default.asp. Example: <% IPAddress = Request.ServerVariables("REMOTE_ADDR") Software = Request.ServerVariables("SERVER_SOFTWARE") Protocol = Request.ServerVariables("SERVER_PROTOCOL") Response.Write "Your IP Address is " & IPAddress & " and your server is running " & Software & " under " & Protocol & "protocol." %> Response Object As the Request object allows you to retrieve and manipulate information sent by the client browser in its HTTP request, the Response object gives you a great deal of control over the HTTP response to the client. It is the object which communicates between the server and the output which is sent to the client. Properties: Buffer Description: The Buffer property indicates whether to buffer page output. When page output is buffered, the server does not send a response to the client until all of the server scripts on the current page have been processed, or until the Flush or End method has been called. The Buffer property cannot be set after the server has sent output to the client. For this reason, the call to Response.Buffer should be the first line of the .asp file. Syntax: Response.Buffer [= flag] where, flag: specifies whether or not to buffer page output. Possible values are: false - No buffering. This is the default value. The server sends output to the client as it is processed. true - The server does not send output to the client until all of the ASP scripts on the current page have been processed, or until the Flush or End method has been called. Example: <% response.Buffer = true %> <% for i = 1 to 100 response.write(i & "
") next %> Page output is buffered CacheControl Description: The CacheControl allows you to set whether proxy servers serving your pages can cache your page. If your pages content is large and doesnt change often, you might want to allow proxy servers to cache the page and thus serve it faster to requesting client browsers. Syntax: Response.CacheControl [=control_header] where, control_header: A cache control header that can be set to "Public" or "Private", a string value. Private - is default and indicates that only private caches may cache this page. Proxy servers will not cache pages with this setting. Public - indicates public caches. Proxy servers will cache pages with this setting. Example: <% Response.CacheControl = "Private" %>

Please enter your bank account number and password to login

Number:
Password:
ContentType Descripton: The ContentType property specifies the HTTP content type for the response. This string is usually of the format type/subtype where type is the general content category and subtype is the specific content type. If no ContentType is specified, the default is text/HTML. Syntax: Response.ContentType [= contenttype ] where, contenttype: A string describing the content type. Possible Values are: text/HTML, image/GIF, image/JPEG, text/plain Example: <% If strData = "jpg" Then Response.ContentType = "image/JPEG" Else Response.ContentType = "text/plain" End If %> Expires Description: The Expires property specifies the length of time before a page cached on a browser expires. If the user returns to the same page before it expires, the cached version is displayed. Syntax: Response. Expires [= number] where, number: The time in minutes before the page expires. Set this parameter to 0 to have the cached page expire immediately. Example: <% Response.Expires = -1 %> Expires Absolute Description: The Expires Absolute property specifies the date and time at which a page cached on a browser expires. If the user returns to the same page before that date and time, the cached version is displayed. If a time is not specified, the page expires at midnight of that day. If a date is not specified, the page expires at the given time on the day that the script is run. Syntax: Response.ExpiresAbsolute [= [date] [time]] where, date: Specifies the date on which the page will expire. If this parameter is not specified, the page will expire at the specified time on the day that the script is run. time: Specifies the time at which the page will expire. If this parameter is not specified, the page will expire at midnight of the specified day. Example: The following example specifies that the page will expire 15 seconds after 1:30 pm on May 31, 2002. <% Response.ExpiresAbsolute=#May 31, 2002 13:30:15# %> IsClientConnected Description: The IsClientConnected property is a read-only property that indicates if the client has disconnected from the server since the last Response.Write. it evaluates to True if the client is still connected to the web server and returns False otherwise. Syntax: Response.IsClientConnected ( ) Example: <% 'check to see if the client is connected If Not Response.IsClientConnected Then 'get the sessionid to send to the shutdown function Shutdownid = Session.SessionID 'perform shutdown processing Shutdown(Shutdownid) End If %> Status Description: The Status property specifies the value of the status line returned by the server. Status values are defined in the HTTP specification. Use this property to modify the status line returned by the server. Syntax: Response.Status = statusdescription where, statusdescription: is a string value containing a three-digit status code that indicates the status of the HTTP request and a short explanation of the status code. Example: <% Response.Status = "401 Unauthorized" %> Methods AddHeader Description: The AddHeader method adds user defined HTML header with a specified value. This method always adds a new HTTP header to the response. If you add an HTTP header with the same name as a previously added header, the second header will be sent in addition to the first; adding the second header does not overwrite the value of the first header with the same name. Once a header has been added, it cannot be removed. If the client sends the web server an HTTP header other than those listed in the ServerVariables collection, you can use HTTP_HeaderName to retrieve it. For example, if the client sends the HTTP header: ClientCustomHeader:CustomHeaderValue then you could retrieve the value for this element using the following syntax: <% Request.ServerVariables("HTTP_ClientCustomHeader") %> This is an advanced method and should not be used without careful planning. If another method of the Response object is satisfying your needs, use it instead of using the AddHeader method. Syntax: Response.AddHeader name, value where, name: the name of the new header variable. value: the value stored in the new header variable. Example: <% ' The following code adds the CUSTOM-ERROR HTML header to ' the HTTP response headers. Response.AddHeader "CUSTOM-ERROR", "Your browser is not IE." %> Because HTTP protocol requires that all headers be sent before content, you must call AddHeader in your script before any output (such as that generated by HTML code or the  HYPERLINK "http://www.html.dk/dokumentation/objects/asp/intr2w2t.htm" Write method) is sent to the client. The exception to this rule is when the  HYPERLINK "http://www.html.dk/dokumentation/objects/asp/intr1fsi.htm" Buffer property is set to TRUE. If the output is buffered, you can call the AddHeader method at any point in the script, as long as it precedes any calls to  HYPERLINK "http://www.html.dk/dokumentation/objects/asp/intr74tk.htm" Flush. Otherwise, the call to AddHeader will generate a run-time error. You should not use underscores in your custom headers. Doing so will increase your chances of uncertainty with headers already present. Use hyphens to separate multiple words instead. Also, to retrieve the value of a custom header with hyphens, replace them with underscores when retrieving the values of your custom headers. AppendToLog Description: The AppendToLog method adds a string to the end of the Web server log entry for the request. You can call it multiple times in one section of script. Each time the method is called it appends the specified string to the existing entry. You can only add up to 80 characters at a time, but you are able to call the AppendToLog method multiple times. Specifically, you can log the following aspects of users visits to your web site, among other things: Date/time of user visit Requested pages IP address of user Length of time connected to server Syntax: Response.AppendToLog strlogentry where, strlogentry: The string to append to the log file. Because fields in the IIS log are comma-delimited, this string cannot contain any comma characters (,). The maximum length of this string is 80 characters. Example: <% Response.Write "Writing to log fie...
" Response.AppendToLog "Isnt this useful?" Response.Write "Log fie written...
" %> Binary Write Description: The Binary Write method writes the specified information to the current HTTP output without any character conversion. This method is useful for writing nonstring information such as binary data required by a custom application. Syntax: Response.BinaryWrite data where, data: is the array of data to send to the HTTP output. Example: <% ' The following code retrieves a binary object ' (in this case a JPG image) and writes it to the ' client using BinaryWrite. (For more information ' on ActiveX Data Objects usage, see Chapter 11.) ' Create an ADO connection object. Set adoCon = Server.CreateObject("ADODB.Connection") ' Use the Open method of the Connection object ' to open an ODBC connection with the database ' represented by the DSN ImageDatabase. adoCon.Open "ImageDatabase" ' Use the Execute method of the ADO Connection object ' to retrieve the binary data field from the database. Set adoRecImgData = adoCon.Execute ("SELECT ImageData FROM Images WHERE ImageId = 1234") ' Create a Field object by setting one equal to a ' specific field in the recordset created previously. Set adoFldImage = adoRecImgData("ImageData") ' Use the ActualSize property of Field object to retrieve ' the size of the data contained in the Field object. After ' this line you will know how many bytes of data reside in ' the Field object. lngFieldDataLength = adoFldImage.ActualSize ' Use the BinaryWrite method to write 4K bytes of binary ' data at a time. So, first we need to determine how many ' 4K blocks the data in the Field object represents. lngBlockCount = lngFieldDataLength / 4096 ' Now lets get how many bytes are left over after removing ' lngBlockCount number of bytes. lngRemainingData = lngFieldDataLength Mod 4096 ' We now must set the HTTP content type Response header ' so that the browser will recognize the data being sent ' as being JPEG image data. Response.ContentType = "image/JPEG" ' Loop through and write the first lngBlockCount number ' of binary blocks of data. For intCounter = 1 to lngBlockCount Response.BinaryWrite adoFldImage.GetChunk(4096) Next ' Now write the last remainder of the binary data. Response.BinaryWrite adoFldImage.GetChunk(lngRemainingData) ' Close the recordset. adoRecImgData.Close %> Displays image data that is stored and retrieved from a DBMS capable of storing binary data. Clear Description: The Clear method erases any buffered HTML output. However, the Clear method only erases the response body; it does not erase response headers. You can use this method to handle error cases. Note that this method will cause a run-time error if Response.Buffer has not been set to TRUE. Syntax: Response.Clear Example: <% Response.Buffer=true %>

This is some text I want to send to the user.

No, I changed my mind. I want to clear the text.

<% Response.Clear %> Cleared End Description: The End method causes the Web server to stop processing the script and return the current result. The remaining contents of the file are not processed. Syntax: Response.End Example: <% Response.Write ("Hello World") Response.End Response.Write ("Is this the End?") %> Flush Description: The Flush method sends buffered output immediately. This method will cause a run-time error if Response.Buffer has not been set to TRUE. Syntax: Response.Flush Example: <% Response.Buffer = true %>

This text will be sent to your browser when my response buffer is flushed.

<% Response.Flush %> Redirect Description: The Redirect method causes the browser to attempt to connect to a different URL. Syntax: Response.Redirect url where, url: The url that the browser is redirected to. Example: ResponseRedirect.asp <% Response.Buffer = true %> <% Response.Write "This is ResponseRedirect.asp" Response.Clear Response.Redirect "ResponseFlush.asp" %> ResponseRedirectReply.asp <% Response.Write "This is ResponseRedirect.asp" %> Write Description: Writes information directly to the HTTP response body. You can also use <%= %> in HTML if you do not want to use Response.Write. Syntax: Response.Write variant where, Example: I just want to say <% Response.Write "Hello World." %> Collections Cookies Description: The Cookies collection sets the value of a cookie. If the specified cookie does not exist, it is created. If the cookie exists, it takes the new value and the old value is discarded. Syntax: Response.Cookies(Name)[(Key)|.Attribute]=Value where, name: is the name of the cookie. key: optional argument which specifies the key to which the value is assigned. attribute: optional argument which can one of the five following parameters: Domain - write-only and allows pages on a domain made up of more than one server to share cookie information. Expires - write-only and is the date on which the cookie expires. Unless a date is specified, the cookie will expire when the session ends. If a date is specified, the cookie will be stored on the client's disk after the session ends. HasKeys - read-only and uses Boolean values to specify whether the cookie contains keys. Path - write-only and if set, the cookie is sent by this path. If this argument is not set, the default is the application path. Secure - write-only and indicates if the cookie is secure. value: specifies the value to assign to the key or attribute. Example: <% Response.Cookies("lastname") = "Peterson" Response.Cookies("user")("firstname") = "Andrew" Response.Cookies("user")("lastname") = "Cooper" %> <% 'The code below iterates through the Cookies collection. 'If a given cookie represents a cookie dictionary, then 'a second, internal for...each construct iterates through 'it retrieving the value of each cookieKey in the dictionary. Dim cookie Dim cookieKey for each cookie in Request.Cookies if Request.Cookies(cookie).HasKeys Then 'The cookie is a dictionary. Iterate through it. %> The cookie dictionary <%=cookie%> has the following values:
<% for each cookieKey in Request.Cookies(cookie) %>     cookieKey: <%= cookieKey %>
    Value: <%= Request.Cookies(cookie)(cookieKey)%>
<% next else 'The cookie represents a single value. %> The cookie <%=cookie%> has the following value: <%= Request.Cookies(cookie)%>
<% end if next %> Session Object You can use the Session object to store information needed for a particular user-session. Variables stored in the Session object are not discarded when the user jumps between pages in the application; instead, these variables persist for the entire user-session. The web server automatically creates a Session object when a user who does not already have a session requests a web page from the application. The server destroys the Session object when the session expires or is abandoned. One common use for the Session object is to store user preferences. A user session can be initiated in one of three ways: A user not already connected to the server requests an Active Server Page that resides in an application containing a GLOBAL.ASA file with code for the Session_OnStart event. A user requests an Active Server Page whose script stores information in any session-scoped variable. A user requests an Active Server Page in an application whose GLOBAL.ASA file instantiates an object using the tag with the SCOPE parameter set to Session. Note that a user session is specific to a given application on your web site. The web server identifies each user with a unique SessionID value. This SessionID variable is assigned to each user at the beginning of his session on the web server and is stored in memory on the web server. The SessionID is stored on the client by writing a cookie containing the SessionID to the users machine. This cookie is sent to the server each time the user makes a request. To identify the user, the server retrieves the cookie and matches it up with a SessionID held in memory. What if the user has cookies turned off or is using an older browser that does not support the use of cookies? Well, if you are using Windows NT or Basic Authentication, you can identify the user from the LOGON_USER element of the Request objects ServerVariables collection. From this information, you can retrieve user-specific data from a database or text files on the server. If you are not using Windows NT or Basic Authentication, you will likely not be able to identify the user. Properties CodePage Description: Specifies or retrieves the code page that will be used by the web server to display dynamic content in the current script. A code page is a character set containing all the alphanumeric characters and punctuation used by a specific locale. Syntax: Session.CodePage (= intCodePageValue) where, intCodePage: An unsigned integer corresponding to a specific character set installed on the server. Setting the CodePage property will cause the system to display content using that character set. Possible Values are: 932 Japanese Kanji 950 Chinese 1252 American English (& most European languages) Example: <% Response.Write(Session.CodePage) %> SessionID Description: A read-only value that uniquely identifies each current users session. Each session has a unique identifier that is generated by the server when the session is created. The session ID is returned as a LONG data type and is stored as a cookie on the client machine. During a users session, the users browser sends this cookie to the web server as a means of identifying the user. The SessionID property is generated the first time a user requests a page from the web server. The web server creates a value for the SessionID property using a complex algorithm and then stores this value in the form of a cookie on the users machine. Subsequently, each time the user requests a page from the web server, this cookie is sent to the server in the HTTP request header. The server is then able to identify the user according to his SessionID. The cookie is reinitialized only when the client restarts his browser or when the webmaster restarts the web server. Note that the SessionID cookie lasts on the client browser and is sent to (and recognized by) the web server until one of the two machines (client or web server) is restarted. This time period has nothing to do with the Timeout property of the Session object. For example, assume a users session ends or is abandoned by using the Abandon method of the Session object. Then the user (without having restarted his browser) revisits the site. Assuming also that the web server has not been restarted since the end of the last session, the web server will start a new session for the user but will use the same SessionID, which is again sent to the web server as part of the HTTP request. Only if both the client browser and the web server applications have not been restarted can you assume a SessionID uniquely identifies a user. Do not use this value as a primary key, for example, as it is reset anytime either browser or server is stopped and restarted. Browser that does not support cookies or that has cookies turned off will not send the SessionID as part of the HTTP request header. In this case, you must rely on some other method to identify users. To maintain information without using cookies, you could either append information from each request onto the QueryString or post the identifying information from a hidden form element on your page. Syntax: Session.SessionID Example: <% Response.Write(Session.SessionID) %> Timeout Description: This property specifies the timeout period assigned to the Session object for the application, in minutes. If the user does not refresh or request a page within the timeout period, the session ends. Syntax: Session.Timeout (= intMinutes) where, intMinutes: Specifies the number of minutes that a session can remain idle before the server terminates it automatically. The default is 20 minutes. Example: <% Response.Write "Default session timeout is: " & Session.TimeOut & "

" Response.Write "Setting new session timeout...

" Session.TimeOut = 15 Response.Write "Your new session timeout will expire in " & Session.TimeOut & " minutes. " %> Methods Abandon Description: The Abandon method destroys all the objects stored in a Session object and releases their resources. If you do not call the Abandon method explicitly, the server destroys these objects when the session times out. The Abandon method is actually processed by the web server after the rest of the current pages script is processed. After the current pages processing is complete, however, any page request by the user initiates a new session on the web server. Syntax: Session.Abandon Example: <% Session("name")="Hello" Session.Abandon Response.Write(Session("name")) %> <% Response.Write(Session("name")) %> Events Session_OnEnd Description: This event occurs when a session is abandoned or times out. Of the server built-in objects, only the  HYPERLINK "http://www.html.dk/dokumentation/objects/asp/intr8zw4.htm" Application,  HYPERLINK "http://www.html.dk/dokumentation/objects/asp/intr7838.htm" Server, and  HYPERLINK "http://www.html.dk/dokumentation/objects/asp/intr12d0.htm" Session objects are available. The OnEnd event procedure, if it exists, resides in the GLOBAL.ASA file for the application that contains the requested page. One of the possible uses of the Session_OnEnd event is to write information concerning the user to a log file or other text file on the server for later use. If you intend to do this, there are several important points you must remember. First, before you can save any information, that information must be saved to a session variable because, as mentioned earlier, you do not have access to the Request object, which is the most common source of user information. You cannot use the AppendToLog method of the Response object, because the Response object is unavailable. In addition, if you intend to write directly to the web servers hard drive, you must know the physical path of the file to which you want to write. This is because, although you do have access to the Server object, you cannot use its MapPath method in the Session_OnEnd event. Syntax: Example: In global.asa file, In test file,

There are <%response.write(Application("visitors"))%> online now!

Session_OnStart Description: This event occurs when the server creates a new session. The server processes this script prior to executing the requested page. The Session_OnStart event is a good time for you to set any session-wide variables, because they will be set before any pages are accessed. All the built-in objects ( HYPERLINK "http://www.html.dk/dokumentation/objects/asp/intr8zw4.htm" Application,  HYPERLINK "javascript:if(confirm('http://www.activeserverpages.dk/iishelp/iis/htm/sdk/crtc4tpw.htm%20%20\\n\\nThis%20file%20was%20not%20retrieved%20by%20Teleport%20Pro,%20because%20it%20is%20addressed%20on%20a%20domain%20or%20path%20outside%20the%20boundaries%20set%20for%20its%20Starting%20Address.%20%20\\n\\nDo%20you%20want%20to%20open%20it%20from%20the%20server?'))window.location='http://www.activeserverpages.dk/iishelp/iis/htm/sdk/crtc4tpw.htm'" ObjectContext,  HYPERLINK "http://www.html.dk/dokumentation/objects/asp/intr5ulw.htm" Request,  HYPERLINK "http://www.html.dk/dokumentation/objects/asp/intr5sj8.htm" Response,  HYPERLINK "http://www.html.dk/dokumentation/objects/asp/intr7838.htm" Server, and  HYPERLINK "http://www.html.dk/dokumentation/objects/asp/intr12d0.htm" Session) are available and can be referenced in the Session_OnStart event script. The Session_OnStart event procedure, if it exists, resides in the GLOBAL.ASA file for the application that contains the requested page. If the clients browser does not support cookies or if the user has manually turned cookies off, the Session_OnStart event is processed every time the user requests a page from the site. No session is started or maintained. Like the OnEnd event, one of the possible uses of the OnStart event is to write information concerning the user to a log file or other text file on the server for later use. If you intend to do this, note that you cannot use the AppendToLog method of the Response object, and if you intend to write directly to the web servers hard drive, you must know the physical path of the file to which you want to write. This is because, although you do have access to the Server object, just as in the OnEnd event of the Session object, you cannot use the MapPath method of the Server object in the Session_OnStart event. Syntax: Example: Same as above. Collections Contents Description: The Contents collection holds any variables stored in the Session object. It also holds any objects created by calling Server.CreateObject. Syntax: Session.Contents(key) where, key: Represents the name of a specific element in the collection. Example: Suppose you have stored the following user information in the Session object: <% Session.Contents("FirstName") = "Sam" Session.Contents("LastName") = "Hello" Session.Contents("Age") = 29 %> You can access an item by using the name you associated with the item when you stored it in the collection. For example, the following expression returns the string "Sam": <%= Session.Contents("FirstName") %> You could also access an item by using the index, or number, associated with an item. For example, the following expression retrieves the information stored in the second slot of the Session object and returns "Hello": <%= Session.Contents(2) %> You can access items by name using a shorthand notation. ASP searches the collections associated with an object in a particular order. If an item with a particular name appears only once in an object's collections, you can eliminate the collection name: <%= Session("FirstName") %> StaticObjects Description: This collection contains all of the objects with session-level scope that are added to the application through the use of the tag. You can use this collection to retrieve properties of a specific object in the collection. You also can use this collection to use a specific method of a given object in the collection. Objects instantiated using Server.CreateObject are not accessible through this collection. Objects created in the GLOBAL.ASA file are not actually instantiated on the server until the first time a property or method of that object is called. For this reason, the StaticObjects collection cannot be used to access these objects properties and methods until some other code in your application has caused them to be instantiated on the server. Syntax: Session.StaticObjects(Key) where, key: Represents the name of a specific element in the collection. Example: strFirstObjName = Session.StaticObjects.Key(1) The above line retrieves the name of the first element in the StaticObjects collection of the Session object. Application Object You can use the Application object to share information among all users of a given application. An ASP-based application is defined as all the .asp files in a virtual directory and its subdirectories. Because more than one user can share the Application object, there are Lock and Unlock methods to ensure that multiple users do not try to alter a property simultaneously. You can store values in the Application Collections. Information stored in the Application collections is available throughout the application and has application scope. The Application object is initialized by IIS the moment the first client requests any file from within the given virtual directory. you can customize this initialization by including code in a special optional file called GLOBAL.ASA. It remains in the servers memory until either the web service is stopped or the application is explicitly unloaded from the web server using the Microsoft Management Console. IIS allows you to instantiate variables and objects with application-level scope. This means that a given variable contains the same value for all clients of your application. Methods Lock Description: The Lock method blocks other clients from modifying the variables stored in the Application object, ensuring that only one client at a time can alter or access the Application variables. If you do not call the Unlock method explicitly, the server unlocks the locked Application object when the .asp file ends or times out. You cannot create a read-only variable by using a call to the Lock method without a corresponding call to Unlock, since IIS automatically unlocks the Application object. You do not have to call the Lock and Unlock methods in the Application_OnStart event procedure. The Application_OnStart event occurs only once regardless of the number of sessions that are eventually initiated. Syntax: Application.Lock Example: <% Response.Buffer=false Application.Lock Application("TotalNumPage2") = Application.Contents("TotalNumPage2") + 1 for i=1 to 300000 a=a+1 b=b+1 a=a-1 b=b-1 next Response.Write "
Value :=" & Application("TotalNumPage2") Application("TotalNumPage2") = Application.Contents("TotalNumPage2") + 1 for i=1 to 300000 a=a+1 b=b+1 a=a-1 b=b-1 next Response.Write "
Value :=" & Application("TotalNumPage2") Application("TotalNumPage2") = Application.Contents("TotalNumPage2") + 1 for i=1 to 300000 a=a+1 b=b+1 a=a-1 b=b-1 next Response.Write "
Value :=" & Application("TotalNumPage2") %> Unlock Description: The Unlock method enables other clients to modify the variables stored in the Application object after it has been locked using the Lock method. If you do not call this method explicitly, the web server unlocks the Application object when the .asp file ends or times out. Syntax: Application.Unlock Example: Same as above... Events Application_OnStart Description: The Application_OnStart event occurs before the first new session is created, that is, before the Session_OnStart event. Only the Application and Server built-in objects are available. Referencing the Session, Request, or Response objects in the Application_OnStart event script causes an error. The Application_OnStart event, if it exists, is the first code run on the server for a given Active Server Pages application. For this reason, it is the best place to initialize application-level variables. Syntax: Example: Application_OnEnd Description: The Application_OnEnd event is triggered when the ASP application itself is unloaded from the web server or when the application is stopped for some reason (i.e., the web service is stopped on the web server). Application_OnEnd is called only once per application. The code for this event procedure resides in the GLOBAL.ASA file and is processed after all other code in the file. It is in the code for the Application_OnEnd event that you will clean up after any application-scoped variables. Only the  HYPERLINK "http://www.html.dk/dokumentation/objects/asp/intr8zw4.htm" Application and  HYPERLINK "http://www.html.dk/dokumentation/objects/asp/intr7838.htm" Server built-in objects are available. Syntax: Example: Collections Contents Description: The Contents collection of the Application object contains all the application- level scoped variables and objects added to the current application through the use of scripts (not through the use of the tag). Syntax: Application.Contents(Key) where, key: Represents the name of a specific element in the Contents collection. Example: You can initialize application-level variables and thus add elements to the Contents collection in one of two ways. First, you can initialize Application variables in the Application_OnStart event procedure in the GLOBAL.ASA file, as given below: <<<<<<<<<<<<<<< FROM GLOBAL.ASA >>>>>>>>>>>>>>>>>> This code resides in the GLOBAL.ASA file at the root of the current application. Sub Application_OnStart Application.Contents.Item(1) = "Georgia" Application.Contents(2) = "Kentucky" Application(3) = "Alabama" Application.Contents.Item("STATE_FOURTH") = "California" Application.Contents("STATE_FIFTH") = "Oregon" Application("STATE_SIXTH") = "Washington" End Sub The above code creates six application-scoped variables, thus adding six elements to the Contents collection. Note that these variables will be instantiated and initialized only at the start of the application, not upon every visit to the site by subsequent users. These variables maintain the same values unless another script changes them for all pages and for all users. Secondly, you can create application-scoped variables and thus add elements to the Contents collection inside any script on any page. The code is as below: <% 'This code exists in the server-side section of a script on the web site. Application.Contents.Item(7) = "Florida" Application.Contents(8) = "Tennessee" Application(9) = "Mississippi" Application.Contents.Item("STATE_TENTH") = "New York" Application.Contents("STATE_ELEVENTH") = "New Jersey" Application("STATE_TWELFTH") = "Vermont" response.write(" " & Application("STATE_TWELFTH")) response.write(" " & Application.Contents("STATE_SIXTH")) %> The above code adds six more application-scoped variables to the application. Note that these variables will be reinitialized every time a user requests the page containing this code StaticObjects Description: This collection contains all of the objects added to the application through the use of the tag. You can add objects to this collection only through the use of the tag in the GLOBAL.ASA file, as in the following example: You cannot add objects to this collection anywhere else in your ASP application. Syntax: Application.StaticObjects(Key) where, key: Represents the name of a specific element in the Contents collection. Example: There are <%= Application.StaticObjects.Count %> items in the Application's StaticObjects collection.
There are <%= Session.StaticObjects.Count %> items in the Session's StaticObjects collection. <% for each a in Session.StaticObjects Response.Write "
"& a next for each a in Application.StaticObjects Response.Write "
"& a next %> Server Object The Server object, as its name implies, represents the web server itself. The Server object provides access to methods and properties on the server. Most of these methods and properties serve as utility functions. Properties ScriptTimeout Description: The ScriptTimeout property specifies the maximum amount of time a script can run before it is terminated. The timeout will not take effect while a server component is processing. If you do not set a value for this property, the default value is 90 seconds. The ScriptTimeout property cannot be set to a value less than that specified in the metabase (Web Server's Registry). Syntax: Server.ScriptTimeout = NumSeconds where, NumSeconds: The number of seconds you want the web server to continue processing your script before it times out, sending the client an ASP error. Example: <% Server.ScriptTimeout = 100 Timeout = Server.ScriptTimeout Response.Write (timeout) %> Methods CreateObject Description: The CreateObject method creates an instance of a server component. Once instantiated, this objects properties and methods can be used just as you can use the properties and methods of the built-in objects that come with ASP. By default, objects created by the Server.CreateObject method have page scope. This means that the server automatically destroys them when it finishes processing the current ASP page. You can also destroy the object by setting the variable to nothing. Syntax: Set myObject = Server.CreateObject( progID ) where, progID: specifies the type of object to create. The format for the strProgId parameter is: [VendorName.]Component[.Version] This value is found in the registry and represents how the components DLL is registered there. You cannot create an object instance with the same name as a built-in object. For example, the following returns an error. <% Set Response = Server.CreateObject ("Response") %> Example: <% Set MyAd = Server.CreateObject ("MSWC.AdRotator") %> The preceding example creates a server component, MyAd, as an MSWC.AdRotator component that can be used to automate rotation of advertisements on a Web page. HTMLEncode Description: If you ever need to display the actual HTML code involved in an HTML page or ASP script, you must use the HTMLEncode method of the Server object. The HTMLEncode method of the Server object allows you to encode the HTML string so that, when it is displayed in the browser, the browser does not simply interpret the HTML as instructions for text layout. If you view source, or open the page as a text file, you will be able to see the encoded HTML. Syntax: Server.HTMLEncode(string) where, string: specifies the string to encode. Example: <%= Server.HTMLEncode("The paragraph tag:

") %> The above code gives the following output: The paragraph tag: < P> MapPath Description: The MapPath method maps the specified relative or virtual path to the corresponding physical directory on the server. The MapPath method does not support relative path syntax (.) or (..). For example, the following relative path, /MyDir/MyFile.txt returns an error. The MapPath method does not check whether the path it returns is valid or exists on the server. Syntax: Server.MapPath(path) where, path: A complete virtual path or a path relative to the path of the current scripts home directory on the server. The method determines how to interpret the string depending on if it starts with either a slash (/) or a backslash (\). If the strPath parameter begins with either of these characters, the string is assumed to be a complete virtual path. Otherwise, the physical path returned is the path relative the current scripts physical directory on the web server. Example: path to current directory
<%= server.mappath(Request.ServerVariables("PATH_INFO"))%> URLEncode Description: Encodes a string that can then be sent over the address line as a query string. Syntax: Server.URLEncode (string) where, string: specifies the string to encode. Example: <% Response.Write(Server.URLEncode("http://www.microsoft.com")) %> FileSystem Object The FileSystem Object is the object that is used to manipulate the filesystem in Active Server Pages. Moving files, opening and reading text files, and looking at drive space are a few of the many functions of the FileSystem. The FileSystem Object actually contains five objects: the main Filesystem object, the Drive object, the Folder object, the File object, and the TextStream object. FileSystem The FileSystemObject object is used to access the file system on the server. This object can manipulate files, folders, and directory paths. It is also possible to retrieve file system information with this object. Syntax: Scripting.FileSystemObject Example: <% dim fs,fname set fs = Server.CreateObject("Scripting.FileSystemObject") set fname = fs.CreateTextFile("c:\test.txt") fname.WriteLine("Hello World!") fname.Close set fname = nothing set fs = nothing %> Properties Drives Description: The Drives property returns a collection of all Drive objects on the computer. It is a read-only property Syntax: [drivecoll=]FileSystemObject.Drives Example: <% Dim fso Set fso = Server.CreateObject("Scripting.FileSystemObject") Dim drives Set drives = fso.Drives Dim isReady For Each drive in drives isReady = drive.IsReady If isReady Then Response.Write "DriveLetter: " & drive.DriveLetter & "
" Response.Write "Path: " & drive.Path & "
" Response.Write "FileSytem: " & drive.FileSystem & "
" Response.Write "TotalSize: " & drive.TotalSize & "
" Response.Write "FreeSpace: " & drive.FreeSpace & "
" Else Response.Write "Driv Letter: " & drive.DriveLetter & "
" Response.Write drive.Path & "
" Response.Write "No other information available." End If Next Set drives = Nothing Set fso = Nothing %> Methods BuildPath Description: Builds the specificed folders on to the existing path. Syntax: Drive Object The Drive object is used to return information about a local disk drive or a network share. The Drive object can return information about a drive's type of file system, free space, serial number, volume name, and more. You cannot return information about a drive's content with the Drive object. For this purpose you will have to use the Folder object. To work with the properties of the Drive object, you will have to create an instance of the Drive object through the FileSystemObject object. First; create a FileSystemObject object and then instantiate the Drive object through the GetDrive method or the Drives property of the FileSystemObject object. The following code illustrates how the FileSystemObject is used to return a TextStream object that can be read from or written to: Set fso = Server.CreateObject("Scripting.FileSystemObject") Set a = fso.CreateTextFile("c:\testfile.txt", True) a.WriteLine("This is a test.") a.Close In the preceding code, the CreateObject function returns the FileSystemObject (fso). e Drives collection. You can iterate the members of the Drives collection using a For Each...Next construct as illustrated in the following code: Dim fso, d, dc, s, n Set fso = CreateObject("Scripting.FileSystemObject") Set dc = fso.Drives 'dc is now a drives collection For Each d in dc s = s & d.DriveLetter & " - " If d.DriveType = 3 Then 'value-3 is for Remote Drives(Network Drives) n = d.ShareName ElseIf d.IsReady Then n = d.VolumeName End If s = s & n & "
" Next Response.write(s) Methods (Totally 24 methods are there) (1) CreateTextFile :- Creates a specified file name and returns a TextStream object that can be used to read from or write to the file. Syntax: set txtstrobj= object.CreateTextFile(filename[, overwrite[, unicode]]) Filename string that identifies the file to create Overwrite optional parameter, when set to true, overwrites the existing file (default false). Unicode optional parameter, when set to true indicates that file is created as unicode file, ASCII otherwise. Example Set fso = CreateObject("Scripting.FileSystemObject") Set a = fso.CreateTextFile("c:\testfile.txt", True) 'overwrites existing file a.WriteLine("This is a test.") 'Writes a single line of text to the file a.Close 'Closes the file (2) OpenTextFile:- Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file. Syntax: set txtstrobj= object.OpenTextFile(filename[, iomode[, create[, format]]]) Filename - string that identifies the file to create iomode - Optional. Indicates input/output mode. Can be one of three constants: ForReading ->1, ForWriting->2, or ForAppending->8. create - optional. If set to true, creates a new file in case the file does not exist. (False Default) format - optional. One of three Tristate values used to indicate the format of the opened file. If omitted, the file is opened as ASCII. Tristate values -2 => Open's file in System's default format -1 => Opens file as Unicode 0 => Opens file in ASCII format. Example : Dim fso, f Set fso = Server.CreateObject("Scripting.FileSystemObject") Set f = fso.OpenTextFile("c:\testfile.txt", 2, True) f.Write "Hello world!" 'Overwrites the file content with this text f.Close (3) GetDriveMethod :- Returns a string containing the name of the drive for a specified path. Syntax : object.GetDriveName(path) path - Required. The path specification for the component whose drive name is to be returned. The GetDriveName method returns a zero-length string ("") if the drive can't be determined. Example : Dim fso Set fso = CreateObject("Scripting.FileSystemObject") GetAName = fso.GetDriveName("c:\asp") Response.write GetAName Note : The GetDriveName method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path. (4) CreateFolder :- Creates a folder. Syntax : object.CreateFolder(foldername) foldername - String that identifies the folder to create. An error occurs if the specified folder already exists. Example: Dim fso, f Set fso = CreateObject("Scripting.FileSystemObject") Set f = fso.CreateFolder("c:\New Folder") 'creates a folder named New Folder (5) CopyFolder :- Recursively copies a folder from one location to another. (Copy command of dos) Syntax : object.CopyFolder source, destination[, overwrite] source - A string folder specification, which can include wildcard characters, for one or more folders to be copied. destination - string destination where the folder and subfolders from source are to be copied. Wildcard characters are not allowed. overwrite - optional. indicates whether existing folders are to be overwritten or not. (default True) Wildcard characters can only be used in the last path component of the source argument. If destination does not exist, the source folder and all its contents gets copied. This is the usual case. If destination is an existing file, an error occurs. If destination is a directory, an attempt is made to copy the folder and all its contents. If a file contained in source already exists in destination, an error occurs if overwrite is False. Otherwise, it will attempt to copy the file over the existing file. If destination is a read-only directory, an error occurs if an attempt is made to copy an existing read-only file into that directory and overwrite is False. (6) DeleteFolder :- Deletes a specified folder and its contents. Syntax : object.DeleteFolder (folderspec[, force]) folderspec- name of the folder to be removed. force - optional. When set to True, removes the read-only folder forcefully. The DeleteFolder method does not distinguish between folders that have contents and those that do not. The specified folder is deleted regardless of whether or not it has contents. An error occurs if no matching folders are found. The DeleteFolder method stops on the first error it encounters. No attempt is made to roll back or undo any changes that were made before an error occurred. Example : Set fso = CreateObject("Scripting.FileSystemObject") fso.DeleteFolder("c:\new folder") (7) MoveFolder :- Moves one or more folders from one location to another. ( Like cut & paste of folder) Syntax : object.MoveFolder( source, destination ) source - . The path to the folder or folders to be moved. The source argument string can contain wildcard characters in the last path component only. destination - The path where the folder or folders are to be moved. The destination argument can't contain wildcard characters. Note :- If source contains wildcards or destination ends with a path separator (\), it is assumed that destination specifies an existing folder in which to move the matching files. Otherwise, destination is assumed to be the name of a destination folder to create. In either case, three things can happen when an individual folder is moved: If destination does not exist, the folder gets moved. This is the usual case. If destination is an existing file, an error occurs. If destination is a directory, an error occurs. An error also occurs if a wildcard character that is used in source doesn't match any folders. The MoveFolder method stops on the first error it encounters. No attempt is made to roll back any changes made before the error occurs. Example : Set fso = CreateObject("Scripting.FileSystemObject") fso.MoveFolder "c:\abc", "c:\windows\desktop\" (8) CopyFile :- Copies one or more files from one location to another. Syntax : object.CopyFile source, destination[, overwrite] source - string file specification, which can include wildcard characters, for one or more files to be copied. destination - string destination where the file or files from source are to be copied. Wildcard characters are not allowed. overwrite - optional. If True, files are overwritten; if False, they are not. default True. (9) MoveFile :- Moves one or more files from one location to another. Syntax : object.MoveFile source, destination source - The path to the file or files to be moved. The source argument string can contain wildcard characters in the last path component only. destination - The path where the file or files are to be moved. The destination argument can't contain wildcard characters. (10) DeleteFile :- Deletes a specified file. Syntax : object.DeleteFile filespec[, force] filespec - The name of the file to delete. The filespec can contain wildcard characters in the last path component. force - Optional. Boolean value that is True if files with the read-only attribute set are to be deleted; False (default) if they are not. An error occurs if no matching files are found. The DeleteFile method stops on the first error it encounters. No attempt is made to roll back or undo any changes that were made before an error occurred. Drive Object Description Provides access to the properties of a particular disk drive or network share. Example Set fso = CreateObject("Scripting.FileSystemObject") Set d = fso.GetDrive(fso.GetDriveName("c:\")) s = "Drive C:\ - " s = s & d.VolumeName & "
" s = s & "Free Space: " & d.FreeSpace s = s & " bytes" Response.write s Properties (1) AvailableSpace - Returns the amount of space available to a user on the specified drive or network share. (2) DriveType - Returns a value indicating the type of a specified drive. Value is as under 0 -> Unknown 1 -> Removable Drive (floppy Drive, ZipDrive, etc) 2 -> Fixed Drive 3 -> Network Drive (Shared with your computer) 4 -> CD-ROM 5 -> RAM Disk (3) IsReady - Returns True if the specified drive is ready; False if it is not. For removable-media drives and CD-ROM drives, IsReady returns True only when the appropriate media is inserted and ready for access. (4) TotalSize - Returns the total space, in bytes, of a drive or network share. (5) VolumeName - Sets or returns the volume name of the specified drive. Read/write. Folder Object Provides access to all the properties of a folder. Properties (1) Attributes - Sets or returns the attributes of files or folders. Read/write or read-only, depending on the attribute. value Description 0 Normal file. No attributes are set. 1 Read-only file. Attribute is read/write. 2 Hidden file. Attribute is read/write. 4 System file. Attribute is read/write. 8 Disk drive volume label. Attribute is read-only. 16 Folder or directory. Attribute is read-only. 32 File has changed since last backup. Attribute is read/write. 64 Link or shortcut. Attribute is read-only. (Alias) 128 Compressed file. Attribute is read-only. (2) DateCreated - Returns the date and time that the specified file or folder was created. Read-only. (3) Name - Sets or returns the name of a specified file or folder. Read/write. (4) ParentFolder - Returns the folder object for the parent of the specified file or folder. Read-only. (5) IsRootFolder - Returns True if the specified folder is the root folder; False if it is not. File Object Provides access to all the properties of a file. Properties Same as that of folder object (Except IsRootFolder) (5) Type - Returns information about the type of a file or folder. For example, for files ending in .TXT, "Text Document" is returned. TextStream Object Facilitates sequential access to a text file. Property (1) Line - Read-only property that returns the current line number in a TextStream file. (2) Column - Read-only property that returns the column number of the current character position in a TextStream file. (3) AtEndOfLine - Read-only property that Returns True if the file pointer immediately precedes the end-of-line marker in a TextStream file; False if it is not. (4) AtEndOfStream - Read-only property that Returns True if the file pointer is at the end of a TextStream file; False if it is not. Note :- The AtEndOfLine and AtEndOfStream properties apply only to TextStream files that are open for reading; otherwise, an error occurs. Method (1) Close - Closes an open TextStream file. (2) Read - Reads a specified number of characters from a TextStream file and returns the resulting string. Syntax : str = object.Read(noOfCharacters) (3) ReadAll - Reads an entire TextStream file and returns the resulting string. Note : For large files, using the ReadAll method wastes memory resources. Other techniques should be used to input a file, such as reading a file line by line. (4) ReadLine - Reads an entire line (up to, but not including, the newline character) from a TextStream file and returns the resulting string. (5) Skip - Skips a specified number of characters when reading a TextStream file. Syntax : object.Skip(NoOfCharactersToBeSkipped) (6) SkipLine - Skips the next line when reading a TextStream file. Note : Skipping a line means reading and discarding all characters in a line up to and including the next newline character. An error occurs if the file is not open for reading. (7) Write - Writes a specified string to a TextStream file. Syntax : object.Write(string) (8) WriteLine - Writes a specified string and newline character to a TextStream file. Syntax : object.WriteLine([string]) (9) WriteBlankLines - Writes a specified number of newline characters to a TextStream file. Syntax : object.WriteBlankLines(NoOfNewLines) Global.asa Reference The Global.asa file is an optional file in which you can specify event scripts and declare objects that have session or application scope. It is not a content file displayed to the users; instead it stores event information and objects used globally by the application. This file must be named Global.asa and must be stored in the root directory of the application. An application can only have one Global.asa file. Global.asa files can contain only the following: Application events Session events Declarations The scripts contained in the Global.asa file may be written in any supported scripting language. If multiple event or object scripts use the same scripting language, they can be combined inside a single set of