TechView with Kamlesh khaliya

Resources for OCP, Oracle Interviews(kamleshkhaliya@gmail.com)

Monday 26 March 2012

interview questions and answers of classic asp 3.0

Hi,

Below are the frequently asked questions on Classic ASP 3.0, if you have more questions and want the answer please share.

Q. How do you implement paging in asp?
Ans – To implement paging we use the property of record set PageSize, pageCount, and absolutePage.
Here
Pagesize propery - define the size of the page means how many records will be there on a page.
PageCountwill be the total no of pages based on the pagesize propery and the total no of records returned by recordset.
AbsolutePageused to Set the current page on click of next or back

For example:
' Set the page size of the recordset
RS.PageSize = nItemsPerPage
' Get the number of pages
nPageCount = RS.PageCount
' Set the current page on click of next or back
rsGuestbook.AbsolutePage = intPageNum

Below is an example :
<%
Dim adoCon, rsGuestbook, strSQL, adoCon1, strEmail, strSQL1, rsEmail, testv, test1
Dim intRecordspp, intTotalRecords, intTotalPages, intPageNum, strBlah1, strBlah2

If Request.QueryString("rpp") = "" Then
intRecordspp = 10
Else
intRecordspp = CInt(Request.QueryString("rpp"))
End If

If Request.QueryString("PageNumber") = "" Then
intPageNum = 1
Else
intPageNum = CInt(Request.QueryString("PageNumber"))
End If

Set adoCon = Server.CreateObject("ADODB.Connection")
adoCon.Open "Driver={mySQL};......
Set rsGuestbook = Server.CreateObject("ADODB.Recordset")
strSQL = "SELECT Name, Comments, Date_stamp FROM users ORDER BY Date_stamp DESC;"
rsGuestbook.CursorType = 3
rsGuestbook.Open strSQL, adoCon
rsGuestbook.PageSize = intRecordspp

If NOT rsGuestbook.EOF Then rsGuestbook.AbsolutePage = intPageNum
intTotalRecords = rsGuestbook.RecordCount
intTotalPages = rsGuestbook.PageCount
%>
<TABLE >
<TR>
<%
If intPageNum = 1 Then
Else %>
<A HREF="gb.asp?PageNumber=<%= intPageNum -1%>&rpp=<%= Request.QueryString("rpp")%>">Back</A>
<%
End If
%>

<% If intPageNum < intTotalPages Then %>
<A HREF="gb.asp?PageNumber=<%= intPageNum +1%>&rpp=<%= Request.QueryString("rpp")%>">Next</A>
<%
Else
End If
%>
<%
for strBlah2 = 1 to intRecordspp
if Not rsGuestbook.EOF Then
%>
<TD CLASS="border">Comment posted by <B><%= rsGuestbook("Name") %></B></TD>
<TD><BR><%= rsGuestbook("Comments") %><P></TD>
<TD align=right><%= rsGuestbook("Date_stamp") %></TD>
<%
rsGuestbook.MoveNext
End If
Next

'Reset server objects
rsGuestbook.Close
Set rsGuestbook = Nothing
Set adoCon = Nothing
Set adoCon1 = Nothing
Set rsEmail = Nothing
%>

Q. If i am submitting one asp page to another asp page and need to validate all the user inputs but i don't know the no of inputs and the name of the controls, then how can i do that?
Ans – We can handle it on the next page since Form and QueryString are the collections so we can traverse the collection like :
for each i in Request.Form
Response.Write(i & " --> VALUE IS " & request.form(i) & "<br />")
next

Q. The Difference Between Server.CreateObject and <OBJECT> tag ? (v. imp)
Ans – Both used to create objects in classic asp 3.0. The Server.CreateObject method creates an instance of the object immediately. However, the <OBJECT> element only creates an instance of the object it specifies when we first reference that object even we have defined it in global.asa either on session or application level. So, if we stop using the object in our code, it won't get created. So performance wise it's <OBJECT> is better than Server.CreateObject.

Q. What is a typeLibrary? And how can we use typeLibrary in asp?
Ans - A type library (.tlb) is a binary file that stores information about a COM or DCOM object's properties and methods in a form that is accessible to other applications at run time. Using a type library, an application or browser can determine which interfaces an object supports, and invoke an object's interface methods. This can occur even if the object and client applications were written in different programming languages.

In asp we can use the METADATA directive to add a reference to the type library for the component or object like :

<!-- METADATA TYPE="TypeLib"
FILE="path_and_name_of_file"
UUID="type_library_uuid"
VERSION="major_version_number.minor_version_number"
LCID="locale_id"
-->

path_and_name_of_file is the absolute physical path to a type library file (.tlb) or ActiveX DLL.

type_library_uuid is the unique identifier for the type library.
Note : Either path_and_name_of_file or the type_library_uuid parameter must be provided.

major_version_number.minor_version_number (optional) defines the version of the component required. If this version is not found the most recent version is used.

locale_id (optional) is the locale identifier to be used.

Below is an example of ADO type libray to use :
<!-- METADATA TYPE="TypeLib"
FILE="c:\Program Files\Common Files\System\ado\msado15.dll"
-->

If ASP is unable to load the type library, it will return an error and halt execution of the page. The possible
error values are:
ASP 0222 Invalid type library specification
ASP 0223 Type library not found
ASP 0224 Type library cannot be loaded
ASP 0225 Type library cannot be wrapped (i.e. ASP cannot create a type library wrapper object from the type library specified)

Q. Can we create objects on client in asp 3.0 and how?
Ans : Yes in classic asp, we can creaet object on client also.
Like :
<OBJECT ID="objThis" RUNAT="CLIENT"
CLASSID="clsid:892D6DA7-E0F9-11D2-B2E9-00105A42AF30"
CODEBASE="http://yourserver.com/components/mycomponent.cab">
<PARAM NAME="param1" VALUE="value1">
<PARAM NAME="param2" VALUE="value2">
</OBJECT>

Note : the CODEBASE attribute, which allows the client to download and install the component from the URL specified if it is not already installed

Q. What is IISRESTART Utility?
Ans - It can be used to stop or start all the services in the correct order, display the service status, reboot the server machine, and enable and disable service management.
For example:
iisrestart /RESTART /TIMEOUT:30 /REBOOTONERROR

If a service fails to stop or restart within the specified timeout period of 30 seconds, the server will reboot.

Q. What is response.redirect and Server.transfer and Server.Execute?
Ans -
Response.redirect : In this the redirection is actually happening on the client, not on our server. When we execute response.redirect, it actually adds an HTTP redirection header to
the output stream being sent from the Web server to the client. This header looks something like this:
HTTP/1.1 302 Object Moved
Location newpage.asp

