Tuesday, September 28, 2010

Response.Flush and Response.Buffer Property

The Flush method sends buffered output immediately. This method causes a run-time error if Response.Buffer has not been set to TRUE.

The Buffer property specifies whether to buffer the output or not. When the output is buffered, the server will hold back the response to the browser until all of the server scripts have been processed, or until the script calls the Flush or End method.

Note: If this property is set, it should be before the tag in the .asp file

in this example, there will be no output sent to the browser before the loop is finished. If buffer was set to False, then it would write a line to the browser every time it went through the loop.


<% for i=1 to 100 response.write(i & "")


IIS5 enables buffering by default, therefore all the output from our ASP is actually sent to the browser only when the page completes its processing. In many cases this approach improves the overall processing speed, and indirectly makes for a more scalable site. However, buffering has two minor defects: (1) the end user might perceive a loss in speed, because she won't see any output until the page is complete, and (2) buffered output has to be maintained on the server, therefore your ASP application is going to take more memory than it would do if buffering were disabled. On server machines with an inadequate amount of memory, large HTML pages can reduce the overall performance.

Fortunately, we can solve both problems with judicious use of the Response.Flush method, that lets we flush the output buffer periodically when sending a large amount of data back to the client. For example, if we are sending back to the client data from thousands of records, we might flush the buffer every 100 records, so that the end user sees some results earlier and we don't tax the server's memory.

Saturday, September 25, 2010

Disconnected Mode in Classic ASP

Dataset is provided in ASP.NET so that users can work in a disconnected mode. There is an alternative in classic ASP also by which we can work in a disconnected mode by storing the values of recordset object in a two dimensional array.

Generally we open a Recordset object and then using a Do While Not objRS.EOF ...Loop, Iterating through each row in the Recordset. This approach is fine and good,

There is an special Recordset method called GetRows(), which reads the contents of the Recordset into a two-dimensional array; then, to display the Recordset data,We can simply iterate through this array.After storing the data into the two dimensional array we can close the recordset and connection object.

While the syntax involved in using the array-based approach is a bit more confusing that simply looping through the Recordset via a Do While Not objRS.EOF ... Loop, the main motivation behind using GetRows() is performance.

Why LOOP and Movenext? They just slow things down...

Most people write database retrieval code like his:

<% '
Open Database
Do UNTIL rs.eof 
process and format data
' Close database

If there are 700 records and 3 columns for example, we have 3,500 database read requests over the wire. 

+2,100 ... Each field read is a request
+700 ..... Each .movenext is +1 request
+700 ..... Each .eof test is +1 request

3,500 requests

Lots of round-trips. Actually I am fudging a little here.... the recordset object actually will maintain buffers in chunk sizes defined by rstemp.cachesize -- setting it will determine how many rows of data it buffers when 1 record is requested. A cachesize for example of 50 would reduce the previous examples trips to the backend database to 14 since when you asked for the first record you got 50. Until the MOVENEXT triggers record 51-101 being retrieved. But those buffers, and their attendant structures ain't free either.

Before we get started there are three important things to remember when working with GetRows; remembering these three things will save you many headaches and hours debugging, trust me! They are:
  •  VBScript arrays start at 0 and go to n-1, where n is the count of the records (or count of columns) in the recordset. If you have 30 records, you will have rows numbered from 0 to 29; if you have 5 columns, you will have columns numbered from 0 to 4. In other words, just as if you had done Dim rows(4,29) to declare the array size yourself.
  • VBScript arrays are arranged by MyArray(ColumnElement, RowNumber) instead of MyArray(RowNumber, ColumnElement)
  • The order of field selection in your SQL statement determines the column subscript used to access that field. If you have 5 fields you will have 0 to 4 column elements.
Imagine that you have the following SELECT SQL statement:

Select fName, lName, Address, City, State, Zip
FROM SomeTable
ORDER BY lName, fName

and that you have already created and opened both Connection and Recordset objects. To read the contents of the Recordset into an array, use:

MyArray = rsMyRecordSet.GetRows()

VBScript sets up MyArray(ColumnCount, RowCount) with ColumnCount being the number of fields selected - 1 (0 based) and RowCount being the number of records returned - 1 (0 based)

To access the elements of an array we need to use integer index values. To get the first column of the first row, we'd use: MyArray(0,0). This approach, however, is very unreadable. To make your code more readable (and hence more maintainable), consider creating constants whose values represent the position in the array for the column and whose name is similar to the column's name. For example, it would be prudent to add:

Const MyFirstNameOrdinal = 0
Const MyLastNameOrdinal = 1
Const MyAddressOrdinal = 2
Const MyCityOrdinal = 3
Const MyZipOrdinal = 4

In this instance you will have five columns in the array numbered 0 through 4

if we want to get the total number of columns or rows, we have to use different UBound statements, as shown below:

Ubound(MyArray,1) 'Returns the Number of Columns
Ubound(MyArray,2) 'Returns the Number of Rows

For our first example I will show how to display the data in some predetermined format, like:

lName, fName : address : city

The code to do this would be a simple loop through each of the rows in the array; then, in the loop body, Response.Write statements would output the proper array values:

For lnLoopCounter = 0 To Ubound(MyArray,2)
Response.Write MyArray(MyLastNameOrdinal, lnLoopCounter) _
& ", " _
& MyArray(MyFirstNameOrdinal, lnLoopCounter) _
& " : " _
& MyArray(MyAddressOrdinal, lnLoopCounter) _
& " : " _
& MyArray(MyCityOrdinal, lnLoopCounter) _
& "
" & vbNewLine

If you were wanting to display the fields in the exact order as they were presented in your SELECT clause you could add an inner loop for the columns. I usually just manually output the columns (as shown above) for simplicity, but either approach will work:

For lnRowCounter = 0 To Ubound(MyArray,2)
For lnColumnCounter = 0 To Ubound(MyArray,1)
Response.Write MyArray(lnColumnCounter, lnRowCounter)

Friday, September 24, 2010

Getting the values of checkbox in ASP form

Checkbox are shown to visitors to get the opinion on a fixed value. Sometime the visitors may have to submit more than one choice out of a group of options

In this article I am simply demonstrating how to get the values of all the checkboxes selected by visitors in classic ASP form

1. Create an selectoption.asp page
2. Put following line of code in it


In the above code the name of all the check boxes are same with different values so they will be treated as a group of checkbox.

3. Now create a ASP page with the name processing.asp and put the bellow mention code in it

Dim strmode, Arrmode,i
strmode =Request("test1 ")

We have used test1 as the common name so all the values of the checkbox for which the visitor has checked will be available as Request("test1 ") as comma separated values. So in the above code the variable mode value will be consisting of all checked values separated by comma. 

4. Now let split the string to get the array of checked values.
Arrmode _a=split(strmode,",")

5. Now we will loop through the array by using for for loop and UBound function to print out the checked values of the checkboxes. 
For i=LBound(Arrmode) to UBound(Arrmode)
        Response.Write Arrmode_a(i) + " "

Saturday, September 18, 2010

Executing Store Procedure by ADO Command Object, Passing Input paramer and store the result in Recordset object

This is a simple example in which i demonstrated how to pass input parameters using command object and save the results in record set object.As mention in my previous post dated  : August 18, 2010,passing input parameters with record set is convenient but it has certain serious drawbacks
  • With command object Output parameters of Store procedures are retrieval while with connection object it’s not possible. 
  • Executing Store procedure using connection object is not very efficient as it take more time to parse the Sql Statements.


CREATE TABLE [dbo].[Employee](
    [EmployeeID] [int] IDENTITY(1,1) NOT NULL,
    [EmployeeFirstName] [varchar](50) ,
    [Salary] [varchar](50) ,
    [EmployeeID] ASC

Store procedure

Create Procedure Sp_Employee
    @EmployeeID Int
    Select * From Employee Where EmployeeID = @EmployeeID

ASP Code for passing input parameter 


    Dim con
    set con =server.createobject("ADODB.Connection")
    Con.Open "Provider=SQLOLEDB; Data Source =localhost; Initial Catalog = test; User Id  =sa;pwd=sa"
    Set ObjCom = server.CreateObject("ADODB.Command")
    Set ObjCom.ActiveConnection = Con
    ObjCom.CommandType = adCmdStoredProc 'also you can use 4
    ObjCom.CommandText = "Sp_Employee"
    ObjCom.parameters.Append  ObjCom.CreateParameter("@EmployeeID", adInteger, adParamInput,,1)
   Set Rs = Server.CreateObject("ADODB.RecordSet")
        RS = ObjCom.Execute

Wednesday, September 8, 2010

ASP Transactions

The ObjectContext object is used to commit or abort transactions. For an .asp page to commit transaction, @TRANSACTION directive should be present in the script.

Transactions are important to maintain data integrity, among other things, and have been used with databases for some time now. Luckily, transactions aren't restricted to databases - you can use them in Active Server Pages as well, and without having to create custom components using Microsoft Transaction Server (MTS). This article will take a look at what transactions are, how they will help ASP developers, and how to implement them.

The ObjectContext object is used to commit or abort transactions. For an .asp page to commit transaction, @TRANSACTION directive should be present in the script.


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.


OnTransactionAbort : This event occurs when the transaction is aborted.

OnTransactionCommit: This event occurs when the transactional script's transaction is committed.

So what does transaction ASP code look like? The answer is, exactly like regular ASP code. We must simply add a one line directive to the beginning code to get it to behave properly:

<%@ TRANSACTION = value %>

Typically, each ASP page will be its own transaction, however, it is possible to continue transactions across more than one page by using the Server.Transfer and Server.Execute methods (new to IIS 5). If the calling page is transacted, and the current page uses "Transaction = Required" or "Transaction = Supported" then the current page will continue the existing transaction, which makes some very complex applications possible. 

Now you simply write ASP code as you would normally, and things will work transactionally.

<%@ TRANSACTION = Required %>

<% strText = Request.form("Textbox") if strText = "" then ObjectContext.SetAbort Response.write("You did not enter the text
Response.write("Processing transaction...
end if

'commit and rollback code
sub OnTransactionCommit()
Response.write("Operation was successful")
End Sub
sub OnTransactionAbort() 
Response.write("Operation was unsuccessful")
End Sub