Tuesday, August 31, 2010

Different ways of Declaring Variables in ASP


Variables are used to store information. When we declared a variable a space in the hip memory is allocated for that variable. This article demonstrates how to declare a variable in classic ASP using VB script, and how to assign a value to it, and use the value in a text.

Declaring variables in ASP is simple, especially since all variables are of type Variant. You don't have to define the variable's type (such as if it's an integer, string, etc.). Rather, you just declare the variable using the Dim keyword and it has the potential to be anything

Variables can be declared one at a time or all at once. Below is an example of both methods.

<% 
          'Single Variable Declarations
               Dim myVar1 
               Dim myVar2 
       'Multiple Variable Declarations
              Dim myVar6, myVar7, myVar8
%>

The below example demonstrate how to initialize a variable at the time of declaration

<% 
         Dim MyVariable : MyVariable = 50 

%>

Monday, August 30, 2010

VB Scrip built in functions


Because VBScript is an interpreted language (and not a compiled language), all of the possible built-in functions are already known to the browser. Therefore, you don't need to include a file or library. The best place to find out what functions already exist is by consulting the MSDN library or web site For its documentation.

Conversion Functions

The conversion functions are as follows:
Function

Name
Return Type
Description
CBool
Boolean
Converts an expression into a Boolean value
CByte
Byte
Converts an expression into Byte number
CDate
Date
Converts and expression into a date or time value
CDbl
Double
Converts an expression into a flowing-point (decimal) number
CInt
Integer
Converts an expression into an integer (natural) number
CCur
Currency
Converts an expression into a currency (monetary) value
CLng
Long
Converts an expression into a long integer (a large natural) number
CSng
Single
Converts an expression into a flowing-point (decimal) number
CStr
String
Converts an expression into a string

Besides the conversion functions, VBScript provides many other functions you can use in your scripts. Some of these functions are:

Language Element
Description
Abs Function
Returns the absolute value of a number.
Array Function
Returns a Variant containing an array.
Asc Function
Returns the ANSI character code corresponding to the first letter in a string.
Atn Function
Returns the arctangent of a number.
CBool Function
Returns an expression that has been converted to a Variant of subtype Boolean.
CByte Function
Returns an expression that has been converted to a Variant of subtype Byte.
CCur Function
Returns an expression that has been converted to a Variant of subtype Currency.
CDate Function
Returns an expression that has been converted to a Variant of subtype Date.
CDbl Function
Returns an expression that has been converted to a Variant of subtype Double.
Chr Function
Returns the character associated with the specified ANSI character code.
CInt Function
Returns an expression that has been converted to a Variant of subtype Integer.
CLng Function
Returns an expression that has been converted to a Variant of subtype Long.
Cos Function
Returns the cosine of an angle.
CreateObject Function
Creates and returns a reference to an Automation object.
CSng Function
Returns an expression that has been converted to a Variant of subtype Single.
CStr Function
Returns an expression that has been converted to a Variant of subtype String.
Date Function
Returns the current system date.
DateAdd Function
Returns a date to which a specified time interval has been added.
DateDiff Function
Returns the number of intervals between two dates.
DatePart Function
Returns the specified part of a given date.
DateSerial Function
Returns a Variant of subtype Date for a specified year, month, and day.
DateValue Function
Returns a Variant of subtype Date.
Day Function
Returns a whole number between 1 and 31, inclusive, representing the day of the month.
Eval Function
Evaluates an expression and returns the result.
Exp Function
Returns e (the base of natural logarithms) raised to a power.
Filter Function
Returns a zero-based array containing subset of a string array based on a specified filter criteria.
Fix Function
Returns the integer portion of a number.
FormatCurrency Function
Returns an expression formatted as a currency value using the currency symbol defined in the system control panel.
FormatDateTime Function
Returns an expression formatted as a date or time.
FormatNumber Function
Returns an expression formatted as a number.
FormatPercent Function
Returns an expression formatted as a percentage (multiplied by 100) with a trailing % character.
GetLocale Function
Returns the current locale ID value.
GetObject Function
Returns a reference to an Automation object from a file.
GetRef Function
Returns a reference to a procedure that can be bound to an event.
Hex Function
Returns a string representing the hexadecimal value of a number.
Hour Function
Returns a whole number between 0 and 23, inclusive, representing the hour of the day.
InputBox Function
Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns the contents of the text box.
InStr Function
Returns the position of the first occurrence of one string within another.
InStrRev Function
Returns the position of an occurrence of one string within another, from the end of string.
Int Function
Returns the integer portion of a number.
IsArray Function
Returns a Boolean value indicating whether a variable is an array.
IsDate Function
Returns a Boolean value indicating whether an expression can be converted to a date.
IsEmpty Function
Returns a Boolean value indicating whether a variable has been initialized.
IsNull Function
Returns a Boolean value that indicates whether an expression contains no valid data (Null).
IsNumeric Function
Returns a Boolean value indicating whether an expression can be evaluated as a number.
IsObject Function
Returns a Boolean value indicating whether an expression references a valid Automation object.
Join Function
Returns a string created by joining a number of substrings contained in an array.
LBound Function
Returns the smallest available subscript for the indicated dimension of an array.
LCase Function
Returns a string that has been converted to lowercase.
Left Function
Returns a specified number of characters from the left side of a string.
Len Function
Returns the number of characters in a string or the number of bytes required to store a variable.
LoadPicture Function
Returns a picture object. Available only on 32-bit platforms.
Log Function
Returns the natural logarithm of a number.
LTrim Function
Returns a copy of a string without leading spaces.
Mid Function
Returns a specified number of characters from a string.
Minute Function
Returns a whole number between 0 and 59, inclusive, representing the minute of the hour.
Month Function
Returns a whole number between 1 and 12, inclusive, representing the month of the year.
MonthName Function
Returns a string indicating the specified month.
MsgBox Function
Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked.
Now Function
Returns the current date and time according to the setting of your computer's system date and time.
Oct Function
Returns a string representing the octal value of a number.
Replace Function
Returns a string in which a specified substring has been replaced with another substring a specified number of times.
RGB Function
Returns a whole number representing an RGB color value.
Right Function
Returns a specified number of characters from the right side of a string.
Rnd Function
Returns a random number.
Round Function
Returns a number rounded to a specified number of decimal places.
RTrim Function
Returns a copy of a string without trailing spaces.
ScriptEngine Function
Returns a string representing the scripting language in use.
ScriptEngineBuildVersion Function
Returns the build version number of the scripting engine in use.
ScriptEngineMajorVersion Function
Returns the major version number of the scripting engine in use.
ScriptEngineMinorVersion Function
Returns the minor version number of the scripting engine in use.
Second Function
Returns a whole number between 0 and 59, inclusive, representing the second of the minute.
SetLocale Function
Sets the global locale and returns the previous locale.
Sgn Function
Returns an integer indicating the sign of a number.
Sin Function
Returns the sine of an angle.
Space Function
Returns a string consisting of the specified number of spaces.
Split Function
Returns a zero-based, one-dimensional array containing a specified number of substrings.
Sqr Function
Returns the square root of a number.
StrComp Function
Returns a value indicating the result of a string comparison.
String Function
Returns a repeating character string of the length specified.
StrReverse Function
Returns a string in which the character order of a specified string is reversed.
Tan Function
Returns the tangent of an angle.
Time Function
Returns a Variant of subtype Date indicating the current system time.
Timer Function
Returns the number of seconds that have elapsed since 12:00 AM (midnight).
TimeSerial Function
Returns a Variant of subtype Date containing the time for a specific hour, minute, and second.
TimeValue Function
Returns a Variant of subtype Date containing the time.
Trim Function
Returns a copy of a string without leading or trailing spaces.
TypeName Function
Returns a string that provides Variant subtype information about a variable.
UBound Function
Returns the largest available subscript for the indicated dimension of an array.
UCase Function
Returns a string that has been converted to uppercase.
VarType Function
Returns a value indicating the subtype of a variable.
Weekday Function
Returns a whole number representing the day of the week.
WeekdayName Function
Returns a string indicating the specified day of the week.
Year Function
Returns a whole number representing the year.

Friday, August 27, 2010

Variable

As there are different types of values used in an application, there are also different requirements to store those values. to prepare a storage area, we type the Dim keyword followed by a name.

The Name of a Variable

To specify the name of a variable, there are rules we must follow:

  • The name of a variable must start with either a letter or an underscore. A name can have only one letter but if we start it with an underscore, then the underscore must be followed by a letter
  • After the first character as an underscore or a letter, the name can contain letters, digits, or underscores in any combination
  • The name must not contain space but it can be made of various words as long as these words are concatenated (added together to produce one word)
  • The name must not contain any symbol other than letters, digits, or underscores
  • After respecting these rules, we can adopt a naming convention that suits us.
Data Types

Unlike some other languages, VBScript recognizes only a data type called Variant when declaring a variable using the following formula:

Dim VariableName

The Variant data type can be used in place of any type. After declaring the variable, its type is still not know. If we had requested a value from the user, before involving it in a calculation, we should first convert it to the appropriate type. Fortunately, VBScript provides the necessary means (functions) to perform this conversion.

Friday, August 20, 2010

Option Explicit


The first two lines of your page should look like the following:
<%@ Language=VBScript %>
<% option explicit %>

Why use option explicit? It forces us to declare our variables before we use them. Think about VBScript for a second, it is untyped, not case sensitive and we can just start using a variable wherever we want if we don't declare option explicit. When we start developing REALLY advanced scripted pages we'll need all the help we can get in keeping your code organized. There is nothing worse than some undeclared variable floating around in global scope. Imagine a team of programmers working together on an asp page that has 12 different server side includes. Now, imagine everyone with a variable named 'i' or 'counter' in global scope. Things can quickly get out of hand on large projects. Enforce good coding standards on yourself and others within our team.

Wednesday, August 18, 2010

Executing Store Procedure (SP) in ASP

A stored procedure is a group of Transact-SQL statements compiled into a single execution plan.

In a layman language a stored procedure is an already written SQL statement that is saved in the database. If we find ourselves using the same query over and over again, it would make sense to put it into a stored procedure. When we put this SQL statement in a stored procedure, we can then run the stored procedure from the database's command environment , using the exec command.

An example is:

CREATE PROCEDURE NameOfStoreProcedure
AS
SELECT FirstName, LastName FROM TableName;
GO

EXEC NameOfStoreProcedure

The name of the stored procedure is "NameOfStoreProcedure ", and "exec" tells SQL Server to execute the code in the stored procedure.

There are two main advantages of using store procedure in our program

  • Because stored procedures are stored within the DBMS, bandwidth and execution time are reduced. This is because a single stored procedure can execute a complex set of SQL statements.
  • With Store procedure we will store our entire business login inside the database itself. So if we plan to migrate from one technology to another say from classic ASP to .NET then we only need to change the user interface reset of the business logic remain same.

Call a stored procedure is through the connection object

The easiest way to call a stored procedure is through the connection object. This can be as simple as four lines of code: 

Dim ObjConn
Set ObjConn = Server.CreateObject("ADODB.Connection")
ObjConn.Open Application("Connection_String")
'Call the stored procedure to increment a counter on the page
ObjConn.Execute "exec NameOfStoreProcedure"

This case assumes there are no parameters, no results, and no error handling. Most of the time, we'll need more than this.

Call a stored procedure using Command Object

One of the major advantages of a Command object over connection object is the ability to use parameters. That means with command object Output parameters of Store procedures are retrieval while with connection object it’s not possible.

Any time we need to get data back from a stored procedure via a parameter, we need to invoke it using the ADO Command object. The sample below demonstrates the minimal properties and methods required to invoke a stored procedure call and return a value in an output parameter. 

Dim objConn
Dim objCmd

'Instantiate objects
Set objConn = Server.CreateObject("ADODB.Connection")
set objCmd = Server.CreateObject("ADODB.Command")
conn.Open Application("ConnectionString")

With objCmd
.ActiveConnection = conn 'We can also just specify a connection string here
.CommandText = "sp_InsertArticle"
.CommandType = adCmdStoredProc 'Requires the adovbs.inc file or typelib meta tag

'Add Input Parameters
.Parameters.Append .CreateParameter("@columnist_id", adDouble, adParamInput, , columnist_id)
.Parameters.Append .CreateParameter("@url", adVarChar, adParamInput, 255, url)
.Parameters.Append .CreateParameter("@title", adVarChar, adParamInput, 99, url)
.Parameters.Append .CreateParameter("@description", adLongVarChar, _
adParamInput, 2147483647, description)

'Add Output Parameters
.Parameters.Append .CreateParameter("@link_id", adInteger, adParamOutput, , 0)

'Execute the function
'If not returning a recordset, use the adExecuteNoRecords parameter option
.Execute, , adExecuteNoRecords
link_id = .Parameters("@link_id")
End With



Tuesday, August 17, 2010

Procedures And Functions


There are two kinds of procedures in VBScript: A sub procedure and a function. The difference lies on their behaviors but their coding (programming) depends of your goal

A procedure can be included in the body of an HTML but to separate the script behavior from the rest of the file, it is usually a good idea to include the procedures in the head section of the file.

The advantage of including a script in the head section is that it is more likely to be interpreted before the section it refers to is reached. If you have done any type of programming before, you may know that interpreters (and compilers) read a program in a top-down approach. Therefore, if the browser (actually the VBScript interpreter) finds a thing in the body section but doesn't know what that thing is because it is in the bottom part of the body section, it may not interpret your script accurately. But if the script is in the head section, the interpreter will have "seen" it before reaching the body section

Sub Procedures

A sub procedure is a section of code that carries an assignment but doesn't give back a result. To create a sub procedure, start the section of code with the Sub keyword followed by a name for the sub procedure. To differentiate the name of the sub procedure with any other regular name, it must be followed by an opening and closing parentheses. The section of the sub procedure code closes with End Sub as follows:

Sub ShowMeTheDough()

End Sub

We can declare variables in the procedure if you need to. These variables are declared and dealt with way, in the same way we learned in the regular script sections. Using declared variables, the above procedure can be written as follows:

Sub DisplayFullName()
Dim FirstName, LastName
Dim FullName

FullName = FirstName & " " & LastName
End Sub

Calling a Procedure

After creating a procedure, you can call it from another procedure, function, or control's event in the body section of an HTML file. To call a simple procedure such as the earlier DisplayFullName, you can just write the name of the sub procedure

In the following example, the above DisplayFullName sub procedure is called when the user clicks the Detail section of the form:

Sub Detailer()
DisplayFullName
End Sub

If you want the procedure to be accessed immediately as soon as the page displays, you can assign its name to the onLoad() event of the body tag

Arguments Passing

To carry an assignment, sometimes a procedure needs one or more values to work on. If a procedure needs a variable, such a variable is called an argument. Another procedure might need more that one argument, thus many arguments. The number and types of arguments of a procedure depends on various factors.

If you are writing your own procedure, then you will decide how many arguments your procedure would need. You also decide on the type of the argument(s). For a procedure that is taking one argument, in the parentheses of the procedure, write a name for the argument. Here is an example:

Sub CalculateArea(Radius)
Dim dblPI
Dim dblArea

dblPI = 3.14159
dblArea = Radius * Radius * dblPI
End Sub

A procedure can take more than one argument. If you are creating such a procedure, between the parentheses of the procedure, write the name of the first argument followed by a comma; add the second argument and subsequent arguments and close the parentheses. There is no relationship between the arguments; for example, they can be of the same type:

Sub CalculatePerimeter(Length, Height)
Dim dblPerimeter

dblPerimeter = 2 * (Length + Height)
End Sub
The arguments of your procedure can also be as varied as you need them to be. Here is an example:
Sub DisplayGreetings(strFullName, intAge)
Dim Sentence
Sentence 

Calling an Argumentative Procedure

We saw already how to call a procedure that doesn't take any argument. Actually, there are various ways you can call a sub procedure. As we saw already, if a sub procedure doesn't take an argument, to call it, you can just write its name. If a sub procedure is taking an argument, to call it, type the name of the sub procedure followed by the name of the argument. If the sub procedure is taking more than one argument, to call it, type the name of the procedure followed by the name of the argument, in the exact order they are passed to the sub procedure, separated by a comma. Here is an example:

Sub Result()
Dim dblHours, dblSalary

CalcAndShowSalary dblHours, dblSalary
End Sub
Sub CalcAndShowSalary(Hours, Salary)
Dim dblResult

dblResult = Hours * Salary
txtResult = dblResult
End Sub

Alternatively, you can use the keyword Call to call a sub procedure. In this case, when calling a procedure using Call, you must include the argument(s) between the parentheses. using Call, the above procedure could call the CalcAndShowSalary as follows:

Sub Result()
Dim dblHours As Double
Dim dblSalary As Double

dblHours = txtHours
dblSalary = txtSalary

Call CalcAndShowSalary(dblHours, dblSalary)
End Sub

Functions

Creating a Function

A function is an assignment that a piece of code can take care for the functionality of a database. The main difference between a sub procedure and a function procedure is that a function can return a value

A function is created like a sub procedure with a few more rules. The creation of function starts with the Function keyword and closes with End Function. Here is an example:

Function FindFullName()

End Function

The name of the function follows the same rules and suggestions we have reviewed for the sub procedures.

To implement a function, remember that it is supposed to return a value. In the body of the function, describe what it is supposed to do. to return the right value, assign the desired value to the name of the function. Here is an example:

Function CalculateArea(Radius)
CalculateArea = Radius * Radius * 3.14159
End Function

A function can also be as complex as performing many and various expressions in order to get a value that can be assigned to the name of the function.

Calling a Function

To call a function, you have two main alternatives. If you want to use the return value of a function in an event or another function, assign the name of the function to the appropriate local variable. Make sure you include the argument(s) of the function between parentheses.