The standard HTTP status message in this header, 302 Object Moved, tells the browser that the resource they requested has moved. The Location header provides the address of the page they want. When a browser receives the 302 Object Moved message it responds by cancelling the current request and sending a new request for the page specified in the Location value.
It can cause spurious messages to be displayed if there is a proxy server in use at the client end of the connection. The proxy server will usually intercept the status message and may itself generate a page that is sent on to the client that made the original request.
Server.Transfer & Server.Execute : This passes the control immediately to another page, which can be an ASP script page or any other resource such as an HTML page, zip file, or other type of file. The Execute method 'calls' the other page, just like we call a subroutine or function in our script code. When the other page or resource has completed execution or streaming to the client, control passes back to the statement following the call to the Execute method in the original page, and execution continues from there. When we use the Transfer method, control does not pass back to the original page, and execution stops at the end of the page or resource we transferred control to. One good thing is that along with the control, context of current page is also passed to the target page or resource( and back to current page in case of EXECUTE method). This includes the values of all the variables in all the intrinsic ASP objects, such as the collections of the Request, Response and Session objects, and all their properties. The Application object context is also transferred, even if the page is within a different virtual application.

Q. In server.execute, Can you pass values to next page and back to the current page and how?
Ans : While executing server.execute, the context of current page is also passed to the target page or resource so we can pass the values with collections of the Request, Response and Session objects.

Q. Is regular expressions available in Classic Asp 3.0?
Ans - VBScript 5.0 now supports regular expressions (again, long available in JavaScript, JScript and other
languages). The RegExp object is used to create and execute a regular expression. For example:

strTarget = "test testing tested attest late start"
Set objRegExp = New RegExp 'create a regular expression
objRegExp.Pattern = "test*" 'set the search pattern
objRegExp.IgnoreCase = False 'set the case sensitivity
objRegExp.Global = True 'set the scope
Set colMatches = objRegExp.Execute(strTarget) 'execute the search
For Each Match in colMatches 'iterate the colMatches collection
Response.Write "Match found at position " & Match.FirstIndex & ". "
Response.Write "Matched value is '" & Match.Value & "'.<BR>"
Next

This produces the result:
Match found at position 0. Matched value is 'test'.
Match found at position 5. Matched value is 'test'.
Match found at position 13. Matched value is 'test'.
Match found at position 22. Matched value is 'test'.

Some Very Important Notes :
  1. In ASP 3.0 buffering is enabled by default, and so no output is sent until we specifically do this with Response.Flush or the end of the page is reached.
  2. Instead of the control name we can use the numeric index number in Form and QueryString like :
    strFirstName = Request.Form(1)
  3. We can also get the entire set of collection values from Form and QueryString like
    strAllFormContent = Request.Form
  4. We can also iterate the collection like :
    For intLoop = 1 To Request.Form.Count
    Response.Write Request.Form(intLoop) & "<BR>"
    Next
    OR
    For Each objItem In Request.Form
Response.Write objItem & " = " & Request.Form(objItem) & "<BR>"
Next
  1. Multiple Value Collection Members
    <FORM ACTION="show_request.asp" METHOD="POST">
<INPUT TYPE="TEXT" NAME="OtherHobby">
<INPUT TYPE="TEXT" NAME="OtherHobby">
<INPUT TYPE="TEXT" NAME="OtherHobby">
<INPUT TYPE="SUBMIT" VALUE="Send">
</FORM>
In this case Form collection will contain values from all the three textbox in the same order and the values will be comma seperated. If the user leaves one or more of them blank in the page when submitting it, the values returned are empty strings. If the user has entered Gardening and Mountaineering in the first and third text boxes, and left the second one empty, accessing
Request.Form("OtherHobby") in our ASP code will return the string:
Gardening, , Mountaineering
  1. To Search Through All the Request Collections means both Form and QueryString, we can use strPage = Request("controlname")
    This is usefull in large application where we don't know by which collection we will receive the value.
  2. Get method is default in asp 3.0

Q. When Do Applications and Sessions Start and End?
Ans -
    An application starts when the first user requests an ASP page that is within the application scope – i.e. the default root directory of the Web site, or a user-defined virtual application within a sub directory of the site. This occurs before any user sessions start.
    A session starts when any user first requests an ASP page within the default application or a virtual application (if they do not already have an active session).
    A session ends when that user has not loaded an ASP page within the timeout period specified for the session. The timeout can be set in script code using the Session.Timeout property, set individually for each application in its Properties dialogue, or set by changing the default in the IIS metabase via the IIS: section of Active Directory. A session also ends after a page containing a call to the Session.Abandon method finishes executing.
    An application ends immediately after the last active session within that application ends.
Q. What data types are supported by vb Script?
Ans – VB Script support only variant data type. But a variant variable in vb script can hold number, string, references of COM objects. And we can also define array of variant.

Q. What is state? Does asp maintain state?
Ans - State means the information regarding a particular user. Asp does not maintain state.
For example maintaining state for a user means remembering their name, or as complex as storing object references or recordsets that are different for each user. If we will not maintain that, we can't do anything when we requires more than one ASP page, as the variables and other references in that page are all destroyed when the page is finished executing. When the user requests the next page, we've lost all the information that they've already provided.

Q. If a customer don't want to display the records of a report on web page then how can i provide the download file prompt without giving him a link and i don't want to write a file on web server?
Ans – We need to set below properties of Response :
Response.Contenttype = '' excel; charset = iso-8859i''
Response.AddHeader = '' Content – disposition '' , '' infile ; fileName = abc.xls''

Q. Can we use server.transfer for different application page on same web server? And is it possible with Response.Redirect?
OR
What is the difference between server.transfer and Response.Redirect?
Ans – In Server.transfer we can use the relative path of same web application only.
But in response.redirect we can use any url on web.

Q. What is the limit of Query String in ASP?
Ans – It varies from browser to browser and also depends on the length of actual URL (Uniform Resource Locator). Microsoft Internet Explorer has a maximum URL length of 2,048 character. So If you are using the GET method, you are limited to a maximum of 2,048 characters, minus the number of characters in the actual path.

Q. How will you host a web application on multiple web servers and what is virtualition?
Ans – We generally do this to balance the processing load on multiple Web Servers.
This is possible in a variety of ways :

  1. DSN Round Robin, which uses the DSN server to balance the load. In this approach
  2. Hardware Load Balancing, which uses a hardware component similar to a router to distribute load.
  3. Microsoft's TCP/IP Network Load Balancing, a software solution for load distribution
  4. Hybrid approaches that combine software and hardware solutions.
Q. You have a input page in asp and on submit you need to validate all the inputs on the next page and if all these are valid then redirect on a third page or if invalid then redirect on the first page and need to maintain the state of all inputs.
How will u achieve this?
Ans – We can use either dictionary object on session level or can maintain the var by query string. But generally we do all king of client validation on the same page with client scripts because this reduce server and network overhead.

Q. What are IIS isolation levels?
Ans – IIS has three level of isolation:-
1.
LOW (IIS process):- With this setting all application executable and components for ASP virtual applications are run in the process (i.e. the memory space) of the Web server executable (Inetinfo.exe). So the Web server is at risk if any one of the executable or components fails. Even this provides the fastest and least resource-intensive application execution option.

Example: If i have hosted yahoo , hotmail .amazon and google on a single PC. So all application and the IIS process runs on the same process.In case any website crashes it affects every one.

2.Medium (Pooled):- With this setting all application executables and components from all ASP virtual applications in the process (i.e. the memory space) of a single shared instance of DLLHost.exe. This protects the Web server executable (Inetinfo.exe) from the risk of any one of the executable or components failing. However, one failed executable or component can cause the DLLHost.exe process to fail, and with it all the other hosted executable and components.

3.High (Isolated):- With this setting alll application executable and components for an ASP virtual application are run in the process (i.e. the memory space) of a single instance of DLLHost.exe, but each ASP application has its own instance of DLLHost.exe which is exclusive to that application. This protects the Web server executable (Inetinfo.exe) from the risk of any one of the executable or components failing, and
protects the virtual application from risk if an executable or component from another virtual application
fails. Microsoft suggests that a maximum of ten isolated virtual applications should be hosted on
any one Web server.

Q. What is Eval function in VB Script of classic asp 3.0?
Ans – This is available in VB Script 5.0. This is used to build a string containing script code that can be evaluated to True or False, and then execute it to obtain a result:

datYourBirthday = Request.Form("Birthday")
strScript = "datYourBirthday = Date()"
If Eval(strScript) Then
Response.Write "Happy Birthday!"
Else
Response.Write "Have a nice day!"
End If

Q. What is Execute in classic asp VB Script?
Ans – Used to execute script code in a string in the same way as the Eval function, but without returning a result. It can be used to dynamically create procedures that are executed later in the code For example:

strCheckBirthday = "Sub CheckBirthday(datYourBirthday)" & vbCrlf _
& " If Eval(datYourBirthday = Date()) Then" & vbCrlf _
& " Response.Write ""Happy Birthday!""" & vbCrlf _
& " Else" & vbCrlf _
& " Response.Write ""Have a nice day!""" & vbCrlf _
& " End If" & vbCrlf _
& "End Sub" & vbCrlf
Execute strCheckBirthday
CheckBirthday(Date())

Q. What are the ASP Scripting Objects?
Ans - The Dictionary object, the
FileSystemObject object, TextStream object.


Q. You are using com in asp and that is interacting many procedures and functions in oracle, and you are getting error from database then how will you debug that?
Ans – We will create a test project in VB and add the code project of com in our test project and call the procedures from this testproject and debug that with the same inputs we are having in asp page.



Q. Suppose you have three text boxes with same name on an asp page then what will happen in request.form and request.querystring? Which text box value will it return?
Ans – The form or querystring collection will return the comma separated values of all the text boxes in the same order in which they appear on page.



Q. I have a text box with name txtABC and i am supplying a parameter txtABC in query string.
What will happened if for fetching data
A. i am using method POST ?
B. i am using method GET?
Ans – In method Post we can get both values,
Form controls values can be collected using request.form collection and querystring parameters value can be collected using request.queryString collection.
But In method get you will be able to get only the form values with method query string in this case we will not be able to concat the query string values after ? Mark like ?name=kamlesh&address=xxxx.
Note : For fetching form values if i am using only Request.Form or Request.QueryString and not using any of the form control name then this will give the complete form value like : firstname=John&lastname=Dove , where the form was having two controls one firstname and second is last name


Q. How do you handles errors in asp?
Ans –
IN VB Script - We put on error resume next on the top of the page or sub, this ignores the error if any occur ed and allow execution to continue from the next line. So for whatever the code we want to catch the errors, we simply check the Err.Number on the next line, If Err.Number <> 0, it means Error Occurred and we need to Trap it. We can log the error in database or in text file on disk for our reference and redirect user to error.asp
IN JAVAScript - we do the same using try and catch blocks like ....
Try {
Code
}catch(exception){
//Here we trap the error
}
finally {
FinallyStatements
}
Q. What is the life cycle of an asp page?
Ans - Client(Browser) sends request to server i.e. IIS for an asp page. Here at IIS level there are some dll files like host.dll and asp.dll etc. these are responsible for interpretation of asp file. After interpretation they substitute server side code with result i.e. Html and javascript etc. And send this to be displayed on client.
If it was the first request to the application then events Application onStart, Session OnStart will execute.
If it was the frist request from a user then events Session OnStart will execute.
Q. How do u prepare the test cases?
Ans – While testing we generally prepare three different type of test cases and Prepare UTP(unit test plan) doc which contains ;
1. Test Description,
A. Release id
B. Objective
C. Module Name
    2. Test Procedure
A. Test id
B. Test case description
C. Test data
D. Required result
E. Actual result
F. Test status(fail/pass)
G. Remarks:
1)Positive test case:Correct data,correct result.
2)Negative test case:Missing data,Proper handle.
3)Exception test case:Exception thrown & catch properly.
Q. What is web accessibility?
Ans - Web accessibility means that Web should be accessible to all users irrespective of culture, education, ability, resources, and physical limitations . It has been developed by World Wide Web Consortium i.e. W3C (called "Recommendations")

Q. What is the difference in CreateObject and Server.CreateObject?
Ans - CreateObject has two parameters one is progid and second is server name so using this we can create objects on remote machines also where as Server.CreateObject have only one parameter that is progid so using this we can create object only on local server.

CreateObject is used in VB and Server.CreateObject is used in asp.

Q. How do you estimate the job?
Ans – First we check if we have done similar enhancement previously or not. If yes then we take that as a reference for estimation. If not then we analyse the module/sub-modules where change is required, the count of files which are required to be changed, like file count from front end and similarly from back end. Then we see the complexity of change and according prepare an estimate. We also add some buffer time to this estimate for addressing any contingencies

Q. What is on error go to 0
and
on error resume next?
For error handling in VB Script there are basically just two options:
On Error Goto 0 (the default)
This causes execution to break when an error happens and show an error message.
On Error Resume Next
This causes the script to continue execution starting with the next line after the error.
When "On Error Resume Next" is enabled, the properties of the Err object are automatically populated with details of the errors that have occurred like err.number and err.description
Methods of Err are :
Clear Method
Raise Method

Q. What is default session time out?
Ans - 20 Min
Q. What is default script time out?
Ans - 90 Sec

Q. How to include a java script file in asp?
Ans - <script language='javascript' src='js/sqltohtml.js'></script>
Q. How to include a .css file in your asp page?
Ans - <link rel='stylesheet' href='css/rb_ie.css' type='text/css'>
Q. How to use css class in asp controls?
Ans –
<link rel='stylesheet' href='css/rb_ie.css' type='text/css'>
like <div class='note'>
Where as rb_ie.css have code like
.note
{
FONT: bold 10px Verdana, Arial, Helvetica, sans-serif;
COLOR: black;
BACKGROUND-COLOR: #f0f8ff
}
Q. Which is the default Scripting Language on the client side?
JavaScript



Q. What are the special sub-types in VB Script?
Ans – In VB Script the main data type is variant which can hold any type of value. The other sub-types are:
EMPTY: has no value
NULL: Value does not exist (conjunction with database)
OBJECT:

Q. What is Cookies collection?
Cookies are text files that store information about the user by which the web server identifies and marks each different visitor to a web site and determines where a user has been before. A cookie can store information only when the user sends it. Individual cookies are limited to 4KB of data. The maximum number of cookies allowed is 300.
Cookies are stored on client’s machine.

Q. What is Extranet?
An area of a web site available only to a set of registered visitors.
Q. What are the properties used to control the expiration of the page?Expires specifies the number of minutes before a page cached on a browser expires.ExpiresAbsolute sets the date and time at which a page cached on a browser expires.


Q. When inserting strings into a SQL table in ASP what is the risk and how can you prevent it?
SQL Injection, to prevent you probably need to use Stored Procedures instead of inline/incode SQL


Q. Which is the default Scripting Language of ASP (server-side)?
VBScript


Q. What is the maximum size of an array?
Up to 60 dimensions.
Q. How do you implement securities on Web?
Ans – prevent
  1. sql injection – We check all input fields in a loop and compare its values with standard list of Oracle (SQL) keywords like DROP, SELECT, UPDATE, INSERT, TRUNCATE etc. Then we compare with special characters like single quotes etc. if we find any of these we log the exception and stop the user from further proceeding by redirecting to an error page
  2. cross browser scripting
  3. cookie hijacking
  4. restrict users via roles

Q. What is the second parameter in CreateObject?
Ans – CreateObject : Creates and returns a reference to a COM object. CreateObject cannot be used to create instances of classes in Visual Basic unless those classes are explicitly exposed as COM components.
Public Shared Function CreateObject( _
ByVal ProgId As String, _
Optional ByVal ServerName As String = "" _
) As Object

ProgId
Required. String. The program ID of the object to create.

ServerName
Optional. String. The name of the network server where the object will be created. If ServerName is an empty string (""), the local computer is used.

Q. What is the difference between error and exception?
Ans - An Exception can be caught and recovered: For example if we are getting NO_DATA_FOUND exception then we can handle it in exception handling section.
An Error is unrecoverable: OutOfMemoryError means that the JVM has no more memory to contin.
Q. How do you debug ASP Application?
Ans – We generally use the Debug option available in interdev and user F10 and F11 for Step Over and Step Into. Or some times we use the response.write and response.end also.
If we come to a point in code where we are calling database objects and some debugging is required then we come to database prompt with the parameter values and debug the object.



Q. What kind of documents you prepare in Application development and enhancement?
And – We follow the below steps during enhancement :
Requirement Analysis and definition in terms of CBR (Client Business Requirement)
Get Sign off on CBR from Client
Do IMPACT ANALYSIS and prepare IMPACT ANALYSIS DOCUMENT - Contain the solution approach along with the list of CIs needs to be change and the impact of the change through out the application.
some neutral person do IMPACT ANALYSIS REVIEW
Prepare SOW (Statement of Work Document) - SOW “a formal document that captures and defines the work activities, deliverables, and timeline.
Do CODE CHECKED OUT
Do CODE CHANGE
Do Code Review
DO IUT (Independent Unit Testing) - Prepare UTP (Unit Test Plan Document) containing positive, negative and exceptional test cases and do testing
Do CODE CHECKED IN
Do SIT (System Integrated Testing)
UAT (User Acceptance Testing)
Prepare Release note - Contains the summary of the change along with the known bugs and limitations if any. This document also contain
1. The release components those should be added or replaced on the production server for example the the asp pages or dlls for front end.
2. Database scripts that needs to be execute on production database schema.
Prepare Check list for the deployment.
Implement on Production


Q Which SCL model you follow?
Ans - Software development life cycle (Waterfall Model)
  1. Requirement Analysis & Definition
  2. System & Software Design
  3. Implementation & Unit Testing
  4. Integration & System Testing
  5. Operations & Maintenance
Q. What is the difference between Name and Id in html controls?
Ans - name= is used to label the fields in the message send to a server with an HTTP (HyperText Transfer Protocol) GET or POST when you hit submit in a form.
id= labels the fields for use by JavaScript and Java DOM (Document Object Model).


Q. What is the getString in recordset?
Ans - The GetString method returns the specified Recordset as a string. This method can be used to fill HTML tables in ASP files.
Set str=objRecordset.GetString(format,n,coldel,rowdel,nullexpr)

format -(Optional) A StringFormatEnum value that specifies the format when retrieving a Recordset as a string
n - (Optional) The number of rows to be converted in the Recordset
coldel - (Optional) If format is set to adClipString it is a column delimiter. Otherwise it is the tab character
rowdel - (Optional) If format is set to adClipString it is a row delimiter. Otherwise it is the carriage return character
nullexpr - (Optional) If format is set to adClipString it is an expression used instead of a null value. Otherwise it is an empty string

Example - To create an HTML table with data from a recordset, we only need to use three of the parameters above:
coldel - the HTML to use as a column-separator
rowdel - the HTML to use as a row-separator
NullExpr - the HTML to use if a column is NULL

<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"

set rs = Server.CreateObject("ADODB.recordset")
rs.Open "SELECT Companyname, Contactname FROM Customers", conn

str=rs.GetString(,,"</td><td>","</td></tr><tr><td>","&nbsp;")
%>
<table border="1" width="100%">
<tr>
<td><%Response.Write(str)%></td>
</tr>
</table>
<%
rs.close
conn.close
set rs = Nothing
set conn = Nothing
%>
</body>
</html>

Q. How to execute a stored procedure by a connection object?
Ans - The Execute method executes a specified query, SQL statement, stored procedure, or provider-specific text.
The results are stored in a new Recordset object if it is a row-returning query. A closed Recordset object will be returned if it is not a row-returning query.
Note: The returned Recordset is always a read-only, forward-only Recordset!
Syntax for row-returning
Set objrs=objconn.Execute(commandtext,ra,options)
Syntax for non-row-returning
objconn.Execute commandtext,ra,options
Where :-
commandtext - Required. The SQL statement, stored procedure, or provider-specific text to execute
ra - Optional. The number of records affected by the query
options - Optional. Sets how the provider should evaluate the commandtext parameter. Can be one or more CommandTypeEnum or ExecuteOptionEnum values. Default is adCmdUnspecified
Example
<%
sql="SELECT companyname FROM Customers"
Set rs=conn.Execute(sql)
%>

- - printed up this
Q. How to upload a file on web server?
Ans -
<form action="demo_form.asp">
<input type="file" name="pic" accept="image/*" />
<input type="submit" />
</form>
Take a working example.......
Q. How do you implement securities on Web?
Ans – prevent
  1. sql injection – We check all input fields in a loop and compare its values with standard list of Oracle (SQL) keywords like DROP, SELECT, UPDATE, INSERT, TRUNCATE etc. Then we compare with special characters like single quotes etc. if we find any of these we log the exception and stop the user from further proceeding by redirecting to an error page
  2. cross browser scripting
  3. cookie highjacking
  4. restrict users via roles

Apart from all these question to clear the interview round you should know the properties, methods, collections, and events of all seven objects of classic asp 3.0, interviewer always put question of Response and Server Objects.

Response Object : used to send output to the user from the server.

Collections

Collection
Description
Sets a cookie value. If the cookie does not exist, it will be created with the value that is specified.
The Response.Cookies command must appear before the <html> tag.

Properties

Property
Description
Specifies whether to buffer the page output or not.
response.Buffer = [True | False]
Sets whether a proxy server can cache the output generated by ASP or not.
response.CacheControl=[Public | Private]

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.
Appends the name of a character-set to the content-type header in the Response object.
response.Charset(charsetname)
Where charsetname is A string that specifies a character set for the page
Example : <%response.Charset="ISO-8859-1"%>
Sets the HTTP content type for the Response object.
response.ContentType[=contenttype]
Exmples of ContentType :
<%response.ContentType="text/HTML"%>
<%response.ContentType="image/GIF"%>
<%response.ContentType="image/JPEG"%>
<%response.ContentType="text/plain"%>

Note :- If an ASP page has no ContentType property set, the default content-type header would be:
content-type:text/html

This example will open an Excel spreadsheet in a browser (if the user has Excel installed):
<%response.ContentType="application/vnd.ms-excel"%>
<html>
<body>
<table>
<tr>
<td>1</td>
<td>2</td>
<tr>
<td>7</td>
<td>8</td>
</table>
</body>
</html>
Sets how long (in minutes) a page will be cached on a browser before it expires.
response.Expires[=number]
Where number - is the time in minutes before the page expires

The following code indicates that the page will never be cached:
<%response.Expires=-1%>

The following code indicates that the page will expire after 1440 minutes (24 hours):
<%response.Expires=1440%>
Sets a date and time when a page cached on a browser will expire. If a user returns to the same page before this date/time, the cached version is displayed.
response.ExpiresAbsolute[=[date][time]]
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.

The following code indicates that the page will expire at 4:00 PM on October 11, 2012:
<%response.ExpiresAbsolute=#October 11,2012 16:00:00#%>
Indicates if the client has disconnected from the server.
response.IsClientConnected
<%
If response.IsClientConnected=true then
response.write("The user is still connected!")
else
response.write("The user is not connected!")
end if
%>
Appends a value to the PICS label response header.
What is PICS?
The PICS (Platform for Internet Content Selection) rating system is used to rate the content in a web site.

One of the most popular rating system is RSACi (Recreational Software Advisory Council on the Internet). RSACi rating system uses four categories: violence, nudity, sex, and language. A number between 0 to 4 is assigned to each category. 0 means that the page does not contain any potentially offensive content and 4 means that the page contains the highest levels of potentially offensive content.

Microsoft IE 3.0 and above and Netscape 4.5 and above support the content ratings. You can set the ratings in IE 5, by selecting Tools and Internet Options. Select the Content tab and click the Enable. When the rating exceeds the defined levels the Content Advisor will block the site.

We can use the META tag or the response.PICS property to add a rating to our site.

<%
response.PICS("(PICS-1.1 <http://www.rsac.org/ratingv01.html>
by " & chr(34) & "your@name.com" & chr(34) &
" for " & chr(34) & "http://www.somesite.com" & chr(34) &
" on " & chr(34) & "2002.10.05T02:15-0800" & chr(34) &
" r (n 2 s 0 v 1 l 2))")
%>

the following header is added:
PICS-label:(PICS-1.1 <http://www.rsac.org/ratingv01.html>
by "your@name.com"
for "http://www.somesite.com"
on "2002.10.05T02:15-0800"
r (n 2 s 0 v 1 l 2))
Specifies the value of the status line returned by the server.
response.Status=statusdescription
statusdescription - is a three-digit number and a description of that code, like 404 Not Found.
Note: Status values are defined in the HTTP specification.

<%
ip=request.ServerVariables("REMOTE_ADDR")
if ip<>"194.248.333.500" then
response.Status="401 Unauthorized"
response.Write(response.Status)
response.End
end if
%>

Methods

Method
Description
Adds a new HTTP header and a value to the HTTP response.
Note: Once a header has been added, it cannot be removed.

Note: In IIS 4.0 you have to call this method before any output is sent to the browser. In IIS 5.0 you can call the AddHeader method at any point in the script, as long as it precedes any calls to the response.Flush method.
response.AddHeader name,value

name - Required. The name of the new header variable (cannot contain underscores)
value- Required. The initial value of the new header variable

Examples
<%Response.AddHeader "WARNING","Error message text"%>
Adds a string to the end of the server log entry.
<%Response.AppendToLog "My log message"%>
Writes data directly to the output without any character conversion.
This method is used to write image data (BLOB) from a database to a browser.
<%
Set objBinaryGen=Server.CreateObject("MyComponents.BinaryGenerator")
pic=objBinaryGen.MakePicture
response.BinaryWrite pic
%>
Clears any buffered HTML output.
Note: This method does not clear the response headers, only the response body.

Note: If response.Buffer is false, this method will cause a run-time error.
response.Clear
Stops processing a script, and returns the current result.
Note: This method will flush the buffer if Response.Buffer has been set to true. If you do not want to return any output to the user, you should call Response.Clear first.
Response.End
Sends buffered HTML output immediately.
Note: If response.Buffer is false, this method will cause a run-time error.
Response.Flush
Redirects the user to a different URL.
<%
Response.Redirect "http://www.w3schools.com"
%>
Writes a specified string to the output
<%
Response.Write "Hello World"
%>

Request Object : The Request object is used to get information from a visitor (browser).

Collections

Collection
Description
ClientCertificate
The ClientCertificate collection holds fields of keys and values from a security certificate that the client browser passes to the Web server.
In order to populate the fields of the ClientCertificate collection, both the Web server and the client browser must support the SSL3.0/PCT1.0 protocol. The Web site must have secure sockets layer (SSL) enabled and request client certificates. After SSL is enabled, the URL of the Web site will start with "https://" instead of "http://". The client browser must be capable of sending a certificate.
Contains all the cookie values sent in a HTTP request.
Note: The Response.Cookies command must appear before the <html> tag.
variablename=Request.Cookies(name)[(key)|.attribute]

name :- Required. The name of the cookie

value :- Required for the Response.Cookies command. The value of the cookie

attribute :- Optional. Specifies information about the cookie. Can be one of the following parameters:
Domain - Write-only. The cookie is sent only to requests to this domain
Expires - Write-only. The date when the cookie expires. If no date is specified, the cookie will expire when the session ends
HasKeys - Read-only. Specifies whether the cookie has keys (This is the only attribute that can be used with the Request.Cookies command)
Path - Write-only. If set, the cookie is sent only to requests to this path. If not set, the application path is used
Secure - Write-only. Indicates if the cookie is secure

key :- Optional. Specifies the key to where the value is assigned
<%
fname=Request.Cookies("firstname")
response.write("Firstname=" & fname)
%>
The Form collection is used to retrieve the values of form elements from a form that uses the POST method.
Request.Form(element)[(index)|.Count]
element - Required. The name of the form element from which the collection is to retrieve values
index - Optional. Specifies one of multiple values for a parameter. From 1 to Request.Form(parameter).Count.
The QueryString collection is used to retrieve the variable values in the HTTP query string.

The HTTP query string is specified by the values following the question mark (?), like this:

<a href= "test.asp?txt=this is a query string test">Link with a query string</a>

The line above generates a variable named txt with the value "this is a query string test".

Query strings are also generated by form submission, or by a user typing a query into the address bar of the browser.

Note: If you want to send large amounts of data (beyond 100 kb) the Request.QueryString cannot be used.
Contains all the server variable values.
Request.ServerVariables (server_variable)
Server Variable Can be like :
REMOTE_HOST - Returns the name of the host making the request
SERVER_NAME - Returns the server's host name, DNS alias, or IP address as it would appear in self-referencing URLs
REQUEST_METHOD - Returns the method used to make the request
QUERY_STRING - Returns the query information stored in the string following the question mark (?) in the HTTP request

Properties

Property
Description
Returns the total number of bytes the client sent in the body of the request

Methods

Method
Description
The BinaryRead method is used to retrieve the data sent to the server from the client as part of a POST request. It will store the data in a safe array (an array that stores information about the number of dimensions and the bounds of its dimensions).

Note: A call to Request.Form after a call to BinaryRead, and vice-versa, will cause an error.
<%
dim a,b
a=Request.TotalBytes
b=Request.BinaryRead(a)
%>

Application Object : An application on the Web may consists of several ASP files that work together to perform some purpose. The Application object is used to tie these files together.

Collections

Collection
Description
Contains all the items appended to the application through a script command.
Application.contents(Key)
Tip: To remove items from the Contents collection, use the Remove and RemoveAll methods.
Contains all the objects appended to the application with the HTML <object> tag.
Application.StaticObjects(Key)
key – is the name of the item to retrieve.

Methods

Method
Description
Deletes an item from the Contents collection.
Application.Contents.Remove(name|index)
name - The name of the item to remove
index - The index of the item to remove
Deletes all items from the Contents collection.
Application.Contents.RemoveAll()
The Lock method prevents other users from modifying the variables in the Application object (used to ensure that only one client at a time can modify the Application variables).

Enables other users to modify the variables in the Application object (after it has been locked using the Lock method).
<%
Application.Lock
Application("visits")=Application("visits")+1
Application.Unlock
%>

This page has been visited
<%=Application("visits")%> times!

Events

Event
Description
Occurs when all user sessions are over, and the application ends.
Note: The MapPath method cannot be used in the Application_OnEnd code.

Sub Application_OnEnd
. . .
End Sub
Occurs before the first new session is created (when the Application object is first referenced)
Note: Referencing to a Session, Request, or Response objects in the Application_OnStart event script will cause an error.

Sub Application_OnStart
. . .
End Sub

Session Object

When you are working with an application on your computer, you open it, do some changes and then you close it. This is much like a Session.
Variables stored in a Session object hold information about one single user, and are available to all pages in one application. Common information stored in session variables are name, id, and preferences. The server creates a new Session object for each new user, and destroys the Session object when the session expires.

Collections

Collection
Description
Contains all the items appended to the session through a script command
Contains all the objects appended to the session with the HTML <object> tag

Properties

Property
Description
Specifies the character set that will be used when displaying dynamic content.
Example of some code pages:
  • 1252 - American English and most European languages
  • 932 - Japanese Kanji
Sets or returns an integer that specifies a location or region. Contents like date, time, and currency will be displayed according to that location or region.

Session.LCID(=LCID)
LCID - A locale identifier

Example -
response.write("<p>")
response.write("Default LCID is: " & Session.LCID & "<br />")
response.write("Date format is: " & date() & "<br />")
response.write("Currency format is: " & FormatCurrency(350))
response.write("</p>")

Session.LCID=1036

response.write("<p>")
response.write("LCID is now: " & Session.LCID & "<br />")
response.write("Date format is: " & date() & "<br />")
response.write("Currency format is: " & FormatCurrency(350))
response.write("</p>")


Output:
Default LCID is: 2048
Date format is: 12/11/2001
Currency format is: $350.00

LCID is now: 1036
Date format is: 11/12/2001
Currency format is: 350,00 F
Returns a unique id for each user. The unique id is generated by the server.
<%
Response.Write(Session.SessionID)
%>

Output:
772766038
Sets or returns the timeout period (in minutes) for the Session object in this application

Methods

Method
Description
Destroys a user session
Deletes an item from the Contents collection
Deletes all items from the Contents collection

Events

Event
Description
Occurs when a session ends
Occurs when a session starts

Server Object

The ASP Server object is used to access properties and methods on the server. Its properties and methods are described below:

Properties

Property
Description
Sets or returns the maximum number of seconds a script can run before it is terminated. Default is 90 seconds

Server.ScriptTimeout=200

Methods

Method
Description
Creates an instance of an object.
Server.CreateObject(progID)
Server.CreateObject("Adodb.Connection")
You cannot create an instance of an object with the same name as a built-in object:
<%
Set Application=Server.CreateObject("Application")
%>
Executes an ASP file from inside another ASP file. After executing the called .asp file, the control is returned to the original .asp file.
Server.Execute("file2.asp")
The GetLastError method returns an ASPError object that describes the error condition that occurred.
By default, a Web site uses the file \iishelp\common\500-100.asp for processing ASP errors. You can either use this file, or create your own.
Applies HTML encoding to a specified string.
Server.HTMLEncode(string)
<%
response.write(Server.HTMLEncode("The image tag: <img>"))
%>

Output:
The image tag: <img>
Maps a specified path to a physical path.
Server.MapPath(path)
path - is a relative or virtual path to map to a physical path. If this parameter starts with / or \, it returns a path as if this parameter is a full virtual path. If this parameter doesn't start with / or \, it returns a path relative to the directory of the .asp file being processed.

Example -
<%
response.write(Server.MapPath("test.asp") & "<br />")
response.write(Server.MapPath("script/test.asp") & "<br />")
response.write(Server.MapPath("/script/test.asp") & "<br />")
response.write(Server.MapPath("\script") & "<br />")
response.write(Server.MapPath("/") & "<br />")
response.write(Server.MapPath("\") & "<br />")
%>

Output:

c:\inetpub\wwwroot\script\test.asp
c:\inetpub\wwwroot\script\script\test.asp
c:\inetpub\wwwroot\script\test.asp
c:\inetpub\wwwroot\script
c:\inetpub\wwwroot
c:\inetpub\wwwroot

The Transfer method sends (transfers) all the state information (all application/session variables and all items in the request collections) created in one ASP file to a second ASP file.
When the second ASP page completes its tasks, it will NOT return to the first ASP page (like the Execute method).
Note: The Transfer method is an efficient alternate for the Response.Redirect. A redirect forces the Web server to handle an extra request while the Server.Transfer method transfers execution to a different ASP page on the server, and avoids the extra round trip.
Server.Transfer("file2.asp")
Applies URL encoding rules to a specified string.
<%
response.write(Server.URLEncode("http://www.w3schools.com"))
%>

Output:
http%3A%2F%2Fwww%2Ew3schools%2Ecom

The ASPError Object

The ASPError object was implemented in ASP 3.0 and is available in IIS5 and later.
The ASPError object is used to display detailed information of any error that occurs in scripts in an ASP page.
Note: The ASPError object is created when Server.GetLastError is called.
The ASPError object's properties are described below (all properties are read-only):

Properties

Property
Description
Returns an error code generated by IIS
Returns a detailed description of the error (if the error is ASP-related)
Returns the source of the error (was the error generated by ASP? By a scripting language? By an object?)
Returns the column position within the file that generated the error
Returns a short description of the error
Returns the name of the ASP file that generated the error
Returns the line number where the error was detected
Returns the standard COM error code for the error
Returns the actual source code of the line where the error occurred

ObjectContext Object
The ObjectContext object is used for transaction handling. It has below methods and events :


Methods
Description
SetAbort
Aborts the transaction initiated by the ASP script.
SetComplete
Declares that there is no reason for the transaction not to complete. So if all the components taking part in the transaction also call SetComplete method then the transaction will complete.




Events
Description
OnTransactionAbort
This event occurs when the transaction is aborted.
OnTransactionCommit
This event occurs when the transactional script's transaction is committed.


Forms and User Input

Request.QueryString is used to collect values in a form with method="get". Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send.
Request.Form is used to collect values in a form with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.

ASP Cookies

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests for a page with a browser, it will send the cookie too.
The Response.Cookies command is used to create cookies:
Response.Cookies("firstname")="Alex"
Response.Cookies("firstname").Expires="May 10,2002"
Note: The Response.Cookies command must appear BEFORE the <html> tag!
The "Request.Cookies" command is used to retrieve a cookie value:
fname=Request.Cookies("firstname")
response.write("Firstname=" & fname)


A Cookie with Keys
If a cookie contains a collection of multiple values, we say that the cookie has Keys.
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"

Read all Cookies

for each x in Request.Cookies
if Request.Cookies(x).HasKeys then
for each y in Request.Cookies(x)
response.write(x & ":" & y & "=" & Request.Cookies(x)(y))
next
else
Response.Write(x & "=" & Request.Cookies(x) & "<br />")
end if
response.write "</p>"
next

What if a Browser Does NOT Support Cookies?

If your application deals with browsers that do not support cookies, you will have to use other methods to pass information from one page to another in your application. There are two ways of doing this:

1. Add parameters to a URL

You can add parameters to a URL:
<a href="welcome.asp?fname=John&lname=Smith">Go to Welcome Page</a>
And retrieve the values in the "welcome.asp" file like this:
fname=Request.querystring("fname")
lname=Request.querystring("lname")

2. Use a form

You can use a form. The form passes the user input to "welcome.asp" when the user clicks on the Submit button:
<form method="post" action="welcome.asp">
First Name: <input type="text" name="fname" value="" />
Last Name: <input type="text" name="lname" value="" />
<input type="submit" value="Submit" />
</form>

Retrieve the values in the "welcome.asp" file like this:
fname=Request.form("fname")
lname=Request.form("lname")
response.write("<p>Hello " & fname & " " & lname & "!</p>")
response.write("<p>Welcome to my Web site!</p>")

Including Files

You can insert the content of one ASP file into another ASP file before the server executes it, with the #include directive. The #include directive is used to create functions, headers, footers, or elements that will be reused on multiple pages
Syntax:
<!--#include virtual="somefile.inc"-->
or
<!--#include file ="somefile.inc"-->
Note : using file option you can include a file that is present on the relative path means in the virtual directory only. If you want to include a file from different drive like D: or F: this is not possible. This can be achived by creating a virtual directory for that file and include this with virtual option in #include.

Global.asa

The Global.asa file is an optional file that can contain declarations of objects, variables, and methods that can be accessed by every page in an ASP application.
Note: The Global.asa file must be stored in the root directory of the ASP application, and each application can only have one Global.asa file.
The Global.asa file can contain only :
  • Application events
  • Session events
  • <object> declarations
  • TypeLibrary declarations
  • the #include directive


Application and Session Events
In Global.asa you can tell the application and session objects what to do when the application/session starts and what to do when the application/session ends. The code for this is placed in event handlers.
Note: We do not use <% and %>, to insert scripts in the Global.asa file, we have to put the subroutines inside the HTML <script> tag:
<script language="vbscript" runat="server">
sub Application_OnStart
' some code
end sub
sub Application_OnEnd
' some code
end sub
sub Session_OnStart
' some code
end sub
sub Session_OnEnd
' some code
end sub
</script>


<object> Declarations
It is also possible to create objects with session or application scope in Global.asa by using the <object> tag.
Note: The <object> tag should be outside the <script> tag!
Syntax:
<object runat="server" scope="scope" id="id"
{progid="progID"|classid="classID"}>
.......
</object>


TypeLibrary Declarations
A TypeLibrary is a container for the contents of a DLL file corresponding to a COM object. By including a call to the TypeLibrary in the Global.asa file, the constants of the COM object can be accessed, and errors can be better reported by the ASP code.
Syntax:
<!--METADATA TYPE="TypeLib"
file="filename"
uuid="typelibraryuuid"
version="versionnumber"
lcid="localeid"
-->

Lifetime and scope of Variables

Sub or Module Level – if we define a variable it is accessible wih in the module only. This will be created and destroyed every time the procedure is executed. No scripts outside the procedure can access or change the variable.

Page Level – if we define a variable outside a procedure can be accessed and changed by any script in the ASP file.

Session Variables

Session variables are used to store information about ONE single user, and are available to all pages in one application. Typically information stored in session variables are name, id, and preferences.

Application Variables

Application variables are also available to all pages in one application. Application variables are used to store information about ALL users in one specific application.

The FileSystemObject Object

The FileSystemObject object is used to access the file system on a server.
This object can manipulate files, folders, and directory paths. It is also possible to retrieve file system information with this object. Below is example to creates a text file (c:\test.txt) and then writes some text to the file:
set fs=Server.CreateObject("Scripting.FileSystemObject")
set fname=fs.CreateTextFile("c:\test.txt",true)
fname.WriteLine("Hello World!")
fname.Close

Properties

Property
Description
Returns a collection of all Drive objects on the computer

Methods

Method
Description
Appends a name to an existing path
Copies one or more files from one location to another
Copies one or more folders from one location to another
Creates a new folder
Creates a text file and returns a TextStream object that can be used to read from, or write to the file
Deletes one or more specified files
Deletes one or more specified folders
Checks if a specified drive exists
Checks if a specified file exists
Checks if a specified folder exists
Returns the complete path from the root of the drive for the specified path
Returns the base name of a specified file or folder
Returns a Drive object corresponding to the drive in a specified path
Returns the drive name of a specified path
Returns the file extension name for the last component in a specified path
Returns a File object for a specified path
Returns the file name or folder name for the last component in a specified path
Returns a Folder object for a specified path
Returns the name of the parent folder of the last component in a specified path
Returns the path to some of Windows' special folders
Returns a randomly generated temporary file or folder
Moves one or more files from one location to another
Moves one or more folders from one location to another
Opens a file and returns a TextStream object that can be used to access the file

The TextStream Object

The TextStream object is used to access the contents of text files.
To create an instance of the TextStream object you can use the CreateTextFile or OpenTextFile methods of the FileSystemObject object, or you can use the OpenAsTextStream method of the File object.
Variable f is an instance of the TextStream object in below code
set f=fs.CreateTextFile("c:\test.txt",true)
f.WriteLine("Hello World!")

Properties

Property
Description
Returns true if the file pointer is positioned immediately before the end-of-line marker in a TextStream file, and false if not
Returns true if the file pointer is at the end of a TextStream file, and false if not
Returns the column number of the current character position in an input stream
Returns the current line number in a TextStream file

Methods

Method
Description
Closes an open TextStream file
Reads a specified number of characters from a TextStream file and returns the result
Reads an entire TextStream file and returns the result
Reads one line from a TextStream file and returns the result
Skips a specified number of characters when reading a TextStream file
Skips the next line when reading a TextStream file
Writes a specified text to a TextStream file
Writes a specified text and a new-line character to a TextStream file
Writes a specified number of new-line character to a TextStream file

The 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.
Note: 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 Drive object's properties are described below:

Properties

Property
Description
Returns the amount of available space to a user on a specified drive or network share
Returns one uppercase letter that identifies the local drive or a network share
Returns the type of a specified drive
Returns the file system in use for a specified drive
Returns the amount of free space to a user on a specified drive or network share
Returns true if the specified drive is ready and false if not
Returns an uppercase letter followed by a colon that indicates the path name for a specified drive
Returns a Folder object that represents the root folder of a specified drive
Returns the serial number of a specified drive
Returns the network share name for a specified drive
Returns the total size of a specified drive or network share
Sets or returns the volume name of a specified drive

The File Object

The File object is used to return information about a specified file.
To work with the properties and methods of the File object, you will have to create an instance of the File object through the FileSystemObject object. First; create a FileSystemObject object and then instantiate the File object through the GetFile method of the FileSystemObject object or through the Files property of the Folder object.


Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set f=fs.GetFile("c:\test.txt")
Response.Write("File created: " & f.DateCreated)

Properties

Property
Description
Sets or returns the attributes of a specified file
Returns the date and time when a specified file was created
Returns the date and time when a specified file was last accessed
Returns the date and time when a specified file was last modified
Returns the drive letter of the drive where a specified file or folder resides
Sets or returns the name of a specified file
Returns the folder object for the parent of the specified file
Returns the path for a specified file
Returns the short name of a specified file (the 8.3 naming convention)
Returns the short path of a specified file (the 8.3 naming convention)
Returns the size, in bytes, of a specified file
Returns the type of a specified file

Methods

Method
Description
Copies a specified file from one location to another
Deletes a specified file
Moves a specified file from one location to another
Opens a specified file and returns a TextStream object to access the file

The Folder Object

The Folder object is used to return information about a specified folder.
To work with the properties and methods of the Folder object, you will have to create an instance of the Folder object through the FileSystemObject object. First; create a FileSystemObject object and then instantiate the Folder object through the GetFolder method of the FileSystemObject object.
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set fo=fs.GetFolder("c:\test")
Response.Write("Folder created: " & fo.DateCreated)

Collections

Collection
Description
Returns a collection of all the files in a specified folder
Returns a collection of all subfolders in a specified folder

Properties

Property
Description
Sets or returns the attributes of a specified folder
Returns the date and time when a specified folder was created
Returns the date and time when a specified folder was last accessed
Returns the date and time when a specified folder was last modified
Returns the drive letter of the drive where the specified folder resides
Returns true if a folder is the root folder and false if not
Sets or returns the name of a specified folder
Returns the parent folder of a specified folder
Returns the path for a specified folder
Returns the short name of a specified folder (the 8.3 naming convention)
Returns the short path of a specified folder (the 8.3 naming convention)
Returns the size of a specified folder
Returns the type of a specified folder

Methods

Method
Description
Copies a specified folder from one location to another
Deletes a specified folder
Moves a specified folder from one location to another
Creates a new text file in the specified folder and returns a TextStream object to access the file


The Dictionary Object

The Dictionary object is used to store information in name/value pairs (referred to as key and item).
Comparing Dictionaries and Arrays:
  • Keys are used to identify the items in a Dictionary object
  • You do not have to call ReDim to change the size of the Dictionary object
  • When deleting an item from a Dictionary, the remaining items will automatically shift up
  • Dictionaries cannot be multidimensional, Arrays can
  • Dictionaries have more built-in functions than Arrays
  • Dictionaries work better than arrays on accessing random elements frequently
  • Dictionaries work better than arrays on locating items by their content
Set d=Server.CreateObject("Scripting.Dictionary")
d.Add "re","Red"
d.Add "gr","Green"
d.Add "bl","Blue"
d.Add "pi","Pink"
Response.Write("The value of key gr is: " & d.Item("gr"))

Properties

Property
Description
Sets or returns the comparison mode for comparing keys in a Dictionary object
Returns the number of key/item pairs in a Dictionary object
Sets or returns the value of an item in a Dictionary object
Sets a new key value for an existing key value in a Dictionary object

Methods

Method
Description
Adds a new key/item pair to a Dictionary object
Returns a Boolean value that indicates whether a specified key exists in the Dictionary object
Returns an array of all the items in a Dictionary object
Returns an array of all the keys in a Dictionary object
Removes one specified key/item pair from the Dictionary object
Removes all the key/item pairs in the Dictionary object



If you have any question asked during interview, please send us on kamleshkhaliya@gmail.com.




5 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home